Strategy Trading & Backtesting
Introduction to Backtesting
The BacktestX Script engine includes a built-in strategy object across Direct Pine Mode and JavaScript scripts, allowing you to simulate long/short trades, commissions, slippage, multi-entry pyramiding, and intrabar MFE/MAE excursions directly on the chart.
The Strategy API
Use the following methods to record simulated trades. When you pass boolean arrays as condArray in JS or execute strategy.entry() inside Direct Pine blocks, the engine draws Execution Arrows on the corresponding candles.
strategy.entry(id, direction, condArray)
strategy.close(id, condArray)- id: A string identifier for the trade (e.g., "MyLong").
- direction: "Long" or "Short".
- condArray: A boolean trigger array (JS) or per-bar condition inside an
ifblock (Pine).
Strategy Tester UI
Whenever a strategy evaluates, the Strategy Tester panel displays Net Profit, Win Rate, Max Drawdown, Avg MFE, Avg MAE, and Total Commission, alongside a chronological trade ledger with per-trade MFE/MAE excursion stats and custom tags.
Advanced Strategy API
0. Capital, Commissions, Slippage & Position Sizing Configuration
ctx.strategy.config(options)/ Pinestrategy(...): Configuresinitial_capital, currency, sizing mode (default_qty_type:percent_of_equity,cash, orfixed),commission_type(percent,cash_per_contract,cash_per_order),commission_value,slippageticks, andpyramiding.ctx.strategy.initial_capital(amount, currency): Programmatically sets starting capital.
1. Order Placement, Resting Queue & Bracket Exits
ctx.strategy.order(id, direction, qty, limit, stop, options): Places a standalone pending limit or stop order that rests in the order queue and executes when price crosses the limit/stop level.ctx.strategy.cancel(id)/ctx.strategy.cancel_all(): Cancels resting pending limit/stop orders by ID or purges the entire order queue.ctx.strategy.exit(id, options): Attaches a bracket exit to open positions with multi-tick Take Profit (profitorlimit), Stop Loss (lossorstop), and dynamic Trailing Stop Loss (trail_pointsandtrail_offset) that ratchets forward with real-time watermark tracking.ctx.strategy.close_all(): Closes all open positions and cancels resting orders immediately at market price.
2. Risk Management
These functions enforce risk rules which the Strategy Tester mathematically honors when generating Net Profit and Drawdown stats:
ctx.strategy.risk.max_drawdown(value, type): Stops trading if the strategy loses a certain amount ('percent'or'cash').ctx.strategy.risk.max_intraday_loss(value, type): Caps the maximum loss allowed per day.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').
3. Real-Time & Closed-Trade Tracking
Read live position balances and closed-trade histories inside your script:
ctx.strategy.equity&openprofit(): Live updating equity balance and floating unrealized PnL.ctx.strategy.position_size&position_avg_price: Net open quantity and weighted average entry price across pyramiding entries.strategy.closedtrades.*(v1.0.6): Accessprofit,entry_price,exit_price,size,commission,entry_bar_index,exit_bar_index,mfe, andmae, plusnetprofit,grossprofit,grossloss,wintrades,losstrades, andopentrades.ctx.strategy.current_index(orbar_index): Automatically synchronized simulation bar index during standard loops.
4. Custom Strategy UI (strategy.set_metric & strategy.tag_trade)
Customize the Strategy Tester UI directly from Pine or JavaScript scripts:
ctx.strategy.setMetric(label, value, color)/strategy.set_metric(...): Injects a custom stats card into the top Key Stats dashboard.- label: Metric title (e.g. "Sharpe Ratio").
- value: Display text/number (e.g. "1.85").
- color: (Optional) Hex code for the value.
ctx.strategy.tagTrade(id, columnName, value, color)/strategy.tag_trade(...): Appends a custom column badge to the trade table for a specific trade ID.- id: Trade ID (e.g. "MACD Long").
- columnName: Column header (e.g. "Confidence").
- value: Row tag value (e.g. "High").
- color: (Optional) Hex color code.
Commissions, Pyramiding & Intrabar MFE/MAE (v1.0.6)
In v1.0.6, the strategy execution engine deducts commission_value and slippage directly inside fills, enforces pyramiding limits with weighted average entry pricing, and tracks intrabar MFE / MAE excursions across every trade automatically—rendering per-trade MFE/MAE badges alongside Avg MFE, Avg MAE, and Total Commission KPIs.
Read the Advanced Strategy Engine Guide and No-Repaint Strategy Tutorial for complete examples and formulas.