Zeal Terminal Open Zeal Terminal

Pine Script v4 · Strategy

Dynamic Price Swing

A Pine Script v4 strategy built on Highest (high, 20), Lowest (low, 20) and ATR (10). It has 12 order rules, 4 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 100% of equity and pays 0.18% commission. 52 settings; defaults include Trade Types Long/Short, 》Color Scheme SH1 and Stop Loss % 50.0.

Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.

Does Dynamic Price Swing repaint?
No
No repainting patterns were found in the source.
Can Dynamic Price Swing be converted to Pine Script v5?
Not tested
The steps are shown below, but the original does not run in Zeal Terminal's engine, so they could not be checked.
Does Dynamic Price Swing use a stop loss?
Yes
strategy.exit sets a stop on line 369, 371, 373, 375.
Does Dynamic Price Swing run in Zeal Terminal?
No
Not yet: In 'array.get()' function. Index NaN is out of bounds, array size is 20.
Does not run in Zeal Terminal yetIn 'array.get()' function. Index NaN is out of bounds, array size is 20. The settings, logic and review below are read from the source, which does not need a run.

Review

What a careful reader of this script would point out, found by checking the source.

  • Likely bug

    highest(high, fastLength) ignores the settings line 161

    Line 161 hard-codes high where line 111 uses “High Source”. Changing those settings moves one band but not this one.

    highest(high, fastLength)highest(high_source, fastLength)
  • Likely bug

    highest(high, slowLength) ignores the settings line 163

    Line 163 hard-codes high where line 111 uses “High Source”. Changing those settings moves one band but not this one.

    highest(high, slowLength)highest(high_source, slowLength)
  • Likely bug

    lowest(low, fastLength) ignores the settings line 162

    Line 162 hard-codes low where line 114 uses “Low Source”. Changing those settings moves one band but not this one.

    lowest(low, fastLength)lowest(low_source, fastLength)
  • Likely bug

    lowest(low, slowLength) ignores the settings line 164

    Line 164 hard-codes low where line 114 uses “Low Source”. Changing those settings moves one band but not this one.

    lowest(low, slowLength)lowest(low_source, slowLength)
  • Check

    23 settings do nothing

    “Backtest Dates, Strategy Selection, and Risk Management Inputs apply to all strategies”, “Average Price Channel strategy buys and sells when price crosses above or below the previous highest high and lowest low”, “Moving Average strategy buys and sells when the price crosses above or below the selected price band, which also is shaded based on what you select.”, “Fibonacci strategy buys and sells when the price crosses above the Fibonacci level selected.”, “Peaks and Valleys buys and sells based on the combined crossing of the VWMA, ALMA, and Average MACD True Range trend lines.”, “The settings for each strategy is grouped. Only the inputs indicated for the selected strategy will impact the triggers.”, “All strategies use the Risk Management and Up/Down Trend Settings.”, “Use Long/Short only for backtest comparisons. Long is if you are starting with FIAT, Short is if you are starting with crypto.”, “═══════════⥑ Gradient ⥏═══════════”, “Use Gradient Color Bars?”, “You can control your gains and losses with these inputs that should be self-explanatory.”, “This section is for adjusting the EMA length and price lookback period for identifying upward/downward zones. You can add the Triple EMA indicator to a new pane to visually tweak these settings.”, “The Average # of bars is what you observe as the number of up and down bars in a cycle”, “For example, if a crypto's chart has 6 up and 4 down for each cycle before it repeats”, “then your Average # of bars is 10 and your Price Lookback Period is 5 (half of the Avg #)”, “For the Moving Average Strategy - define the percentage from the center price line you want trades to occur”, “the default is to use the first band (shaded in green and red) or you can choose to use the second or third price channel bands.”, “The standard Fibonacci retracement levels are available in the drop down selection for the Fibonacci strategy.”, “Level 1 is where the trade will happen if the price crosses and the zone is up (for sell) and down (for buy)”, “Level 2 is where the trade will always happen when the price crosses regardless of trend indicators.”, “Peaks and Valleys is a more aggressive form of the moving average strategy. You can change the type of MA to have faster scalps.”, “Here you can either copy and paste a trigger message for a bot or a custom message for an Email or SMS alert”, “replace the alert body message with {{strategy.order.alert_message}} for a single message to map to alll long/short triggers.” are declared but never read.

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    4 settings have no label

    In the settings dialog message_long_entry (line 105), message_long_exit (line 106), message_short_entry (line 107), message_short_exit (line 108) show an empty name. The labels on this page come from the variable names.

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

  • Note

    Uses long =, which v5 renamed line 346

    long = on line 346, 350. v5 writes it as direction = strategy.long or strategy.short.

Upgrade and export

Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.

  • Upgrading to v5 renames highest → ta.highest, max → math.max, lowest → ta.lowest, min → math.min, atr → ta.atr, sma → ta.sma, vwma → ta.vwma, ema → ta.ema, wma → ta.wma, abs → math.abs, cmo → ta.cmo, alma → ta.alma, rsi → ta.rsi, bb → ta.bb, crossover → ta.crossover, crossunder → ta.crossunder.

v4 → v5

Not verified

The v4 script does not run in Zeal Terminal's engine (In 'array.get()' function. Index NaN is out of bounds, array size is 20.), so this step could not be checked.

  • Line 2: //@version=4 → //@version=5
  • Line 35: input(type = input.time) → input.time()
  • Line 36: input(type = input.time) → input.time()
  • Line 68: input(type = input.integer) → input.int()
  • Line 70: input(type = input.integer) → input.int()
  • Line 111: highest → ta.highest
