Skip to Content
While25SDK docs
Trading

Positions and funds

Positions, funds and P&L as exact figures, and what this module itself holds.

p = while25.portfolio.position("EQ:US:AAPL")   # None when flat
every = while25.portfolio.positions()           # the whole account: one dict per broker row, [] when flat
f = while25.portfolio.funds()                  # margin_used, margin_available, assets, figures — or None
if f is None:
    why = while25.portfolio.funds_unavailable_reason()   # the broker's own words
d = while25.portfolio.day_pnl()                # today's ACCOUNT P&L (a Money) — or None

Figures are exact. position()'s quantity is a Decimal; its average_price and last_price are Decimal | None; its pnl is a while25.Money | None — a frozen (value: Decimal, currency: str) pair that reads as "1234.5 USD". A position's last_price and pnl are None until its instrument has ticked since the broker snapshot.

Binance futures P&L follows the account's "P&L on" choice (risk policy: Last price, the default, or Mark price; the loss limits follow it): every row states pnl_price ("mark" | "last") and mark_price (Decimal | None); a stop held there keeps the price the choice named when it was placed (mine()["held_stops"][i]["triggers_on"]: "mark" | "last"); a trailing stop on the mark placed before the contract's first mark waits for it (its trigger_price is None until then); average_price there is the fills' average (fees and funding are outside positions on Binance and Coinbase futures); funds()["contract_settings"] is [{"instrument_key", "symbol", "margin_type": "cross" | "isolated", "leverage"}], as the tickets show them.

Fees are included where brokers send them. A position's average_price takes each fill's fee when the broker reports one (IBKR's commissions), raising a long's average and lowering a short's; where the broker reports none (Alpaca, Zerodha and Upstox today) it stays at the fill prices. Don't add a fee the broker sent to it again yourself.

A symbol held under more than one product (intraday and delivery, say) comes back as ONE combined position: quantity summed; pnl summed only when every row states one and they are all in the same currency (a long in INR and a short in USD cannot be honestly added, so it is None); average_price is the quantity-weighted average, quantized to 9 decimal places, and only across rows on the same side (a long averaged against a short is None, never a guess). position()["rows"] keeps each broker row exactly as reported, and ["products"] names them, so nothing is lost by combining.

day_pnl(), realised_pnl() and unrealised_pnl() are account-level Money | None figures from the broker's own account line (day P&L falls back to the platform's portfolio summary when it holds rows); each is None when nobody stated it — never a sum over positions, which vanish when a position closes.

positions() is the account's every holding, as the broker reports it: one dict per row, with the same fields as position()["rows"] (instrument_key, symbol, product, quantity, average_price, last_price, pnl), and nothing combined. A symbol held under two products is two rows here and one combined position in position(). It is the whole account, other strategies' and manual trades included: for what this module holds, read my_positions() below.

for row in while25.portfolio.positions():
    ctx.log(f"{row['symbol']} {row['product']}: {row['quantity']} @ {row['average_price']}")

Never cached: a stale position feeding a sizing decision is a money bug.

When one of the combined rows states no quantity, the whole quantity is None (never summed as 0), and then there is no side and no average_price either.

What this module holds: my_position(), my_positions(), orders.mine()

mine = while25.portfolio.my_position("EQ:US:AAPL")   # None when it has nothing there
every = while25.portfolio.my_positions()              # one dict per instrument, [] for none
working = while25.orders.mine()                       # its working orders and held stops

position() is the account's; this is the module's own, changed by its own orders and ended by a square off of the whole position (a POSITION_SQUARED_OFF event says so), and kept across a Stop and a restart of the app, so a strategy deployed again (the same id) reads where it left off. my_position(key) takes the instrument key, or its symbol when that names one instrument the module has (two: ValueError), and returns:

