Skip to main content

Advanced Strategy Techniques

Taking multiple targets with MACD, coding strategy trailing stops, Keltner Band mean reversion, and crypto momentum strategies.

MACD Strategy with Two Targets

Taking partial profit is a professional technique that locks in gains while keeping exposure to larger moves. This strategy splits each position into two halves. The first half exits at a fixed take-profit (1.5x ATR). The second half trails with an ATR-based stop, allowing it to ride extended trends. On SOL and ETH during momentum phases, the trailing half frequently captures 3–5x the initial risk while the first half has already secured profit.

pine-MACD with split targets and trailing
1//@version=5
2strategy("MACD Two Targets", overlay=true,
3 initial_capital=10000,
4 default_qty_type=strategy.fixed,
5 pyramiding=0,
6 commission_value=0.075, slippage=2)
7
8// === INPUTS ===
9macdFast = input.int(12, "MACD Fast")
10macdSlow = input.int(26, "MACD Slow")
11macdSignal = input.int(9, "MACD Signal")
12riskPct = input.float(1.0, "Risk %")
13tp1Mult = input.float(1.5, "TP1 ATR Mult")
14trailMult = input.float(2.5, "Trail ATR Mult")
15
16// === CALCULATIONS ===
17[macdLine, signalLine, hist] = ta.macd(close, macdFast, macdSlow, macdSignal)
18atr = ta.atr(14)
19ema200 = ta.ema(close, 200)
20
21// === POSITION SIZING ===
22stopDist = atr * 2
23riskAmt = strategy.equity * riskPct / 100
24totalQty = riskAmt / stopDist
25halfQty = totalQty / 2
26
27// === ENTRY ===
28bullSignal = ta.crossover(macdLine, signalLine) and macdLine < 0 and close > ema200
29
30if bullSignal
31 entryPrice = close
32 stopPrice = entryPrice - stopDist
33
34 // Entry: full position
35 strategy.entry("MACD Long", strategy.long, qty=totalQty)
36
37 // TP1: close half at 1.5x ATR profit
38 strategy.exit("TP1", "MACD Long",
39 qty = halfQty,
40 limit = entryPrice + atr * tp1Mult,
41 stop = stopPrice,
42 comment = "TP1 hit")
43
44 // TP2: trail the remaining half
45 strategy.exit("Trail", "MACD Long",
46 trail_points = atr * trailMult / syminfo.mintick,
47 trail_offset = atr * 1.0 / syminfo.mintick,
48 stop = stopPrice,
49 comment = "Trailed out")
50
51// === EXIT ON REVERSAL ===
52if ta.crossunder(macdLine, signalLine) and macdLine > 0
53 strategy.close_all(comment="MACD bearish cross")
54
55// === VISUALS ===
56plot(ema200, "EMA 200", color.yellow, 2)
57plotshape(bullSignal, "Entry Signal", shape.triangleup,
58 location.belowbar, color.green, size=size.small)
1

Calculate full position size

Risk $100 (1% of $10,000) with a stop at 2x ATR. If ATR is $2,000 on BTC daily, stop distance is $4,000. Position = $100 / $4,000 = 0.025 BTC. Half = 0.0125 BTC.
2

Enter with single entry order

One strategy.entry() call for the full quantity. Then two strategy.exit() calls: one for each half. The first exit uses qty=halfQty with a limit target.
3

TP1 locks in profit

When price reaches 1.5x ATR above entry, half the position closes. This typically covers the risk on the trade. The remaining half now rides for free.
4

Trail the remainder

The trailing stop on the second half follows price up. With trail_points at 2.5x ATR and trail_offset at 1x ATR, the stop trails 1 ATR behind the highest price, activated after price moves 2.5 ATR from entry.

Coding Strategy Trailing Stops

Trailing stops are the most important exit technique in trend-following strategies. They let winners run while protecting gains. PineScript supports three approaches: built-in trailing via strategy.exit(), manual ATR-based trailing with variables, and chandelier stops. Each has trade-offs in responsiveness versus whipsaw protection.

