closePosition
ctx.order.closePosition(reason?)
At a glance — close the current open position at market. The optional reason
string is attached to logs and the close event. Returns an
OrderTicket; the close is confirmed
asynchronously through onPositionClosed.
Signature
closePosition(reason?: string): OrderTicketExample
import { crossedOver, crossedUnder, defineStrategy, EMA } from '@nexpips/sdk-trading';
/** * Croisement de moyennes exponentielles. Golden cross (EMA rapide passe * au-dessus de la lente) → entrée ; death cross → sortie. Montre `EMA`, * `crossedOver` et `crossedUnder`. */export default defineStrategy({ symbol: 'EURUSD', timeframe: 'H1', risk: { maxRiskPercentPerTrade: 1, maxOpenPositions: 1, maxDailyLossPercent: 5 }, setup: (api) => { const fast = api.use(EMA, { source: 'close', period: 12 }); const slow = api.use(EMA, { source: 'close', period: 26 });
return { onBar(ctx) { if (ctx.position.isFlat && !ctx.position.hasPendingOrder && crossedOver(fast, slow)) { ctx.order.marketBuy({ riskPercent: 1, stopLoss: { type: 'atr', period: 14, multiple: 2 }, takeProfit: { type: 'rr', value: 2 }, }); return; }
if (ctx.position.isLong && crossedUnder(fast, slow)) { ctx.order.closePosition('ema death cross'); } }, }; },});Close the long on an EMA death cross.
To know
- Calling
closePositionwhile flat (ctx.position.isFlat) is a code bug and throwsStrategyInvariantError. Guard withPositionReader.
See also
modifyPosition— adjust instead of closeonPositionClosed·PositionReader