Most sizing code answers one question: how many shares can I buy so a stop-out costs 1% of the account. That works for a new position. It goes wrong when the agent already owns the stock, because the formula doesn't know about the shares you have.
Here is a test account I used. Margin account, $50,000 equity, $21,340 cash.
MSFT 18 @ 420 Technology
NVDA 40 @ 185 Technology
JNJ 60 @ 155 Health Care
XOM 40 @ 110 Energy
The agent wants more NVDA at $185 with a stop at $170.
Step 1: size by risk
import requests
AFA = "https://agent-financial-advisor.agent-financial-advisor.workers.dev/v1/tools/"
positions = [
{"symbol": "MSFT", "quantity": 18, "market_price": 420, "sector": "Technology"},
{"symbol": "NVDA", "quantity": 40, "market_price": 185, "sector": "Technology"},
{"symbol": "JNJ", "quantity": 60, "market_price": 155, "sector": "Health Care"},
{"symbol": "XOM", "quantity": 40, "market_price": 110, "sector": "Energy"},
]
size = requests.post(AFA + "position_size", json={
"equity": 50000, "entry_price": 185, "stop_price": 170,
"method": "fixed_fractional", "risk_pct": 0.01, "max_position_pct": 0.2,
}).json()
print(size["quantity"], size["position_pct_of_equity"], size["binding_constraint"])
33 0.1221 fixed_fractional
33 shares, $495 at risk, 12.2% of equity. Looks fine. The 20% cap didn't bind because the sizer only sees this order. It has no idea there are already 40 shares in the account.
Step 2: check the order against the account
pre_trade_check gets the positions, so it can do the math on the total.
body = {
"account": {"type": "margin", "equity": 50000, "cash": 21340, "positions": positions},
"order": {"symbol": "NVDA", "side": "buy", "quantity": 33,
"order_type": "market", "stop_loss_price": 170},
"market": {"last_price": 185, "avg_daily_volume": 180000000},
}
r = requests.post(AFA + "pre_trade_check", json=body).json()
print(r["decision"], r["suggested_quantity"])
for c in r["checks"]:
if c["status"] != "pass":
print(c["id"], c["message"])
approve_with_warnings 14
concentration NVDA would be 27% of equity (limit 20%). Max additional quantity: 14.
40 + 33 = 73 shares, $13,505, 27% of the account. The max you can add and stay at 20% is 14. Risk per trade passed (0.99%), so the risk rule was never the problem. The position cap was.
The default cap is 20%. You can change it with "policy": {"max_position_pct": 0.15} if you want a tighter book.
Step 3: sectors
The single-name check doesn't look at sectors. MSFT and NVDA are both Technology. Before the trade that is $14,960, about 29.9%. I let the agent cap sectors at 35%, so I ran the post-trade book through portfolio_review:
holdings = [{"symbol": p["symbol"], "quantity": p["quantity"], "price": p["market_price"],
"sector": p["sector"], "asset_class": "equity"} for p in positions_after]
review = requests.post(AFA + "portfolio_review", json={
"holdings": holdings, "cash": 18750,
"limits": {"max_single_weight": 0.2, "max_sector_weight": 0.35},
}).json()
print(review["sector_weights"])
for f in review["findings"]:
print(f["severity"], f["issue"])
positions_after is the same list with NVDA at 54 shares (14 added), and cash is $21,340 minus 14 × $185. Output:
{'Technology': 0.351, 'Health Care': 0.186, 'Energy': 0.088}
medium Technology sector is 35.1% (limit 35%).
medium Effective number of holdings is 4.1; the portfolio behaves like a concentrated book.
Just over. The sector room is easy to work out yourself, so I do that locally and use the review as a second look:
def sector_room(positions, equity, sector, price, max_sector_pct=0.35):
held = sum(p["quantity"] * p["market_price"] for p in positions if p["sector"] == sector)
return max(0, int((max_sector_pct * equity - held) // price))
print(sector_room(positions, 50000, "Technology", 185)) # 13
Putting it together
qty = min(size["quantity"], r["suggested_quantity"] or size["quantity"],
sector_room(positions, 50000, "Technology", 185))
33 by risk, 14 by the position cap, 13 by the sector cap. The agent buys 13. Whatever limit is smallest wins, and the agent should log which one it was so you can see later why the order was smaller than it asked for.
Limits
- Positions need current prices. If the agent passes avg cost instead of market price, every percentage is off. This one is alot easier to get wrong than it sounds when positions come from a cache.
- Equity has to match the positions plus cash. My first run had them out of sync and the review flagged JNJ over 20% when it wasn't.
- The first 5 calls a day need no signup.
POST /v1/keysgives a free key with 25 calls a day. - It's rule-based analysis for software, not investment advice.
The API is the Agent Financial Advisor API. The same tools are on the MCP server at /mcp.
Disclosure: I built this. If your agent caps something else before it adds to a position, like correlation or beta, I'd like to hear how you do it.
Top comments (0)