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.
1//@version=52strategy("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)78// === 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")1516// === CALCULATIONS ===17[macdLine, signalLine, hist] = ta.macd(close, macdFast, macdSlow, macdSignal)18atr = ta.atr(14)19ema200 = ta.ema(close, 200)2021// === POSITION SIZING ===22stopDist = atr * 223riskAmt = strategy.equity * riskPct / 10024totalQty = riskAmt / stopDist25halfQty = totalQty / 22627// === ENTRY ===28bullSignal = ta.crossover(macdLine, signalLine) and macdLine < 0 and close > ema2002930if bullSignal31 entryPrice = close32 stopPrice = entryPrice - stopDist3334 // Entry: full position35 strategy.entry("MACD Long", strategy.long, qty=totalQty)3637 // TP1: close half at 1.5x ATR profit38 strategy.exit("TP1", "MACD Long",39 qty = halfQty,40 limit = entryPrice + atr * tp1Mult,41 stop = stopPrice,42 comment = "TP1 hit")4344 // TP2: trail the remaining half45 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")5051// === EXIT ON REVERSAL ===52if ta.crossunder(macdLine, signalLine) and macdLine > 053 strategy.close_all(comment="MACD bearish cross")5455// === VISUALS ===56plot(ema200, "EMA 200", color.yellow, 2)57plotshape(bullSignal, "Entry Signal", shape.triangleup,58 location.belowbar, color.green, size=size.small)Calculate full position size
Enter with single entry order
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.TP1 locks in profit
Trail the remainder
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.
1//@version=52strategy("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)56method = 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")1112atr = ta.atr(atrLen)1314// === MANUAL ATR TRAILING STOP ===15var float atrTrailStop = na16if strategy.position_size > 017 newStop = close - atr * atrM18 atrTrailStop := math.max(nz(atrTrailStop, newStop), newStop)19else20 atrTrailStop := na2122// === PERCENTAGE TRAILING STOP ===23var float pctTrailStop = na24var float highestSinceEntry = na25if strategy.position_size > 026 highestSinceEntry := math.max(nz(highestSinceEntry, high), high)27 pctTrailStop := highestSinceEntry * (1 - pctTrail / 100)28else29 highestSinceEntry := na30 pctTrailStop := na3132// === CHANDELIER STOP ===33chandelierHigh = ta.highest(high, chandLen)34chandelierStop = chandelierHigh - atr * atrM3536// === 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 * atrM40 highestSinceEntry := high4142// === EXIT BASED ON SELECTED METHOD ===43activeStop = method == "ATR" ? atrTrailStop :44 method == "Percent" ? pctTrailStop :45 chandelierStop4647if strategy.position_size > 0 and close < activeStop48 strategy.close("Long", comment=method + " trail hit")4950plot(strategy.position_size > 0 ? activeStop : na,51 "Trail Stop", color.red, 2, plot.style_stepline)| ATR Trail | Adapts 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 Trail | Simple 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 Stop | Uses 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.
1//@version=52strategy("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)78kcLen = 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")1314// === KELTNER CHANNELS ===15basis = ta.ema(close, kcLen)16atr = ta.atr(kcLen)17upper = basis + atr * kcMult18lower = basis - atr * kcMult19rsi = ta.rsi(close, rsiLen)2021// === MEAN REVERSION ENTRIES ===22// Long: price was below lower band, now closing back inside + RSI oversold23longSetup = close[1] < lower[1] and close > lower and rsi < rsiOS24// Short: price was above upper band, now closing back inside + RSI overbought25shortSetup = close[1] > upper[1] and close < upper and rsi > rsiOB2627if longSetup28 strategy.entry("KC Long", strategy.long)29 strategy.exit("KC TP/SL", "KC Long",30 limit = basis,31 stop = lower - atr * 0.5)3233if shortSetup34 strategy.entry("KC Short", strategy.short)35 strategy.exit("KC TP/SL S", "KC Short",36 limit = basis,37 stop = upper + atr * 0.5)3839// Time exit: 15 bars max hold40if strategy.position_size != 041 entryBar = strategy.opentrades.entry_bar_index(0)42 if bar_index - entryBar > 1543 strategy.close_all(comment="Time exit")4445plot(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.
1//@version=52strategy("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)78// === 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 (%)")1314// === CALCULATIONS ===15roc = ta.roc(close, rocLen)16volMA = ta.sma(volume, volLen)17volRatio = volume / volMA1819// Volume-weighted momentum: ROC scaled by volume participation20vwMomentum = roc * math.min(volRatio, 3.0) // Cap at 3x to avoid outliers2122// Trend context: price above 21 and 50 EMA23ema21 = ta.ema(close, 21)24ema50 = ta.ema(close, 50)25inUptrend = close > ema21 and ema21 > ema502627// Momentum regime detection28smoothMom = ta.ema(vwMomentum, 5)29momRising = smoothMom > smoothMom[1] and smoothMom > 03031// === ENTRIES ===32// Buy: positive momentum rising, in uptrend, volume above average33buySignal = momRising and inUptrend and volRatio > 1.0 and34 strategy.position_size == 03536if buySignal37 strategy.entry("Momentum Long", strategy.long)3839// === EXITS ===40// Momentum exhaustion: ROC extremely high41if vwMomentum > momentumOB * 242 strategy.close("Momentum Long", comment="Blow-off top")4344// Trend break: price closes below 50 EMA45if close < ema5046 strategy.close("Momentum Long", comment="Trend break")4748// Trailing stop using 21 EMA as dynamic support49if strategy.position_size > 0 and close < ema21 and close[1] > ema21[1]50 strategy.close("Momentum Long", comment="EMA21 break")5152plot(ema21, "21 EMA", color.blue, 2)53plot(ema50, "50 EMA", color.orange, 2)Weekly strategies require patience
Put this lesson to work
Free on Thrive, no account needed.