Zeal Terminal Open in Zeal Terminal

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
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (23)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$90,737$202,527Equity from $100,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots. 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.
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

Verified

Same 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")⋯

Clean v5

VerifiedDownload the v5 script

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.

SettingDefaultType and rangeFeeds
Order settings
Order directionBothstring · 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.0float · min 1.0 · step 0.1fTakeProfitLong 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.0float · min 0.0 · max 100.0First 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.0float · min 1.0 · step 0.1sTakeProfitLong sTakeProfitShort
Allow price retracingPrice retracing is the adjustment of the entry price if the order does not get filled immediately after the entry condition.trueboolline 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.3int · min 0cancel 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.trueboolentry 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 pricestring · options ["Highest or lowest price", "Highest or lowest pivot"]tempStopPriceLong tempStopPriceShort
Stop loss lookback3int · min 1_array lowPrice highPrice
Close open orders if MA trend turns directionfalseboolline 216
Stop loss retracing if a new signal is givenfalseboolnewSignalLong newSignalShort
MA settings
Price sourceFor MA and oscillator calculations.closesourcemomentum volatility kama getOsc line 47 line 48 line 50 line 51
MA long period80int · min 1longMa
MA short period8int · min 1shortMa
MA displacement0int · min 0longMa shortMa
Moving average typeEMAstring · options ["EMA", "HMA", "KAMA", "SMA", "WMA"]line 47 line 48 line 49 line 50
KAMA's slow periodFor fast alpha.3int · min 1fastAlpha
MA trend typeO_CROSSvalue · 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 typeSlow stochasticstring · options ["RSI", "Slow stochastic"]getOsc
Oscillator trend typeO_DISREGARDvalue · options [O_DISREGARD, O_TREND_FAVOR, O_TREND_CONTRARY]oscBull oscBear cancel Long cancel Short line 199 line 202
Oscillator period8int · min 1getOsc
Overbought level70int · min 1 · max 100oscBull oscBear
Oversold level30int · min 1 · max 100oscBull oscBear

