DocsStrategy APIposition

ctx.position()

Get information about the current position.

Signature

ctx.position(symbol)

Returns

PropertyTypeDescription
qtynumberPosition quantity (+ long, - short, 0 flat)
avgPricenumberAverage entry price
sidestring'long', 'short', or 'flat'

Example

function onBar(ctx, i) { const pos = ctx.position('ASSET'); // Check position state if (pos.qty === 0) { // Flat - look for entries } else if (pos.qty > 0) { // Long position const unrealizedPnl = (ctx.series.close[i] - pos.avgPrice) / pos.avgPrice; if (unrealizedPnl > 0.05) { ctx.order.close('ASSET', { signal: 'takeProfit' }); } if (unrealizedPnl < -0.02) { ctx.order.close('ASSET', { signal: 'stopLoss' }); } } else if (pos.qty < 0) { // Short position const unrealizedPnl = (pos.avgPrice - ctx.series.close[i]) / pos.avgPrice; if (unrealizedPnl > 0.05) { ctx.order.close('ASSET', { signal: 'takeProfit' }); } } }

Common Patterns

Position-aware entries

if (pos.qty === 0 && entryCondition) { ctx.order.market('ASSET', 1, { signal: 'buy' }); }

Calculate unrealized PnL

const pos = ctx.position('ASSET'); if (pos.qty > 0) { const pnlPercent = (ctx.series.close[i] - pos.avgPrice) / pos.avgPrice * 100; }

Track entry bar

function onBar(ctx, i) { const pos = ctx.position('ASSET'); // Just entered a position if (pos.qty > 0 && ctx.state.prevQty === 0) { ctx.state.entryBar = i; ctx.state.entryPrice = pos.avgPrice; } ctx.state.prevQty = pos.qty; }

Related

positionqtyavgPriceqsl