Advanced Strategy Engine & Automated Risk Management
The ctx.strategy engine in BacktestX v1.0.6 delivers full Pine Script v5/v6 strategy parity—featuring native bracket orders, ratcheting trailing stops, resting limit/stop queues, compounding sizing, execution-realistic commissions, slippage, multi-entry pyramiding, and intrabar MFE/MAE excursion analytics.
Capital, Commissions & Dynamic Position Sizing
Configure starting capital, currency, position sizing modes, commissions, slippage, and pyramiding via ctx.strategy.config() or Pine strategy(...):
ctx.strategy.config({
initial_capital: 100000,
currency: 'USD',
default_qty_type: ctx.strategy.percent_of_equity, // 'percent_of_equity' | 'cash' | 'fixed'
default_qty_value: 15, // 15% compounding per trade
commission_type: 'percent', // 'percent' | 'cash_per_contract' | 'cash_per_order'
commission_value: 0.05,
slippage: 2,
pyramiding: 3
});
ctx.strategy.percent_of_equity: Sizes each trade as a percentage of live compounding equity (cash + unrealized profit).ctx.strategy.cash: Allocates a fixed cash dollar amount per trade.ctx.strategy.fixed: Default contract or share quantity.
Order Types & Pending Resting Queue
BacktestX supports both direct market executions and resting pending limit/stop orders:
// 1. Market entry with custom sizing options
ctx.strategy.entry('Long_Trade', 'long', {
qty_type: 'percent_of_equity',
qty: 15
});
// 2. Standalone Limit Buy Order resting on the book
ctx.strategy.order('Pullback_Limit', 'long', 5, entryPrice);
// 3. Explicit order cancellation by ID or cancel all resting orders
ctx.strategy.cancel('Pullback_Limit');
ctx.strategy.cancel_all();
Pending orders placed via ctx.strategy.order() rest in an internal simulation queue across future bars and automatically execute when price reaches your limit/stop price level.
Live Position State
During a ctx.run() or Direct Pine loop, calling strategy.entry() / close() synchronously updates internal state trackers readable on the same and subsequent bars:
ctx.strategy.position_size: Open position quantity (positive = long, negative = short,0= flat).ctx.strategy.position_avg_price: Volume-weighted average entry price across scaled pyramiding entries.ctx.strategy.openprofit(): Floating unrealized profit/loss against the current bar's close.strategy.netprofit,strategy.grossprofit,strategy.grossloss,strategy.wintrades,strategy.losstrades,strategy.opentrades, andstrategy.closedtrades.*(profit,entry_price,exit_price,size,commission,entry_bar_index,exit_bar_index,mfe,mae).
Bracket Orders & Dynamic Trailing Stop Loss
ctx.strategy.exit() attaches native bracket protection to open positions. It automatically manages multi-tick Take Profit, Stop Loss, and watermark-ratcheted Trailing Stops:
ctx.strategy.exit('Long_Exit', {
from_entry: 'Long_Trade',
profit: 3.0 * curAtr, // Take profit distance from entry
loss: 1.5 * curAtr, // Stop loss distance from entry
trail_points: 1.0 * curAtr, // Profit needed before trailing stop activates
trail_offset: 0.8 * curAtr // Trail distance behind peak watermark
});
- Watermark Ratcheting: Once the trade moves into profit by
trail_points, BacktestX tracks the highest high (for Longs) or lowest low (for Shorts). The stop price automatically ratchets upward/downward at a distance oftrail_offsetand never recedes. - Absolute Targets: You can also specify absolute price targets with
limitandstop. - Position Close: Use
ctx.strategy.close(id)orctx.strategy.close_all()to liquidate immediately at market.
Automated Risk Management Guard Suite
You can configure global strategy risk rules that will automatically halt trading if certain drawdown thresholds are breached.
ctx.strategy.risk.max_drawdown(15, 'percent'); // Halt simulation if drawdown hits 15%
ctx.strategy.risk.max_intraday_loss(4, 'percent'); // Halt for day if daily loss hits 4%
ctx.strategy.risk.max_cons_loss_days(3); // Halt after 3 consecutive loss days
ctx.strategy.risk.max_intraday_filled_orders(6); // Max 6 filled trades per day
ctx.strategy.risk.max_position_size(10); // Maximum units allowed
ctx.strategy.risk.allow_entry_in('long'); // 'long', 'short', or 'all'
ctx.strategy.risk.max_drawdown(value, type): Automatically terminates execution and liquidates positions when portfolio drawdown exceeds threshold ('percent'or'cash').ctx.strategy.risk.max_intraday_loss(value, type): Restricts further entries for the remainder of the calendar day once daily loss limit is reached.ctx.strategy.risk.max_cons_loss_days(count): Halts strategy execution after consecutive losing sessions.ctx.strategy.risk.max_intraday_filled_orders(count): Hard-caps the number of filled trades allowed per day to prevent overtrading.ctx.strategy.risk.max_position_size(count): Enforces strict position exposure limits.ctx.strategy.risk.allow_entry_in(direction): Restricts trade direction ('long','short', or'all').
Commissions, Slippage, Pyramiding & MFE/MAE Analytics (v1.0.6)
BacktestX v1.0.6 deducts commission_type (percent, cash_per_contract, cash_per_order) and slippage ticks directly on fills, enforces multi-entry pyramiding with weighted position_avg_price tracking, computes intrabar MFE / MAE badges + Avg MFE / Avg MAE / Total Commission KPIs, and supports custom strategy.set_metric() KPI cards & strategy.tag_trade() columns.
See also Strategy & Backtesting (Costs & MFE/MAE) and the No-Repaint Pyramiding Tutorial.
Complete Strategy Example
Here is a complete, ready-to-run BacktestX strategy showcasing compounding percent_of_equity, ATR bracket exits, dynamic trailing stop, pullback limit orders, cancellations, and risk guards:
const bars = ctx.bars;
if (!bars || bars.length < 50) return;
// 1. Account & Sizing Configuration (15% Compounding Equity)
ctx.strategy.config({
initial_capital: 100000,
currency: 'USD',
default_qty_type: ctx.strategy.percent_of_equity,
default_qty_value: 15
});
// 2. Automated Risk Management Rules
ctx.strategy.risk.max_drawdown(15, 'percent');
ctx.strategy.risk.max_intraday_loss(4, 'percent');
ctx.strategy.risk.max_cons_loss_days(3);
ctx.strategy.risk.max_intraday_filled_orders(6);
// 3. Technical Indicators
const closes = bars.map(b => b.close);
const fastEMA = ctx.ema(closes, 9);
const slowEMA = ctx.ema(closes, 21);
const atr = ctx.atr(bars, 14);
// 4. Bar-by-bar Strategy Loop
for (let i = 1; i < bars.length; i++) {
const b = bars[i];
if (isNaN(fastEMA[i]) || isNaN(slowEMA[i]) || isNaN(atr[i])) continue;
const curAtr = atr[i] || 1;
// Bullish crossover: Enter Long with Bracket TP, SL & Trailing Stop
if (fastEMA[i - 1] <= slowEMA[i - 1] && fastEMA[i] > slowEMA[i]) {
ctx.strategy.entry('Long_Trade', 'long', {
qty_type: 'percent_of_equity',
qty: 15
});
ctx.strategy.exit('Long_Exit', {
from_entry: 'Long_Trade',
profit: 3.0 * curAtr,
loss: 1.5 * curAtr,
trail_points: 1.0 * curAtr,
trail_offset: 0.8 * curAtr
});
}
// Standalone resting limit buy on pullbacks
if (fastEMA[i] > slowEMA[i] && b.close < fastEMA[i]) {
ctx.strategy.order('Pullback_Limit', 'long', 5, b.close - 0.5 * curAtr);
}
// Cancel resting order if trend breaks
if (b.close < slowEMA[i]) {
ctx.strategy.cancel('Pullback_Limit');
}
// Bearish crossover: close all long positions
if (fastEMA[i - 1] >= slowEMA[i - 1] && fastEMA[i] < slowEMA[i]) {
ctx.strategy.close_all();
}
}
// 5. Render EMAs on chart
ctx.plot(fastEMA, { title: 'Fast EMA (9)', color: '#089981', width: 2 });
ctx.plot(slowEMA, { title: 'Slow EMA (21)', color: '#f23645', width: 2 });