Pine Script v4 · Strategy
Reversal closing price
A Pine Script v4 strategy built on Change (close, _period), Rising (shortMa, 1) and Falling (shortMa, 1). It has 15 order rules, 3 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 1000 in cash and pays no commission. 23 settings; defaults include Order direction Both, 1st target reward to risk ratio 1.0 and 1st target liquidation percent 0.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 Reversal closing price repaint?
- No
- No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 14 of 14 trades.
- How did Reversal closing price do on BTCUSDT 1D with default settings?
- −9.99%
- From 26 Jan 2024 to 21 Oct 2026, over 53 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Can Reversal closing price be converted to Pine Script v5?
- Yes
- The upgrade takes 1 step, from v4; each was run before and after on the same candles with identical results, and the v5 script can be downloaded below.
- Does Reversal closing price use a stop loss?
- Yes
- strategy.exit sets a stop on line 178, 179, 180, 181.
- Does Reversal closing price run in Zeal Terminal?
- Yes
- It compiles in 56 ms and runs 1,000 bars in 107 ms, in the browser.
BTCUSDT · 1D · default settings
- MA short
- MA long
- Stop price
- Second take profit price
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- −9.99%
- −$9,992.90
- Buy and hold
- +102.5%
- same period
- Closed trades
- 53
- 15 won · 38 lost
- Profitable
- 28.3%
- of closed trades
- Profit factor
- 0.74
- gross profit ÷ gross loss
- Max drawdown
- 10.69%
- −$10,688.00
One run with the author's default settings, $100,000 starting capital, commission as the script sets it. A long position was still open at the last bar. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.
Review
What a careful reader of this script would point out, found by checking the source and the backtest.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
-
Note
Uses an argument v6 removed
when = on line 178, 180. The upgraded version below moves each call inside an if block.
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 abs → math.abs, change → ta.change, sum → math.sum, pow → math.pow, ema → ta.ema, hma → ta.hma, sma → ta.sma, wma → ta.wma, sign → math.sign, rising → ta.rising, falling → ta.falling, stoch → ta.stoch, rsi → ta.rsi, lowest → ta.lowest, highest → ta.highest, barssince → ta.barssince, round_to_mintick → math.round_to_mintick, tostring → str.tostring, pivotlow → ta.pivotlow, pivothigh → ta.pivothigh, max → math.max.
- 2 strategy calls use the when = argument (line 178, 180). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
v4 → v5
VerifiedSame 53 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 1: //@version=4 → //@version=5
- Line 41: abs → math.abs
- Line 41: change → ta.change
- Line 42: sum → math.sum
- Line 42: abs → math.abs
- Line 42: change → ta.change
39 more edits
- Line 44: pow → math.pow
- Line 47: ema → ta.ema
- Line 48: hma → ta.hma
- Line 50: sma → ta.sma
- Line 51: wma → ta.wma
- Line 55: sign → math.sign
- Line 56: rising → ta.rising
- Line 57: rising → ta.rising
- Line 58: falling → ta.falling
- Line 59: falling → ta.falling
- Line 88: sma → ta.sma
- Line 88: sma → ta.sma
- Line 88: stoch → ta.stoch
- Line 88: rsi → ta.rsi
- Line 92: lowest → ta.lowest
- Line 93: highest → ta.highest
- Line 107: strategy.entry(…, true) → strategy.entry(…, strategy.long)
- Line 109: barssince → ta.barssince
- Line 110: round_to_mintick → math.round_to_mintick
- Line 111: tostring → str.tostring
- Line 113: pivotlow → ta.pivotlow
- Line 114: pivothigh → ta.pivothigh
- Line 127: lowest → ta.lowest
- Line 128: highest → ta.highest
- Line 140: abs → math.abs
- Line 141: abs → math.abs
- Line 154: strategy.entry(…, true) → strategy.entry(…, strategy.long)
- Line 155: tostring → str.tostring
- Line 158: strategy.entry(…, false) → strategy.entry(…, strategy.short)
- Line 159: tostring → str.tostring
- Line 185: barssince → ta.barssince
- Line 186: barssince → ta.barssince
- Line 187: barssince → ta.barssince
- Line 188: falling → ta.falling
- Line 188: max → math.max
- Line 189: rising → ta.rising
- Line 189: max → math.max
- Line 199: barssince → ta.barssince
- Line 202: barssince → ta.barssince
-//@version=4+//@version=5// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/⋯getKama(_period) =>- momentum = abs(change(i_src, _period))+ momentum = math.abs(ta.change(i_src, _period))- volatility = sum(abs(change(i_src)), _period)+ volatility = math.sum(math.abs(ta.change(i_src)), _period) efficiencyRatio = volatility != 0 ? momentum / volatility : 0- smoothingConstant = pow((efficiencyRatio * (fastAlpha - slowAlpha)) + slowAlpha, 2)+ smoothingConstant = math.pow((efficiencyRatio * (fastAlpha - slowAlpha)) + slowAlpha, 2) var kama = 0.0 kama := nz(kama[1], i_src) + smoothingConstant * (i_src - nz(kama[1], i_src))-f_ma(_period) => I_MA_TYPE == "EMA" ? ema(i_src, _period) :+f_ma(_period) => I_MA_TYPE == "EMA" ? ta.ema(i_src, _period) :- I_MA_TYPE == "HMA" ? hma(i_src, _period) :+ I_MA_TYPE == "HMA" ? ta.hma(i_src, _period) : I_MA_TYPE == "KAMA" ? getKama(_period) :- I_MA_TYPE == "SMA" ? sma(i_src, _period) :+ I_MA_TYPE == "SMA" ? ta.sma(i_src, _period) :- wma(i_src, _period)+ ta.wma(i_src, _period)longMa = f_ma(I_MA_LONG_PERIOD)[I_MA_DISPLACEMENT]⋯maDirection = "Neutral"-crossSign = sign((shortMa / longMa) - 1)+crossSign = math.sign((shortMa / longMa) - 1)-risingShort = rising(shortMa, 1)+risingShort = ta.rising(shortMa, 1)-risingLong = rising(longMa, 1)+risingLong = ta.rising(longMa, 1)-fallingShort = falling(shortMa, 1)+fallingShort = ta.falling(shortMa, 1)-fallingLong = falling(longMa, 1)+fallingLong = ta.falling(longMa, 1)if I_MA_TREND_TYPE == O_CROSS⋯var I_OVERSOLD = input(30, "Oversold level", minval=1, maxval=100, inline="Oscillator levels", group="Oscillator settings")-getOsc = I_OSC_TYPE == "Slow stochastic" ? sma(sma(stoch(close, high, low, I_OSC_PERIOD), 3), 3) : rsi(i_src, I_OSC_PERIOD)+getOsc = I_OSC_TYPE == "Slow stochastic" ? ta.sma(ta.sma(ta.stoch(close, high, low, I_OSC_PERIOD), 3), 3) : ta.rsi(i_src, I_OSC_PERIOD)oscBull = I_OSC_TREND_TYPE == O_DISREGARD ? true : I_OSC_TREND_TYPE == "In favor of the trend" ? getOsc >= I_OVERBOUGHT : getOsc <= I_OVERSOLD⋯// RCP -rcpBull = low[0] < lowest(2)[1] and close[0] > close[1]+rcpBull = low[0] < ta.lowest(2)[1] and close[0] > close[1]-rcpBear = high[0] > highest(2)[1] and close[0] < close[1]+rcpBear = high[0] > ta.highest(2)[1] and close[0] < close[1]// Order variables ⋯if barstate.isfirst- strategy.entry("Get risk size", true)+ strategy.entry("Get risk size", strategy.long) START_PRICE := close-if barssince(barstate.isfirst) >= 1 and strategy.position_entry_name == "Get risk size"+if ta.barssince(barstate.isfirst) >= 1 and strategy.position_entry_name == "Get risk size"- RISK_SIZE := round_to_mintick(strategy.position_size * START_PRICE)+ RISK_SIZE := math.round_to_mintick(strategy.position_size * START_PRICE)- strategy.close("Get risk size", comment="The risk size is " + tostring(RISK_SIZE) + " " + syminfo.currency)+ strategy.close("Get risk size", comment="The risk size is " + str.tostring(RISK_SIZE) + " " + syminfo.currency)// Last top and bottom-_pivotLow = pivotlow(1, 1)+_pivotLow = ta.pivotlow(1, 1)-_pivotHigh = pivothigh(1, 1)+_pivotHigh = ta.pivothigh(1, 1)f_getPivot(_pivot) =>⋯// Stop loss calculations-lowPrice = lowest(sellPrice, I_STOP_LOOKBACK)+lowPrice = ta.lowest(sellPrice, I_STOP_LOOKBACK)-highPrice = highest(buyPrice, I_STOP_LOOKBACK)+highPrice = ta.highest(buyPrice, I_STOP_LOOKBACK)var stopPriceLong = 0.0⋯ - stopTicksLong := abs(buyPrice - stopPriceLong)+ stopTicksLong := math.abs(buyPrice - stopPriceLong)- stopTicksShort := abs(sellPrice - stopPriceShort)+ stopTicksShort := math.abs(sellPrice - stopPriceShort)// Retrace stop if a new signal is given⋯// Entry orders-f_enterLong() => strategy.entry("Long", true, orderSizeLong, stop=I_WAIT_CONFIRM ? buyPrice : na,+f_enterLong() => strategy.entry("Long", strategy.long, orderSizeLong, stop=I_WAIT_CONFIRM ? buyPrice : na,- comment="Entry long with a " + tostring(orderSizeLong * buyPrice, format.mintick) + " " + syminfo.currency + " order")+ comment="Entry long with a " + str.tostring(orderSizeLong * buyPrice, format.mintick) + " " + syminfo.currency + " order")if longCondition f_enterLong()-f_enterShort() => strategy.entry("Short", false, orderSizeShort, stop=I_WAIT_CONFIRM ? sellPrice : na,+f_enterShort() => strategy.entry("Short", strategy.short, orderSizeShort, stop=I_WAIT_CONFIRM ? sellPrice : na,- comment="Entry short with a " + tostring(orderSizeShort * sellPrice, format.mintick) + " " + syminfo.currency + " order")+ comment="Entry short with a " + str.tostring(orderSizeShort * sellPrice, format.mintick) + " " + syminfo.currency + " order")if shortCondition⋯ if I_ALLOW_RETRACING and I_WAIT_CONFIRM- sinceLong = barssince(longCondition)+ sinceLong = ta.barssince(longCondition)- sinceShort = barssince(shortCondition)+ sinceShort = ta.barssince(shortCondition)- sinceClosed = barssince(closed)+ sinceClosed = ta.barssince(closed)- fallingBuyPrice = falling(buyPrice, max(nz(sinceLong), 1))+ fallingBuyPrice = ta.falling(buyPrice, math.max(nz(sinceLong), 1))- risingSellPrice = rising(sellPrice, max(nz(sinceShort), 1))+ risingSellPrice = ta.rising(sellPrice, math.max(nz(sinceShort), 1)) ⋯ - if barssince(betterPriceLong) >= 1 and ((I_MA_TREND_TYPE == "Disregard MA trend" ? false : maBear) or (I_OSC_TREND_TYPE == O_DISREGARD ? false : oscBear))+ if ta.barssince(betterPriceLong) >= 1 and ((I_MA_TREND_TYPE == "Disregard MA trend" ? false : maBear) or (I_OSC_TREND_TYPE == O_DISREGARD ? false : oscBear)) strategy.cancel("Long") - if barssince(betterPriceShort) >= 1 and ((I_MA_TREND_TYPE == "Disregard MA trend" ? false : maBull) or (I_OSC_TREND_TYPE == O_DISREGARD ? false : oscBull))+ if ta.barssince(betterPriceShort) >= 1 and ((I_MA_TREND_TYPE == "Disregard MA trend" ? false : maBull) or (I_OSC_TREND_TYPE == O_DISREGARD ? false : oscBull)) strategy.cancel("Short")⋯Same 53 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 6: input() → input.string()
- Line 7: input() → input.float()
- Line 8: input() → input.float()
- Line 9: input() → input.float()
- Line 10: input() → input.bool()
- Line 13: input() → input.int()
17 more edits
- Line 16: input() → input.bool()
- Line 19: input() → input.string()
- Line 22: input() → input.int()
- Line 23: input() → input.bool()
- Line 24: input() → input.bool()
- Line 26: input() → input.source()
- Line 27: input() → input.int()
- Line 28: input() → input.int()
- Line 29: input() → input.int()
- Line 30: input() → input.string()
- Line 31: input() → input.int()
- Line 81: input() → input.string()
- Line 85: input() → input.int()
- Line 86: input() → input.int()
- Line 87: input() → input.int()
- Line 178: when = I_FIRST_PER → if block
- Line 180: when = I_FIRST_PER → if block
⋯// Settings-var I_ORDER_DIRECTION = input("Both", "Order direction", options=["Both", "Long", "Short"], group="Order settings")+var I_ORDER_DIRECTION = input.string("Both", "Order direction", options=["Both", "Long", "Short"], group="Order settings")-var I_FIRST_RRR = input(1.0, "1st target reward to risk ratio", minval=1.0, step=0.1,tooltip="Please keep this value lower than the second target RRR, otherwise it will mess up the orders.", inline="First RRR", group="Order settings")+var I_FIRST_RRR = input.float(1.0, "1st target reward to risk ratio", minval=1.0, step=0.1,tooltip="Please keep this value lower than the second target RRR, otherwise it will mess up the orders.", inline="First RRR", group="Order settings")-var I_FIRST_PER = input(0.0, "1st target liquidation percent", minval=0.0, maxval=100.0, tooltip="How much of the order, in percentage, to liquidate on the first target.\n\nIf you don't want to liquidate anything, you can keep this as 0.", inline="First RRR", group="Order settings")+var I_FIRST_PER = input.float(0.0, "1st target liquidation percent", minval=0.0, maxval=100.0, tooltip="How much of the order, in percentage, to liquidate on the first target.\n\nIf you don't want to liquidate anything, you can keep this as 0.", inline="First RRR", group="Order settings")-var I_SECOND_RRR = input(2.0, "2nd target reward to risk ratio", minval=1.0, step=0.1, tooltip="Please keep this value higher than the first target RRR, otherwise it will mess up the orders.", group="Order settings")+var I_SECOND_RRR = input.float(2.0, "2nd target reward to risk ratio", minval=1.0, step=0.1, tooltip="Please keep this value higher than the first target RRR, otherwise it will mess up the orders.", group="Order settings")-var I_ALLOW_RETRACING = input(true, "Allow price retracing",+var I_ALLOW_RETRACING = input.bool(true, "Allow price retracing", tooltip="Price retracing is the adjustment of the entry price if the order does not get filled immediately after the entry condition.", inline="Retracing settings", group="Order settings")-var I_RETRACING_TOLERANCE = input(3, "Price retracing tolerance", minval=0,+var I_RETRACING_TOLERANCE = input.int(3, "Price retracing tolerance", minval=0, tooltip="This setting only matters if you enabled price retracing.\n\nIt cancels the order if it does not get filled after X bars since the entry condition.\n\nChange it to 0 to be disabled.", inline="Retracing settings", group="Order settings")-var I_WAIT_CONFIRM = input(true, "Wait for the confirmation of the signal",+var I_WAIT_CONFIRM = input.bool(true, "Wait for the confirmation of the signal", tooltip="The confirmation is given by the breakout of the bar that started the signal.\n\nIf you don't want to wait for it, and enter at market price when the signal is given, unchek the box.", group="Order settings")-var I_STOP_TYPE = input("Highest or lowest price", "Stop type", options=["Highest or lowest price", "Highest or lowest pivot"],+var I_STOP_TYPE = input.string("Highest or lowest price", "Stop type", options=["Highest or lowest price", "Highest or lowest pivot"], tooltip="When calculating the highest/lowest, the strategy will take account the stop lookback.\n\nFor example, if you set the type to use the price, set the looback to 3, and a long order is open, it will take the lowest price of the last 3 candles and use it as the stop loss.", group="Stop settings")-var I_STOP_LOOKBACK = input(3, "Stop loss lookback", minval=1, group="Stop settings")+var I_STOP_LOOKBACK = input.int(3, "Stop loss lookback", minval=1, group="Stop settings")-var I_MA_CLOSE_ORDER = input(false, "Close open orders if MA trend turns direction", group="Stop settings")+var I_MA_CLOSE_ORDER = input.bool(false, "Close open orders if MA trend turns direction", group="Stop settings")-var I_STOP_RETRACE = input(false, "Stop loss retracing if a new signal is given", group="Stop settings")+var I_STOP_RETRACE = input.bool(false, "Stop loss retracing if a new signal is given", group="Stop settings")// MA calculation and plot-i_src = input(close, "Price source", tooltip="For MA and oscillator calculations.", group="MA settings")+i_src = input.source(close, "Price source", tooltip="For MA and oscillator calculations.", group="MA settings")-var I_MA_LONG_PERIOD = input(80, "MA long period", minval=1, inline="MA period", group="MA settings")+var I_MA_LONG_PERIOD = input.int(80, "MA long period", minval=1, inline="MA period", group="MA settings")-var I_MA_SHORT_PERIOD = input(8, "MA short period", minval=1, inline="MA period", group="MA settings")+var I_MA_SHORT_PERIOD = input.int(8, "MA short period", minval=1, inline="MA period", group="MA settings")-var I_MA_DISPLACEMENT = input(0, "MA displacement", minval=0, group="MA settings")+var I_MA_DISPLACEMENT = input.int(0, "MA displacement", minval=0, group="MA settings")-var I_MA_TYPE = input("EMA", "Moving average type", options=["EMA", "HMA", "KAMA", "SMA", "WMA"], group="MA settings")+var I_MA_TYPE = input.string("EMA", "Moving average type", options=["EMA", "HMA", "KAMA", "SMA", "WMA"], group="MA settings")-var I_FAST_ALPHA = input(3, "KAMA's slow period", minval=1, tooltip="For fast alpha.", group="MA settings")+var I_FAST_ALPHA = input.int(3, "KAMA's slow period", minval=1, tooltip="For fast alpha.", group="MA settings")var O_CROSS = "Crossover/crossunder"⋯// Oscillator -var I_OSC_TYPE = input("Slow stochastic", "Oscillator type", options=["RSI", "Slow stochastic"], group="Oscillator settings")+var I_OSC_TYPE = input.string("Slow stochastic", "Oscillator type", options=["RSI", "Slow stochastic"], group="Oscillator settings")var O_TREND_FAVOR = "In favor of the trend"⋯var I_OSC_TREND_TYPE = input(O_DISREGARD, "Oscillator trend type", options=[O_DISREGARD, O_TREND_FAVOR, O_TREND_CONTRARY], group="Oscillator settings")-var I_OSC_PERIOD = input(8, "Oscillator period", minval=1, group="Oscillator settings")+var I_OSC_PERIOD = input.int(8, "Oscillator period", minval=1, group="Oscillator settings")-var I_OVERBOUGHT = input(70, "Overbought level", minval=1, maxval=100, inline="Oscillator levels", group="Oscillator settings")+var I_OVERBOUGHT = input.int(70, "Overbought level", minval=1, maxval=100, inline="Oscillator levels", group="Oscillator settings")-var I_OVERSOLD = input(30, "Oversold level", minval=1, maxval=100, inline="Oscillator levels", group="Oscillator settings")+var I_OVERSOLD = input.int(30, "Oversold level", minval=1, maxval=100, inline="Oscillator levels", group="Oscillator settings")getOsc = I_OSC_TYPE == "Slow stochastic" ? ta.sma(ta.sma(ta.stoch(close, high, low, I_OSC_PERIOD), 3), 3) : ta.rsi(i_src, I_OSC_PERIOD)⋯// Exit orders-strategy.exit("First long", "Long", qty_percent=I_FIRST_PER, limit=fTakeProfitLong, stop=stopPriceLong, comment="First exit", when=I_FIRST_PER)+if I_FIRST_PER+ strategy.exit("First long", "Long", qty_percent=I_FIRST_PER, limit=fTakeProfitLong, stop=stopPriceLong, comment="First exit")strategy.exit("Second long", "Long", limit=sTakeProfitLong, stop=stopPriceLong, comment="Second exit")-strategy.exit("First short", "Short", qty_percent=I_FIRST_PER, limit=fTakeProfitShort, stop=stopPriceShort, comment="First exit", when=I_FIRST_PER)+if I_FIRST_PER+ strategy.exit("First short", "Short", qty_percent=I_FIRST_PER, limit=fTakeProfitShort, stop=stopPriceShort, comment="First exit")strategy.exit("Second short", "Short", limit=sTakeProfitShort, stop=stopPriceShort, comment="Second exit")⋯Does it run in Pine Script v6?
No
The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L175:C5: cannot use 'float' as a condition — Pine Script v6 does not cast 'int' or 'float' to 'bool' implicitly. Wrap it in bool(). The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
-//@version=5+//@version=6// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/⋯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 |
|---|---|---|---|
| Order settings | |||
| Order direction | Both | string · options ["Both", "Long", "Short"] | longCondition shortCondition |
| 1st target reward to risk ratioPlease keep this value lower than the second target RRR, otherwise it will mess up the orders. | 1.0 | float · min 1.0 · step 0.1 | fTakeProfitLong fTakeProfitShort |
| 1st target liquidation percentHow much of the order, in percentage, to liquidate on the first target.\n\nIf you don't want to liquidate anything, you can keep this as 0. | 0.0 | float · min 0.0 · max 100.0 | First take profit price exit First long exit First short |
| 2nd target reward to risk ratioPlease keep this value higher than the first target RRR, otherwise it will mess up the orders. | 2.0 | float · min 1.0 · step 0.1 | sTakeProfitLong sTakeProfitShort |
| Allow price retracingPrice retracing is the adjustment of the entry price if the order does not get filled immediately after the entry condition. | true | bool | line 184 |
| Price retracing toleranceThis setting only matters if you enabled price retracing.\n\nIt cancels the order if it does not get filled after X bars since the entry condition.\n\nChange it to 0 to be disabled. | 3 | int · min 0 | cancel Long cancel Short line 205 line 206 line 209 |
| Wait for the confirmation of the signalThe confirmation is given by the breakout of the bar that started the signal.\n\nIf you don't want to wait for it, and enter at market price when the signal is given, unchek the box. | true | bool | entry Long entry Short line 184 |
| Stop settings | |||
| Stop typeWhen calculating the highest/lowest, the strategy will take account the stop lookback.\n\nFor example, if you set the type to use the price, set the looback to 3, and a long order is open, it will take the lowest price of the last 3 candles and use it as the stop loss. | Highest or lowest price | string · options ["Highest or lowest price", "Highest or lowest pivot"] | tempStopPriceLong tempStopPriceShort |
| Stop loss lookback | 3 | int · min 1 | _array lowPrice highPrice |
| Close open orders if MA trend turns direction | false | bool | line 216 |
| Stop loss retracing if a new signal is given | false | bool | newSignalLong newSignalShort |
| MA settings | |||
| Price sourceFor MA and oscillator calculations. | close | source | momentum volatility kama getOsc line 47 line 48 line 50 line 51 |
| MA long period | 80 | int · min 1 | longMa |
| MA short period | 8 | int · min 1 | shortMa |
| MA displacement | 0 | int · min 0 | longMa shortMa |
| Moving average type | EMA | string · options ["EMA", "HMA", "KAMA", "SMA", "WMA"] | line 47 line 48 line 49 line 50 |
| KAMA's slow periodFor fast alpha. | 3 | int · min 1 | fastAlpha |
| MA trend type | O_CROSS | value · options [O_CROSS, O_LONG_DIRECT, O_LONG_SHORT_DIRECT, O_DISREGARD] | maBull maBear maColor cancel Long cancel Short line 60 line 66 line 68 line 71 line 73 MA short line 199 line 202 |
| Oscillator settings | |||
| Oscillator type | Slow stochastic | string · options ["RSI", "Slow stochastic"] | getOsc |
| Oscillator trend type | O_DISREGARD | value · options [O_DISREGARD, O_TREND_FAVOR, O_TREND_CONTRARY] | oscBull oscBear cancel Long cancel Short line 199 line 202 |
| Oscillator period | 8 | int · min 1 | getOsc |
| Overbought level | 70 | int · min 1 · max 100 | oscBull oscBear |
| Oversold level | 30 | int · min 1 · max 100 | oscBull oscBear |
What it calculates
- Change (
change,ta.changein v5)Price source (close), _periodmomentum · line 41 - Change (
change,ta.changein v5)Price source (close)volatility · line 42 - Rising (
rising,ta.risingin v5)shortMa, 1risingShort · line 56 - Rising (
rising,ta.risingin v5)longMa, 1risingLong · line 57 - Falling (
falling,ta.fallingin v5)shortMa, 1fallingShort · line 58 - Falling (
falling,ta.fallingin v5)longMa, 1fallingLong · line 59 - SMA / Stoch / RSI (
sma,ta.smain v5)sma(stoch(close, high, low, I_OSC_PERIOD), 3), 3 · chosen by Oscillator typegetOsc · line 88 - Pivotlow (
pivotlow,ta.pivotlowin v5)1, 1_pivotLow · line 113 - Pivothigh (
pivothigh,ta.pivothighin v5)1, 1_pivotHigh · line 114 - Lowest (
lowest,ta.lowestin v5)sellPrice, Stop loss lookback (3)lowPrice · line 127 - Highest (
highest,ta.highestin v5)buyPrice, Stop loss lookback (3)highPrice · line 128 - Barssince (
barssince,ta.barssincein v5)longConditionsinceLong · line 185 - Barssince (
barssince,ta.barssincein v5)shortConditionsinceShort · line 186 - Barssince (
barssince,ta.barssincein v5)closedsinceClosed · line 187 - Falling (
falling,ta.fallingin v5)buyPrice, max(nz(sinceLong), 1)fallingBuyPrice · line 188 - Rising (
rising,ta.risingin v5)sellPrice, max(nz(sinceShort), 1)risingSellPrice · line 189
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 97 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 Get risk size long | barstate.isfirst | On | 107 |
| Close Get risk size | barssince(barstate.isfirst) >= 1 and strategy.position_entry_name == "Get risk size" | On | 111 |
| Open Long long | every bar | On | 154 |
| Open Short short | every bar | On | 158 |
| Exit First long stop and limit | I_FIRST_PER | On | 178 |
| Exit Second long stop and limit | every bar | On | 179 |
| Exit First short stop and limit | I_FIRST_PER | On | 180 |
| Exit Second short stop and limit | every bar | On | 181 |
| cancel Long | barssince(betterPriceLong) >= 1 and ((I_MA_TREND_TYPE == "Disregard MA trend" ? false : maBear) or (I_OSC_TREND_TYPE == O_DISREGARD ? false : oscBear)) | On | 200 |
| cancel Short | barssince(betterPriceShort) >= 1 and ((I_MA_TREND_TYPE == "Disregard MA trend" ? false : maBull) or (I_OSC_TREND_TYPE == O_DISREGARD ? false : oscBull)) | On | 203 |
| cancel Long | sinceLong >= I_RETRACING_TOLERANCE | On | 207 |
| cancel Short | sinceShort >= I_RETRACING_TOLERANCE | On | 210 |
| cancel_all | longCondition[1] or shortCondition[1] | On | 213 |
| Close Long | maBull | On | 218 |
| Close Short | maBear | On | 221 |
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, and the live replay matched history.
- 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 timingprocess_orders_on_close = true: orders fill at the signal bar's close.
The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.
Other markets
The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | −10.0% | +102.5% | 53 | 28% | 0.74 | 10.7% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −2.0% | +5.5% | 36 | 31% | 0.92 | 8.6% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +0.0% | +9.8% | 49 | 35% | 1.00 | 10.0% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −8.0% | +8.4% | 48 | 27% | 0.76 | 16.9% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +5.0% | +16.7% | 41 | 39% | 1.20 | 4.9% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −8.0% | +21.5% | 42 | 29% | 0.73 | 15.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +15.0% | +148.3% | 49 | 45% | 1.56 | 5.1% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −2.0% | +17.1% | 48 | 33% | 0.94 | 9.4% | 8 May 2026 – 21 Oct 2026 |
Backtests are simulations on historical data and are not investment advice.
The trades
By market direction
| At entry, last 90 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 15 | 20% | −$6,000.00 |
| Sideways market | 25 | 36% | $7.10 |
| Falling market | 13 | 23% | −$4,000.00 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
19.2%
The 95th percentile of the worst drawdown when the same 53 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 11.0% to 19.2%; the tick is what actually happened, 10.0%. Order luck alone moves it this much.
All 53 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 26 Jan 2024 41,823.50 | 27 Jan 2024 42,120.60 | 1 | $7.10 |
| long | 17 Apr 2024 64,365.00 | 17 Apr 2024 61,600.00 | 0 | −$1,000.00 |
| long | 21 Apr 2024 65,419.00 | 30 Apr 2024 59,600.00 | 9 | −$1,000.00 |
| long | 10 May 2024 63,429.00 | 10 May 2024 60,630.00 | 0 | −$1,000.00 |
| short | 11 Jul 2024 57,157.80 | 11 Jul 2024 59,470.00 | 0 | −$1,000.00 |
| short | 12 Jul 2024 57,050.00 | 13 Jul 2024 59,650.00 | 1 | −$1,000.00 |
| short | 18 Jul 2024 63,854.00 | 19 Jul 2024 66,128.60 | 1 | −$1,000.00 |
| long | 26 Jul 2024 66,175.50 | 1 Aug 2024 63,456.70 | 6 | −$1,000.00 |
| short | 12 Aug 2024 58,286.70 | 23 Aug 2024 61,858.00 | 11 | −$1,000.00 |
| short | 4 Sep 2024 57,415.00 | 6 Sep 2024 52,625.70 | 2 | $2,000.00 |
| long | 27 Sep 2024 65,839.00 | 1 Oct 2024 62,670.00 | 4 | −$1,000.00 |
| long | 4 Oct 2024 61,477.20 | 10 Oct 2024 59,828.10 | 6 | −$1,000.00 |
| long | 24 Oct 2024 67,472.80 | 29 Oct 2024 71,898.50 | 5 | $2,000.00 |
| long | 25 Nov 2024 98,564.00 | 25 Nov 2024 95,734.80 | 0 | −$1,000.00 |
| long | 4 Dec 2024 96,305.50 | 5 Dec 2024 101,760.00 | 1 | $2,000.00 |
| long | 21 Dec 2024 98,233.00 | 30 Dec 2024 92,232.50 | 9 | −$1,000.00 |
| long | 23 Jan 2025 106,394.00 | 27 Jan 2025 99,550.00 | 4 | −$1,000.00 |
| long | 10 Feb 2025 97,323.10 | 12 Feb 2025 94,713.00 | 2 | −$1,000.00 |
| long | 14 Feb 2025 98,083.90 | 18 Feb 2025 94,088.20 | 4 | −$1,000.00 |
| short | 7 Mar 2025 87,836.00 | 10 Mar 2025 77,886.70 | 3 | $2,000.00 |
| short | 21 Mar 2025 83,655.20 | 24 Mar 2025 87,453.70 | 3 | −$1,000.00 |
| short | 3 Apr 2025 82,320.00 | 22 Apr 2025 88,500.00 | 19 | −$1,000.00 |
| long | 1 May 2025 95,228.50 | 8 May 2025 100,085.00 | 7 | $2,000.00 |
| long | 16 May 2025 104,193.00 | 21 May 2025 109,812.00 | 5 | $2,000.00 |
| long | 26 May 2025 109,300.00 | 29 May 2025 106,601.00 | 3 | −$1,000.00 |
| long | 1 Jun 2025 104,900.00 | 5 Jun 2025 103,069.00 | 4 | −$1,000.00 |
| long | 14 Jun 2025 106,180.00 | 20 Jun 2025 102,664.00 | 6 | −$1,000.00 |
| long | 3 Jul 2025 109,730.00 | 13 Jul 2025 118,990.00 | 10 | $2,000.00 |
| long | 4 Aug 2025 114,800.00 | 11 Aug 2025 120,560.00 | 7 | $2,000.00 |
| long | 21 Aug 2025 114,615.00 | 21 Aug 2025 112,380.00 | 0 | −$1,000.00 |
| long | 27 Aug 2025 112,371.00 | 29 Aug 2025 108,667.00 | 2 | −$1,000.00 |
| short | 6 Sep 2025 110,207.00 | 10 Sep 2025 113,385.00 | 4 | −$1,000.00 |
| long | 16 Sep 2025 116,758.00 | 22 Sep 2025 114,384.00 | 6 | −$1,000.00 |
| short | 22 Oct 2025 107,474.00 | 26 Oct 2025 114,000.00 | 4 | −$1,000.00 |
| short | 28 Oct 2025 113,830.00 | 30 Oct 2025 108,690.00 | 2 | $2,000.00 |
| short | 12 Nov 2025 102,476.00 | 17 Nov 2025 92,428.20 | 5 | $2,000.00 |
| short | 29 Nov 2025 90,180.60 | 1 Dec 2025 84,357.80 | 2 | $2,000.00 |
| short | 18 Dec 2025 85,314.00 | 22 Dec 2025 90,365.90 | 4 | −$1,000.00 |
| short | 23 Dec 2025 87,900.00 | 2 Jan 2026 90,588.20 | 10 | −$1,000.00 |
| short | 16 Feb 2026 68,000.00 | 4 Mar 2026 70,983.00 | 16 | −$1,000.00 |
| short | 18 Mar 2026 73,399.20 | 22 Mar 2026 68,197.50 | 4 | $2,000.00 |
| short | 2 Apr 2026 67,578.70 | 6 Apr 2026 69,310.00 | 4 | −$1,000.00 |
| short | 7 Apr 2026 68,300.00 | 7 Apr 2026 70,351.50 | 0 | −$1,000.00 |
| short | 9 Apr 2026 70,707.20 | 9 Apr 2026 72,857.00 | 0 | −$1,000.00 |
| short | 15 Apr 2026 73,795.50 | 17 Apr 2026 76,038.00 | 2 | −$1,000.00 |
| long | 21 Apr 2026 76,558.60 | 6 May 2026 82,227.30 | 15 | $2,000.00 |
| long | 9 May 2026 80,500.00 | 13 May 2026 79,181.50 | 4 | −$1,000.00 |
| long | 24 May 2026 77,404.20 | 27 May 2026 74,289.60 | 3 | −$1,000.00 |
| short | 23 Jun 2026 63,312.00 | 25 Jun 2026 58,690.30 | 2 | $2,000.00 |
| short | 16 Jul 2026 64,485.00 | 20 Jul 2026 65,600.00 | 4 | −$1,000.00 |
| short | 28 Jul 2026 63,605.60 | 19 Aug 2026 65,744.60 | 22 | −$1,000.00 |
| long | 14 Sep 2026 77,450.00 | 15 Sep 2026 76,046.60 | 1 | −$1,000.00 |
| long | 25 Sep 2026 84,942.50 | 28 Sep 2026 82,874.90 | 3 | −$1,000.00 |
Similar scripts
Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Reversal closing price this page | — | v4 strategy | −10.0% | 53 | 10.7% |
| MACD 5 iN 1 [Pro-Tool] by HamidBox | sma rsi pivotlow pivothigh highest lowest | v4 strategy | No trades on this market | ||
| TICK Scalping strategy, SPY 1 min by PtGambler | sma pivotlow pivothigh rsi barssince lowest highest | v5 strategy | No trades on this market | ||
| ICHIMOKU Crypto Swing Strategy by exlux99 | highest lowest sma rising falling | v4 strategy | does not run in Zeal Terminal | ||
| X48 - Strategy - MA Type Cross + TPSL - Future&Spot - V.2 by X4815162342 | rsi sma highest lowest pivothigh pivotlow | v5 strategy | does not run in Zeal Terminal | ||
| VXD Supercycle by Vvaz_ | sma pivothigh pivotlow highest lowest rsi | v5 strategy | does not run in Zeal Terminal | ||
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 56 ms | With a workaround 1,000 bars in 107 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
Zeal Terminal's engine currently reads an order side written as true, false as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 107, 154, 158) so the engine trades the way the script says. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
“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.
//@version=4// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © Coded by Eduardo Mattjestrategy("Reversal closing price", "RCP", overlay=true, default_qty_type=strategy.cash, default_qty_value=1000, initial_capital=100000, process_orders_on_close=true)// Settingsvar I_ORDER_DIRECTION = input("Both", "Order direction", options=["Both", "Long", "Short"], group="Order settings")var I_FIRST_RRR = input(1.0, "1st target reward to risk ratio", minval=1.0, step=0.1,tooltip="Please keep this value lower than the second target RRR, otherwise it will mess up the orders.", inline="First RRR", group="Order settings")var I_FIRST_PER = input(0.0, "1st target liquidation percent", minval=0.0, maxval=100.0, tooltip="How much of the order, in percentage, to liquidate on the first target.\n\nIf you don't want to liquidate anything, you can keep this as 0.", inline="First RRR", group="Order settings")var I_SECOND_RRR = input(2.0, "2nd target reward to risk ratio", minval=1.0, step=0.1, tooltip="Please keep this value higher than the first target RRR, otherwise it will mess up the orders.", group="Order settings")var I_ALLOW_RETRACING = input(true, "Allow price retracing", tooltip="Price retracing is the adjustment of the entry price if the order does not get filled immediately after the entry condition.", inline="Retracing settings", group="Order settings")var I_RETRACING_TOLERANCE = input(3, "Price retracing tolerance", minval=0, tooltip="This setting only matters if you enabled price retracing.\n\nIt cancels the order if it does not get filled after X bars since the entry condition.\n\nChange it to 0 to be disabled.", inline="Retracing settings", group="Order settings")var I_WAIT_CONFIRM = input(true, "Wait for the confirmation of the signal", tooltip="The confirmation is given by the breakout of the bar that started the signal.\n\nIf you don't want to wait for it, and enter at market price when the signal is given, unchek the box.", group="Order settings")var I_STOP_TYPE = input("Highest or lowest price", "Stop type", options=["Highest or lowest price", "Highest or lowest pivot"], tooltip="When calculating the highest/lowest, the strategy will take account the stop lookback.\n\nFor example, if you set the type to use the price, set the looback to 3, and a long order is open, it will take the lowest price of the last 3 candles and use it as the stop loss.", group="Stop settings")var I_STOP_LOOKBACK = input(3, "Stop loss lookback", minval=1, group="Stop settings")var I_MA_CLOSE_ORDER = input(false, "Close open orders if MA trend turns direction", group="Stop settings")var I_STOP_RETRACE = input(false, "Stop loss retracing if a new signal is given", group="Stop settings")// MA calculation and ploti_src = input(close, "Price source", tooltip="For MA and oscillator calculations.", group="MA settings")var I_MA_LONG_PERIOD = input(80, "MA long period", minval=1, inline="MA period", group="MA settings")var I_MA_SHORT_PERIOD = input(8, "MA short period", minval=1, inline="MA period", group="MA settings")var I_MA_DISPLACEMENT = input(0, "MA displacement", minval=0, group="MA settings")var I_MA_TYPE = input("EMA", "Moving average type", options=["EMA", "HMA", "KAMA", "SMA", "WMA"], group="MA settings")var I_FAST_ALPHA = input(3, "KAMA's slow period", minval=1, tooltip="For fast alpha.", group="MA settings")var O_CROSS = "Crossover/crossunder"var O_LONG_DIRECT = "Long MA is up/down"var O_LONG_SHORT_DIRECT = "Long and short MA are up/down"var O_DISREGARD = "Disregard"var I_MA_TREND_TYPE = input(O_CROSS, "MA trend type", options=[O_CROSS, O_LONG_DIRECT, O_LONG_SHORT_DIRECT, O_DISREGARD], group="MA settings")fastAlpha = 2.0 / (I_FAST_ALPHA + 1)slowAlpha = 2.0 / (31)getKama(_period) => momentum = abs(change(i_src, _period)) volatility = sum(abs(change(i_src)), _period) efficiencyRatio = volatility != 0 ? momentum / volatility : 0 smoothingConstant = pow((efficiencyRatio * (fastAlpha - slowAlpha)) + slowAlpha, 2) var kama = 0.0 kama := nz(kama[1], i_src) + smoothingConstant * (i_src - nz(kama[1], i_src))f_ma(_period) => I_MA_TYPE == "EMA" ? ema(i_src, _period) : I_MA_TYPE == "HMA" ? hma(i_src, _period) : I_MA_TYPE == "KAMA" ? getKama(_period) : I_MA_TYPE == "SMA" ? sma(i_src, _period) : wma(i_src, _period)longMa = f_ma(I_MA_LONG_PERIOD)[I_MA_DISPLACEMENT]shortMa = f_ma(I_MA_SHORT_PERIOD)[I_MA_DISPLACEMENT]maDirection = "Neutral"crossSign = sign((shortMa / longMa) - 1)risingShort = rising(shortMa, 1)risingLong = rising(longMa, 1)fallingShort = falling(shortMa, 1)fallingLong = falling(longMa, 1)if I_MA_TREND_TYPE == O_CROSS if crossSign == 1 maDirection := "Bull" else if crossSign == -1 maDirection := "Bear"else if risingLong if I_MA_TREND_TYPE == O_LONG_DIRECT maDirection := "Bull" if risingShort and I_MA_TREND_TYPE == O_LONG_SHORT_DIRECT maDirection := "Bull"else if fallingLong if I_MA_TREND_TYPE == O_LONG_DIRECT maDirection := "Bear" if fallingShort and I_MA_TREND_TYPE == O_LONG_SHORT_DIRECT maDirection := "Bear"maBull = I_MA_TREND_TYPE == O_DISREGARD ? true : maDirection == "Bull"maBear = I_MA_TREND_TYPE == O_DISREGARD ? true : maDirection == "Bear"maColor = I_MA_TREND_TYPE == O_DISREGARD or maDirection == "Neutral" ? color.gray : maBull ? color.teal : color.redplot(I_MA_TREND_TYPE != O_LONG_DIRECT ? shortMa : na, "MA short", maColor, 3)plot(longMa, "MA long", maColor, 3)// Oscillator var I_OSC_TYPE = input("Slow stochastic", "Oscillator type", options=["RSI", "Slow stochastic"], group="Oscillator settings")var O_TREND_FAVOR = "In favor of the trend"var O_TREND_CONTRARY = "Contrary to the trend"var I_OSC_TREND_TYPE = input(O_DISREGARD, "Oscillator trend type", options=[O_DISREGARD, O_TREND_FAVOR, O_TREND_CONTRARY], group="Oscillator settings")var I_OSC_PERIOD = input(8, "Oscillator period", minval=1, group="Oscillator settings")var I_OVERBOUGHT = input(70, "Overbought level", minval=1, maxval=100, inline="Oscillator levels", group="Oscillator settings")var I_OVERSOLD = input(30, "Oversold level", minval=1, maxval=100, inline="Oscillator levels", group="Oscillator settings")getOsc = I_OSC_TYPE == "Slow stochastic" ? sma(sma(stoch(close, high, low, I_OSC_PERIOD), 3), 3) : rsi(i_src, I_OSC_PERIOD)oscBull = I_OSC_TREND_TYPE == O_DISREGARD ? true : I_OSC_TREND_TYPE == "In favor of the trend" ? getOsc >= I_OVERBOUGHT : getOsc <= I_OVERSOLDoscBear = I_OSC_TREND_TYPE == O_DISREGARD ? true : I_OSC_TREND_TYPE == "In favor of the trend" ? getOsc <= I_OVERSOLD : getOsc >= I_OVERBOUGHT// RCP rcpBull = low[0] < lowest(2)[1] and close[0] > close[1]rcpBear = high[0] > highest(2)[1] and close[0] < close[1]// Order variables inMarket = strategy.opentrades != 0closed = strategy.closedtrades[0] > strategy.closedtrades[1]longPosition = strategy.position_entry_name == "Long"shortPosition = strategy.position_entry_name == "Short"buyPrice = high + syminfo.minticksellPrice = low - syminfo.minticklongCondition = rcpBull and I_ORDER_DIRECTION != "Short" and maBull and oscBull and not inMarketshortCondition = rcpBear and I_ORDER_DIRECTION != "Long" and maBear and oscBear and not inMarket// Get risk sizevar START_PRICE = 0.0var RISK_SIZE = 0.0if barstate.isfirst strategy.entry("Get risk size", true) START_PRICE := closeif barssince(barstate.isfirst) >= 1 and strategy.position_entry_name == "Get risk size" RISK_SIZE := round_to_mintick(strategy.position_size * START_PRICE) strategy.close("Get risk size", comment="The risk size is " + tostring(RISK_SIZE) + " " + syminfo.currency)// Last top and bottom_pivotLow = pivotlow(1, 1)_pivotHigh = pivothigh(1, 1)f_getPivot(_pivot) => var _array = array.new_float(I_STOP_LOOKBACK, 0.0) if not na(_pivot) array.remove(_array, 0) array.push(_array, _pivot) _arraylowPivots = f_getPivot(_pivotLow)lowPIvotPrice = array.min(lowPivots) - syminfo.mintickhighPivots = f_getPivot(_pivotHigh)highPivotPrice = array.max(highPivots) + syminfo.mintick// Stop loss calculationslowPrice = lowest(sellPrice, I_STOP_LOOKBACK)highPrice = highest(buyPrice, I_STOP_LOOKBACK)var stopPriceLong = 0.0var stopPriceShort = 0.0var stopTicksLong = 0.0var stopTicksShort = 0.0tempStopPriceLong = I_STOP_TYPE == "Highest or lowest price" or lowPrice < lowPIvotPrice ? lowPrice : lowPIvotPricetempStopPriceShort = I_STOP_TYPE == "Highest or lowest price" or highPrice > highPivotPrice ? highPrice : highPivotPrice if not inMarket stopPriceLong := tempStopPriceLong stopPriceShort := tempStopPriceShort stopTicksLong := abs(buyPrice - stopPriceLong) stopTicksShort := abs(sellPrice - stopPriceShort)// Retrace stop if a new signal is givennewSignalLong = rcpBull and tempStopPriceLong > stopPriceLong and I_STOP_RETRACEnewSignalShort = rcpBear and tempStopPriceShort < stopPriceShort and I_STOP_RETRACEif newSignalLong or newSignalShort stopPriceLong := tempStopPriceLong stopPriceShort := tempStopPriceShortorderSizeLong = RISK_SIZE / stopTicksLongorderSizeShort = RISK_SIZE / stopTicksShortstopPrice = longPosition ? stopPriceLong : shortPosition ? stopPriceShort : naf_plotVar(_var) => _var ? _var : _var[1]plot(f_plotVar(stopPrice), "Stop price", color.red, 2, plot.style_linebr)// Entry ordersf_enterLong() => strategy.entry("Long", true, orderSizeLong, stop=I_WAIT_CONFIRM ? buyPrice : na, comment="Entry long with a " + tostring(orderSizeLong * buyPrice, format.mintick) + " " + syminfo.currency + " order")if longCondition f_enterLong()f_enterShort() => strategy.entry("Short", false, orderSizeShort, stop=I_WAIT_CONFIRM ? sellPrice : na, comment="Entry short with a " + tostring(orderSizeShort * sellPrice, format.mintick) + " " + syminfo.currency + " order")if shortCondition f_enterShort()// Take profit calculationsvar fTakeProfitLong = 0.0var fTakeProfitShort = 0.0var sTakeProfitLong = 0.0var sTakeProfitShort = 0.0if not inMarket fTakeProfitLong := buyPrice + stopTicksLong * I_FIRST_RRR fTakeProfitShort := sellPrice - stopTicksShort * I_FIRST_RRR sTakeProfitLong := buyPrice + stopTicksLong * I_SECOND_RRR sTakeProfitShort := sellPrice - stopTicksShort * I_SECOND_RRRfTakeProfitPrice = longPosition ? fTakeProfitLong : shortPosition ? fTakeProfitShort : nasTakeProfitPrice = longPosition ? sTakeProfitLong : shortPosition ? sTakeProfitShort : naplot(I_FIRST_PER ? f_plotVar(fTakeProfitPrice) : na, "First take profit price", color.teal, 1, plot.style_linebr)plot(f_plotVar(sTakeProfitPrice), "Second take profit price", color.teal, 2, plot.style_linebr)// Exit ordersstrategy.exit("First long", "Long", qty_percent=I_FIRST_PER, limit=fTakeProfitLong, stop=stopPriceLong, comment="First exit", when=I_FIRST_PER)strategy.exit("Second long", "Long", limit=sTakeProfitLong, stop=stopPriceLong, comment="Second exit")strategy.exit("First short", "Short", qty_percent=I_FIRST_PER, limit=fTakeProfitShort, stop=stopPriceShort, comment="First exit", when=I_FIRST_PER)strategy.exit("Second short", "Short", limit=sTakeProfitShort, stop=stopPriceShort, comment="Second exit")// Price retracing ordersif not inMarket if I_ALLOW_RETRACING and I_WAIT_CONFIRM sinceLong = barssince(longCondition) sinceShort = barssince(shortCondition) sinceClosed = barssince(closed) fallingBuyPrice = falling(buyPrice, max(nz(sinceLong), 1)) risingSellPrice = rising(sellPrice, max(nz(sinceShort), 1)) betterPriceLong = sinceClosed >= sinceLong and sinceLong >= 1 and maBull and oscBull and fallingBuyPrice if betterPriceLong f_enterLong() betterPriceShort = sinceClosed >= sinceShort and sinceShort >= 1 and maBear and oscBear and risingSellPrice if betterPriceShort f_enterShort() if barssince(betterPriceLong) >= 1 and ((I_MA_TREND_TYPE == "Disregard MA trend" ? false : maBear) or (I_OSC_TREND_TYPE == O_DISREGARD ? false : oscBear)) strategy.cancel("Long") if barssince(betterPriceShort) >= 1 and ((I_MA_TREND_TYPE == "Disregard MA trend" ? false : maBull) or (I_OSC_TREND_TYPE == O_DISREGARD ? false : oscBull)) strategy.cancel("Short") if I_RETRACING_TOLERANCE if sinceLong >= I_RETRACING_TOLERANCE strategy.cancel("Long") if sinceShort >= I_RETRACING_TOLERANCE strategy.cancel("Short") else if longCondition[1] or shortCondition[1] strategy.cancel_all()// MA cross close ordersvar CROSS_COMMENT = "MA Cross"if I_MA_CLOSE_ORDER if maBull strategy.close("Long", comment=CROSS_COMMENT) if maBear strategy.close("Short", comment=CROSS_COMMENT)