pine-Three trailing stop methods compared
1//@version=5
2strategy("Trailing Stop Comparison", overlay=true,
3 initial_capital=10000, default_qty_type=strategy.percent_of_equity,
4 default_qty_value=95, commission_value=0.075)
5
6method = input.string("ATR", "Trail Method", options=["ATR", "Percent", "Chandelier"])
7atrLen = input.int(14, "ATR Length")
8atrM = input.float(3.0, "ATR Multiplier")
9pctTrail = input.float(5.0, "Percent Trail (%)")
10chandLen = input.int(22, "Chandelier Length")
11
12atr = ta.atr(atrLen)
13
14// === MANUAL ATR TRAILING STOP ===
15var float atrTrailStop = na
16if strategy.position_size > 0
17 newStop = close - atr * atrM
18 atrTrailStop := math.max(nz(atrTrailStop, newStop), newStop)
19else
20 atrTrailStop := na
21
22// === PERCENTAGE TRAILING STOP ===
23var float pctTrailStop = na
24var float highestSinceEntry = na
25if strategy.position_size > 0
26 highestSinceEntry := math.max(nz(highestSinceEntry, high), high)
27 pctTrailStop := highestSinceEntry * (1 - pctTrail / 100)
28else
29 highestSinceEntry := na
30 pctTrailStop := na
31
32// === CHANDELIER STOP ===
33chandelierHigh = ta.highest(high, chandLen)
34chandelierStop = chandelierHigh - atr * atrM
35
36// === ENTRY (simple EMA cross) ===
37if ta.crossover(ta.ema(close, 9), ta.ema(close, 21))
38 strategy.entry("Long", strategy.long)
39 atrTrailStop := close - atr * atrM
40 highestSinceEntry := high
41
42// === EXIT BASED ON SELECTED METHOD ===
43activeStop = method == "ATR" ? atrTrailStop :
44 method == "Percent" ? pctTrailStop :
45 chandelierStop
46
47if strategy.position_size > 0 and close < activeStop
48 strategy.close("Long", comment=method + " trail hit")
49
50plot(strategy.position_size > 0 ? activeStop : na,
51 "Trail Stop", color.red, 2, plot.style_stepline)
ATR TrailAdapts to volatility. Wider in volatile markets, tighter in calm ones. Best for BTC and ETH where volatility shifts dramatically between consolidation and trending phases. 3x ATR is a common starting point.
Percent TrailSimple and predictable. A 5% trailing stop always gives back exactly 5% from the peak. Good for range-bound trading. Weakness: does not adapt to volatility, too tight during BTC pumps, too loose during low-vol grinds.
Chandelier StopUses the highest high over N bars minus ATR. Similar to ATR trail but anchored to the channel high rather than the current close. Better at surviving deep wicks because it references the extreme, not the close.

Keltner Band Mean Reversion System

Keltner Channels use ATR instead of standard deviation for their bands, making them smoother and less reactive to single outlier candles than Bollinger Bands. This mean-reversion system enters when price touches the outer band and reverses back inside, targeting the middle band. On ETH 4H charts, this produces consistent small wins during sideways markets.

