ctx.order.reduce()
Reduce the current position by a percentage.
Signature
ctx.order.reduce(symbol, fraction, metadata?)
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Asset symbol |
fraction | number | Fraction to close (0.5 = 50%) |
metadata | object | Optional order metadata |
Example
function onBar(ctx, i) { const pos = ctx.position('ASSET'); if (pos.qty > 0) { const pnl = (ctx.series.close[i] - pos.avgPrice) / pos.avgPrice; // Take profit at 5%: close half if (pnl > 0.05 && !ctx.state.tookProfit) { ctx.order.reduce('ASSET', 0.5, { signal: 'takeProfit', reason: '5pct_gain' }); ctx.state.tookProfit = true; } // Take profit at 10%: close remaining if (pnl > 0.10) { ctx.order.close('ASSET', { signal: 'takeProfit', reason: '10pct_gain' }); } } }
Scaling Out Pattern
function init(ctx) { ctx.state.scaleOutLevel = 0; } function onBar(ctx, i) { const pos = ctx.position('ASSET'); if (pos.qty === 0) { ctx.state.scaleOutLevel = 0; return; } const pnl = (ctx.series.close[i] - pos.avgPrice) / pos.avgPrice; // Scale out at 3%, 6%, 9% if (pnl > 0.03 && ctx.state.scaleOutLevel === 0) { ctx.order.reduce('ASSET', 0.33, { signal: 'scale_out_1' }); ctx.state.scaleOutLevel = 1; } if (pnl > 0.06 && ctx.state.scaleOutLevel === 1) { ctx.order.reduce('ASSET', 0.5, { signal: 'scale_out_2' }); ctx.state.scaleOutLevel = 2; } if (pnl > 0.09 && ctx.state.scaleOutLevel === 2) { ctx.order.close('ASSET', { signal: 'scale_out_final' }); } }
Related
- ctx.order.close() — Full exit
- ctx.order.market() — Entry orders
ordersreducepartialexitqsl