75 more edits
  • Line 112: highest → ta.highest
  • Line 113: max → math.max
  • Line 114: lowest → ta.lowest
  • Line 115: lowest → ta.lowest
  • Line 116: min → math.min
  • Line 128: atr → ta.atr
  • Line 129: atr → ta.atr
  • Line 131: atr → ta.atr
  • Line 132: atr → ta.atr
  • Line 134: sma → ta.sma
  • Line 134: vwma → ta.vwma
  • Line 135: sma → ta.sma
  • Line 135: vwma → ta.vwma
  • Line 136: sma → ta.sma
  • Line 136: vwma → ta.vwma
  • Line 137: sma → ta.sma
  • Line 138: sma → ta.sma
  • Line 140: ema → ta.ema
  • Line 140: ema → ta.ema
  • Line 140: ema → ta.ema
  • Line 141: ema → ta.ema
  • Line 141: ema → ta.ema
  • Line 141: ema → ta.ema
  • Line 142: ema → ta.ema
  • Line 142: ema → ta.ema
  • Line 142: ema → ta.ema
  • Line 143: ema → ta.ema
  • Line 143: ema → ta.ema
  • Line 143: ema → ta.ema
  • Line 144: ema → ta.ema
  • Line 144: ema → ta.ema
  • Line 144: ema → ta.ema
  • Line 145: ema → ta.ema
  • Line 145: ema → ta.ema
  • Line 145: ema → ta.ema
  • Line 146: ema → ta.ema
  • Line 146: ema → ta.ema
  • Line 146: ema → ta.ema
  • Line 151: ema → ta.ema
  • Line 153: sma → ta.sma
  • Line 155: vwma → ta.vwma
  • Line 157: wma → ta.wma
  • Line 161: highest → ta.highest
  • Line 162: lowest → ta.lowest
  • Line 163: highest → ta.highest
  • Line 164: lowest → ta.lowest
  • Line 197: ema → ta.ema
  • Line 197: abs → math.abs
  • Line 198: ema → ta.ema
  • Line 230: sma → ta.sma
  • Line 231: sma → ta.sma
  • Line 232: sma → ta.sma
  • Line 233: cmo → ta.cmo
  • Line 234: cmo → ta.cmo
  • Line 235: alma → ta.alma
  • Line 235: sma → ta.sma
  • Line 235: sma → ta.sma
  • Line 236: ema → ta.ema
  • Line 236: ema → ta.ema
  • Line 236: ema → ta.ema
  • Line 237: sma → ta.sma
  • Line 238: alma → ta.alma
  • Line 238: sma → ta.sma
  • Line 287: max → math.max
  • Line 297: rsi → ta.rsi
  • Line 299: bb → ta.bb
  • Line 302: crossover → ta.crossover
  • Line 302: crossunder → ta.crossunder
  • Line 315: crossunder → ta.crossunder
  • Line 318: crossover → ta.crossover
  • Line 328: crossover → ta.crossover
  • Line 333: crossover → ta.crossover
  • Line 336: crossunder → ta.crossunder
  • Line 346: long = true → direction = strategy.long
  • Line 350: long = false → direction = strategy.short
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/-//@version=4+//@version=5//**********************************************************************************************************⋯//Backtest dates with auto finish date of today-start = input(defval = timestamp("21 June 2021 00:00 -0500"), title = "Start Time", type = input.time, group="Backtest Dates")+start = input.time(defval = timestamp("21 June 2021 00:00 -0500"), title = "Start Time", group="Backtest Dates")-finish = input(defval = timestamp("31 December 2021 00:00 -0600"), title = "End Time", type = input.time, group="Backtest Dates")+finish = input.time(defval = timestamp("31 December 2021 00:00 -0600"), title = "End Time", group="Backtest Dates")window()  => time >= start and time <= finish ? true : false       // create function "within window of time"⋯TargetProfit = tp/100-ld = input(10, "Stop Trading After This Many Losing Days", type=input.integer, minval=0, maxval=100, step=1, group="Risk Management")+ld = input.int(10, "Stop Trading After This Many Losing Days", minval=0, maxval=100, step=1, group="Risk Management")strategy.risk.max_cons_loss_days(count=ld)-ml = input(50, "Maximum % of Equity Lost to Halt Trading", type=input.integer, minval=1, maxval=100, step=1, group="Risk Management")+ml = input.int(50, "Maximum % of Equity Lost to Halt Trading", minval=1, maxval=100, step=1, group="Risk Management")strategy.risk.max_drawdown(value=ml, type=strategy.percent_of_equity)⋯// -------------------------------- Price Channel Calculation -----------------------------------high1 = highest(high_source, AvgLkbk)+high1 = ta.highest(high_source, AvgLkbk)-high2 = highest(high_source, lkbk)+high2 = ta.highest(high_source, lkbk)-lasthigh = max(high1, high2)+lasthigh = math.max(high1, high2)-low1 = lowest(low_source, AvgLkbk)+low1 = ta.lowest(low_source, AvgLkbk)-low2 = lowest(low_source, lkbk)+low2 = ta.lowest(low_source, lkbk)-lastlow = min(low1, low2)+lastlow = math.min(low1, low2)hiHighs = lasthigh[1]⋯HMA     = usePrice ? hiHighs : CMA + (CMA * (InnerValue / 100))-HMA2    = usePrice ? na : useFib ? CMA + (atr(lkbk)*Fib1) : CMA + (CMA * (OuterValue / 100))+HMA2    = usePrice ? na : useFib ? CMA + (ta.atr(lkbk)*Fib1) : CMA + (CMA * (OuterValue / 100))-HMA3    = usePrice ? na : useFib ? CMA + (atr(lkbk)*Fib2) : CMA + (CMA * (ExtremeValue / 100))+HMA3    = usePrice ? na : useFib ? CMA + (ta.atr(lkbk)*Fib2) : CMA + (CMA * (ExtremeValue / 100))LMA     = usePrice ? loLows : CMA - (CMA * (InnerValue / 100))-LMA2    = usePrice ? na : useFib ? CMA - (atr(lkbk)*Fib1) : CMA - (CMA * (OuterValue / 100))+LMA2    = usePrice ? na : useFib ? CMA - (ta.atr(lkbk)*Fib1) : CMA - (CMA * (OuterValue / 100))-LMA3    = usePrice ? na : useFib ? CMA - (atr(lkbk)*Fib2) : CMA - (CMA * (ExtremeValue / 100))+LMA3    = usePrice ? na : useFib ? CMA - (ta.atr(lkbk)*Fib2) : CMA - (CMA * (ExtremeValue / 100))// For Price Channels-ma3 = sma(close, 3), vwma3 = vwma(close, 3)+ma3 = ta.sma(close, 3), vwma3 = ta.vwma(close, 3)-ma5 = sma(close, 5), vwma5 = vwma(close, 5)+ma5 = ta.sma(close, 5), vwma5 = ta.vwma(close, 5)-ma9 = sma(close, 9), vwma9 = vwma(close, 9)+ma9 = ta.sma(close, 9), vwma9 = ta.vwma(close, 9)-ma10 = sma(close,10)+ma10 = ta.sma(close,10)-ma15 = sma(close,15)+ma15 = ta.sma(close,15)// For Fibonacci-MA1 = ema(close,5),HA1 = ema(high,5),LA1 = ema(low,5)+MA1 = ta.ema(close,5),HA1 = ta.ema(high,5),LA1 = ta.ema(low,5)-MA2 = ema(close,8),HA2 = ema(high,8),LA2 = ema(low,8)+MA2 = ta.ema(close,8),HA2 = ta.ema(high,8),LA2 = ta.ema(low,8)-MA3 = ema(close,13),HA3 = ema(high,13),LA3 = ema(low,13)+MA3 = ta.ema(close,13),HA3 = ta.ema(high,13),LA3 = ta.ema(low,13)-MA4 = ema(close,21),HA4 = ema(high,21),LA4 = ema(low,21)+MA4 = ta.ema(close,21),HA4 = ta.ema(high,21),LA4 = ta.ema(low,21)-MA5 = ema(close,34),HA5 = ema(high,34),LA5 = ema(low,34)+MA5 = ta.ema(close,34),HA5 = ta.ema(high,34),LA5 = ta.ema(low,34)-MA6 = ema(close,55),HA6 = ema(high,55),LA6 = ema(low,55)+MA6 = ta.ema(close,55),HA6 = ta.ema(high,55),LA6 = ta.ema(low,55)-MA7 = ema(close,89),HA7 = ema(high,89),LA7 = ema(low,89)+MA7 = ta.ema(close,89),HA7 = ta.ema(high,89),LA7 = ta.ema(low,89)// For Peaks and Valleys⋯    if maInput == "EMA"-        ma := ema(src, length)+        ma := ta.ema(src, length)    if maInput == "SMA"-        ma := sma(src, length)+        ma := ta.sma(src, length)    if maInput == "VWMA"-        ma := vwma(src, length)+        ma := ta.vwma(src, length)    if maInput == "WMA"-        ma := wma(src, length)+        ma := ta.wma(src, length)    ma⋯SlowAvgValue = getMA(close, slowLength)-fHi = highest(high, fastLength)+fHi = ta.highest(high, fastLength)-fLo = lowest(low, fastLength)+fLo = ta.lowest(low, fastLength)-sHi = highest(high, slowLength)+sHi = ta.highest(high, slowLength)-sLo = lowest(low, slowLength)+sLo = ta.lowest(low, slowLength)FastStoch = (FastAvgValue - fHi) / (fHi - fLo)⋯    wper      = (t*2) - 1-    avrng     = ema(abs(x - x[1]), t)+    avrng     = ta.ema(math.abs(x - x[1]), t)-    smoothrng = ema(avrng, wper)*m+    smoothrng = ta.ema(avrng, wper)*m    smoothrng⋯    r_val-ma20 = sma(close,20)+ma20 = ta.sma(close,20)-ma50 = sma(close,50)+ma50 = ta.sma(close,50)-ma200 = sma(close,200)+ma200 = ta.sma(close,200)-change2 = cmo(close, 2)+change2 = ta.cmo(close, 2)-change9 = cmo(close, 9)+change9 = ta.cmo(close, 9)-trendline =  alma((close-sma(close,40))/sma(close,40)*100,21,0.85,6)+trendline =  ta.alma((close-ta.sma(close,40))/ta.sma(close,40)*100,21,0.85,6)-tradingline = ema(ema(ema((2*close+high+low)/4,4),4),4)+tradingline = ta.ema(ta.ema(ta.ema((2*close+high+low)/4,4),4),4)-fastLine = ( sma((tradingline-xrf(tradingline,1))/xrf(tradingline,1)*100,1))*10+fastLine = ( ta.sma((tradingline-xrf(tradingline,1))/xrf(tradingline,1)*100,1))*10-slowLine = alma( sma((tradingline-xrf(tradingline,1))/xrf(tradingline,1)*100,2),3,0.85,6)*10+slowLine = ta.alma( ta.sma((tradingline-xrf(tradingline,1))/xrf(tradingline,1)*100,2),3,0.85,6)*10pd = (high[1] - close[1]) / close[1]⋯    var int _size = array.size(c_gradients) - 1-    int _colorStep = int(_size * (_src - _min)) / int(max(_max - _min, 10e-10))+    int _colorStep = int(_size * (_src - _min)) / int(math.max(_max - _min, 10e-10))    _colorStep := _colorStep > _size ? _size : _colorStep < 0 ? 0 : _colorStep⋯// ————— Rsi as a source-rsi = rsi(close, 100)+rsi = ta.rsi(close, 100)// ————— Bollinger bands on top of Rsi as gradient's min and max-[_, rsiUpperBand, rsiLowerBand] = bb(rsi, 200, 1.618)+[_, rsiUpperBand, rsiLowerBand] = ta.bb(rsi, 200, 1.618)// ————— Colorize the bounded sourcecolor c_rsi = f_colGrad(rsi, rsiLowerBand, rsiUpperBand)-barcolor(i_barcolor ? crossover(STMACD, STMACDAvg) ? color.red : crossunder(STMACD, STMACDAvg) ? color.yellow : BullShit ? color.white : c_rsi : na)+barcolor(i_barcolor ? ta.crossover(STMACD, STMACDAvg) ? color.red : ta.crossunder(STMACD, STMACDAvg) ? color.yellow : BullShit ? color.white : c_rsi : na)// ============================================================================= Entry and Exit Logic ======================================================================⋯MS1 = (band == 1 ? high > HMA : band == 2 ? high > HMA2 : band == 3 ? high > HMA3 : na) and shortCond and window()-MS2 = (band == 1 ? high > HMA : band == 2 ? high > HMA2 : band == 3 ? high > HMA3 : na) and crossunder(STMACD, STMACDAvg) and window()+MS2 = (band == 1 ? high > HMA : band == 2 ? high > HMA2 : band == 3 ? high > HMA3 : na) and ta.crossunder(STMACD, STMACDAvg) and window()MA_Sell = MS1 or MS2MB1 = (band == 1 ? low<LMA : band == 2 ? low < LMA2 : band == 3 ? low < LMA3 : na)  and longCond and window()-MB2 = (band == 1 ? low<LMA : band == 2 ? low < LMA2 : band == 3 ? low < LMA3 : na) and crossover(STMACD, STMACDAvg) and window()+MB2 = (band == 1 ? low<LMA : band == 2 ? low < LMA2 : band == 3 ? low < LMA3 : na) and ta.crossover(STMACD, STMACDAvg) and window()MA_Buy = MB1 or MB2⋯Fib_Buy2 = low<=LMA3 and BullShit and window()-Fib_Buy3 = low <= LMA2 and crossover(STMACD, STMACDAvg) and window()+Fib_Buy3 = low <= LMA2 and ta.crossover(STMACD, STMACDAvg) and window()Fib_Buy = Fib_Buy1 or Fib_Buy2 or Fib_Buy3⋯// LS is for Long Sell and is the same for Short Sells-LB = low < loLows and crossover(STMACD, STMACDAvg) and window()+LB = low < loLows and ta.crossover(STMACD, STMACDAvg) and window()SB = low < loLows and BullShit and window()PVBuy = LB or SB-SS1 = high >= hiHighs and crossunder(STMACD, STMACDAvg) and window()+SS1 = high >= hiHighs and ta.crossunder(STMACD, STMACDAvg) and window()LS1 = BullShit and high >= hiHighs and window()⋯if (GoLong and strat_val==0 and strategy.position_size==0 and barstate.isconfirmed)-    strategy.entry(id="MIXED", long=true, oca_type=strategy.oca.cancel, oca_name="Mixed Entry", alert_message = message_long_entry)+    strategy.entry(id="MIXED", direction = strategy.long, oca_type=strategy.oca.cancel, oca_name="Mixed Entry", alert_message = message_long_entry)if (GoLong and strat_val==1 and strategy.position_size==0 and barstate.isconfirmed)⋯if (GoShort and strat_val==0 and strategy.position_size==0 and strategy.position_size[1]==0 and barstate.isconfirmed)-    strategy.entry(id="MIXED", long=false, oca_type=strategy.oca.cancel, oca_name="Mixed Entry", alert_message = message_short_entry)+    strategy.entry(id="MIXED", direction = strategy.short, oca_type=strategy.oca.cancel, oca_name="Mixed Entry", alert_message = message_short_entry)if (GoShort and strat_val==-1 and strategy.position_size==0 and barstate.isconfirmed) ⋯

