Moving-average trend¶
Request a long position when the 3-period SMA of the midpoint price is above the 9-period SMA, and a short position when it is below.
Complete strategy¶
//@version=1
symbol: RELIANCE
run: each bar
size: 100 shares per instrument
entry:
long when: sma(hl2, 3) > sma(hl2, 9)
short when: sma(hl2, 3) < sma(hl2, 9)
exit:
long when: sma(hl2, 3) < sma(hl2, 9)
short when: sma(hl2, 3) > sma(hl2, 9)
# SMA crossover on hl2, stop-and-reverse. crossover/crossunder expressed as the
# state comparison (the declarative equivalent under framework-managed position).
# Original long(100)/short(100) share counts are declared explicitly above.
Read the rule¶
This sample uses greater/less-than state comparisons, not crossing-only events. hl2 is the average of high and low. The moving-average library explains the explicit-input form used here. Check that shorting is supported for the selected account and instrument.
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.
Follow the two directions¶
| Rule | Declaration in the sample |
|---|---|
| Long entry | long when: sma(hl2, 3) > sma(hl2, 9) |
| Short entry | short when: sma(hl2, 3) < sma(hl2, 9) |
| Long exit | long when: sma(hl2, 3) < sma(hl2, 9) |
| Short exit | short when: sma(hl2, 3) > sma(hl2, 9) |
| Size | size: 100 shares per instrument |
hl2 is (high + low) / 2. The three- and nine-bar SMAs average that series. Equality satisfies neither strict direction. The reverse relationship both exits the old side and supplies the other side's entry intent; execution still resolves orders and confirmed holdings.
The size is a fixed target of 100 units, not 100% allocation and not an extra 100 on every true bar. The cash required depends on price. This sample has no protective price stop.
Change the horizon¶
Try a longer fast/slow pair while keeping the fast period below the slow one. Change the periods consistently in entries and exits. Use crosses over/crosses under if you deliberately want transition-only signals; they are a different rule, not a shorter spelling for these comparisons.
Learn the concept Compare state and crossing →