DocsStrategy APIorders

ctx.order.close()

Close the entire current position.

Signature

ctx.order.close(symbol, metadata?)

Parameters

NameTypeDescription
symbolstringAsset symbol
metadataobjectOptional order metadata

Behavior

  • If long → places market sell for full position
  • If short → places market buy to cover
  • If flat → no order placed

Example

function onBar(ctx, i) { const pos = ctx.position('ASSET'); const rsi = ctx.ind.rsi[i]; // Exit long on overbought if (pos.qty > 0 && rsi > 70) { ctx.order.close('ASSET', { signal: 'sell', reason: 'rsi_overbought' }); } // Exit short on oversold if (pos.qty < 0 && rsi < 30) { ctx.order.close('ASSET', { signal: 'cover', reason: 'rsi_oversold' }); } }

Common Patterns

Crossover exit

if (q.crossUnder(ctx.ind.fastEma, ctx.ind.slowEma, i)) { ctx.order.close('ASSET', { signal: 'sell' }); }

Time-based exit

if (i - ctx.state.entryBar >= 20) { ctx.order.close('ASSET', { signal: 'timeout', reason: '20_bars' }); }

Stop loss (manual)

const pos = ctx.position('ASSET'); if (pos.qty > 0) { const pnl = (ctx.series.close[i] - pos.avgPrice) / pos.avgPrice; if (pnl < -0.02) { ctx.order.close('ASSET', { signal: 'stop_loss' }); } }

Related

orderscloseexitpositionqsl