Clean v5

Not verified

Neither version placed a trade on any of the 8 markets, so there was nothing to compare.

  • Line 33: input() → input.bool()
  • Line 39: input() → input.bool()
  • Line 40: input() → input.bool()
  • Line 41: input() → input.bool()
  • Line 42: input() → input.bool()
  • Line 43: input() → input.bool()
41 more edits
  • Line 44: input() → input.bool()
  • Line 45: input() → input.string()
  • Line 50: input() → input.bool()
  • Line 51: input() → input.string()
  • Line 54: input() → input.bool()
  • Line 55: input() → input.bool()
  • Line 57: input() → input.bool()
  • Line 58: input() → input.bool()
  • Line 63: input() → input.bool()
  • Line 64: input() → input.float()
  • Line 66: input() → input.float()
  • Line 73: input() → input.bool()
  • Line 74: input() → input.int()
  • Line 75: input() → input.int()
  • Line 76: input() → input.bool()
  • Line 77: input() → input.bool()
  • Line 78: input() → input.bool()
  • Line 79: input() → input.int()
  • Line 80: input() → input.int()
  • Line 81: input() → input.source()
  • Line 82: input() → input.source()
  • Line 83: input() → input.float()
  • Line 86: input() → input.bool()
  • Line 87: input() → input.bool()
  • Line 88: input() → input.float()
  • Line 89: input() → input.float()
  • Line 90: input() → input.float()
  • Line 91: input() → input.string()
  • Line 94: input() → input.bool()
  • Line 95: input() → input.bool()
  • Line 96: input() → input.bool()
  • Line 97: input() → input.float()
  • Line 98: input() → input.float()
  • Line 100: input() → input.bool()
  • Line 101: input() → input.string()
  • Line 103: input() → input.bool()
  • Line 104: input() → input.bool()
  • Line 105: input() → input.string()
  • Line 106: input() → input.string()
  • Line 107: input() → input.string()
  • Line 108: input() → input.string()
⋯//Instructions-general = input(false, "Backtest Dates, Strategy Selection, and Risk Management Inputs apply to all strategies")+general = input.bool(false, "Backtest Dates, Strategy Selection, and Risk Management Inputs apply to all strategies")//Backtest dates with auto finish date of today⋯// Strategy Selection - Long, Short, or Both-general2 = input(false, "Average Price Channel strategy buys and sells when price crosses above or below the previous highest high and lowest low", group="Strategy Descriptions")+general2 = input.bool(false, "Average Price Channel strategy buys and sells when price crosses above or below the previous highest high and lowest low", group="Strategy Descriptions")-general3 = input(false, "Moving Average strategy buys and sells when the price crosses above or below the selected price band, which also is shaded based on what you select.", group="Strategy Descriptions")+general3 = input.bool(false, "Moving Average strategy buys and sells when the price crosses above or below the selected price band, which also is shaded based on what you select.", group="Strategy Descriptions")-general4 = input(false, "Fibonacci strategy buys and sells when the price crosses above the Fibonacci level selected.", group="Strategy Descriptions")+general4 = input.bool(false, "Fibonacci strategy buys and sells when the price crosses above the Fibonacci level selected.", group="Strategy Descriptions")-general5 = input(false, "Peaks and Valleys buys and sells based on the combined crossing of the VWMA, ALMA, and Average MACD True Range trend lines.", group="Strategy Descriptions")+general5 = input.bool(false, "Peaks and Valleys buys and sells based on the combined crossing of the VWMA, ALMA, and Average MACD True Range trend lines.", group="Strategy Descriptions")-general5b = input(false, "The settings for each strategy is grouped. Only the inputs indicated for the selected strategy will impact the triggers.", group="Strategy Descriptions")+general5b = input.bool(false, "The settings for each strategy is grouped. Only the inputs indicated for the selected strategy will impact the triggers.", group="Strategy Descriptions")-general5c = input(false, "All strategies use the Risk Management and Up/Down Trend Settings.", group="Strategy Descriptions")+general5c = input.bool(false, "All strategies use the Risk Management and Up/Down Trend Settings.", group="Strategy Descriptions")-trigger = input ("Average Price Channel", "Select a Price Swing Trigger", options=["Average Price Channel", "Moving Average", "Fibonacci", "Peaks and Valleys"], group="Strategy Selection")+trigger = input.string ("Average Price Channel", "Select a Price Swing Trigger", options=["Average Price Channel", "Moving Average", "Fibonacci", "Peaks and Valleys"], group="Strategy Selection")usePrice = trigger=="Average Price Channel" ? true : false⋯usePV = trigger == "Peaks and Valleys" ? true : false-general6 = input(false, "Use Long/Short only for backtest comparisons. Long is if you are starting with FIAT, Short is if you are starting with crypto.", group="Strategy Selection")+general6 = input.bool(false, "Use Long/Short only for backtest comparisons. Long is if you are starting with FIAT, Short is if you are starting with crypto.", group="Strategy Selection")-strat = input(title="Trade Types", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"], group="Strategy Selection")+strat = input.string(title="Trade Types", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"], group="Strategy Selection")strat_val = strat == "Long Only" ? 1 : strat == "Long/Short" ? 0 : -1// ————— Inputs-var bool    _1          = input(false,      "═══════════⥑ Gradient ⥏═══════════", group="Visualization Selection")+var bool    _1          = input.bool(false,      "═══════════⥑ Gradient ⥏═══════════", group="Visualization Selection")-var bool    colorbars   = input(true,       "Use Gradient Color Bars?", group="Visualization Selection")+var bool    colorbars   = input.bool(true,       "Use Gradient Color Bars?", group="Visualization Selection")var string  i_scheme    = input(SH1,        " 》Color Scheme",  options = [SH1, SH2, SH3, SH4, SH5, SH6, SH7], group="Visualization Selection")-var bool    i_invert    = input(false,      "Invert Colors", group="Visualization Selection")+var bool    i_invert    = input.bool(false,      "Invert Colors", group="Visualization Selection")-var bool    i_barcolor  = input(false,      "Colorize Bars", group="Visualization Selection")+var bool    i_barcolor  = input.bool(false,      "Colorize Bars", group="Visualization Selection")// }⋯// Risk Management Inputs-general7 = input(false, "You can control your gains and losses with these inputs that should be self-explanatory.", group="Risk Management")+general7 = input.bool(false, "You can control your gains and losses with these inputs that should be self-explanatory.", group="Risk Management")-sl= input(50.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01, group="Risk Management")+sl= input.float(50.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01, group="Risk Management")stoploss = sl/100-tp = input(50.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01, group="Risk Management")+tp = input.float(50.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01, group="Risk Management")TargetProfit = tp/100⋯// General Settings-general8 = input(false, "This section is for adjusting the EMA length and price lookback period for identifying upward/downward zones. You can add the Triple EMA indicator to a new pane to visually tweak these settings.", group="Up/Down Trend Settings")+general8 = input.bool(false, "This section is for adjusting the EMA length and price lookback period for identifying upward/downward zones. You can add the Triple EMA indicator to a new pane to visually tweak these settings.", group="Up/Down Trend Settings")-fastLength = input(5, minval=1, title="EMA Fast Length", group="Up/Down Trend Settings")+fastLength = input.int(5, minval=1, title="EMA Fast Length", group="Up/Down Trend Settings")-slowLength = input(12, minval=1, title="EMA Slow Length", group="Up/Down Trend Settings")+slowLength = input.int(12, minval=1, title="EMA Slow Length", group="Up/Down Trend Settings")-general9 = input(false, "The Average # of bars is what you observe as the number of up and down bars in a cycle", group="Up/Down Trend Settings")+general9 = input.bool(false, "The Average # of bars is what you observe as the number of up and down bars in a cycle", group="Up/Down Trend Settings")-general10 = input(false, "For example, if a crypto's chart has 6 up and 4 down for each cycle before it repeats", group="Up/Down Trend Settings")+general10 = input.bool(false, "For example, if a crypto's chart has 6 up and 4 down for each cycle before it repeats", group="Up/Down Trend Settings")-general11 = input(false, "then your Average # of bars is 10 and your Price Lookback Period is 5 (half of the Avg #)", group="Up/Down Trend Settings")+general11 = input.bool(false, "then your Average # of bars is 10 and your Price Lookback Period is 5 (half of the Avg #)", group="Up/Down Trend Settings")-AvgLkbk = input(20, minval=1, title="Average # of bars in Up/Down Trend", group="Up/Down Trend Settings")+AvgLkbk = input.int(20, minval=1, title="Average # of bars in Up/Down Trend", group="Up/Down Trend Settings")-lkbk = input(10,"Price Lookback Period", group="Up/Down Trend Settings")+lkbk = input.int(10,"Price Lookback Period", group="Up/Down Trend Settings")-high_source = input(high,"High Source", group="Up/Down Trend Settings")+high_source = input.source(high,"High Source", group="Up/Down Trend Settings")-low_source= input(low,"Low Source", group="Up/Down Trend Settings")+low_source= input.source(low,"Low Source", group="Up/Down Trend Settings")-diff1 = input(2.5, "High Price Knife Percentage (% difference to trigger a quick sell)", group="Price Channel Settings")+diff1 = input.float(2.5, "High Price Knife Percentage (% difference to trigger a quick sell)", group="Price Channel Settings")diff = diff1/100// Moving Average Inputs-general12 = input(false, "For the Moving Average Strategy - define the percentage from the center price line you want trades to occur", group="Moving Average Settings")+general12 = input.bool(false, "For the Moving Average Strategy - define the percentage from the center price line you want trades to occur", group="Moving Average Settings")-general13 = input(false, "the default is to use the first band (shaded in green and red) or you can choose to use the second or third price channel bands.", group="Moving Average Settings")+general13 = input.bool(false, "the default is to use the first band (shaded in green and red) or you can choose to use the second or third price channel bands.", group="Moving Average Settings")-InnerValue = input(1.6, title="1st Price Band %", group="Moving Average Settings")+InnerValue = input.float(1.6, title="1st Price Band %", group="Moving Average Settings")-OuterValue = input(2.6, title="2nd Price Band %", group="Moving Average Settings")+OuterValue = input.float(2.6, title="2nd Price Band %", group="Moving Average Settings")-ExtremeValue = input(4.2, title="Extreme Price Band %", group="Moving Average Settings")+ExtremeValue = input.float(4.2, title="Extreme Price Band %", group="Moving Average Settings")-BandUse = input("First", "Select Price Band to Trigger Trades", options=["First", "Second", "Extremes"], group="Strategy Selection")+BandUse = input.string("First", "Select Price Band to Trigger Trades", options=["First", "Second", "Extremes"], group="Strategy Selection")band = BandUse == "First" ? 1 : BandUse == "Second" ? 2 : BandUse == "Extremes" ? 3 : na// Fib Inputs-general14 = input(false, "The standard Fibonacci retracement levels are available in the drop down selection for the Fibonacci strategy.", group="Fibonacci Settings")+general14 = input.bool(false, "The standard Fibonacci retracement levels are available in the drop down selection for the Fibonacci strategy.", group="Fibonacci Settings")-general15 = input(false, "Level 1 is where the trade will happen if the price crosses and the zone is up (for sell) and down (for buy)", group="Fibonacci Settings")+general15 = input.bool(false, "Level 1 is where the trade will happen if the price crosses and the zone is up (for sell) and down (for buy)", group="Fibonacci Settings")-general16 = input(false, "Level 2 is where the trade will always happen when the price crosses regardless of trend indicators.", group="Fibonacci Settings")+general16 = input.bool(false, "Level 2 is where the trade will always happen when the price crosses regardless of trend indicators.", group="Fibonacci Settings")-Fib1 = input(1.618, "Fibonacci Level 1", options=[1.382, 1.618, 1.786, 2.000, 2.272, 2.382, 2.618, 3, 3.382, 3.618], group="Fibonacci Settings")+Fib1 = input.float(1.618, "Fibonacci Level 1", options=[1.382, 1.618, 1.786, 2.000, 2.272, 2.382, 2.618, 3, 3.382, 3.618], group="Fibonacci Settings")-Fib2 = input(2.618, "Fibonacci Level 2", options=[1.382, 1.618, 1.786, 2.000, 2.272, 2.382, 2.618, 3, 3.382, 3.618], group="Fibonacci Settings")+Fib2 = input.float(2.618, "Fibonacci Level 2", options=[1.382, 1.618, 1.786, 2.000, 2.272, 2.382, 2.618, 3, 3.382, 3.618], group="Fibonacci Settings")// Peaks and Valleys Inputs-general17 = input(false, "Peaks and Valleys is a more aggressive form of the moving average strategy. You can change the type of MA to have faster scalps.", group="Peaks and Valleys Options")+general17 = input.bool(false, "Peaks and Valleys is a more aggressive form of the moving average strategy. You can change the type of MA to have faster scalps.", group="Peaks and Valleys Options")-maInput = input(title="MA Type (EMA is default - the rest experimental)", defval="EMA", options=["EMA", "SMA", "VWMA", "WMA"],  group="Peaks and Valleys Options")+maInput = input.string(title="MA Type (EMA is default - the rest experimental)", defval="EMA", options=["EMA", "SMA", "VWMA", "WMA"],  group="Peaks and Valleys Options")//Entry area for custom bot messages (i.e. Quadency, 3Commas, etc)-general18 = input(false, "Here you can either copy and paste a trigger message for a bot or a custom message for an Email or SMS alert", group="Bot Webhook Messages")+general18 = input.bool(false, "Here you can either copy and paste a trigger message for a bot or a custom message for an Email or SMS alert", group="Bot Webhook Messages")-general19 = input(false, "replace the alert body message with {{strategy.order.alert_message}} for a single message to map to alll long/short triggers.", group="Bot Webhook Messages")+general19 = input.bool(false, "replace the alert body message with {{strategy.order.alert_message}} for a single message to map to alll long/short triggers.", group="Bot Webhook Messages")-message_long_entry  = input("long entry message", group="Bot Webhook Messages")+message_long_entry  = input.string("long entry message", group="Bot Webhook Messages")-message_long_exit   = input("long exit message", group="Bot Webhook Messages")+message_long_exit   = input.string("long exit message", group="Bot Webhook Messages")-message_short_entry = input("short entry message", group="Bot Webhook Messages")+message_short_entry = input.string("short entry message", group="Bot Webhook Messages")-message_short_exit  = input("short exit message", group="Bot Webhook Messages")+message_short_exit  = input.string("short exit message", group="Bot Webhook Messages")// ================================================================ Where the Magic Happens ========================================================================⋯

