How to Write a Trading Strategy in Pine Script
A Pine Script strategy defines simulated orders for TradingView's broker emulator. Write down the entry, exit, size, and execution assumptions first, then implement them with strategy(). Changing an indicator's declaration alone does not supply missing order rules.
Define a small, complete rule set
This example enters long after price crosses above a 20-bar SMA and closes that long after price crosses below it. It never intentionally opens a short. It has no protective stop or profit target; those omissions are part of the example's scope, not a recommendation for live use.
The configured 10% of equity is position allocation, not a guaranteed loss budget. Commission and slippage are illustrative assumptions that must be replaced with values appropriate to the instrument and execution venue.
//@version=6
strategy("Price SMA Long Example", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent, commission_value=0.1, slippage=1)
length = input.int(20, "SMA length", minval=1)
ma = ta.sma(close, length)
crossUp = ta.crossover(close, ma)
crossDown = ta.crossunder(close, ma)
if crossUp and strategy.position_size == 0
strategy.entry("Long", strategy.long)
if crossDown and strategy.position_size > 0
strategy.close("Long")
plot(ma, "SMA", color.orange)
Inspect how orders differ from signals
By default, the strategy calculates at bar close and a newly created market order fills on the next available tick, typically the following historical bar's open. A marker at the signal close is therefore not automatically the fill price. TradingView's strategy documentation explains its broker-emulator assumptions.
strategy.close("Long") closes entries with that ID using a market order. strategy.entry(..., strategy.short) would instead open a short and can reverse an existing long. Do not label the latter merely “sell” if the intended rule is to exit without taking opposite exposure. Price-based exits use strategy.exit() with appropriate stop or limit parameters.
Run a reproducible check
Open Pine Editor, create a strategy, replace its source with the complete example, save, and add it to a standard candlestick chart. Record the symbol, exchange, timeframe, available test dates, and strategy properties.
Inspect several trades in Strategy Tester. Confirm the preceding close crossed the SMA, the next fill uses the configured emulator rules, and a cross-down closes the long rather than opening a short. If there are no trades, check available bars, input values, capital, and whether a qualifying cross occurred. An open final trade may remain when the sample ends.
Evaluate performance without selecting only winners
A single favorable period cannot establish consistency across samples. Reserve data outside parameter selection, retain the results of unsuccessful parameter trials, and test sensitivity to costs and gaps. Read both trade-level results and equity drawdown; a high win rate can still lose money when losses are larger than gains.
Changing the length is a new test, not proof of adaptability. Adding RSI or a trend filter also changes the rule set and sample. Document those changes before evaluating them. The backtesting workflow covers the broader process.
Pineify can help draft a strategy from explicit rules. Compare generated code with those rules, validate its syntax, and inspect simulated trades. A strategy on a TradingView chart does not directly submit live broker orders, and compiling successfully does not validate profitability.
Is a short entry the same as closing a long?
No. A short entry can reverse a long into a short position. Use the intended closing or exit instruction when you only want to leave the long.
Does this example have a stop-loss?
No. It closes on the opposite price/SMA cross. Define and test a separate protective exit if that is required by your specification.
Why does the fill appear after the signal?
Under the default calculation model, the strategy creates an order at bar close and fills it on the next available tick. Inspect the emulator settings before interpreting results.

