Write your first strategy: strategy() code and the Strategy Tester
Write your first strategy in Pine-compatible script: an EMA crossover with an ATR stop, target, commission and slippage, then read the Strategy Tester report.
A strategy is a script that declares strategy() instead of indicator() and uses strategy.entry, strategy.exit and strategy.close to place simulated orders. When you add one to a SuperCharting chart, the broker emulator fills those orders on the chart's history and the Strategy Tester opens under the chart with the results. This tutorial writes a complete EMA crossover strategy with a stop and a target, then shows where to read the report.
Pine Script is TradingView's language; SuperCharting runs Pine-compatible strategies in the same version 6 syntax. Backtest results describe the past only. Past results do not guarantee future results, and nothing here is a trading recommendation.
From indicator to strategy
If you built the crossover in write your first indicator, you already have the signal. A strategy adds three things:
- The declaration.
strategy("Name", ...)with the account settings for the test: starting capital, order size, commission and slippage. - Entries.
strategy.entry("Long", strategy.long)sends a market order. By default it fills at the open of the next bar, as a real order sent after a bar closes would. - Exits.
strategy.exitsets a stop and a take-profit for an open entry;strategy.closecloses it at market.
The complete strategy
//@version=6
strategy("EMA Cross Strategy", overlay=true, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent, commission_value=0.05, slippage=2)
fastLen = input.int(9, "Fast EMA length", minval=1)
slowLen = input.int(21, "Slow EMA length", minval=1)
atrLen = input.int(14, "ATR length", minval=1)
stopMul = input.float(2.0, "Stop (x ATR)", minval=0.1, step=0.1)
tpMul = input.float(3.0, "Target (x ATR)", minval=0.1, step=0.1)
fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)
atr = ta.atr(atrLen)
plot(fast, "Fast EMA", color=color.teal)
plot(slow, "Slow EMA", color=color.orange)
if ta.crossover(fast, slow) and strategy.position_size == 0
strategy.entry("Long", strategy.long)
strategy.exit("Long exit", from_entry="Long", stop=close - stopMul * atr, limit=close + tpMul * atr)
if ta.crossunder(fast, slow)
strategy.close("Long", comment="Cross down")
What each part does
The strategy() line
initial_capital=100000: the test starts with 100,000 in the chart's currency.default_qty_type=strategy.percent_of_equityanddefault_qty_value=10: each entry uses 10% of current equity.commission_type=strategy.commission.percentandcommission_value=0.05: 0.05% of the trade value is charged on every entry and every exit.slippage=2: market and stop orders fill 2 ticks worse than the price that triggered them.
You can change all of these later on the Properties tab of the strategy's settings without editing the code. Keep commission and slippage realistic for your broker and market; a strategy that only works with zero costs does not work.
Entry, stop and target
The entry fires when the fast EMA crosses above the slow EMA and no position is open (strategy.position_size == 0). On the same bar, strategy.exit attaches a stop two ATRs below the close and a target three ATRs above. The ATR (average true range) scales both to how much the market is moving, so the same rule works on a quiet day and a busy one.
The second exit
If the averages cross back down before the stop or target is reached, strategy.close("Long") closes the trade at market. The comment "Cross down" appears as the label of the exit marker on the chart, so you can tell which exit closed each trade.
How to run a strategy in SuperCharting
- Open a chart, for example XAUUSD on 1 hour or NSE:NIFTY on 15 minutes, and press Ctrl + E.
- Paste the strategy above. Wait for the console to show "✓ EMA Cross Strategy (strategy)".
- Click Add to chart. Entry and exit markers appear on the bars, and the Strategy Tester opens under the chart on the strategy's first result.
- Read Key stats at the top: Total PnL, Max drawdown, Profitable trades and Profit factor.
- Switch to the table view for the List of trades. Click a trade to jump to it on the chart.
- Change an input in the strategy's settings (for example Stop to 1.5) and watch the report update.
If you close the tester, right-click the strategy's name in the chart legend and choose Strategy Tester to open it again. The report is explained section by section in the Strategy Tester guide.
Check the result before you trust it
A first backtest is a starting point, not an answer. Before you draw any conclusion:
- Count the trades. Ten trades say very little; look for dozens across different market conditions.
- Compare with buy and hold. The tester's Benchmarking section compares the strategy with simply holding the symbol over the same period.
- Test another period and symbol. Use the Testing period button to limit the test to part of the history, then run the rest separately. The backtesting guide shows how to keep a period aside for an honest check.
- Be careful with tuning. The Optimise button searches the inputs for the best result, which is useful and easy to overdo. Read strategy optimiser before you start.
Common mistakes in a first strategy
- Entering on every bar. Without the
strategy.position_size == 0check, pyramiding settings decide whether repeat signals add to the position. The default allows one entry per direction. - Stops placed above the entry for a long. A stop above the price fills at once. Check the sign of each calculation.
- Expecting fills on the signal bar. Market orders fill on the next bar's open. To fill on the bar's close, set Order execution delay to None on the Properties tab, or add
process_orders_on_close=trueto the strategy() line, and know that this is less realistic. - Looking only at profit. A strategy with a large profit and a 40% drawdown may be impossible to follow in practice.
Writing and testing strategies is part of every SuperCharting account, and the site is currently free to use.
Frequently asked questions
Can a strategy go short?
Yes. Use strategy.entry("Short", strategy.short) with its own strategy.exit. A short entry while a long is open reverses the position.
Why do my trades fill one bar after the signal?
That is the default: an order sent at a bar's close fills at the next bar's open. It matches what you could do in real trading.
Can I get an alert when the strategy trades?
Yes. The Strategy Tester has an Add alert on strategy button. The alert fires on each order fill, and the message can include placeholders such as {{strategy.order.action}} and {{strategy.order.price}}.
Does a good backtest mean the strategy will make money?
No. It shows how the rules behaved on past data with the costs you set. Past results do not guarantee future results.