Does it run in Pine Script v6?

Not tested

Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/-//@version=5+//@version=6//**********************************************************************************************************⋯

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
Backtest Dates, Strategy Selection, and Risk Management Inputs apply to all strategiesfalseboolunused
Backtest Dates
Start Timetimestamp("21 June 2021 00:00 -0500")timeline 37
End Timetimestamp("31 December 2021 00:00 -0600")timeline 37
Strategy Descriptions
Average Price Channel strategy buys and sells when price crosses above or below the previous highest high and lowest lowfalseboolunused
Moving Average strategy buys and sells when the price crosses above or below the selected price band, which also is shaded based on what you select.falseboolunused
Fibonacci strategy buys and sells when the price crosses above the Fibonacci level selected.falseboolunused
Peaks and Valleys buys and sells based on the combined crossing of the VWMA, ALMA, and Average MACD True Range trend lines.falseboolunused
The settings for each strategy is grouped. Only the inputs indicated for the selected strategy will impact the triggers.falseboolunused
All strategies use the Risk Management and Up/Down Trend Settings.falseboolunused
Strategy Selection
Select a Price Swing TriggerAverage Price Channelstring · options ["Average Price Channel", "Moving Average", "Fibonacci", "Peaks and Valleys"]usePrice useMA useFib usePV
Use Long/Short only for backtest comparisons. Long is if you are starting with FIAT, Short is if you are starting with crypto.falseboolunused
Trade TypesLong/Shortstring · options ["Long Only", "Long/Short", "Short Only"]strat_val
Select Price Band to Trigger TradesFirststring · options ["First", "Second", "Extremes"]band
Visualization Selection
═══════════⥑ Gradient ⥏═══════════falseboolunused
Use Gradient Color Bars?trueboolunused
》Color SchemeSH1value · options [SH1, SH2, SH3, SH4, SH5, SH6, SH7]line 260 line 262 line 264 line 266 line 268 line 270 line 272
Invert Colorsfalseboolline 276
Colorize Barsfalseboolbarcolor
Risk Management
You can control your gains and losses with these inputs that should be self-explanatory.falseboolunused
Stop Loss %50.0float · min 0 · max 100 · step 0.01stoploss
Target Profit %50.0float · min 0 · max 100 · step 0.01TargetProfit
Stop Trading After This Many Losing Days10int (written input.integer) · min 0 · max 100 · step 1line 69
Maximum % of Equity Lost to Halt Trading50int (written input.integer) · min 1 · max 100 · step 1line 71
Up/Down Trend Settings
This section is for adjusting the EMA length and price lookback period for identifying upward/downward zones. You can add the Triple EMA indicator to a new pane to visually tweak these settings.falseboolunused
EMA Fast Length5int · min 1FastAvgValue fHi fLo
EMA Slow Length12int · min 1SlowAvgValue sHi sLo smrng
The Average # of bars is what you observe as the number of up and down bars in a cyclefalseboolunused
For example, if a crypto's chart has 6 up and 4 down for each cycle before it repeatsfalseboolunused
then your Average # of bars is 10 and your Price Lookback Period is 5 (half of the Avg #)falseboolunused
Average # of bars in Up/Down Trend20int · min 1high1 low1 STMACDAvg
Price Lookback Period10inthigh2 low2 HMA2 HMA3 LMA2 LMA3 smrng line 175
High Sourcehighsourcehigh1 high2 src
Low Sourcelowsourcelow1 low2
Price Channel Settings
High Price Knife Percentage (% difference to trigger a quick sell)2.5floatdiff
Moving Average Settings
For the Moving Average Strategy - define the percentage from the center price line you want trades to occurfalseboolunused
the default is to use the first band (shaded in green and red) or you can choose to use the second or third price channel bands.falseboolunused
1st Price Band %1.6floatHMA LMA
2nd Price Band %2.6floatHMA2 LMA2
Extreme Price Band %4.2floatHMA3 LMA3
Fibonacci Settings
The standard Fibonacci retracement levels are available in the drop down selection for the Fibonacci strategy.falseboolunused
Level 1 is where the trade will happen if the price crosses and the zone is up (for sell) and down (for buy)falseboolunused
Level 2 is where the trade will always happen when the price crosses regardless of trend indicators.falseboolunused
Fibonacci Level 11.618float · options [1.382, 1.618, 1.786, 2.000, 2.272, 2.382, 2.618, 3, 3.382, 3.618]HMA2 LMA2
Fibonacci Level 22.618float · options [1.382, 1.618, 1.786, 2.000, 2.272, 2.382, 2.618, 3, 3.382, 3.618]HMA3 LMA3
Peaks and Valleys Options
Peaks and Valleys is a more aggressive form of the moving average strategy. You can change the type of MA to have faster scalps.falseboolunused
MA Type (EMA is default - the rest experimental)EMAstring · options ["EMA", "SMA", "VWMA", "WMA"]line 150 line 152 line 154 line 156
Bot Webhook Messages
Here you can either copy and paste a trigger message for a bot or a custom message for an Email or SMS alertfalseboolunused
replace the alert body message with {{strategy.order.alert_message}} for a single message to map to alll long/short triggers.falseboolunused
Message long entry (no label in the script)long entry messagestringentry MIXED entry LONG
Message long exit (no label in the script)long exit messagestringclose LONG close MIXED exit Exit Long exit Exit Mixed
Message short entry (no label in the script)short entry messagestringentry MIXED entry SHORT
Message short exit (no label in the script)short exit messagestringclose SHORT close MIXED exit Exit Short exit Exit Mixed

