Pine Script v4 · Strategy
72s Strat- Backtesting Adaptive HMA+ pt.1
A Pine Script v4 strategy built on ATR (21), Highest (34) and Lowest (34). It has 12 order rules, 6 entries among them, and trades long and short with the default settings; 2 entries are switched off until a setting enables them. Exits wait for a signal; there is no stop loss. Each trade is one contract and pays .5 commission. 20 settings; defaults include Order Size (in Lot) 0.1, Base Minimum Profit before exit (ATR) 1 and Default Target Profit (ATR) 3.
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 72s Strat- Backtesting Adaptive HMA+ pt.1 repaint?
- No
- No repainting patterns were found in the source.
- Can 72s Strat- Backtesting Adaptive HMA+ pt.1 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.
- What alerts does 72s Strat- Backtesting Adaptive HMA+ pt.1 have?
- 12
- "Buy signal at "+tostring(close); "Sell signal at "+tostring(close); "OverBuy signal at "+tostring(close); "OverSell signal at "+tostring(close); and more.
- Does 72s Strat- Backtesting Adaptive HMA+ pt.1 use a stop loss?
- No
- Every exit waits for a signal; nothing limits a losing trade before it fires.
- Does 72s Strat- Backtesting Adaptive HMA+ pt.1 run in Zeal Terminal?
- No
- Not yet: Pine Script v4 Error at @L246:C13: 'strategy.max_drawdown' is not available in Pine Script v4. It was added in a later version.
Review
What a careful reader of this script would point out, found by checking the source.
-
Likely bug
atr(21) ignores the settings line 7
Line 7 hard-codes 21 where line 34 uses “Charged if ATR”. Changing those settings moves one band but not this one.
atr(21)atr(atrFast) -
Likely bug
atr(40) ignores the settings line 65
Line 65 hard-codes 40 where line 34 uses “Charged if ATR”. Changing those settings moves one band but not this one.
atr(40)atr(atrFast) -
Likely bug
atr(40) ignores the settings line 65
Line 65 hard-codes 40 where line 34 uses “Charged if ATR”. Changing those settings moves one band but not this one.
atr(40)atr(atrFast) -
Likely bug
atr(40) ignores the settings line 66
Line 66 hard-codes 40 where line 34 uses “Charged if ATR”. Changing those settings moves one band but not this one.
atr(40)atr(atrFast) -
Likely bug
atr(40) ignores the settings line 66
Line 66 hard-codes 40 where line 34 uses “Charged if ATR”. Changing those settings moves one band but not this one.
atr(40)atr(atrFast) -
Likely bug
atr(40) ignores the settings line 67
Line 67 hard-codes 40 where line 34 uses “Charged if ATR”. Changing those settings moves one band but not this one.
atr(40)atr(atrFast) -
Likely bug
atr(40) ignores the settings line 67
Line 67 hard-codes 40 where line 34 uses “Charged if ATR”. Changing those settings moves one band but not this one.
atr(40)atr(atrFast) -
Likely bug
atr(5) ignores the settings line 99
Line 99 hard-codes 5 where line 34 uses “Charged if ATR”. Changing those settings moves one band but not this one.
atr(5)atr(atrFast) -
Likely bug
crossunder(close, dynamicHMA) ignores the settings line 175
Line 175 hard-codes close where line 172 uses “RSI Length”. Changing those settings moves one band but not this one.
crossunder(close,dynamicHMA)crossunder(rsi, dynamicHMA) -
Likely bug
crossunder(close, minorHMA) ignores the settings line 182
Line 182 hard-codes close where line 172 uses “RSI Length”. Changing those settings moves one band but not this one.
crossunder(close, minorHMA)crossunder(rsi, minorHMA) -
Likely bug
crossover(close, dynamicHMA) ignores the settings line 176
Line 176 hard-codes close where line 173 uses “RSI Length”. Changing those settings moves one band but not this one.
crossover(close,dynamicHMA)crossover(rsi, dynamicHMA) -
Likely bug
crossover(close, minorHMA) ignores the settings line 183
Line 183 hard-codes close where line 173 uses “RSI Length”. Changing those settings moves one band but not this one.
crossover(close, minorHMA)crossover(rsi, minorHMA) -
Check
No stop loss
Every exit waits for a signal. Nothing limits a losing trade before the exit condition fires.
-
Note
The 2ndbuy side is off by default line 216
Its orders only fire after “Activate 2nd order with xHMA+ exits” is switched on. The figures on this page cover buy and sell and overbuy and oversell trades only.
-
Note
The 2ndsell side is off by default line 217
Its orders only fire after “Activate 2nd order with xHMA+ exits” is switched on. The figures on this page cover buy and sell and overbuy and oversell trades only.
-
Note
Uses an argument v6 removed
when = on line 211, 212, 213, 214, 216, 217, 222, 223, 224, 225, 227, 228. The upgraded version below moves each call inside an if block.
-
Note
Uses iff(), which v5 removed line 38
iff() on line 38, 39, 48. v5 writes it as the ternary c ? a : b.
-
Note
Uses transp =, which v5 removed line 69
transp = on line 69, 70, 71, 72, 73, 74, 76, 232, 233, 234. v5 folds the transparency into the colour with color.new(c, transp).
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 atr → ta.atr, rsi → ta.rsi, avg → math.avg, max → math.max, min → math.min, atan → math.atan, highest → ta.highest, lowest → ta.lowest, sqrt → math.sqrt, round → math.round, acos → math.acos, wma → ta.wma, floor → math.floor, ema → ta.ema, tostring → str.tostring, crossunder → ta.crossunder, crossover → ta.crossover, ceil → math.ceil.
- 12 strategy calls use the when = argument (line 211, 212, 213, 214, 216, 217, 222, 223, 224, 225, 227, 228). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
v4 → v5
Not verifiedThe v4 script does not run in Zeal Terminal's engine (Pine Script v4 Error at @L246:C13: 'strategy.max_drawdown' is not available in Pine Script v4. It was added in a later version.), so this step could not be checked.
- Line 3: //@version=4 → //@version=5
- Line 7: atr → ta.atr
- Line 30: rsi → ta.rsi
- Line 34: atr → ta.atr
- Line 34: atr → ta.atr
- Line 36: avg → math.avg
76 more edits
- Line 37: avg → math.avg
- Line 38: iff(c, a, b) → (c ? a : b)
- Line 38: max → math.max
- Line 38: min → math.min
- Line 39: iff(c, a, b) → (c ? a : b)
- Line 39: max → math.max
- Line 39: min → math.min
- Line 41: atan → math.atan
- Line 42: highest → ta.highest
- Line 42: lowest → ta.lowest
- Line 46: sqrt → math.sqrt
- Line 47: round → math.round
- Line 47: acos → math.acos
- Line 48: iff(c, a, b) → (c ? a : b)
- Line 58: wma → ta.wma
- Line 58: wma → ta.wma
- Line 58: wma → ta.wma
- Line 58: floor → math.floor
- Line 58: sqrt → math.sqrt
- Line 65: atr → ta.atr
- Line 65: atr → ta.atr
- Line 66: atr → ta.atr
- Line 66: atr → ta.atr
- Line 67: atr → ta.atr
- Line 67: atr → ta.atr
- Line 69: transp = 72 → color.new(color.green, 72)
- Line 70: transp = 72 → color.new(color.red, 72)
- Line 71: transp = 72 → color.new(color.gray, 72)
- Line 72: transp = 72 → color.new(color.gray, 72)
- Line 73: transp = 100 → color.new(color.white, 100)
- Line 74: transp = 100 → color.new(color.white, 100)
- Line 76: transp = 90 → color.new(colZone, 90)
- Line 83: ema → ta.ema
- Line 99: atr → ta.atr
- Line 108: tostring → str.tostring
- Line 110: tostring → str.tostring
- Line 112: tostring → str.tostring
- Line 114: tostring → str.tostring
- Line 116: tostring → str.tostring
- Line 118: tostring → str.tostring
- Line 134: highest → ta.highest
- Line 135: lowest → ta.lowest
- Line 172: crossunder → ta.crossunder
- Line 173: crossover → ta.crossover
- Line 175: crossunder → ta.crossunder
- Line 176: crossover → ta.crossover
- Line 177: crossunder → ta.crossunder
- Line 179: crossover → ta.crossover
- Line 182: crossunder → ta.crossunder
- Line 183: crossover → ta.crossover
- Line 192: tostring → str.tostring
- Line 194: tostring → str.tostring
- Line 196: tostring → str.tostring
- Line 198: tostring → str.tostring
- Line 200: tostring → str.tostring
- Line 202: tostring → str.tostring
- Line 232: transp = 50 removed: the call sets no colour to fold it into, so its default colour loses the transparency
- Line 233: transp = 50 → color.new(color.red, 50)
- Line 234: transp = 50 → color.new(color.green, 50)
- Line 240: round → math.round
- Line 241: round → math.round
- Line 242: round → math.round
- Line 243: round → math.round
- Line 244: round → math.round
- Line 245: round → math.round
- Line 246: ceil → math.ceil
- Line 248: tostring → str.tostring
- Line 248: tostring → str.tostring
- Line 248: tostring → str.tostring
- Line 248: tostring → str.tostring
- Line 249: tostring → str.tostring
- Line 249: tostring → str.tostring
- Line 250: tostring → str.tostring
- Line 250: tostring → str.tostring
- Line 252: tostring → str.tostring
- Line 254: tostring → str.tostring
⋯// 2020 © io72signals / Antorio Bergasdito-//@version=4+//@version=5strategy("72s Strategy: Adaptive Hull Moving Average+ pt.1", shorttitle="72s Strat: Adaptive HMA+ pt.1", overlay=true, ⋯ slippage=3, max_bars_back=1000)-atrBase = atr(21)+atrBase = ta.atr(21)src = close⋯useBg = input(true, title="Background color to differentiate movement", group="OTHER")-rsi = rsi(input(close,"RSI Source", inline="RSI", group="OTHER"), input(14, "RSI Length", inline="RSI", group="OTHER"))+rsi = ta.rsi(input(close,"RSI Source", inline="RSI", group="OTHER"), input(14, "RSI Length", inline="RSI", group="OTHER"))//}...inputs⋯//Condition to adapt to:-charged = atr(atrFast) > atr(atrSlow) //<--Volatility Meter. Change it to whatever match your strat/pair/tf.+charged = ta.atr(atrFast) > ta.atr(atrSlow) //<--Volatility Meter. Change it to whatever match your strat/pair/tf.//Dynamics -var float dynamicLength = avg(minLength,maxLength)+var float dynamicLength = math.avg(minLength,maxLength)-var float minorLength = avg(minorMin,minorMax)+var float minorLength = math.avg(minorMin,minorMax)-dynamicLength := iff(charged, max(minLength, dynamicLength * (1 - adaptPct)), min(maxLength, dynamicLength * (1 + adaptPct)))+dynamicLength := (charged ? math.max(minLength, dynamicLength * (1 - adaptPct)) : math.min(maxLength, dynamicLength * (1 + adaptPct)))-minorLength := iff(charged, max(minorMin, minorLength * (1 - adaptPct)), min(minorMax, minorLength * (1 + adaptPct)))+minorLength := (charged ? math.max(minorMin, minorLength * (1 - adaptPct)) : math.min(minorMax, minorLength * (1 + adaptPct)))//Slope calculation to determine whether market is in trend, or in consolidation or choppy, or might about to change current trend-pi = atan(1) * 4+pi = math.atan(1) * 4-highestHigh = highest(34), lowestLow = lowest(34)+highestHigh = ta.highest(34), lowestLow = ta.lowest(34)slope_range = 25 / (highestHigh - lowestLow) * lowestLow⋯ dt = (_ma[2] - _ma) / src * slope_range - c = sqrt(1 + dt * dt)+ c = math.sqrt(1 + dt * dt)- xAngle = round(180 * acos(1 / c) / pi)+ xAngle = math.round(180 * math.acos(1 / c) / pi)- maAngle = iff(dt > 0, -xAngle, xAngle)+ maAngle = (dt > 0 ? -xAngle : xAngle) maAngle⋯//Adaptive HMA -xhma(_src,_length) => _return = wma(2 * wma(_src, _length / 2) - wma(_src, _length), floor(sqrt(_length))) +xhma(_src,_length) => _return = ta.wma(2 * ta.wma(_src, _length / 2) - ta.wma(_src, _length), math.floor(math.sqrt(_length))) dynamicHMA = xhma(src,int(dynamicLength)) //<--Batman - Our main xHMA+⋯//Envelope the main DynamicHMA with ATR band, just one way to approximate current price distance to MA. Other usages/methods may vary.-upperTL = dynamicHMA + mult * atr(40) , lowerTL = dynamicHMA - mult * atr(40) //<--Half distance zone+upperTL = dynamicHMA + mult * ta.atr(40) , lowerTL = dynamicHMA - mult * ta.atr(40) //<--Half distance zone-topTL = dynamicHMA + (mult*2) * atr(40) , botTL = dynamicHMA - (mult*2) * atr(40) //<--One distance zone+topTL = dynamicHMA + (mult*2) * ta.atr(40) , botTL = dynamicHMA - (mult*2) * ta.atr(40) //<--One distance zone-stopupperTL = dynamicHMA + (mult/2) * atr(40), stoplowerTL = dynamicHMA - (mult/2) * atr(40) //<--Half of the half. If need ie. tighter SL or trailing+stopupperTL = dynamicHMA + (mult/2) * ta.atr(40), stoplowerTL = dynamicHMA - (mult/2) * ta.atr(40) //<--Half of the half. If need ie. tighter SL or trailing//Plotting Distance Zone-plot(showZone?upperTL:na, color=color.green, transp=72)+plot(showZone?upperTL:na, color=color.new(color.green, 72))-plot(showZone?lowerTL:na, color=color.red, transp=72)+plot(showZone?lowerTL:na, color=color.new(color.red, 72))-plot(showZone?topTL:na, color=color.gray, transp=72)+plot(showZone?topTL:na, color=color.new(color.gray, 72))-plot(showZone?botTL:na, color=color.gray, transp=72)+plot(showZone?botTL:na, color=color.new(color.gray, 72))-sutl = plot(showZone?stopupperTL:na, color=color.white, transp=100)+sutl = plot(showZone?stopupperTL:na, color=color.new(color.white, 100))-sltl = plot(showZone?stoplowerTL:na, color=color.white, transp=100)+sltl = plot(showZone?stoplowerTL:na, color=color.new(color.white, 100))colZone = showZone? color.purple:color.new(color.white,100)-fill(sutl, sltl, color=colZone, transp=90)+fill(sutl, sltl, color=color.new(colZone, 90))plot(showMA?dynamicHMA:na, "Adaptive HMA+", dynColor(dynamicHMA, #6fbf73, #c0f5ae, #eb4d5c, #f2b1d4, color.yellow), 3)⋯//EMA 200. (Not being use in here. But since they've been a BFF since long, thought I'm just gonna put it here..)-emma200 = ema(close,200) //, plot(emma200)+emma200 = ta.ema(close,200) //, plot(emma200)//}...adaptive HMA+⋯//Plot 'em up-atrPos = 0.2 * atr(5)+atrPos = 0.2 * ta.atr(5)plotshape(buy? dynamicHMA-atrPos:na,color=color.green, location=location.absolute, style=shape.labelup, text="buy", textcolor=color.white, size = size.small)⋯if buy- alert("Buy signal at "+tostring(close), alert.freq_once_per_bar_close)+ alert("Buy signal at "+str.tostring(close), alert.freq_once_per_bar_close)if sell- alert("Sell signal at "+tostring(close), alert.freq_once_per_bar_close)+ alert("Sell signal at "+str.tostring(close), alert.freq_once_per_bar_close)if overBuy- alert("OverBuy signal at "+tostring(close), alert.freq_once_per_bar_close)+ alert("OverBuy signal at "+str.tostring(close), alert.freq_once_per_bar_close)if overSell- alert("OverSell signal at "+tostring(close), alert.freq_once_per_bar_close)+ alert("OverSell signal at "+str.tostring(close), alert.freq_once_per_bar_close)if doubleUp and secondBuy- alert("2nd Buy signal at "+tostring(close), alert.freq_once_per_bar_close)+ alert("2nd Buy signal at "+str.tostring(close), alert.freq_once_per_bar_close)if doubleUp and secondSell- alert("2nd Sell signal at "+tostring(close), alert.freq_once_per_bar_close)+ alert("2nd Sell signal at "+str.tostring(close), alert.freq_once_per_bar_close)//}...signals⋯ // to be outside this max point, then this one will be use as SL.-lastHigh = highest(high, 48) + (5 * pip()) //<--Last High/Low. If use as SL-point, adjust the lookback length +lastHigh = ta.highest(high, 48) + (5 * pip()) //<--Last High/Low. If use as SL-point, adjust the lookback length -lastLow = lowest(low, 48) - (5 * pip()) // according to where your comfort lies (and position-size).+lastLow = ta.lowest(low, 48) - (5 * pip()) // according to where your comfort lies (and position-size).//Delivering SL from inputs⋯//Simplified RSI Exits-RSIexitBuy = crossunder(rsi,70) or rsi<50+RSIexitBuy = ta.crossunder(rsi,70) or rsi<50-RSIexitSell = crossover(rsi,30) or rsi>50+RSIexitSell = ta.crossover(rsi,30) or rsi>50//Exit Conditions-exitBuy = ( close >= minBuyProfit and (RSIexitBuy or crossunder(close,dynamicHMA)) ) or stopLossBuy or takeProfitBuy +exitBuy = ( close >= minBuyProfit and (RSIexitBuy or ta.crossunder(close,dynamicHMA)) ) or stopLossBuy or takeProfitBuy -exitSell = ( close <= minSellProfit and (RSIexitSell or crossover(close,dynamicHMA) ) ) or stopLossSell or takeProfitSell+exitSell = ( close <= minSellProfit and (RSIexitSell or ta.crossover(close,dynamicHMA) ) ) or stopLossSell or takeProfitSell-exitoverBuy = ( close >= minBuyProfit and (crossunder(rsi,45) or (open<stopupperTL and hl2<stopupperTL)) ) or (open<dynamicHMA and rsi<60)+exitoverBuy = ( close >= minBuyProfit and (ta.crossunder(rsi,45) or (open<stopupperTL and hl2<stopupperTL)) ) or (open<dynamicHMA and rsi<60) or stopLossBuy or takeProfitBuy -exitoverSell = ( close <= minSellProfit and (crossover(rsi,55) or (open>stoplowerTL and hl2>stoplowerTL)) ) or (open>dynamicHMA and rsi>40)+exitoverSell = ( close <= minSellProfit and (ta.crossover(rsi,55) or (open>stoplowerTL and hl2>stoplowerTL)) ) or (open>dynamicHMA and rsi>40) or stopLossSell or takeProfitSell //Alternative 2nd Exits at Robin's (or SL)-exitSecondBuy = (close >= minBuyProfit and crossunder(close, minorHMA)) or stopLossBuy+exitSecondBuy = (close >= minBuyProfit and ta.crossunder(close, minorHMA)) or stopLossBuy-exitSecondSell = (close <= minSellProfit and crossover(close, minorHMA)) or stopLossSell+exitSecondSell = (close <= minSellProfit and ta.crossover(close, minorHMA)) or stopLossSell ⋯ if normOrder == 1 and exitBuy - normOrder := 0, alert("Close Buy Position/s at "+tostring(close), alert.freq_once_per_bar_close)+ normOrder := 0, alert("Close Buy Position/s at "+str.tostring(close), alert.freq_once_per_bar_close) if normOrder == 1 and exitSell- normOrder := 0, alert("Close Sell Position/s at "+tostring(close), alert.freq_once_per_bar_close)+ normOrder := 0, alert("Close Sell Position/s at "+str.tostring(close), alert.freq_once_per_bar_close) if riskOrder == 1 and exitoverBuy - riskOrder := 0, alert("Close overBuy Position/s at "+tostring(close), alert.freq_once_per_bar_close)+ riskOrder := 0, alert("Close overBuy Position/s at "+str.tostring(close), alert.freq_once_per_bar_close) if riskOrder == 1 and exitoverSell- riskOrder := 0, alert("Close overSell Position/s at "+tostring(close), alert.freq_once_per_bar_close)+ riskOrder := 0, alert("Close overSell Position/s at "+str.tostring(close), alert.freq_once_per_bar_close)if in2ndBuyExit- alert("Close 2nd Buy Position/s at "+tostring(close), alert.freq_once_per_bar_close)+ alert("Close 2nd Buy Position/s at "+str.tostring(close), alert.freq_once_per_bar_close)if in2ndSellExit- alert("Close 2nd Sell Position/s at "+tostring(close), alert.freq_once_per_bar_close)+ alert("Close 2nd Sell Position/s at "+str.tostring(close), alert.freq_once_per_bar_close) ⋯// plot(strategy.position_size>0? minBuyProfit : strategy.position_size<0? minSellProfit : na, color=orderCol, style=plot.style_linebr, linewidth=1, title="Minimum Profit")-plot(strategy.position_size != 0? entryPrice:na, style=plot.style_cross, transp=50)+plot(strategy.position_size != 0? entryPrice:na, style=plot.style_cross)-plot(useSL and strategy.position_size>0? buySL : useSL and strategy.position_size<0? sellSL : na, color=color.red, style=plot.style_cross, linewidth=1, title="Stop Loss", transp=50)+plot(useSL and strategy.position_size>0? buySL : useSL and strategy.position_size<0? sellSL : na, color=color.new(color.red, 50), style=plot.style_cross, linewidth=1, title="Stop Loss")-plot(strategy.position_size>0? buyTP : strategy.position_size<0? sellTP : na, color=color.green, style=plot.style_cross, linewidth=1, title="Take Profit", transp=50)+plot(strategy.position_size>0? buyTP : strategy.position_size<0? sellTP : na, color=color.new(color.green, 50), style=plot.style_cross, linewidth=1, title="Take Profit")//}...orders⋯mUnit = lotSize*pip()-ppip = round((strategy.grossprofit-strategy.grossprofit[1]) / syminfo.pointvalue/mUnit,1)+ppip = math.round((strategy.grossprofit-strategy.grossprofit[1]) / syminfo.pointvalue/mUnit,1)-lpip = round((strategy.grossloss-strategy.grossloss[1]) / syminfo.pointvalue/mUnit,1)+lpip = math.round((strategy.grossloss-strategy.grossloss[1]) / syminfo.pointvalue/mUnit,1)-pipGain = round((strategy.grossprofit/syminfo.pointvalue)/mUnit)+pipGain = math.round((strategy.grossprofit/syminfo.pointvalue)/mUnit)-pipLoss = round((strategy.grossloss/syminfo.pointvalue)/mUnit)+pipLoss = math.round((strategy.grossloss/syminfo.pointvalue)/mUnit)-avg_ppip = round((pipGain/strategy.wintrades),1)+avg_ppip = math.round((pipGain/strategy.wintrades),1)-pctProfit = round(strategy.wintrades/strategy.closedtrades * 100, 2)+pctProfit = math.round(strategy.wintrades/strategy.closedtrades * 100, 2)-maxDD = ceil(strategy.max_drawdown/ syminfo.pointvalue/mUnit) //check if our margin can handle DD's pips*orderSize+maxDD = math.ceil(strategy.max_drawdown/ syminfo.pointvalue/mUnit) //check if our margin can handle DD's pips*orderSizevar txt2 = ""-txt = "Total trades: "+ tostring(strategy.closedtrades)+"\n("+tostring(pctProfit)+"%) Win: "+tostring(strategy.wintrades)+" / Loss: "+tostring(strategy.losstrades)++txt = "Total trades: "+ str.tostring(strategy.closedtrades)+"\n("+str.tostring(pctProfit)+"%) Win: "+str.tostring(strategy.wintrades)+" / Loss: "+str.tostring(strategy.losstrades)+- "\nAverage win pips per trade: "+ tostring(avg_ppip) + " pips\n\nApproximate (*give n take)\nTotal Pip Gain: "+ tostring(pipGain) +" pips"++ "\nAverage win pips per trade: "+ str.tostring(avg_ppip) + " pips\n\nApproximate (*give n take)\nTotal Pip Gain: "+ str.tostring(pipGain) +" pips"+- "\nTotal Pip Loss: "+tostring(pipLoss)+ " pips"+"\n\nMax Drawdown so far: "+tostring(maxDD)+" pips"+ "\nTotal Pip Loss: "+str.tostring(pipLoss)+ " pips"+"\n\nMax Drawdown so far: "+str.tostring(maxDD)+" pips"if strategy.wintrades>strategy.wintrades[1]- txt2 := "\n\nLast closed trade: Bagged "+tostring(ppip)+" pips 👻"+ txt2 := "\n\nLast closed trade: Bagged "+str.tostring(ppip)+" pips 👻"if strategy.losstrades>strategy.losstrades[1]- txt2 := "\n\nLast closed trade: Blew "+tostring(lpip)+" pips 😪"+ txt2 := "\n\nLast closed trade: Blew "+str.tostring(lpip)+" pips 😪"txt += txt2⋯Clean v5
VerifiedSame 9 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 11: input() → input.float()
- Line 12: input() → input.int()
- Line 13: input() → input.int()
- Line 14: input() → input.bool()
- Line 15: input() → input.string()
- Line 17: input() → input.float()
26 more edits
- Line 18: input() → input.bool()
- Line 19: input() → input.int()
- Line 20: input() → input.int()
- Line 21: input() → input.int()
- Line 22: input() → input.int()
- Line 23: input() → input.int()
- Line 24: input() → input.bool()
- Line 25: input() → input.float()
- Line 26: input() → input.int()
- Line 27: input() → input.int()
- Line 28: input() → input.bool()
- Line 29: input() → input.bool()
- Line 30: input() → input.source()
- Line 30: input() → input.int()
- Line 211: when = buy → if block
- Line 212: when = sell → if block
- Line 213: when = overBuy → if block
- Line 214: when = overSell → if block
- Line 216: when = secondBuy → if block
- Line 217: when = secondSell → if block
- Line 222: when = exitBuy → if block
- Line 223: when = exitSell → if block
- Line 224: when = exitoverBuy → if block
- Line 225: when = exitoverSell → if block
- Line 227: when = exitSecondBuy → if block
- Line 228: when = exitSecondSell → if block
⋯//{ INPUTS-orderSize = input(0.1, title="Order Size (in Lot)", step=.1, group="ORDERS")+orderSize = input.float(0.1, title="Order Size (in Lot)", step=.1, group="ORDERS")-minProfit = input(1, step=.1, title="Base Minimum Profit before exit (ATR)", group="ORDERS") * atrBase+minProfit = input.int(1, step=.1, title="Base Minimum Profit before exit (ATR)", group="ORDERS") * atrBase-takeProfit = input(3, step=.1, title="Default Target Profit (ATR)", group="ORDERS") * atrBase+takeProfit = input.int(3, step=.1, title="Default Target Profit (ATR)", group="ORDERS") * atrBase-useSL = input(true, title="Use StopLoss", group="ORDERS")+useSL = input.bool(true, title="Use StopLoss", group="ORDERS")-SLInput = input("Half Distance Zone", title="Base StopLoss Point", +SLInput = input.string("Half Distance Zone", title="Base StopLoss Point", options=["One Distance Zone", "Half Distance Zone", "Last High/Low", "ATR Only"], group="ORDERS")-maxSL = input(4.5, step=.1, title="Maximum StopLoss (ATR)", group="ORDERS") * atrBase+maxSL = input.float(4.5, step=.1, title="Maximum StopLoss (ATR)", group="ORDERS") * atrBase-doubleUp = input(false, "Activate 2nd order with xHMA+ exits", group="ORDERS") //If enable, set pyramiding to at least: 2+doubleUp = input.bool(false, "Activate 2nd order with xHMA+ exits", group="ORDERS") //If enable, set pyramiding to at least: 2-minLength = input(172, title="Minimum:", group="Adaptive HMA+ Period", inline="HMA+")+minLength = input.int(172, title="Minimum:", group="Adaptive HMA+ Period", inline="HMA+")-maxLength = input(233, title="Maximum:", group="Adaptive HMA+ Period", inline="HMA+")+maxLength = input.int(233, title="Maximum:", group="Adaptive HMA+ Period", inline="HMA+")-flat = input(17, title="Flat Market when xHMA's slope below", group="Market Movement")+flat = input.int(17, title="Flat Market when xHMA's slope below", group="Market Movement")-atrFast = input(14, "Charged if ATR", group="Market Movement", inline="volality", minval=2, maxval=34)+atrFast = input.int(14, "Charged if ATR", group="Market Movement", inline="volality", minval=2, maxval=34)-atrSlow = input(46, ">= ATR", group="Market Movement", inline="volality", minval=21, maxval=120)+atrSlow = input.int(46, ">= ATR", group="Market Movement", inline="volality", minval=21, maxval=120)-showZone = input(false, title="Show Adaptive HMA+ Distance Zone", group="DISTANCE ZONE")+showZone = input.bool(false, title="Show Adaptive HMA+ Distance Zone", group="DISTANCE ZONE")-mult = input(2.7, title="Distance (Envelope) Multiplier", step=.1, group="DISTANCE ZONE") +mult = input.float(2.7, title="Distance (Envelope) Multiplier", step=.1, group="DISTANCE ZONE") -minorMin = input(89, title="Minimum:", group="Minor Adaptive HMA+ Period", inline="mHMA+")+minorMin = input.int(89, title="Minimum:", group="Minor Adaptive HMA+ Period", inline="mHMA+")-minorMax = input(121, title="Maximum:", group="Minor Adaptive HMA+ Period", inline="mHMA+")+minorMax = input.int(121, title="Maximum:", group="Minor Adaptive HMA+ Period", inline="mHMA+")-showMA = input(true, title="Show MA?", group="OTHER")+showMA = input.bool(true, title="Show MA?", group="OTHER")-useBg = input(true, title="Background color to differentiate movement", group="OTHER")+useBg = input.bool(true, title="Background color to differentiate movement", group="OTHER")-rsi = ta.rsi(input(close,"RSI Source", inline="RSI", group="OTHER"), input(14, "RSI Length", inline="RSI", group="OTHER"))+rsi = ta.rsi(input.source(close,"RSI Source", inline="RSI", group="OTHER"), input.int(14, "RSI Length", inline="RSI", group="OTHER"))//}...inputs⋯//ENTRIES-strategy.entry("buy", strategy.long, qty=lotSize, when=buy )+if buy+ strategy.entry("buy", strategy.long, qty=lotSize )-strategy.entry("sell", strategy.short, qty=lotSize, when=sell)+if sell+ strategy.entry("sell", strategy.short, qty=lotSize)-strategy.entry("overBuy", strategy.long, qty=lotSize, when=overBuy )+if overBuy+ strategy.entry("overBuy", strategy.long, qty=lotSize )-strategy.entry("overSell", strategy.short, qty=lotSize, when=overSell)+if overSell+ strategy.entry("overSell", strategy.short, qty=lotSize)if doubleUp- strategy.entry("2ndBuy", strategy.long, qty=lotSize, when=secondBuy )+ if secondBuy+ strategy.entry("2ndBuy", strategy.long, qty=lotSize )- strategy.entry("2ndSell", strategy.short, qty=lotSize, when=secondSell) + if secondSell+ strategy.entry("2ndSell", strategy.short, qty=lotSize) //EXITS⋯//accordingly. And delete stopLossBuy, stopLossSell, takeProfitBuy, takeProfitSell definitions from above.-strategy.close("buy", when=exitBuy , comment="close buy")+if exitBuy+ strategy.close("buy" , comment="close buy")-strategy.close("sell", when=exitSell, comment="close sell")+if exitSell+ strategy.close("sell", comment="close sell")-strategy.close("overBuy", when=exitoverBuy , comment="close overBuy")+if exitoverBuy+ strategy.close("overBuy" , comment="close overBuy")-strategy.close("overSell", when=exitoverSell, comment="close overSell")+if exitoverSell+ strategy.close("overSell", comment="close overSell")if doubleUp- strategy.close("2ndBuy", when=exitSecondBuy , comment="close 2nd Buy")+ if exitSecondBuy+ strategy.close("2ndBuy" , comment="close 2nd Buy")- strategy.close("2ndSell", when=exitSecondSell, comment="close 2nd Sell")+ if exitSecondSell+ strategy.close("2ndSell", comment="close 2nd Sell")//}---actions⋯Does it run in Pine Script v6?
No
The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 9 before, 0 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// 2020 © io72signals / Antorio Bergasdito-//@version=5+//@version=6strategy("72s Strategy: Adaptive Hull Moving Average+ pt.1", shorttitle="72s Strat: Adaptive HMA+ pt.1", overlay=true, ⋯Settings
Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| ORDERS | |||
| Order Size (in Lot) | 0.1 | float · step .1 | lotSize |
| Base Minimum Profit before exit (ATR) | 1 | int · step .1 | minBuyProfit minSellProfit |
| Default Target Profit (ATR) | 3 | int · step .1 | buyTP sellTP |
| Use StopLoss | true | bool | stopLossBuy stopLossSell Stop Loss |
| Base StopLoss Point | Half Distance Zone | string · options ["One Distance Zone", "Half Distance Zone", "Last High/Low", "ATR Only"] | SLBuy SLSell |
| Maximum StopLoss (ATR) | 4.5 | float · step .1 | SLHighMax SLLowMax |
| Activate 2nd order with xHMA+ exits | false | bool | in2ndBuyExit in2ndSellExit entry 2ndBuy entry 2ndSell close 2ndBuy close 2ndSell plotshape line 115 line 117 line 215 line 226 |
| Adaptive HMA+ Period | |||
| Minimum: | 172 | int | dynamicLength |
| Maximum: | 233 | int | dynamicLength |
| Market Movement | |||
| Flat Market when xHMA's slope below | 17 | int | notgreat upSig dnSig line 54 line 55 line 56 |
| Charged if ATR | 14 | int · min 2 · max 34 | charged |
| >= ATR | 46 | int · min 21 · max 120 | charged |
| DISTANCE ZONE | |||
| Show Adaptive HMA+ Distance Zone | false | bool | sutl sltl colZone plot |
| Distance (Envelope) Multiplier | 2.7 | float · step .1 | upperTL lowerTL topTL botTL stopupperTL stoplowerTL |
| Minor Adaptive HMA+ Period | |||
| Minimum: | 89 | int | minorLength |
| Maximum: | 121 | int | minorLength |
| OTHER | |||
| Show MA? | true | bool | Adaptive HMA+ minor HMA+ |
| Background color to differentiate movement | true | bool | bgcolor |
| RSI Source | close | source | buy sell overBuy overSell secondBuy secondSell RSIexitBuy RSIexitSell exitoverBuy exitoverSell |
| RSI Length | 14 | int | buy sell overBuy overSell secondBuy secondSell RSIexitBuy RSIexitSell exitoverBuy exitoverSell |
What it calculates
- ATR (
atr,ta.atrin v5)21atrBase · line 7 - Highest (
highest,ta.highestin v5)34highestHigh · line 42 - Lowest (
lowest,ta.lowestin v5)34lowestLow · line 42 - WMA (
wma,ta.wmain v5)2 * wma(_src, _length / 2) - wma(_src, _length), floor(sqrt(_length))_return · line 58 - ATR (
atr,ta.atrin v5)40upperTL · line 65 - ATR (
atr,ta.atrin v5)40lowerTL · line 65 - ATR (
atr,ta.atrin v5)40topTL · line 66 - ATR (
atr,ta.atrin v5)40botTL · line 66 - ATR (
atr,ta.atrin v5)40stopupperTL · line 67 - ATR (
atr,ta.atrin v5)40stoplowerTL · line 67 - EMA (
ema,ta.emain v5)close, 200emma200 · line 83 - ATR (
atr,ta.atrin v5)5atrPos · line 99 - Highest (
highest,ta.highestin v5)high, 48lastHigh · line 134 - Lowest (
lowest,ta.lowestin v5)low, 48lastLow · line 135
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 136 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open buy long | buyupSig and not upSig[1] and close>dynamicHMA and low<=upperTL and (rsi>51 and rsi<=70) | On | 211 |
| Open sell short | selldnSig and not dnSig[1] and close<dynamicHMA and high>=lowerTL and (rsi<49 and rsi>=30) | On | 212 |
| Open overBuy long | overBuyupSig and not upSig[1] and rsi>70 and close>dynamicHMA and hl2>upperTL and minorHMA>dynamicHMA | On | 213 |
| Open overSell short | overSelldnSig and not dnSig[1] and rsi<30 and close<dynamicHMA and hl2<lowerTL and minorHMA<dynamicHMA | On | 214 |
| Open 2ndBuy long | secondBuy(buy or overBuy) and rsi[1]<rsi | Off “Activate 2nd order with xHMA+ exits” | 216 |
| Open 2ndSell short | secondSell(sell or overSell) and rsi[1]>rsi | Off “Activate 2nd order with xHMA+ exits” | 217 |
| Close buy | exitBuy( close >= minBuyProfit and (RSIexitBuy or crossunder(close,dynamicHMA)) ) or stopLossBuy or takeProfitBuy | On | 222 |
| Close sell | exitSell( close <= minSellProfit and (RSIexitSell or crossover(close,dynamicHMA) ) ) or stopLossSell or takeProfitSell | On | 223 |
| Close overBuy | exitoverBuy( close >= minBuyProfit and (crossunder(rsi,45) or (open<stopupperTL and hl2<stopupperTL)) ) or (open<dynamicHMA and rsi<60)
or stopLossBuy or takeProfitBuy | On | 224 |
| Close overSell | exitoverSell( close <= minSellProfit and (crossover(rsi,55) or (open>stoplowerTL and hl2>stoplowerTL)) ) or (open>dynamicHMA and rsi>40)
or stopLossSell or takeProfitSell | On | 225 |
| Close 2ndBuy | exitSecondBuy(close >= minBuyProfit and crossunder(close, minorHMA)) or stopLossBuy | Off “Activate 2nd order with xHMA+ exits” | 227 |
| Close 2ndSell | exitSecondSell(close <= minSellProfit and crossover(close, minorHMA)) or stopLossSell | Off “Activate 2nd order with xHMA+ exits” | 228 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| (no title) | alert | "Buy signal at "+tostring(close) | 108 |
| (no title) | alert | "Sell signal at "+tostring(close) | 110 |
| (no title) | alert | "OverBuy signal at "+tostring(close) | 112 |
| (no title) | alert | "OverSell signal at "+tostring(close) | 114 |
| (no title) | alert | "2nd Buy signal at "+tostring(close) | 116 |
| (no title) | alert | "2nd Sell signal at "+tostring(close) | 118 |
| (no title) | alert | "Close Buy Position/s at "+tostring(close) | 192 |
| (no title) | alert | "Close Sell Position/s at "+tostring(close) | 194 |
| (no title) | alert | "Close overBuy Position/s at "+tostring(close) | 196 |
| (no title) | alert | "Close overSell Position/s at "+tostring(close) | 198 |
| (no title) | alert | "Close 2nd Buy Position/s at "+tostring(close) | 200 |
| (no title) | alert | "Close 2nd Sell Position/s at "+tostring(close) | 202 |
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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Richard's Strategy by Deepak8369 | highest lowest atr ema | v4 strategy | +34.6% | 70 | 26.3% |
| Classic Long Term Trend Following System by Robrecht99 | ema highest lowest atr | v5 strategy | +2.9% | 5 | 1.1% |
| Strategy Myth-Busting #1 - UT Bot+STC+Hull [MYN] by myncrypto | atr ema lowest highest | v5 strategy | −30.7% | 10 | 63.5% |
| Strategy for UT Bot Alerts indicator by StrategiesForEveryone | ema atr highest lowest | v5 strategy | −4.5% | 42 | 15.7% |
| Simple and Profitable Scalping Strategy (ForexSignals TV) by kevinmck100 | ema atr highest lowest | v5 strategy | No trades on this market | ||
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | No Pine Script v4 Error at @L246:C13: 'strategy.max_drawdown' is not available in Pine Script v4. It was added in a later version. | Not measured | |
| PineTS | No v5 and v6 only | — | Not measured |
“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/// 2020 © io72signals / Antorio Bergasdito//@version=4strategy("72s Strategy: Adaptive Hull Moving Average+ pt.1", shorttitle="72s Strat: Adaptive HMA+ pt.1", overlay=true, pyramiding=1, initial_capital=1000, commission_type=strategy.commission.cash_per_order, commission_value=.5, slippage=3, max_bars_back=1000)atrBase = atr(21)src = closeadaptPct = 0.03141//{ INPUTSorderSize = input(0.1, title="Order Size (in Lot)", step=.1, group="ORDERS")minProfit = input(1, step=.1, title="Base Minimum Profit before exit (ATR)", group="ORDERS") * atrBasetakeProfit = input(3, step=.1, title="Default Target Profit (ATR)", group="ORDERS") * atrBaseuseSL = input(true, title="Use StopLoss", group="ORDERS")SLInput = input("Half Distance Zone", title="Base StopLoss Point", options=["One Distance Zone", "Half Distance Zone", "Last High/Low", "ATR Only"], group="ORDERS")maxSL = input(4.5, step=.1, title="Maximum StopLoss (ATR)", group="ORDERS") * atrBasedoubleUp = input(false, "Activate 2nd order with xHMA+ exits", group="ORDERS") //If enable, set pyramiding to at least: 2minLength = input(172, title="Minimum:", group="Adaptive HMA+ Period", inline="HMA+")maxLength = input(233, title="Maximum:", group="Adaptive HMA+ Period", inline="HMA+")flat = input(17, title="Flat Market when xHMA's slope below", group="Market Movement")atrFast = input(14, "Charged if ATR", group="Market Movement", inline="volality", minval=2, maxval=34)atrSlow = input(46, ">= ATR", group="Market Movement", inline="volality", minval=21, maxval=120)showZone = input(false, title="Show Adaptive HMA+ Distance Zone", group="DISTANCE ZONE")mult = input(2.7, title="Distance (Envelope) Multiplier", step=.1, group="DISTANCE ZONE") minorMin = input(89, title="Minimum:", group="Minor Adaptive HMA+ Period", inline="mHMA+")minorMax = input(121, title="Maximum:", group="Minor Adaptive HMA+ Period", inline="mHMA+")showMA = input(true, title="Show MA?", group="OTHER")useBg = input(true, title="Background color to differentiate movement", group="OTHER")rsi = rsi(input(close,"RSI Source", inline="RSI", group="OTHER"), input(14, "RSI Length", inline="RSI", group="OTHER"))//}...inputs//{ ADAPTIVE HMA+//Condition to adapt to:charged = atr(atrFast) > atr(atrSlow) //<--Volatility Meter. Change it to whatever match your strat/pair/tf.//Dynamics var float dynamicLength = avg(minLength,maxLength)var float minorLength = avg(minorMin,minorMax)dynamicLength := iff(charged, max(minLength, dynamicLength * (1 - adaptPct)), min(maxLength, dynamicLength * (1 + adaptPct)))minorLength := iff(charged, max(minorMin, minorLength * (1 - adaptPct)), min(minorMax, minorLength * (1 + adaptPct)))//Slope calculation to determine whether market is in trend, or in consolidation or choppy, or might about to change current trendpi = atan(1) * 4highestHigh = highest(34), lowestLow = lowest(34)slope_range = 25 / (highestHigh - lowestLow) * lowestLowcalcslope(_ma)=> dt = (_ma[2] - _ma) / src * slope_range c = sqrt(1 + dt * dt) xAngle = round(180 * acos(1 / c) / pi) maAngle = iff(dt > 0, -xAngle, xAngle) maAngle //MA coloring+ to mark market dynamics dynColor(_ma,_col1a,_col1b,_col2a,_col2b,_col0) => slope = calcslope(_ma) slope >= flat ? charged? _col1a : _col1b : slope < flat and slope > -flat ? _col0 : slope <= -flat ? charged? _col2a : _col2b : _col0//Adaptive HMA xhma(_src,_length) => _return = wma(2 * wma(_src, _length / 2) - wma(_src, _length), floor(sqrt(_length))) dynamicHMA = xhma(src,int(dynamicLength)) //<--Batman - Our main xHMA+minorHMA = xhma(src,int(minorLength)) //<--Robin - Faster minor xHMA+ (Optional). Can be use to assist for // faster entry, slower exit point, or pullbacks info too._slope = calcslope(dynamicHMA)plotchar(_slope, "slope is:", "", location.top) //<--Output current slope to Data Window, for our reference when optimizing Strategy//Envelope the main DynamicHMA with ATR band, just one way to approximate current price distance to MA. Other usages/methods may vary.upperTL = dynamicHMA + mult * atr(40) , lowerTL = dynamicHMA - mult * atr(40) //<--Half distance zonetopTL = dynamicHMA + (mult*2) * atr(40) , botTL = dynamicHMA - (mult*2) * atr(40) //<--One distance zonestopupperTL = dynamicHMA + (mult/2) * atr(40), stoplowerTL = dynamicHMA - (mult/2) * atr(40) //<--Half of the half. If need ie. tighter SL or trailing//Plotting Distance Zoneplot(showZone?upperTL:na, color=color.green, transp=72)plot(showZone?lowerTL:na, color=color.red, transp=72)plot(showZone?topTL:na, color=color.gray, transp=72)plot(showZone?botTL:na, color=color.gray, transp=72)sutl = plot(showZone?stopupperTL:na, color=color.white, transp=100)sltl = plot(showZone?stoplowerTL:na, color=color.white, transp=100)colZone = showZone? color.purple:color.new(color.white,100)fill(sutl, sltl, color=colZone, transp=90)plot(showMA?dynamicHMA:na, "Adaptive HMA+", dynColor(dynamicHMA, #6fbf73, #c0f5ae, #eb4d5c, #f2b1d4, color.yellow), 3)plot(showMA?minorHMA:na, "minor HMA+", dynColor(minorHMA, #6fbf73, #c0f5ae, #eb4d5c, #f2b1d4, color.yellow), 1)//Backgroud color to differentiate market conditionnotgreat = _slope < flat and _slope > -flatbgcolor(useBg? charged? na : #afb4b9 : na)//EMA 200. (Not being use in here. But since they've been a BFF since long, thought I'm just gonna put it here..)emma200 = ema(close,200) //, plot(emma200)//}...adaptive HMA+//{ SIGNALS//Base; When HMA+ turn to a darker color and market is out from low volatilityupSig = _slope >= flat and chargeddnSig = _slope <= -flat and charged//Default buy/sell, when market switchs to the above base condition, and typical price is still in tolerated distance, and RSI is on the right side.buy = upSig and not upSig[1] and close>dynamicHMA and low<=upperTL and (rsi>51 and rsi<=70)sell = dnSig and not dnSig[1] and close<dynamicHMA and high>=lowerTL and (rsi<49 and rsi>=30)//Alternative buy/sell, when price is a bit far from MA, and RSI is still on the same side but already on oversold/overbought (relatively).overBuy = upSig and not upSig[1] and rsi>70 and close>dynamicHMA and hl2>upperTL and minorHMA>dynamicHMAoverSell= dnSig and not dnSig[1] and rsi<30 and close<dynamicHMA and hl2<lowerTL and minorHMA<dynamicHMA//Alternative additional buy/sell with different exits at Robin's.secondBuy = (buy or overBuy) and rsi[1]<rsisecondSell = (sell or overSell) and rsi[1]>rsi//Plot 'em upatrPos = 0.2 * atr(5)plotshape(buy? dynamicHMA-atrPos:na,color=color.green, location=location.absolute, style=shape.labelup, text="buy", textcolor=color.white, size = size.small)plotshape(sell? dynamicHMA+atrPos:na, color=color.red, location=location.absolute, style=shape.labeldown, text="sell", textcolor=color.white, size = size.small)plotshape(overBuy? dynamicHMA-atrPos:na,color=color.green, location=location.absolute, style=shape.labelup, text="overBuy", textcolor=color.white, size = size.small)plotshape(overSell?dynamicHMA+atrPos:na, color=color.red, location=location.absolute, style=shape.labeldown, text="overSell", textcolor=color.white, size = size.small)plotshape(doubleUp and secondBuy? dynamicHMA-atrPos*8:na,color=color.green, location=location.absolute, style=shape.labelup, text="+buy", textcolor=color.white, size = size.small)plotshape(doubleUp and secondSell?dynamicHMA+atrPos*8:na, color=color.red, location=location.absolute, style=shape.labeldown, text="+sell", textcolor=color.white, size = size.small)//Alert if buy alert("Buy signal at "+tostring(close), alert.freq_once_per_bar_close)if sell alert("Sell signal at "+tostring(close), alert.freq_once_per_bar_close)if overBuy alert("OverBuy signal at "+tostring(close), alert.freq_once_per_bar_close)if overSell alert("OverSell signal at "+tostring(close), alert.freq_once_per_bar_close)if doubleUp and secondBuy alert("2nd Buy signal at "+tostring(close), alert.freq_once_per_bar_close)if doubleUp and secondSell alert("2nd Sell signal at "+tostring(close), alert.freq_once_per_bar_close)//}...signals//{ ORDERS//(I use Lot just because it's how I usually trade, matches my flow when thinking/planning. Change the "qty" in "strategy.entry()" below to use other UOM.)//Forex pairs are 100,000 units per 1 lot. Units per 1 lot vary on non-forex pairs, please check with your broker and change accordingly if necessary.//(ie: In MT4 and MT5 right click a symbol and then click Specification. The Contract Size field tells how many units are in one lot.)standard1LotUnits = syminfo.type == "forex" ? 100000 : syminfo.ticker == "XAUUSD" ? 100 : syminfo.ticker == "XAGUSD" ? 5000 : syminfo.type == "crypto" ? 1 : 1000lotSize = standard1LotUnits * orderSize pip() => syminfo.mintick * (syminfo.type == "forex" ? 10 : 1)//{ StopLossSLHighMax = high + maxSL, SLLowMax = low - maxSL //<--Maximum StopLoss. If a chosen SL-point from input above happen // to be outside this max point, then this one will be use as SL.lastHigh = highest(high, 48) + (5 * pip()) //<--Last High/Low. If use as SL-point, adjust the lookback length lastLow = lowest(low, 48) - (5 * pip()) // according to where your comfort lies (and position-size).//Delivering SL from inputsSLBuy = SLInput == "One Distance Zone"? botTL : SLInput == "Half Distance Zone"? lowerTL : SLInput == "Last High/Low"? lastLow : SLInput == "ATR Only"? SLLowMax : SLLowMaxSLSell= SLInput == "One Distance Zone"? topTL : SLInput == "Half Distance Zone"? upperTL : SLInput == "Last High/Low"? lastHigh: SLInput == "ATR Only"? SLHighMax: SLHighMax//}---stopLoss//float entryPrice = na, float normOrder = 0, float riskOrder = 0float buyTP = na, float sellTP = na, float buySL = na, float sellSL = naentryPrice := nz(entryPrice[1]), normOrder := nz(normOrder[1]), riskOrder := nz(riskOrder[1])buyTP:=nz(buyTP[1]), sellTP:=nz(sellTP[1]), buySL:=nz(buySL[1]), sellSL :=nz(sellSL[1])//This part will also make your TP/SL change dynamically if there's a new signal while you have an open position.//If you want to fire this TP/SL only in a new position, then add "strategy.position_size == 0" if (buy or sell or overBuy or overSell) //and strategy.position_size == 0 entryPrice := close if buy or sell and strategy.position_size == 0 normOrder := 1 if overBuy or overSell and strategy.position_size == 0 riskOrder := 1 buyTP := high + takeProfit sellTP := low - takeProfit if buy or overBuy buySL := SLLowMax<SLBuy? SLBuy:SLLowMax if sell or overSell sellSL:= SLHighMax>SLSell? SLSell:SLHighMax //Trailing Minimum-Profit. --Just a simple helper to prevent premature exit rule. Or at least to have a//change to get break-even (after commission) if market turns its back on us, before heading to stoploss area.minBuyProfit = strategy.position_avg_price + minProfit minSellProfit = strategy.position_avg_price - minProfit //{ Exit Points//TP/SL ExitsstopLossBuy = useSL? low <=buySL : nastopLossSell = useSL? high>=sellSL: natakeProfitBuy = high>= buyTPtakeProfitSell = low <= sellTP //Simplified RSI ExitsRSIexitBuy = crossunder(rsi,70) or rsi<50RSIexitSell = crossover(rsi,30) or rsi>50//Exit ConditionsexitBuy = ( close >= minBuyProfit and (RSIexitBuy or crossunder(close,dynamicHMA)) ) or stopLossBuy or takeProfitBuy exitSell = ( close <= minSellProfit and (RSIexitSell or crossover(close,dynamicHMA) ) ) or stopLossSell or takeProfitSellexitoverBuy = ( close >= minBuyProfit and (crossunder(rsi,45) or (open<stopupperTL and hl2<stopupperTL)) ) or (open<dynamicHMA and rsi<60) or stopLossBuy or takeProfitBuy exitoverSell = ( close <= minSellProfit and (crossover(rsi,55) or (open>stoplowerTL and hl2>stoplowerTL)) ) or (open>dynamicHMA and rsi>40) or stopLossSell or takeProfitSell //Alternative 2nd Exits at Robin's (or SL)exitSecondBuy = (close >= minBuyProfit and crossunder(close, minorHMA)) or stopLossBuyexitSecondSell = (close <= minSellProfit and crossover(close, minorHMA)) or stopLossSell //Plotting and Alert for ExitsinBuyExit = strategy.position_size > 0 and ((normOrder == 1 and exitBuy) or (riskOrder == 1 and exitoverBuy))inSellExit = strategy.position_size < 0 and ((normOrder == 1 and exitSell) or (riskOrder == 1 and exitoverSell))in2ndBuyExit = strategy.position_size > 0 and (doubleUp and exitSecondBuy)in2ndSellExit= strategy.position_size < 0 and (doubleUp and exitSecondSell)if inBuyExit or inSellExit if normOrder == 1 and exitBuy normOrder := 0, alert("Close Buy Position/s at "+tostring(close), alert.freq_once_per_bar_close) if normOrder == 1 and exitSell normOrder := 0, alert("Close Sell Position/s at "+tostring(close), alert.freq_once_per_bar_close) if riskOrder == 1 and exitoverBuy riskOrder := 0, alert("Close overBuy Position/s at "+tostring(close), alert.freq_once_per_bar_close) if riskOrder == 1 and exitoverSell riskOrder := 0, alert("Close overSell Position/s at "+tostring(close), alert.freq_once_per_bar_close)if in2ndBuyExit alert("Close 2nd Buy Position/s at "+tostring(close), alert.freq_once_per_bar_close)if in2ndSellExit alert("Close 2nd Sell Position/s at "+tostring(close), alert.freq_once_per_bar_close) plotchar(inBuyExit, color=color.green, location=location.abovebar, char="ⓧ", size=size.tiny)plotchar(inSellExit, color=color.red, location=location.belowbar, char="ⓧ", size=size.tiny)plotchar(in2ndBuyExit, color=color.teal, location=location.abovebar, char="ⓧ", size=size.tiny)plotchar(in2ndSellExit, color=color.maroon, location=location.belowbar, char="ⓧ", size=size.tiny)//}---exit points//{ Actions//ENTRIESstrategy.entry("buy", strategy.long, qty=lotSize, when=buy )strategy.entry("sell", strategy.short, qty=lotSize, when=sell)strategy.entry("overBuy", strategy.long, qty=lotSize, when=overBuy )strategy.entry("overSell", strategy.short, qty=lotSize, when=overSell)if doubleUp strategy.entry("2ndBuy", strategy.long, qty=lotSize, when=secondBuy ) strategy.entry("2ndSell", strategy.short, qty=lotSize, when=secondSell) //EXITS//We use just "strategy.close" because we already set limit conditions above for SL and TP, fires at candle close. If you want to//separate exit data or exit at the exact SL/TP you can add such as: strategy.exit("exitbuy", from_entry="buy", stop=buySL, limit=buyTP)//accordingly. And delete stopLossBuy, stopLossSell, takeProfitBuy, takeProfitSell definitions from above.strategy.close("buy", when=exitBuy , comment="close buy")strategy.close("sell", when=exitSell, comment="close sell")strategy.close("overBuy", when=exitoverBuy , comment="close overBuy")strategy.close("overSell", when=exitoverSell, comment="close overSell")if doubleUp strategy.close("2ndBuy", when=exitSecondBuy , comment="close 2nd Buy") strategy.close("2ndSell", when=exitSecondSell, comment="close 2nd Sell")//}---actionsorderCol = strategy.position_size>0? color.green : strategy.position_size<0? color.red : na// plot(strategy.position_size>0? minBuyProfit : strategy.position_size<0? minSellProfit : na, color=orderCol, style=plot.style_linebr, linewidth=1, title="Minimum Profit")plot(strategy.position_size != 0? entryPrice:na, style=plot.style_cross, transp=50)plot(useSL and strategy.position_size>0? buySL : useSL and strategy.position_size<0? sellSL : na, color=color.red, style=plot.style_cross, linewidth=1, title="Stop Loss", transp=50)plot(strategy.position_size>0? buyTP : strategy.position_size<0? sellTP : na, color=color.green, style=plot.style_cross, linewidth=1, title="Take Profit", transp=50)//}...orders//{------------------------------------------------------------------------//Below is just fancy stuff approximating gain in pips. You probably don't need this.//(Also I'm not too sure this is the right way calculating pip gain in pine. If somebody knows how, kindly correct me please)mUnit = lotSize*pip()ppip = round((strategy.grossprofit-strategy.grossprofit[1]) / syminfo.pointvalue/mUnit,1)lpip = round((strategy.grossloss-strategy.grossloss[1]) / syminfo.pointvalue/mUnit,1)pipGain = round((strategy.grossprofit/syminfo.pointvalue)/mUnit)pipLoss = round((strategy.grossloss/syminfo.pointvalue)/mUnit)avg_ppip = round((pipGain/strategy.wintrades),1)pctProfit = round(strategy.wintrades/strategy.closedtrades * 100, 2)maxDD = ceil(strategy.max_drawdown/ syminfo.pointvalue/mUnit) //check if our margin can handle DD's pips*orderSizevar txt2 = ""txt = "Total trades: "+ tostring(strategy.closedtrades)+"\n("+tostring(pctProfit)+"%) Win: "+tostring(strategy.wintrades)+" / Loss: "+tostring(strategy.losstrades)+ "\nAverage win pips per trade: "+ tostring(avg_ppip) + " pips\n\nApproximate (*give n take)\nTotal Pip Gain: "+ tostring(pipGain) +" pips"+ "\nTotal Pip Loss: "+tostring(pipLoss)+ " pips"+"\n\nMax Drawdown so far: "+tostring(maxDD)+" pips"if strategy.wintrades>strategy.wintrades[1] txt2 := "\n\nLast closed trade: Bagged "+tostring(ppip)+" pips 👻"if strategy.losstrades>strategy.losstrades[1] txt2 := "\n\nLast closed trade: Blew "+tostring(lpip)+" pips 😪"txt += txt2label pvtLabel = label.new(time, lowestLow, text=txt, color=color.new(color.white,100), xloc=xloc.bar_time, style=label.style_label_left, textcolor=color.gray, textalign=text.align_left)label.set_x(pvtLabel, label.get_x(pvtLabel) + ((time-time[1]) * 21))label.delete(pvtLabel[1])//}