Skip to content

marketBuy

ctx.order.marketBuy(params)

At a glance — send a buy order at market. The position only exists once the broker confirms the fill asynchronously via onOrderFilled. Until then, ctx.position.hasPendingOrder returns true.

Signature

marketBuy(params: EntryParams): OrderTicket

EntryParams requires a non-zero riskPercent and a stopLoss (mandatory by design — the SDK refuses any entry without one to protect users from unbounded losses).

Examples

Simple case

order/market-buy-simple
import { defineStrategy } from '@nexpips/sdk-trading';
/**
* Acheter au marché si on est flat, avec un stop-loss à 20 pips.
*
* Pattern : entrée propre — vérifier `hasPendingOrder` ET `isFlat`
* pour éviter d'envoyer un ordre alors qu'un précédent est encore
* en attente de confirmation broker.
*/
export default defineStrategy({
symbol: 'EURUSD',
timeframe: 'H1',
risk: {
maxRiskPercentPerTrade: 1,
maxOpenPositions: 1,
maxDailyLossPercent: 5,
},
setup: () => ({
onBar(ctx) {
if (!ctx.position.isFlat) return;
if (ctx.position.hasPendingOrder) return;
ctx.order.marketBuy({
riskPercent: 1,
stopLoss: { type: 'pips', value: 20 },
takeProfit: { type: 'rr', value: 2 },
});
},
}),
});

Buy when flat with a 20-pip stop and 1:2 R:R take-profit.

To know

  • The order is not filled when the method returns. Treat the returned OrderTicket as a correlation ID, then react in onOrderFilled / onOrderRejected.
  • The runtime enforces R5–R13 invariants (maxRiskPercentPerTrade, maxOpenPositions, presence of stop-loss, sane riskPercent, etc.). Violating them throws StrategyInvariantError at order construction.
  • Possible rejection reasons surface via onOrderRejected with a RejectReason: no_liquidity, requote, market_closed, insufficient_margin, broker_error, connection_lost, invalid_volume_too_small, invalid_volume_too_large.

See also