What it calculates

  • Highest (highest, ta.highest in v5)High Source (high), Average # of bars in Up/Down Trend (20)high1 · line 111
  • Highest (highest, ta.highest in v5)High Source (high), Price Lookback Period (10)high2 · line 112
  • Lowest (lowest, ta.lowest in v5)Low Source (low), Average # of bars in Up/Down Trend (20)low1 · line 114
  • Lowest (lowest, ta.lowest in v5)Low Source (low), Price Lookback Period (10)low2 · line 115
  • ATR (atr, ta.atr in v5)Price Lookback Period (10)HMA2 · line 128
  • ATR (atr, ta.atr in v5)Price Lookback Period (10)HMA3 · line 129
  • ATR (atr, ta.atr in v5)Price Lookback Period (10)LMA2 · line 131
  • ATR (atr, ta.atr in v5)Price Lookback Period (10)LMA3 · line 132
  • SMA (sma, ta.sma in v5)close, 3ma3 · line 134
  • VWMA (vwma, ta.vwma in v5)close, 3vwma3 · line 134
  • SMA (sma, ta.sma in v5)close, 5ma5 · line 135
  • VWMA (vwma, ta.vwma in v5)close, 5vwma5 · line 135
  • SMA (sma, ta.sma in v5)close, 9ma9 · line 136
  • VWMA (vwma, ta.vwma in v5)close, 9vwma9 · line 136
  • SMA (sma, ta.sma in v5)close, 10ma10 · line 137
  • SMA (sma, ta.sma in v5)close, 15ma15 · line 138
  • EMA (ema, ta.ema in v5)close, 5MA1 · line 140
  • EMA (ema, ta.ema in v5)high, 5HA1 · line 140
  • EMA (ema, ta.ema in v5)low, 5LA1 · line 140
  • EMA (ema, ta.ema in v5)close, 8MA2 · line 141
  • EMA (ema, ta.ema in v5)high, 8HA2 · line 141
  • EMA (ema, ta.ema in v5)low, 8LA2 · line 141
  • EMA (ema, ta.ema in v5)close, 13MA3 · line 142
  • EMA (ema, ta.ema in v5)high, 13HA3 · line 142
  • EMA (ema, ta.ema in v5)low, 13LA3 · line 142
  • EMA (ema, ta.ema in v5)close, 21MA4 · line 143
  • EMA (ema, ta.ema in v5)high, 21HA4 · line 143
  • EMA (ema, ta.ema in v5)low, 21LA4 · line 143
  • EMA (ema, ta.ema in v5)close, 34MA5 · line 144
  • EMA (ema, ta.ema in v5)high, 34HA5 · line 144
  • EMA (ema, ta.ema in v5)low, 34LA5 · line 144
  • EMA (ema, ta.ema in v5)close, 55MA6 · line 145
  • EMA (ema, ta.ema in v5)high, 55HA6 · line 145
  • EMA (ema, ta.ema in v5)low, 55LA6 · line 145
  • EMA (ema, ta.ema in v5)close, 89MA7 · line 146
  • EMA (ema, ta.ema in v5)high, 89HA7 · line 146
  • EMA (ema, ta.ema in v5)low, 89LA7 · line 146
  • EMA / SMA / VWMA / WMA (ema, ta.ema in v5)src, lengthma · line 151
  • Highest (highest, ta.highest in v5)high, EMA Fast Length (5)fHi · line 161
  • Lowest (lowest, ta.lowest in v5)low, EMA Fast Length (5)fLo · line 162
  • Highest (highest, ta.highest in v5)high, EMA Slow Length (12)sHi · line 163
  • Lowest (lowest, ta.lowest in v5)low, EMA Slow Length (12)sLo · line 164
  • EMA (ema, ta.ema in v5)abs(x - x[1]), tavrng · line 197
  • EMA (ema, ta.ema in v5)avrng, wpersmoothrng · line 198
  • SMA (sma, ta.sma in v5)close, 20ma20 · line 230
  • SMA (sma, ta.sma in v5)close, 50ma50 · line 231
  • SMA (sma, ta.sma in v5)close, 200ma200 · line 232
  • CMO (cmo, ta.cmo in v5)close, 2change2 · line 233
  • CMO (cmo, ta.cmo in v5)close, 9change9 · line 234
  • ALMA / SMA (alma, ta.alma in v5)(close-sma(close,40))/sma(close,40)*100, 21, 0.85, 6trendline · line 235
  • EMA (ema, ta.ema in v5)ema(ema((2*close+high+low)/4,4),4), 4tradingline · line 236
  • SMA (sma, ta.sma in v5)(tradingline-xrf(tradingline,1))/xrf(tradingline,1)*100, 1fastLine · line 237
  • ALMA / SMA (alma, ta.alma in v5)sma((tradingline-xrf(tradingline,1))/xrf(tradingline,1)*100,2), 3, 0.85, 6slowLine · line 238
  • RSI (rsi, ta.rsi in v5)close, 100rsi · line 297
  • BB (bb, ta.bb in v5)rsi, 200, 1.618rsiUpperBand · line 299
  • BB (bb, ta.bb in v5)rsi, 200, 1.618rsiLowerBand · line 299
  • Crossunder (crossunder, ta.crossunder in v5)STMACD, STMACDAvgMS2 · line 315
  • Crossover (crossover, ta.crossover in v5)STMACD, STMACDAvgMB2 · line 318

Signal flow

How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.

The script has 185 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open MIXED long(GoLong and strat_val==0 and strategy.position_size==0 and barstate.isconfirmed)On346
Open LONG long(GoLong and strat_val==1 and strategy.position_size==0 and barstate.isconfirmed)On348
Open MIXED short(GoShort and strat_val==0 and strategy.position_size==0 and strategy.position_size[1]==0 and barstate.isconfirmed)On350
Open SHORT short(GoShort and strat_val==-1 and strategy.position_size==0 and barstate.isconfirmed)On352
Close LONG(CloseLong and strategy.position_size > 0 and strat_val==1 and barstate.isconfirmed)On354
Close MIXED(CloseLong and strategy.position_size > 0 and strat_val==0 and barstate.isconfirmed)On356
Close SHORT(CloseShort and strategy.position_size < 0 and strat_val==-1 and barstate.isconfirmed)On358
Close MIXED(CloseShort and strategy.position_size < 0 and strat_val==0 and barstate.isconfirmed)On360
Exit Exit Long stop and limit(strategy.position_size > 0 and strat_val==1)On369
Exit Exit Mixed stop and limit(strategy.position_size > 0 and strat_val==0)On371
Exit Exit Short stop and limit(strategy.position_size < 0 and strat_val==-1)On373
Exit Exit Mixed stop and limit(strategy.position_size < 0 and strat_val==0)On375

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Does it repaint?

No

No repainting patterns in the source.

The live replay needs a run, and this script does not run in Zeal Terminal yet; the answer comes from the checks on the source alone.

  • ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
  • ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.

The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.

Similar scripts

Indicators and strategies built from the same calculations.

ScriptSharesTypeNetTradesMax drawdown
Multi MA Trend Following Strategy Template by TradeAutomationalma ema sma vwma wma atr highest lowestv5 strategy+12.3%326.9%
Bear & Bull Zone Signal Strategy by Solutions1978rsi ema highest lowest sma vwmav4 strategyNo trades on this market
CCI-RSI MR by monikabhayhighest lowest sma atr rsi bbv4 strategyNo trades on this market
Open Close Cross Strategy plus Explorer by roses27sma ema wma vwma alma atrv4 strategydoes not run in Zeal Terminal
Ultra Moving Average Rating Trend Strategy by exlux99ema wma highest lowest sma alma vwmav5 strategy+2.8%52.4%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2No In 'array.get()' function. Index NaN is out of bounds, array size is 20.Not measured
PineTSNo v5 and v6 only—Not measured