Key
instrument_key, symbolthe instrument
quantityits PART, a signed Decimal: what its orders bought and sold outside any bracket or combo; Decimal(0) when all it has there is in brackets or combos
productthe part's pocket ("DELIVERY", "INTRADAY", "MARGIN"; "" where a market keeps one per instrument); None across several pockets (each is in rows)
average_price, last_priceDecimal, or None when not known
pnlWhile25's unrealised P&L on the part, a Money; None when the price or the multiplier is not known
closed_pnl, closed_pnl_besideon each of rows (as on each mine() part): what the part closed, a Money or None, and beside it the fees its fills paid in another asset (Binance's BNB), a list of Money, one per asset, never converted; a BNB-paid fee is never in average_price or pnl
account_quantitythe pocket's whole net on the account beside it, a signed Decimal; None until the broker's first position report of the session (never 0), and None across several pockets
rows, productseach part as stated, one per pocket, and their pockets
bracketsits brackets there: bracket_id, group_label, side, product, quantity_held, entry_average, last_price, pnl, broker_held, waiting_for_entry
combosits combos' legs there (see Combos)

Parts in several pockets combine by position()'s rules. my_positions() lists every instrument the module has a part, a bracket or a combo leg on. orders.mine(instrument_key=None) lists its working orders and the stops While25 holds for it, one dict each: order_id, instrument_key, symbol, side, order_type (MKT, LMT, STP, STP LMT, MIT, LIT, TRAIL), product, validity, hours, quantity, filled_quantity, price, trigger_price, status (PENDING, OPEN, or TRIGGER_PENDING for a stop held by While25), held_by, tag, bracket_id, group_label and role (ENTRY, EXIT, TAKE_PROFIT, PROTECTIVE_STOP, ENTRY_STOP, BRACKET_ENTRY, BRACKET_TAKE_PROFIT, BRACKET_STOP, COMBO_LEG). All three are reads: they need no order rights, on_stop may call them, and they are answered from what While25 already holds, so a strategy may ask every tick. NOT_READY while While25 cannot tell yet (its order path is not up, or it is not attached to Python): ask again, never read it as flat.

funds() returns {"margin_used": Money | None, "margin_available": Money | None, "assets": [...]}, or None when the broker has not stated the account's funds at all — a panel must render that as unavailable rather than as a number. Each figure is None where the venue does not state it: Alpaca states no available margin, so its margin_available is None on a funded account; render that as "not stated", never as 0, and never gate an order on it. It is not a rare path: Upstox refuses the funds route outside its service hours, and a broker that has told you nothing has not told you the account is empty. Write if f is None:, never f = while25.portfolio.funds() or {} and never .get("margin_available", 0) — a fabricated zero is indistinguishable from a drained account, which is the one mistake this API is shaped to prevent. assets is [], never absent, when the venue states no per-asset breakdown — each entry is {"asset": str, "free": Decimal | None, "locked": Decimal | None, "total": Decimal | None}, for the crypto venues that report balances per coin.

figures is every figure the broker states, under its own names and in its own order (the Funds tab's rows); [] from a While25 that sends none. Each is {"section": str, "label": str, "column": str, "kind": "money" | "units" | "percent" | "number" | "text", "value": Decimal | None, "text": str | None, "currency": str | None, "field": str, "roles": [str], "key_types": [str]}: value is None on a "text" figure (its word is in text), column says which of several ("Securities", a currency, "Hold"; "" = the figure itself), and field is the broker's own key. roles mark the money the broker lets you put into a new trade ("available": IBKR's Current Available Funds, Alpaca's Buying power), its margin in use ("margin_used") and its margin still free ("margin_available"); margin_used / margin_available are those figures' values. key_types names the instrument kinds those roles answer for on an account holding several kinds (Coinbase spot + US futures: "CRYPTO", "FUT"); [] = every kind.

f = while25.portfolio.funds()
avail = next((g for g in f["figures"] if "available" in g["roles"]), None) if f else None
while25.log(f'{avail["label"]}: {avail["value"]}' if avail else "available: not stated")

There is no cash figure. It used to exist and was filled with available_margin under a second name; a relabelled quantity is a wrong number, so it was removed rather than left to be believed.