What it calculates

  • Change (change, ta.change in v5)Price source (close), _periodmomentum · line 41
  • Change (change, ta.change in v5)Price source (close)volatility · line 42
  • Rising (rising, ta.rising in v5)shortMa, 1risingShort · line 56
  • Rising (rising, ta.rising in v5)longMa, 1risingLong · line 57
  • Falling (falling, ta.falling in v5)shortMa, 1fallingShort · line 58
  • Falling (falling, ta.falling in v5)longMa, 1fallingLong · line 59
  • SMA / Stoch / RSI (sma, ta.sma in v5)sma(stoch(close, high, low, I_OSC_PERIOD), 3), 3 · chosen by Oscillator typegetOsc · line 88
  • Pivotlow (pivotlow, ta.pivotlow in v5)1, 1_pivotLow · line 113
  • Pivothigh (pivothigh, ta.pivothigh in v5)1, 1_pivotHigh · line 114
  • Lowest (lowest, ta.lowest in v5)sellPrice, Stop loss lookback (3)lowPrice · line 127
  • Highest (highest, ta.highest in v5)buyPrice, Stop loss lookback (3)highPrice · line 128
  • Barssince (barssince, ta.barssince in v5)longConditionsinceLong · line 185
  • Barssince (barssince, ta.barssince in v5)shortConditionsinceShort · line 186
  • Barssince (barssince, ta.barssince in v5)closedsinceClosed · line 187
  • Falling (falling, ta.falling in v5)buyPrice, max(nz(sinceLong), 1)fallingBuyPrice · line 188
  • Rising (rising, ta.rising in 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

OrderFires whenBy defaultLine
Open Get risk size longbarstate.isfirstOn107
Close Get risk sizebarssince(barstate.isfirst) >= 1 and strategy.position_entry_name == "Get risk size"On111
Open Long longevery barOn154
Open Short shortevery barOn158
Exit First long stop and limitI_FIRST_PEROn178
Exit Second long stop and limitevery barOn179
Exit First short stop and limitI_FIRST_PEROn180
Exit Second short stop and limitevery barOn181
cancel Longbarssince(betterPriceLong) >= 1 and ((I_MA_TREND_TYPE == "Disregard MA trend" ? false : maBear) or (I_OSC_TREND_TYPE == O_DISREGARD ? false : oscBear))On200
cancel Shortbarssince(betterPriceShort) >= 1 and ((I_MA_TREND_TYPE == "Disregard MA trend" ? false : maBull) or (I_OSC_TREND_TYPE == O_DISREGARD ? false : oscBull))On203
cancel LongsinceLong >= I_RETRACING_TOLERANCEOn207
cancel ShortsinceShort >= I_RETRACING_TOLERANCEOn210
cancel_all longCondition[1] or shortCondition[1]On213
Close LongmaBullOn218
Close ShortmaBearOn221

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.

14/14trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. Orders are decided once per closed bar, so nothing can change mid-bar.
  • 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.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D−10.0%+102.5%5328%0.7410.7%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−2.0%+5.5%3631%0.928.6%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+0.0%+9.8%4935%1.0010.0%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−8.0%+8.4%4827%0.7616.9%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+5.0%+16.7%4139%1.204.9%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−8.0%+21.5%4229%0.7315.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+15.0%+148.3%4945%1.565.1%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−2.0%+17.1%4833%0.949.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 barsTradesWonP&L
Rising market1520%−$6,000.00
Sideways market2536%$7.10
Falling market1323%−$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.

0%22%
All 53 trades
SideEntryExitBarsP&L
long26 Jan 2024 41,823.5027 Jan 2024 42,120.601$7.10
long17 Apr 2024 64,365.0017 Apr 2024 61,600.000−$1,000.00
long21 Apr 2024 65,419.0030 Apr 2024 59,600.009−$1,000.00
long10 May 2024 63,429.0010 May 2024 60,630.000−$1,000.00
short11 Jul 2024 57,157.8011 Jul 2024 59,470.000−$1,000.00
short12 Jul 2024 57,050.0013 Jul 2024 59,650.001−$1,000.00
short18 Jul 2024 63,854.0019 Jul 2024 66,128.601−$1,000.00
long26 Jul 2024 66,175.501 Aug 2024 63,456.706−$1,000.00
short12 Aug 2024 58,286.7023 Aug 2024 61,858.0011−$1,000.00
short4 Sep 2024 57,415.006 Sep 2024 52,625.702$2,000.00
long27 Sep 2024 65,839.001 Oct 2024 62,670.004−$1,000.00
long4 Oct 2024 61,477.2010 Oct 2024 59,828.106−$1,000.00
long24 Oct 2024 67,472.8029 Oct 2024 71,898.505$2,000.00
long25 Nov 2024 98,564.0025 Nov 2024 95,734.800−$1,000.00
long4 Dec 2024 96,305.505 Dec 2024 101,760.001$2,000.00
long21 Dec 2024 98,233.0030 Dec 2024 92,232.509−$1,000.00
long23 Jan 2025 106,394.0027 Jan 2025 99,550.004−$1,000.00
long10 Feb 2025 97,323.1012 Feb 2025 94,713.002−$1,000.00
long14 Feb 2025 98,083.9018 Feb 2025 94,088.204−$1,000.00
short7 Mar 2025 87,836.0010 Mar 2025 77,886.703$2,000.00
short21 Mar 2025 83,655.2024 Mar 2025 87,453.703−$1,000.00
short3 Apr 2025 82,320.0022 Apr 2025 88,500.0019−$1,000.00
long1 May 2025 95,228.508 May 2025 100,085.007$2,000.00
long16 May 2025 104,193.0021 May 2025 109,812.005$2,000.00
long26 May 2025 109,300.0029 May 2025 106,601.003−$1,000.00
long1 Jun 2025 104,900.005 Jun 2025 103,069.004−$1,000.00
long14 Jun 2025 106,180.0020 Jun 2025 102,664.006−$1,000.00
long3 Jul 2025 109,730.0013 Jul 2025 118,990.0010$2,000.00
long4 Aug 2025 114,800.0011 Aug 2025 120,560.007$2,000.00
long21 Aug 2025 114,615.0021 Aug 2025 112,380.000−$1,000.00
long27 Aug 2025 112,371.0029 Aug 2025 108,667.002−$1,000.00
short6 Sep 2025 110,207.0010 Sep 2025 113,385.004−$1,000.00
long16 Sep 2025 116,758.0022 Sep 2025 114,384.006−$1,000.00
short22 Oct 2025 107,474.0026 Oct 2025 114,000.004−$1,000.00
short28 Oct 2025 113,830.0030 Oct 2025 108,690.002$2,000.00
short12 Nov 2025 102,476.0017 Nov 2025 92,428.205$2,000.00
short29 Nov 2025 90,180.601 Dec 2025 84,357.802$2,000.00
short18 Dec 2025 85,314.0022 Dec 2025 90,365.904−$1,000.00
short23 Dec 2025 87,900.002 Jan 2026 90,588.2010−$1,000.00
short16 Feb 2026 68,000.004 Mar 2026 70,983.0016−$1,000.00
short18 Mar 2026 73,399.2022 Mar 2026 68,197.504$2,000.00
short2 Apr 2026 67,578.706 Apr 2026 69,310.004−$1,000.00
short7 Apr 2026 68,300.007 Apr 2026 70,351.500−$1,000.00
short9 Apr 2026 70,707.209 Apr 2026 72,857.000−$1,000.00
short15 Apr 2026 73,795.5017 Apr 2026 76,038.002−$1,000.00
long21 Apr 2026 76,558.606 May 2026 82,227.3015$2,000.00
long9 May 2026 80,500.0013 May 2026 79,181.504−$1,000.00
long24 May 2026 77,404.2027 May 2026 74,289.603−$1,000.00
short23 Jun 2026 63,312.0025 Jun 2026 58,690.302$2,000.00
short16 Jul 2026 64,485.0020 Jul 2026 65,600.004−$1,000.00
short28 Jul 2026 63,605.6019 Aug 2026 65,744.6022−$1,000.00
long14 Sep 2026 77,450.0015 Sep 2026 76,046.601−$1,000.00
long25 Sep 2026 84,942.5028 Sep 2026 82,874.903−$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.

ScriptSharesTypeNetTradesMax drawdown
Reversal closing price this page—v4 strategy−10.0%5310.7%
MACD 5 iN 1 [Pro-Tool] by HamidBoxsma rsi pivotlow pivothigh highest lowestv4 strategyNo trades on this market
TICK Scalping strategy, SPY 1 min by PtGamblersma pivotlow pivothigh rsi barssince lowest highestv5 strategyNo trades on this market
ICHIMOKU Crypto Swing Strategy by exlux99highest lowest sma rising fallingv4 strategydoes not run in Zeal Terminal
X48 - Strategy - MA Type Cross + TPSL - Future&Spot - V.2 by X4815162342rsi sma highest lowest pivothigh pivotlowv5 strategydoes not run in Zeal Terminal
VXD Supercycle by Vvaz_sma pivothigh pivotlow highest lowest rsiv5 strategydoes not run in Zeal Terminal

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 56 msWith a workaround 1,000 bars in 107 msNot measured
PineTSNo 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)