Zeal Terminal's engine currently reads an order side written as long = true, long = false as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 346, 350) so the engine trades the way the script says.

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0///@version=4//**********************************************************************************************************// Gradient Color Bars incorporated based on Color Gradient Function script by e2e4mfck//**********************************************************************************************************// ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗██████╗     ██████╗ ██╗   ██╗    //██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝██╔══██╗    ██╔══██╗╚██╗ ██╔╝                       //██║     ██████╔╝█████╗  ███████║   ██║   █████╗  ██║  ██║    ██████╔╝ ╚████╔╝                        //██║     ██╔══██╗██╔══╝  ██╔══██║   ██║   ██╔══╝  ██║  ██║    ██╔══██╗  ╚██╔╝                         //╚██████╗██║  ██║███████╗██║  ██║   ██║   ███████╗██████╔╝    ██████╔╝   ██║                          // ╚═════╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═════╝     ╚═════╝    ╚═╝                                                                                                                               //███████╗ ██████╗ ██╗     ██╗   ██╗████████╗██╗ ██████╗ ███╗   ██╗███████╗ ██╗ █████╗ ███████╗ █████╗ //██╔════╝██╔═══██╗██║     ██║   ██║╚══██╔══╝██║██╔═══██╗████╗  ██║██╔════╝███║██╔══██╗╚════██║██╔══██╗//███████╗██║   ██║██║     ██║   ██║   ██║   ██║██║   ██║██╔██╗ ██║███████╗╚██║╚██████║    ██╔╝╚█████╔╝//╚════██║██║   ██║██║     ██║   ██║   ██║   ██║██║   ██║██║╚██╗██║╚════██║ ██║ ╚═══██║   ██╔╝ ██╔══██╗//███████║╚██████╔╝███████╗╚██████╔╝   ██║   ██║╚██████╔╝██║ ╚████║███████║ ██║ █████╔╝   ██║  ╚█████╔╝//╚══════╝ ╚═════╝ ╚══════╝ ╚═════╝    ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝╚══════╝ ╚═╝ ╚════╝    ╚═╝   ╚════╝                                                                                                      strategy(shorttitle='DPS',title='Dynamic Price Swing', overlay=true, initial_capital = 1000, process_orders_on_close=false, close_entries_rule="ANY", default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent, commission_value=0.18, calc_on_every_tick=false)// ————— Constantsvar string SH1 = "Red ⮀ Green"var string SH2 = "Purple ⮀ Blue"var string SH3 = "Yellow ⮀  DarkGreen"var string SH4 = "White ⮀ Black"var string SH5 = "White ⮀ Blue"var string SH6 = "White ⮀ Red"var string SH7 = "Rainbow"bgcolor(color.new(#000000,15), title="Dark Background")white = color.new(color.white, 50)// -----------------  Strategy Inputs -------------------------------------------------------------//Instructionsgeneral = input(false, "Backtest Dates, Strategy Selection, and Risk Management Inputs apply to all strategies")//Backtest dates with auto finish date of todaystart = input(defval = timestamp("21 June 2021 00:00 -0500"), title = "Start Time", type = input.time, group="Backtest Dates")finish = input(defval = timestamp("31 December 2021 00:00 -0600"), title = "End Time", type = input.time, group="Backtest Dates")window()  => time >= start and time <= finish ? true : false       // create function "within window of time"// Strategy Selection - Long, Short, or Bothgeneral2 = input(false, "Average Price Channel strategy buys and sells when price crosses above or below the previous highest high and lowest low", group="Strategy Descriptions")general3 = input(false, "Moving Average strategy buys and sells when the price crosses above or below the selected price band, which also is shaded based on what you select.", group="Strategy Descriptions")general4 = input(false, "Fibonacci strategy buys and sells when the price crosses above the Fibonacci level selected.", group="Strategy Descriptions")general5 = input(false, "Peaks and Valleys buys and sells based on the combined crossing of the VWMA, ALMA, and Average MACD True Range trend lines.", group="Strategy Descriptions")general5b = input(false, "The settings for each strategy is grouped. Only the inputs indicated for the selected strategy will impact the triggers.", group="Strategy Descriptions")general5c = input(false, "All strategies use the Risk Management and Up/Down Trend Settings.", group="Strategy Descriptions")trigger = input ("Average Price Channel", "Select a Price Swing Trigger", options=["Average Price Channel", "Moving Average", "Fibonacci", "Peaks and Valleys"], group="Strategy Selection")usePrice = trigger=="Average Price Channel" ? true : falseuseMA = trigger == "Moving Average" ? true : falseuseFib = trigger == "Fibonacci" ? true : falseusePV = trigger == "Peaks and Valleys" ? true : falsegeneral6 = input(false, "Use Long/Short only for backtest comparisons. Long is if you are starting with FIAT, Short is if you are starting with crypto.", group="Strategy Selection")strat = input(title="Trade Types", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"], group="Strategy Selection")strat_val = strat == "Long Only" ? 1 : strat == "Long/Short" ? 0 : -1// ————— Inputsvar bool    _1          = input(false,      "═══════════⥑ Gradient ⥏═══════════", group="Visualization Selection")var bool    colorbars   = input(true,       "Use Gradient Color Bars?", group="Visualization Selection")var string  i_scheme    = input(SH1,        " 》Color Scheme",  options = [SH1, SH2, SH3, SH4, SH5, SH6, SH7], group="Visualization Selection")var bool    i_invert    = input(false,      "Invert Colors", group="Visualization Selection")var bool    i_barcolor  = input(false,      "Colorize Bars", group="Visualization Selection")// }// —————————— Color array {var color[] c_gradients = array.new_color(na)// Risk Management Inputsgeneral7 = input(false, "You can control your gains and losses with these inputs that should be self-explanatory.", group="Risk Management")sl= input(50.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01, group="Risk Management")stoploss = sl/100tp = input(50.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01, group="Risk Management")TargetProfit = tp/100ld = input(10, "Stop Trading After This Many Losing Days", type=input.integer, minval=0, maxval=100, step=1, group="Risk Management")strategy.risk.max_cons_loss_days(count=ld)ml = input(50, "Maximum % of Equity Lost to Halt Trading", type=input.integer, minval=1, maxval=100, step=1, group="Risk Management")strategy.risk.max_drawdown(value=ml, type=strategy.percent_of_equity)// General Settingsgeneral8 = input(false, "This section is for adjusting the EMA length and price lookback period for identifying upward/downward zones. You can add the Triple EMA indicator to a new pane to visually tweak these settings.", group="Up/Down Trend Settings")fastLength = input(5, minval=1, title="EMA Fast Length", group="Up/Down Trend Settings")slowLength = input(12, minval=1, title="EMA Slow Length", group="Up/Down Trend Settings")general9 = input(false, "The Average # of bars is what you observe as the number of up and down bars in a cycle", group="Up/Down Trend Settings")general10 = input(false, "For example, if a crypto's chart has 6 up and 4 down for each cycle before it repeats", group="Up/Down Trend Settings")general11 = input(false, "then your Average # of bars is 10 and your Price Lookback Period is 5 (half of the Avg #)", group="Up/Down Trend Settings")AvgLkbk = input(20, minval=1, title="Average # of bars in Up/Down Trend", group="Up/Down Trend Settings")lkbk = input(10,"Price Lookback Period", group="Up/Down Trend Settings")high_source = input(high,"High Source", group="Up/Down Trend Settings")low_source= input(low,"Low Source", group="Up/Down Trend Settings")diff1 = input(2.5, "High Price Knife Percentage (% difference to trigger a quick sell)", group="Price Channel Settings")diff = diff1/100// Moving Average Inputsgeneral12 = input(false, "For the Moving Average Strategy - define the percentage from the center price line you want trades to occur", group="Moving Average Settings")general13 = input(false, "the default is to use the first band (shaded in green and red) or you can choose to use the second or third price channel bands.", group="Moving Average Settings")InnerValue = input(1.6, title="1st Price Band %", group="Moving Average Settings")OuterValue = input(2.6, title="2nd Price Band %", group="Moving Average Settings")ExtremeValue = input(4.2, title="Extreme Price Band %", group="Moving Average Settings")BandUse = input("First", "Select Price Band to Trigger Trades", options=["First", "Second", "Extremes"], group="Strategy Selection")band = BandUse == "First" ? 1 : BandUse == "Second" ? 2 : BandUse == "Extremes" ? 3 : na// Fib Inputsgeneral14 = input(false, "The standard Fibonacci retracement levels are available in the drop down selection for the Fibonacci strategy.", group="Fibonacci Settings")general15 = input(false, "Level 1 is where the trade will happen if the price crosses and the zone is up (for sell) and down (for buy)", group="Fibonacci Settings")general16 = input(false, "Level 2 is where the trade will always happen when the price crosses regardless of trend indicators.", group="Fibonacci Settings")Fib1 = input(1.618, "Fibonacci Level 1", options=[1.382, 1.618, 1.786, 2.000, 2.272, 2.382, 2.618, 3, 3.382, 3.618], group="Fibonacci Settings")Fib2 = input(2.618, "Fibonacci Level 2", options=[1.382, 1.618, 1.786, 2.000, 2.272, 2.382, 2.618, 3, 3.382, 3.618], group="Fibonacci Settings")// Peaks and Valleys Inputsgeneral17 = input(false, "Peaks and Valleys is a more aggressive form of the moving average strategy. You can change the type of MA to have faster scalps.", group="Peaks and Valleys Options")maInput = input(title="MA Type (EMA is default - the rest experimental)", defval="EMA", options=["EMA", "SMA", "VWMA", "WMA"],  group="Peaks and Valleys Options")//Entry area for custom bot messages (i.e. Quadency, 3Commas, etc)general18 = input(false, "Here you can either copy and paste a trigger message for a bot or a custom message for an Email or SMS alert", group="Bot Webhook Messages")general19 = input(false, "replace the alert body message with {{strategy.order.alert_message}} for a single message to map to alll long/short triggers.", group="Bot Webhook Messages")message_long_entry  = input("long entry message", group="Bot Webhook Messages")message_long_exit   = input("long exit message", group="Bot Webhook Messages")message_short_entry = input("short entry message", group="Bot Webhook Messages")message_short_exit  = input("short exit message", group="Bot Webhook Messages")// ================================================================ Where the Magic Happens ========================================================================// -------------------------------- Price Channel Calculation ----------------------------------high1 = highest(high_source, AvgLkbk)high2 = highest(high_source, lkbk)lasthigh = max(high1, high2)low1 = lowest(low_source, AvgLkbk)low2 = lowest(low_source, lkbk)lastlow = min(low1, low2)hiHighs = lasthigh[1]loLows = lastlow[1]mids = (hiHighs + loLows)/2plot(series = usePrice ?  mids: na, title="Price Midline", color=white, linewidth=1)plot(series = usePrice ?  hiHighs: na, title="Price High Line", color=white, linewidth=1)plot(series = usePrice ? loLows: na, title="Price Low Line", color=white, linewidth=1)// --------------------------------- Moving Averages -------------------------------------------// Improved Price ChannelsCMA = midsCenteredMA= plot(series = usePrice ? na : CMA, color=color.blue , linewidth=2)HMA     = usePrice ? hiHighs : CMA + (CMA * (InnerValue / 100))HMA2    = usePrice ? na : useFib ? CMA + (atr(lkbk)*Fib1) : CMA + (CMA * (OuterValue / 100))HMA3    = usePrice ? na : useFib ? CMA + (atr(lkbk)*Fib2) : CMA + (CMA * (ExtremeValue / 100))LMA     = usePrice ? loLows : CMA - (CMA * (InnerValue / 100))LMA2    = usePrice ? na : useFib ? CMA - (atr(lkbk)*Fib1) : CMA - (CMA * (OuterValue / 100))LMA3    = usePrice ? na : useFib ? CMA - (atr(lkbk)*Fib2) : CMA - (CMA * (ExtremeValue / 100))// For Price Channelsma3 = sma(close, 3), vwma3 = vwma(close, 3)ma5 = sma(close, 5), vwma5 = vwma(close, 5)ma9 = sma(close, 9), vwma9 = vwma(close, 9)ma10 = sma(close,10)ma15 = sma(close,15)// For FibonacciMA1 = ema(close,5),HA1 = ema(high,5),LA1 = ema(low,5)MA2 = ema(close,8),HA2 = ema(high,8),LA2 = ema(low,8)MA3 = ema(close,13),HA3 = ema(high,13),LA3 = ema(low,13)MA4 = ema(close,21),HA4 = ema(high,21),LA4 = ema(low,21)MA5 = ema(close,34),HA5 = ema(high,34),LA5 = ema(low,34)MA6 = ema(close,55),HA6 = ema(high,55),LA6 = ema(low,55)MA7 = ema(close,89),HA7 = ema(high,89),LA7 = ema(low,89)// For Peaks and ValleysgetMA(src, length) =>    ma = 0.0    if maInput == "EMA"        ma := ema(src, length)    if maInput == "SMA"        ma := sma(src, length)    if maInput == "VWMA"        ma := vwma(src, length)    if maInput == "WMA"        ma := wma(src, length)    maFastAvgValue = getMA(close, fastLength)SlowAvgValue = getMA(close, slowLength)fHi = highest(high, fastLength)fLo = lowest(low, fastLength)sHi = highest(high, slowLength)sLo = lowest(low, slowLength)FastStoch = (FastAvgValue - fHi) / (fHi - fLo)SlowStoch = (SlowAvgValue - sLo) / (sHi - sLo)STMACD = (FastStoch - SlowStoch) * 100STMACDAvg = getMA(STMACD, AvgLkbk)// ====================================== Trend Direction Calculations ===========================================// -------------- Volume Trend------------------cumUp = 0.0cntUp = 0cumDown = 0.0cntDown = 0for i=0 to lkbk-1    if close[i] > open[i]        cumUp := cumUp + volume[i]        cntUp := cntUp + 1    else        cumDown := cumDown + volume[i]        cntDown := cntDown + 1averagevolumeup = (cumUp/cntUp)averagevolumedown = -(cumDown/cntDown)volUp = (averagevolumeup) <= volume and close > openvolDown = (averagevolumedown) >= -volume and close < openflow = cumUp - cumDown//Call bullshit when trend doesn't agree with the numbers (fake pumps and dumps)BullShit1 = flow > 0 and flow[1] > 0 and volDownBullShit2 = flow < 0 and flow[1] < 0 and volUpBullShit = BullShit1 or BullShit2upVol = volUp and flow > 0 and not BullShitdownVol = volDown and flow < 0 and not BullShit// ----------------- Range Breakout Trend -------------------src = high_sourcesmoothrng(x, t, m)=>    wper      = (t*2) - 1    avrng     = ema(abs(x - x[1]), t)    smoothrng = ema(avrng, wper)*m    smoothrngsmrng = smoothrng(close, slowLength, lkbk)rngfilt(x, r)=>    rngfilt  = x    rngfilt := x > nz(rngfilt[1]) ? ((x - r) < nz(rngfilt[1]) ? nz(rngfilt[1]) : (x - r)) : ((x + r) > nz(rngfilt[1]) ? nz(rngfilt[1]) : (x + r))    rngfiltfilt = rngfilt(src, smrng)upward   = 0.0upward  := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])downward = 0.0downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])hband = filt + smrnglband = filt - smrnguptrend1 = (src > filt) and (src > src[1]) and (upward > 0)uptrend2 = (src > filt) and (src < src[1]) and (upward > 0)longCond = uptrend1 or uptrend2downtrend1 = (src < filt) and (src < src[1]) and (downward > 0)downtrend2 = (src < filt) and (src > src[1]) and (downward > 0)shortCond = downtrend1 or downtrend2CondIni = 0CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]stroking = longCond and CondIni[1] == -1//  Arnaud Legoux Moving Average ( ALMA ) xrf(values, length) =>    r_val = float(na)    if length >= 1        for i = 0 to length by 1            if na(r_val) or not na(values[i])                r_val  :=  values[i]                r_val    r_valma20 = sma(close,20)ma50 = sma(close,50)ma200 = sma(close,200)change2 = cmo(close, 2)change9 = cmo(close, 9)trendline =  alma((close-sma(close,40))/sma(close,40)*100,21,0.85,6)tradingline = ema(ema(ema((2*close+high+low)/4,4),4),4)fastLine = ( sma((tradingline-xrf(tradingline,1))/xrf(tradingline,1)*100,1))*10slowLine = alma( sma((tradingline-xrf(tradingline,1))/xrf(tradingline,1)*100,2),3,0.85,6)*10pd = (high[1] - close[1]) / close[1]// Breakout (upward momentum) and Dumpout (downward momentumm) conditions based on ALMA indicator triggers combined with volume trend as a crosscheck to reduce false alerts// Fakeout based on patterns where the high point of the price is a reverse knife (when high is greater than 2% of the close price) - this typically leads to a small dump of FOOMO sellersbreakout = fastLine>slowLine and fastLine<0 and longConddumpout = fastLine<slowLine and fastLine>0 and shortCondfakeout = pd > diff or high >= HMA3// ------------------------ Price Channel Plots --------------------------------------------------------Ctr_Top = (useMA or useFib) ? (band==1 ? mids : band==2 ? HMA : band == 3 ? HMA2: na) : midsCtr_Bottom = (useMA or useFib) ? (band==1 ? mids : band==2 ? LMA : band == 3 ? LMA2: na) : midsupper_function = (useMA or useFib) ? (band==1 ? HMA : band==2 ? HMA2 : band == 3 ? HMA3: na) : hiHighslower_function = (useMA or useFib) ? (band==1 ? LMA : band==2 ? LMA2 : band == 3 ? LMA3: na) : loLowsCtr1       = plot(Ctr_Top, color=white)Ctr2    = plot(Ctr_Bottom, color=white)Upper   = plot(upper_function, color=white)Lower   = plot(lower_function, color=white)upper_color = color.new(color.green, 90)lower_color = color.new(color.red, 90)fill(Ctr1, Upper, upper_color)fill(Ctr2, Lower, lower_color)// ————— Fill the array with colors only on the first iteration of the scriptif barstate.isfirst    if i_scheme == SH1        array.push(c_gradients, #ff0000), array.push(c_gradients, #ff2c00), array.push(c_gradients, #fe4200), array.push(c_gradients, #fc5300), array.push(c_gradients, #f96200), array.push(c_gradients, #f57000), array.push(c_gradients, #f07e00), array.push(c_gradients, #ea8a00), array.push(c_gradients, #e39600), array.push(c_gradients, #dca100), array.push(c_gradients, #d3ac00), array.push(c_gradients, #c9b600), array.push(c_gradients, #bfc000), array.push(c_gradients, #b3ca00), array.push(c_gradients, #a6d400), array.push(c_gradients, #97dd00), array.push(c_gradients, #86e600), array.push(c_gradients, #71ee00), array.push(c_gradients, #54f700), array.push(c_gradients, #1eff00)    else if i_scheme == SH2        array.push(c_gradients, #ff00d4), array.push(c_gradients, #f71fda), array.push(c_gradients, #ef2ee0), array.push(c_gradients, #e63ae5), array.push(c_gradients, #de43ea), array.push(c_gradients, #d44bee), array.push(c_gradients, #cb52f2), array.push(c_gradients, #c158f6), array.push(c_gradients, #b75df9), array.push(c_gradients, #ac63fb), array.push(c_gradients, #a267fe), array.push(c_gradients, #966bff), array.push(c_gradients, #8b6fff), array.push(c_gradients, #7e73ff), array.push(c_gradients, #7276ff), array.push(c_gradients, #6479ff), array.push(c_gradients, #557bff), array.push(c_gradients, #437eff), array.push(c_gradients, #2e80ff), array.push(c_gradients, #0082ff)    else if i_scheme == SH3        array.push(c_gradients, #fafa6e), array.push(c_gradients, #e0f470), array.push(c_gradients, #c7ed73), array.push(c_gradients, #aee678), array.push(c_gradients, #97dd7d), array.push(c_gradients, #81d581), array.push(c_gradients, #6bcc86), array.push(c_gradients, #56c28a), array.push(c_gradients, #42b98d), array.push(c_gradients, #2eaf8f), array.push(c_gradients, #18a48f), array.push(c_gradients, #009a8f), array.push(c_gradients, #00908d), array.push(c_gradients, #008589), array.push(c_gradients, #007b84), array.push(c_gradients, #0c707d), array.push(c_gradients, #196676), array.push(c_gradients, #215c6d), array.push(c_gradients, #275263), array.push(c_gradients, #2a4858)    else if i_scheme == SH4        array.push(c_gradients, #ffffff), array.push(c_gradients, #f0f0f0), array.push(c_gradients, #e1e1e1), array.push(c_gradients, #d2d2d2), array.push(c_gradients, #c3c3c3), array.push(c_gradients, #b5b5b5), array.push(c_gradients, #a7a7a7), array.push(c_gradients, #999999), array.push(c_gradients, #8b8b8b), array.push(c_gradients, #7e7e7e), array.push(c_gradients, #707070), array.push(c_gradients, #636363), array.push(c_gradients, #575757), array.push(c_gradients, #4a4a4a), array.push(c_gradients, #3e3e3e), array.push(c_gradients, #333333), array.push(c_gradients, #272727), array.push(c_gradients, #1d1d1d), array.push(c_gradients, #121212), array.push(c_gradients, #000000)    else if i_scheme == SH5        array.push(c_gradients, #ffffff), array.push(c_gradients, #f4f5fa), array.push(c_gradients, #e9ebf5), array.push(c_gradients, #dee1f0), array.push(c_gradients, #d3d7eb), array.push(c_gradients, #c8cde6), array.push(c_gradients, #bdc3e1), array.push(c_gradients, #b2b9dd), array.push(c_gradients, #a7b0d8), array.push(c_gradients, #9ca6d3), array.push(c_gradients, #919dce), array.push(c_gradients, #8594c9), array.push(c_gradients, #7a8bc4), array.push(c_gradients, #6e82bf), array.push(c_gradients, #6279ba), array.push(c_gradients, #5570b5), array.push(c_gradients, #4768b0), array.push(c_gradients, #385fab), array.push(c_gradients, #2557a6), array.push(c_gradients, #004fa1)    else if i_scheme == SH6        array.push(c_gradients, #ffffff), array.push(c_gradients, #fff4f1), array.push(c_gradients, #ffe9e3), array.push(c_gradients, #ffded6), array.push(c_gradients, #ffd3c8), array.push(c_gradients, #fec8bb), array.push(c_gradients, #fdbdae), array.push(c_gradients, #fbb2a1), array.push(c_gradients, #f8a794), array.push(c_gradients, #f69c87), array.push(c_gradients, #f3917b), array.push(c_gradients, #f0856f), array.push(c_gradients, #ec7a62), array.push(c_gradients, #e86e56), array.push(c_gradients, #e4634a), array.push(c_gradients, #df563f), array.push(c_gradients, #db4933), array.push(c_gradients, #d63a27), array.push(c_gradients, #d0291b), array.push(c_gradients, #cb0e0e)    else if i_scheme == SH7        array.push(c_gradients, #E50000), array.push(c_gradients, #E6023B), array.push(c_gradients, #E70579), array.push(c_gradients, #E908B7), array.push(c_gradients, #E00BEA), array.push(c_gradients, #A70DEB), array.push(c_gradients, #6E10ED), array.push(c_gradients, #3613EE), array.push(c_gradients, #162DEF), array.push(c_gradients, #1969F1), array.push(c_gradients, #1CA4F2), array.push(c_gradients, #1FDFF4), array.push(c_gradients, #22F5D2), array.push(c_gradients, #25F69C), array.push(c_gradients, #28F867), array.push(c_gradients, #2CF933), array.push(c_gradients, #5DFA2F), array.push(c_gradients, #96FC32), array.push(c_gradients, #CDFD35), array.push(c_gradients, #FFF938)        // Invert colors in array    if i_invert        array.reverse(c_gradients)        // ————— Rescale function // Credits to LucF, https://www.pinecoders.com/faq_and_code/#how-can-i-rescale-an-indicator-from-one-scale-to-anotherf_rescale(_src, _min, _max) =>    // Rescales series with known min/max to the color array size.    // Dependency : c_gradients array    // _src       : series to rescale.    // _min, _max : min/max values of series to rescale.    var int _size = array.size(c_gradients) - 1    int _colorStep = int(_size * (_src - _min)) / int(max(_max - _min, 10e-10))    _colorStep := _colorStep > _size ? _size : _colorStep < 0 ? 0 : _colorStep    int(_colorStep)// ————— Result// Dependency : c_gradients arrayf_colGrad(_src, _min, _max) => array.get(c_gradients, f_rescale(_src, _min, _max))// Example:// resultColor = f_colGrad(_src, _min, _max)// }// ————— Rsi as a sourcersi = rsi(close, 100)// ————— Bollinger bands on top of Rsi as gradient's min and max[_, rsiUpperBand, rsiLowerBand] = bb(rsi, 200, 1.618)// ————— Colorize the bounded sourcecolor c_rsi = f_colGrad(rsi, rsiLowerBand, rsiUpperBand)barcolor(i_barcolor ? crossover(STMACD, STMACDAvg) ? color.red : crossunder(STMACD, STMACDAvg) ? color.yellow : BullShit ? color.white : c_rsi : na)// ============================================================================= Entry and Exit Logic ======================================================================// Entry Logic//Logic for Channel Buy/SellCB1 = low < loLows and longCond and window()CB2 = breakout and window()Channel_Buy = CB1 or CB2CS1 = high >= hiHighs and shortCond and window()CS2 = dumpout and window()CS3 = fakeout and window()Channel_Sell = CS1 or CS2 or CS3//Logic for Moving AverageMS1 = (band == 1 ? high > HMA : band == 2 ? high > HMA2 : band == 3 ? high > HMA3 : na) and shortCond and window()MS2 = (band == 1 ? high > HMA : band == 2 ? high > HMA2 : band == 3 ? high > HMA3 : na) and crossunder(STMACD, STMACDAvg) and window()MA_Sell = MS1 or MS2MB1 = (band == 1 ? low<LMA : band == 2 ? low < LMA2 : band == 3 ? low < LMA3 : na)  and longCond and window()MB2 = (band == 1 ? low<LMA : band == 2 ? low < LMA2 : band == 3 ? low < LMA3 : na) and crossover(STMACD, STMACDAvg) and window()MA_Buy = MB1 or MB2//Logic for FibFib_Sell1 = high[1]>=HMA2 and high>=HMA3 and window()Fib_Sell2 = high[1]>=HMA2 and close<HMA3 and window()Fib_Sell3 = high >= HMA2 and BullShit and window()Fib_Sell4 = high > HMA3 and window()Fib_Sell = Fib_Sell1 or Fib_Sell2 or Fib_Sell3 or Fib_Sell4Fib_Buy1 = low[3]<=LMA3 and low[2]<=LMA3 and low[1]<=LMA3 and low<=LMA3 and window()Fib_Buy2 = low<=LMA3 and BullShit and window()Fib_Buy3 = low <= LMA2 and crossover(STMACD, STMACDAvg) and window()Fib_Buy = Fib_Buy1 or Fib_Buy2 or Fib_Buy3//----- Logic for Peaks and Valleys -----------------------------// LB is Long Buy logic and SB is Short Buy Logic// LS is for Long Sell and is the same for Short SellsLB = low < loLows and crossover(STMACD, STMACDAvg) and window()SB = low < loLows and BullShit and window()PVBuy = LB or SBSS1 = high >= hiHighs and crossunder(STMACD, STMACDAvg) and window()LS1 = BullShit and high >= hiHighs and window()PVSell = LS1 or SS1// ------------------------ Strategy Trades -------------------------------------------------------------GoLong = usePrice ? Channel_Buy : useMA ? MA_Buy : useFib ? Fib_Buy : usePV ? PVBuy : falseGoShort = usePrice ? Channel_Sell : useMA ? MA_Sell : useFib ? Fib_Sell : usePV ? PVSell : falseCloseShort= usePrice ? Channel_Buy : useMA ? MA_Buy : useFib ? Fib_Buy : usePV ? PVBuy : falseCloseLong = usePrice ? Channel_Sell : useMA ? MA_Sell : useFib ? Fib_Sell : usePV ? PVSell : false// Strategy Open and Closeif (GoLong and strat_val==0 and strategy.position_size==0 and barstate.isconfirmed)    strategy.entry(id="MIXED", long=true, oca_type=strategy.oca.cancel, oca_name="Mixed Entry", alert_message = message_long_entry)if (GoLong and strat_val==1 and strategy.position_size==0 and barstate.isconfirmed)    strategy.entry("LONG", strategy.long, alert_message = message_long_entry)if (GoShort and strat_val==0 and strategy.position_size==0 and strategy.position_size[1]==0 and barstate.isconfirmed)    strategy.entry(id="MIXED", long=false, oca_type=strategy.oca.cancel, oca_name="Mixed Entry", alert_message = message_short_entry)if (GoShort and strat_val==-1 and strategy.position_size==0 and barstate.isconfirmed)     strategy.entry("SHORT", strategy.short, alert_message = message_short_entry)if(CloseLong and strategy.position_size > 0 and strat_val==1 and barstate.isconfirmed)    strategy.close("LONG", alert_message = message_long_exit)if(CloseLong and strategy.position_size > 0 and strat_val==0 and barstate.isconfirmed)    strategy.close("MIXED", alert_message = message_long_exit)if(CloseShort and strategy.position_size < 0 and strat_val==-1 and barstate.isconfirmed)    strategy.close("SHORT", alert_message = message_short_exit)if(CloseShort and strategy.position_size < 0 and strat_val==0 and barstate.isconfirmed)    strategy.close("MIXED", alert_message = message_short_exit)// -------------------- RISK MANAGEMENT FUNCTIONS ------------------------//Calculate stop and take profit priceslongStopPrice  = strategy.position_avg_price * (1 - stoploss)longTakePrice  = strategy.position_avg_price * (1 + TargetProfit)shortStopPrice = strategy.position_avg_price * (1 + stoploss)shortTakePrice = strategy.position_avg_price * (1 - TargetProfit)//Set exit strategy parametersif (strategy.position_size > 0 and strat_val==1)    strategy.exit(id="Exit Long", from_entry = "LONG", stop = longStopPrice, limit = longTakePrice, alert_message = message_long_exit)if (strategy.position_size > 0 and strat_val==0)    strategy.exit(id="Exit Mixed", from_entry = "MIXED", oca_name="Mixed Entry", stop = longStopPrice, limit = longTakePrice, alert_message = message_long_exit)if (strategy.position_size < 0 and strat_val==-1)    strategy.exit(id="Exit Short", from_entry = "SHORT", stop = shortStopPrice, limit = shortTakePrice, alert_message = message_short_exit)if (strategy.position_size < 0 and strat_val==0)    strategy.exit(id="Exit Mixed", from_entry = "MIXED", oca_name="Mixed Entry", stop = shortStopPrice, limit = shortTakePrice, alert_message = message_short_exit)