pine-Keltner channel mean reversion
1//@version=5
2strategy("Keltner Mean Reversion", overlay=true,
3 initial_capital=10000,
4 default_qty_type=strategy.percent_of_equity,
5 default_qty_value=90,
6 commission_value=0.075, slippage=2)
7
8kcLen = input.int(20, "KC Length")
9kcMult = input.float(2.0, "KC Multiplier")
10rsiLen = input.int(7, "RSI Confirmation Length")
11rsiOB = input.int(75, "RSI OB for Short")
12rsiOS = input.int(25, "RSI OS for Long")
13
14// === KELTNER CHANNELS ===
15basis = ta.ema(close, kcLen)
16atr = ta.atr(kcLen)
17upper = basis + atr * kcMult
18lower = basis - atr * kcMult
19rsi = ta.rsi(close, rsiLen)
20
21// === MEAN REVERSION ENTRIES ===
22// Long: price was below lower band, now closing back inside + RSI oversold
23longSetup = close[1] < lower[1] and close > lower and rsi < rsiOS
24// Short: price was above upper band, now closing back inside + RSI overbought
25shortSetup = close[1] > upper[1] and close < upper and rsi > rsiOB
26
27if longSetup
28 strategy.entry("KC Long", strategy.long)
29 strategy.exit("KC TP/SL", "KC Long",
30 limit = basis,
31 stop = lower - atr * 0.5)
32
33if shortSetup
34 strategy.entry("KC Short", strategy.short)
35 strategy.exit("KC TP/SL S", "KC Short",
36 limit = basis,
37 stop = upper + atr * 0.5)
38
39// Time exit: 15 bars max hold
40if strategy.position_size != 0
41 entryBar = strategy.opentrades.entry_bar_index(0)
42 if bar_index - entryBar > 15
43 strategy.close_all(comment="Time exit")
44
45plot(upper, "Upper KC", color.new(color.blue, 30))
46plot(basis, "Basis", color.new(color.gray, 30))
47plot(lower, "Lower KC", color.new(color.blue, 30))

Bitcoin Cycle Momentum Strategy

Bitcoin moves in multi-year cycles driven by halving events, and within those cycles, momentum indicators behave differently than traditional assets. This strategy combines the Rate of Change (ROC) with a volume-weighted momentum oscillator to identify the sweet spot of a BTC cycle: the phase where price is accelerating on increasing volume. It uses weekly timeframe data for position trades lasting weeks to months.

pine-BTC cycle momentum system
1//@version=5
2strategy("BTC Cycle Momentum", overlay=true,
3 initial_capital=10000,
4 default_qty_type=strategy.percent_of_equity,
5 default_qty_value=95,
6 commission_value=0.075, slippage=3)
7
8// === INPUTS ===
9rocLen = input.int(21, "ROC Length")
10volLen = input.int(14, "Volume MA Length")
11momentumOB = input.float(15, "Momentum Overbought (%)")
12momentumOS = input.float(-15, "Momentum Oversold (%)")
13
14// === CALCULATIONS ===
15roc = ta.roc(close, rocLen)
16volMA = ta.sma(volume, volLen)
17volRatio = volume / volMA
18
19// Volume-weighted momentum: ROC scaled by volume participation
20vwMomentum = roc * math.min(volRatio, 3.0) // Cap at 3x to avoid outliers
21
22// Trend context: price above 21 and 50 EMA
23ema21 = ta.ema(close, 21)
24ema50 = ta.ema(close, 50)
25inUptrend = close > ema21 and ema21 > ema50
26
27// Momentum regime detection
28smoothMom = ta.ema(vwMomentum, 5)
29momRising = smoothMom > smoothMom[1] and smoothMom > 0
30
31// === ENTRIES ===
32// Buy: positive momentum rising, in uptrend, volume above average
33buySignal = momRising and inUptrend and volRatio > 1.0 and
34 strategy.position_size == 0
35
36if buySignal
37 strategy.entry("Momentum Long", strategy.long)
38
39// === EXITS ===
40// Momentum exhaustion: ROC extremely high
41if vwMomentum > momentumOB * 2
42 strategy.close("Momentum Long", comment="Blow-off top")
43
44// Trend break: price closes below 50 EMA
45if close < ema50
46 strategy.close("Momentum Long", comment="Trend break")
47
48// Trailing stop using 21 EMA as dynamic support
49if strategy.position_size > 0 and close < ema21 and close[1] > ema21[1]
50 strategy.close("Momentum Long", comment="EMA21 break")
51
52plot(ema21, "21 EMA", color.blue, 2)
53plot(ema50, "50 EMA", color.orange, 2)

Weekly strategies require patience

A weekly BTC momentum strategy may only generate 10–15 trades per year. This means you need multiple years of data for a statistically meaningful backtest. On TradingView, use the "Deep Backtesting" feature (Premium) to access extended history. With only 10 trades, one lucky or unlucky outcome distorts your entire performance summary. Treat any strategy with fewer than 30 trades as preliminary, not proven.

Put this lesson to work

Free on Thrive, no account needed.