ctx.pos()
Warning:
ctx.pos()does NOT track real position state during a backtest. It always reports flat (qty: 0), regardless of orders already placed in the run. Never use it to decide whether you currently hold a position, or to gate entry/exit logic - doing so means your exits will never fire. Track position yourself with actx.stateflag instead (see below).Note:
ctx.position()is not a real method - the function is namedctx.pos().
Signature
ctx.pos(symbol)
Returns
| Property | Type | Description |
|---|---|---|
qty | number | Always 0 during a backtest - do not rely on this |
avgPrice | number | Always 0 during a backtest - do not rely on this |
The correct pattern: track position yourself with ctx.state
Every working strategy template tracks its own position with a ctx.state flag, set on entry and
cleared on exit, and stores whatever it needs (entry price, entry bar) alongside it:
function onBar(ctx, i) { const close = ctx.close[i]; if (ctx.state.inPosition) { const unrealizedPnl = (close - ctx.state.entryPrice) / ctx.state.entryPrice; if (unrealizedPnl > 0.05) { ctx.order.close('ASSET', { signal: 'takeProfit' }); ctx.state.inPosition = false; } else if (unrealizedPnl < -0.02) { ctx.order.close('ASSET', { signal: 'stopLoss' }); ctx.state.inPosition = false; } return; } // Flat - look for entries if (/* entry condition */) { ctx.order.market('ASSET', 1, { signal: 'buy' }); ctx.state.inPosition = true; ctx.state.entryPrice = close; ctx.state.entryBar = i; } }
Common Patterns
Position-aware entries
if (!ctx.state.inPosition && entryCondition) { ctx.order.market('ASSET', 1, { signal: 'buy' }); ctx.state.inPosition = true; ctx.state.entryPrice = ctx.close[i]; }
Calculate unrealized PnL
if (ctx.state.inPosition) { const pnlPercent = (ctx.close[i] - ctx.state.entryPrice) / ctx.state.entryPrice * 100; }
Track entry bar
function onBar(ctx, i) { if (!ctx.state.inPosition && /* entry condition */) { ctx.order.market('ASSET', 1, { signal: 'buy' }); ctx.state.inPosition = true; ctx.state.entryBar = i; ctx.state.entryPrice = ctx.close[i]; } }
Related
- ctx.order.market() — Enter positions
- ctx.order.close() — Exit positions
positionqtyavgPriceqslstate