Docs

ITMScript

Trail a stop on both sides of price

Draw a stop that rides below a rising close and above a falling one at an ATR distance, built with scan.

Draw a stop that rides below a rising close and above a falling one, at a distance set by the ATR.

itm
//@itmscript 2
study("Trailing stop", overlay=true)
len = input.int(14, "ATR length", min=2, max=100)
mult = input.float(3, "ATR multiple", min=0.5, max=10, step=0.1)
gap = mult * ta.atr(len)
ratchet(acc, now, before, dist) => now > nz(acc) and before > nz(acc) ? math.max(nz(acc), now - dist) : now < nz(acc) and before < nz(acc) ? math.min(nz(acc), now + dist) : now > nz(acc) ? now - dist : now + dist
stop = scan([close, close[1], gap], na, ratchet)
shown = stop > 0 ? stop : na
plot(shown, "Stop", color=close > stop ? color.green : color.red, width=2, style=stepline)

What you see

A stepped line is drawn over the candles. While the close stays above it, the line is green. It follows the close upward at the distance you set and never falls.

On the first bar that closes under the line, the line jumps to the close plus the distance and turns red. It then follows the close downward and never rises. If the close climbs back toward it, the line holds its place. On the first bar that closes above it, the line jumps to the close minus the distance and turns green again.

The plot starts on the first bar that has an ATR. A stop that is not above zero is not drawn.

The function ratchet takes the carried stop, the close, the close one bar back and the distance. It has three branches. When the close and the close one bar back are both above the stop, it keeps the higher of the old stop and the new candidate. When both are below, it keeps the lower. Otherwise the close has just crossed the stop, and the stop moves to the other side of the close at the distance. Each read of the carried stop is wrapped in nz, so the first bar reads it as zero.

Change these inputs

  • ATR length. The window of the average true range, from 2 to 100 bars.
  • ATR multiple. The distance of the stop from the close, in multiples of the ATR. From 0.5 to 10. A larger number keeps the stop further away and gives price more room.