Skip to content

Trend with stops and targets

Enter long when the shorter moving average is above the longer one. Exit on the reverse relationship or a protective price rule.

Complete strategy

02_sma_crossover_with_risk.strat
//@version=1

symbol: RELIANCE
run: each bar
size: 100 shares per instrument
stop: 2%
target: 4%
trail: 2%

entry:
    long when: sma(hl2, 3) > sma(hl2, 9)
exit:
    long when: sma(hl2, 3) < sma(hl2, 9)

Read the rule

The stop and trail are 2%; the target is 4%. Fixed quantity is 100 units in this maintained sample. Adjust quantity deliberately for the instrument and capital. Do not treat a protective level as a guaranteed fill price.

Try it in the editor

Copy the script into a TradeScript draft, resolve diagnostics and use the historical backtest flow. Start by inspecting an entry and exit or a portfolio rebalance. Change one value at a time.

Read signals and protection separately

Rule Declaration in the sample
Entry long when: sma(hl2, 3) > sma(hl2, 9)
Signal exit long when: sma(hl2, 3) < sma(hl2, 9)
Quantity size: 100 shares per instrument
Stop stop: 2%
Target target: 4%
Trail trail: 2%

At a long entry of 100, the fixed stop is 98 and target 104. The trailing rule follows favourable movement, so it can become tighter than the original stop. A reverse-average signal can close the position before a price level is reached. Equality alone does not satisfy the signal exit.

These protection percentages describe price moves. With 100 units entered at 100, a two-point move corresponds to 200 before costs; it is not a 2% portfolio loss budget.

Compare one protection change

Change the target or trail alone, leaving quantity and moving-average periods fixed. Inspect which exit reason actually closed each trade. Reducing the position quantity changes money exposure; moving the stop changes the protected price distance. They answer different questions.

Learn the concept Understand protection →