Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Modulo Logic + EMA Strat

A Pine Script v4 strategy built on Lowest (10), Highest (10) and Valuewhen (bought, LL). It has 10 order rules, 8 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 100% of equity and pays 0.04 commission. 17 settings; defaults include Strategy Direction 0, Dividend close and Divisor 4.

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 Modulo Logic + EMA Strat repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 2 of 2 trades.
How did Modulo Logic + EMA Strat do on BTCUSDT 1D with default settings?
−50.83%
From 26 Jan 2024 to 21 Oct 2026, over 16 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can Modulo Logic + EMA Strat 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 Modulo Logic + EMA Strat use a stop loss?
Yes
strategy.exit sets a stop on line 117, 118.
Does Modulo Logic + EMA Strat run in Zeal Terminal?
Yes
It compiles in 33 ms and runs 1,000 bars in 135 ms, in the browser.

BTCUSDT · 1D · default settings

  • Plot
  • SL
  • SSL
  • TP
  • STP
  • Bullish Setup
  • Bearish Setup
  • 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 (17)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$4,808$20,253Equity from $10,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.
Net profit
−50.83%
−$5,083.49
Buy and hold
+102.5%
same period
Closed trades
16
5 won · 11 lost
Profitable
31.3%
of closed trades
Profit factor
0.40
gross profit ÷ gross loss
Max drawdown
54.71%
−$5,470.59

One run with the author's default settings, $10,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

    2 settings do nothing

    “-----------------Strategy Inputs-------------------”, “-----------------General Inputs-------------------” are declared but never read.

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    Uses an argument v6 removed

    when = on line 80, 81, 83, 84, 87, 88, 90, 91, 117, 118. 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 lowest → ta.lowest, highest → ta.highest, valuewhen → ta.valuewhen, atr → ta.atr, ema → ta.ema.
  • 10 strategy calls use the when = argument (line 80, 81, 83, 84, 87, 88, 90, 91, 117, 118). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Verified

Same 16 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 11: //@version=4 → //@version=5
  • Line 21: input(type = input.integer) → input.int()
  • Line 44: lowest → ta.lowest
  • Line 45: highest → ta.highest
  • Line 46: valuewhen → ta.valuewhen
  • Line 47: valuewhen → ta.valuewhen
6 more edits
  • Line 53: atr → ta.atr
  • Line 56: valuewhen → ta.valuewhen
  • Line 57: valuewhen → ta.valuewhen
  • Line 70: ema → ta.ema
  • Line 97: valuewhen → ta.valuewhen
  • Line 109: valuewhen → ta.valuewhen
⋯// that usually struggles when the market is ranging.-//@version=4+//@version=5//@version=4⋯     slippage=0)-direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)+direction = input.int(0, title = "Strategy Direction", minval=-1, maxval=1)strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))⋯// Price Action Stop and Take Profit-LL=(lowest(i_SPL))*(1-i_PercIncrement)+LL=(ta.lowest(i_SPL))*(1-i_PercIncrement)-HH=(highest(i_SPL))*(1+i_PercIncrement)+HH=(ta.highest(i_SPL))*(1+i_PercIncrement)-LL_price = valuewhen(bought, LL, 0)+LL_price = ta.valuewhen(bought, LL, 0)-HH_price = valuewhen(bought, HH, 0)+HH_price = ta.valuewhen(bought, HH, 0)entry_LL_price = strategy.position_size > 0 ? LL_price : na ⋯// ATR Stop-ATR=atr(i_ATR)*i_ATRMult+ATR=ta.atr(i_ATR)*i_ATRMultATRLong = ohlc4 - ATRATRShort = ohlc4 + ATR-ATRLongStop = valuewhen(bought, ATRLong, 0)+ATRLongStop = ta.valuewhen(bought, ATRLong, 0)-ATRShortStop = valuewhen(bought, ATRShort, 0)+ATRShortStop = ta.valuewhen(bought, ATRShort, 0)LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ⋯evennumber=modulo==0-MA=ema(close, MALen)+MA=ta.ema(close, MALen)plot(MA)⋯//TrailingStop-dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0))+dif=(ta.valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price⋯var Ststop = float(na)-Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 +Sdif=strategy.position_avg_price-(ta.valuewhen(strategy.position_size<0  and strategy.position_size[1]>=0, low,0))⋯

Clean v5

VerifiedDownload the v5 script

Same 16 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 24: input() → input.bool()
  • Line 25: input() → input.source()
  • Line 26: input() → input.int()
  • Line 27: input() → input.bool()
  • Line 28: input() → input.int()
  • Line 30: input() → input.bool()
20 more edits
  • Line 32: input() → input.bool()
  • Line 33: input() → input.string()
  • Line 34: input() → input.int()
  • Line 35: input() → input.int()
  • Line 36: input() → input.int()
  • Line 37: input() → input.int()
  • Line 38: input() → input.int()
  • Line 39: input() → input.bool()
  • Line 75: input() → input.bool()
  • Line 76: input() → input.bool()
  • Line 80: when = SELL and strategy.position_size == 0 → if block
  • Line 81: when = BUY and strategy.position_size == 0 → if block
  • Line 83: when = SELL → if block
  • Line 84: when = BUY → if block
  • Line 87: when = BUY and strategy.position_size == 0 → if block
  • Line 88: when = SELL and strategy.position_size == 0 → if block
  • Line 90: when = BUY → if block
  • Line 91: when = SELL → if block
  • Line 117: when = i_SL → if block
  • Line 118: when = i_SL → if block
⋯/////////////////////// STRATEGY INPUTS ////////////////////////////////////////-title1=input(true, "-----------------Strategy Inputs-------------------")  +title1=input.bool(true, "-----------------Strategy Inputs-------------------")  -a=input(close, title="Dividend")+a=input.source(close, title="Dividend")-b=input(4, title="Divisor")+b=input.int(4, title="Divisor")-usemod=input(true, title="Use Modulo Logic")+usemod=input.bool(true, title="Use Modulo Logic")-MALen=input(70, title="EMA Length")+MALen=input.int(70, title="EMA Length")/////////////////////// BACKTESTER /////////////////////////////////////////////-title2=input(true, "-----------------General Inputs-------------------")  +title2=input.bool(true, "-----------------General Inputs-------------------")  // Backtester General Inputs-i_SL=input(true, title="Use Stop Loss and Take Profit")+i_SL=input.bool(true, title="Use Stop Loss and Take Profit")-i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])+i_SLType=input.string(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])-i_SPL=input(defval=10, title="Swing Point Lookback")+i_SPL=input.int(defval=10, title="Swing Point Lookback")-i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01+i_PercIncrement=input.int(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01-i_ATR = input(14, title="ATR Length")+i_ATR = input.int(14, title="ATR Length")-i_ATRMult = input(4, step=.1, title="ATR Multiple")+i_ATRMult = input.int(4, step=.1, title="ATR Multiple")-i_TPRRR = input(1, step=.1, title="Take Profit Risk Reward Ratio")+i_TPRRR = input.int(1, step=.1, title="Take Profit Risk Reward Ratio")-TS=input(false, title="Trailing Stop")+TS=input.bool(false, title="Trailing Stop")// Bought and Sold Boolean Signal⋯//Trading Inputs-DPR=input(true, "Allow Direct Position Reverse")+DPR=input.bool(true, "Allow Direct Position Reverse")-reverse=input(false, "Reverse Trades")+reverse=input.bool(false, "Reverse Trades")// Entries⋯    if not DPR-        strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0)+        if SELL and strategy.position_size == 0+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0)+        if BUY and strategy.position_size == 0+            strategy.entry("short", strategy.short)    else     -        strategy.entry("long", strategy.long, when=SELL)+        if SELL+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=BUY)+        if BUY+            strategy.entry("short", strategy.short)else    if not DPR -        strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0)+        if BUY and strategy.position_size == 0+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0)+        if SELL and strategy.position_size == 0+            strategy.entry("short", strategy.short)    else-        strategy.entry("long", strategy.long, when=BUY)+        if BUY+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=SELL)+        if SELL+            strategy.entry("short", strategy.short)SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop⋯    Ststop := na-strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL, when=i_SL)+if i_SL+    strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL)-strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL, when=i_SL)+if i_SL+    strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL)/////////////////////// PLOTS //////////////////////////////////////////////////⋯

Does it run in Pine Script v6?

No

The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 16 before, 26 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// that usually struggles when the market is ranging.-//@version=5+//@version=6//@version=4⋯

Settings

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

SettingDefaultType and rangeFeeds
Strategy Direction0int (written input.integer) · min -1 · max 1line 22
-----------------Strategy Inputs-------------------trueboolunused
Dividendclosesourcemodulo
Divisor4intmodulo
Use Modulo LogictrueboolBUY SELL
EMA Length70intMA
-----------------General Inputs-------------------trueboolunused
Use Stop Loss and Take Profittrueboolexit TP & SL SL SSL TP STP
Type Of StopATR Stopstring · options ["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]SL SSL TP STP
Swing Point Lookback10intLL HH
Swing Point SL Perc Increment3int · step .1LL HH
ATR Length14intATR
ATR Multiple4int · step .1ATR
Take Profit Risk Reward Ratio1int · step .1tp stp ATRtp ATRstp
Trailing Stopfalseboolexit TP & SL SL SSL
Allow Direct Position Reversetrueboolentry long entry short entry long entry short entry long entry short entry long entry short line 79 line 86
Reverse Tradesfalseboolline 78

What it calculates

  • Lowest (lowest, ta.lowest in v5)Swing Point Lookback (10)LL · line 44
  • Highest (highest, ta.highest in v5)Swing Point Lookback (10)HH · line 45
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, LL, 0LL_price · line 46
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, HH, 0HH_price · line 47
  • ATR (atr, ta.atr in v5)ATR Length (14)ATR · line 53
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, ATRLong, 0ATRLongStop · line 56
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, ATRShort, 0ATRShortStop · line 57
  • EMA (ema, ta.ema in v5)close, EMA Length (70)MA · line 70

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.

i_SPLSwing Point Lookbacksetting · 10i_PercIncrementSwing Point SL Perc Inc…setting · 3high · low · closehigh · low · closeprice datai_ATRATR Lengthsetting · 14i_ATRMultATR Multiplesetting · 4closecloseprice dataMALenEMA Lengthsetting · 70i_TPRRRTake Profit Risk Reward…setting · 1ohlc4ohlc4price databDivisorsetting · 4i_SLTypeType Of Stopsetting · ATR Stophighhighprice datalowlowprice dataLLLowest→ LLHHHighest→ HHLL_priceValuewhen→ LL_priceHH_priceValuewhen→ HH_priceATRATR→ ATRATRLongStopValuewhen→ ATRLongStopATRShortStopValuewhen→ ATRShortStopMAEMA→ MAentry_LL_priceentry_LL_pricevalueentry_HH_priceentry_HH_pricevaluetptpvaluestpstpvalueATRLong, ATRShortATRLong · ATRShort2 valuesLongSL_ATR_priceLongSL_ATR_pricevalueShortSL_ATR_priceShortSL_ATR_pricevalueATRtpATRtpvalueATRstpATRstpvaluemodulomodulovalueBUY, SELLBUY · SELL2 valuesSLSLvalueSSLSSLvalueTPTPvalueSTPSTPvaluetrailOffsettrailOffsetvaluetstoptstopvalueStrailOffsetStrailOffsetvalueStstopStstopvalueboughtboughtconditionevennumberevennumberconditiondifdifconditionSdifSdifconditionentry:longOpen longstrategy.entryentry:shortOpen shortstrategy.entryexit:TP & SLexit TP & SLstrategy.exitplot:71plotplotplot:120SLplotplot:121SSLplotplot:122TPplotplot:123STPplotplotshape:125Bullish Setupplotshapeplotshape:127Bearish Setupplotshape

Order rules

OrderFires whenBy defaultLine
Open long longSELL and strategy.position_size == 0On80
Open short shortBUY and strategy.position_size == 0On81
Open long longSELLOn83
Open short shortBUYOn84
Open long longBUY and strategy.position_size == 0On87
Open short shortSELL and strategy.position_size == 0On88
Open long longBUYOn90
Open short shortSELLOn91
Exit TP & SL stop and limiti_SLOn117
Exit TP & SL stop and limiti_SLOn118

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.

2/2trades 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 timingOrders fill at the next bar's open, after the signal bar has closed.

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

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−50.8%+102.5%1631%0.4054.7%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−31.6%+5.5%2025%0.3336.0%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+66.0%+9.8%667%2.7821.4%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−5.9%+8.4%650%0.6812.1%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−23.2%+16.7%450%0.5553.1%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−2.5%+21.5%250%0.7513.7%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+28.5%+148.3%475%2.6721.1%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−4.4%+17.1%10%0.004.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 market50%−$3,734.44
Sideways market850%−$214.51
Falling market333%−$1,132.57

Rising and falling mean the market moved more than 15% over the 90 bars before entry.

How bad could the drawdown be?

66.0%

The 95th percentile of the worst drawdown when the same 16 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 50.8% to 66.0%; the tick is what actually happened, 51.4%. Order luck alone moves it this much.

0%76%
All 16 trades
SideEntryExitBarsP&L
long7 Apr 2024 68,896.001 May 2024 60,672.0024−$1,200.72
short1 May 2024 60,672.006 May 2024 64,012.005−$491.63
long6 May 2024 64,012.005 Aug 2024 51,618.7091−$1,614.52
long26 Aug 2024 64,220.006 Sep 2024 56,180.0011−$842.63
short6 Sep 2024 56,180.0026 Sep 2024 65,648.6020−$991.12
long8 Oct 2024 62,224.0028 Oct 2024 69,929.1020$597.36
long23 Nov 2024 98,892.0018 Feb 2025 95,780.0087−$175.94
short18 Feb 2025 95,780.0026 Feb 2025 82,673.808$718.67
short14 Apr 2025 83,760.0027 Apr 2025 94,628.0013−$783.24
long27 Apr 2025 94,628.0019 May 2025 107,065.0022$681.22
long13 Jul 2025 117,420.0022 Aug 2025 112,500.0040−$251.63
short22 Aug 2025 112,500.0011 Sep 2025 113,960.0020−$77.82
long11 Sep 2025 113,960.005 Oct 2025 124,191.0024$495.25
short1 Dec 2025 90,360.0031 Jan 2026 77,819.0061$836.66
long18 Apr 2026 77,072.002 Jun 2026 66,199.4045−$978.12
short2 Jul 2026 60,024.0020 Aug 2026 70,145.9049−$1,003.34

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
Modulo Logic + EMA Strat this page—v4 strategy−50.8%1654.7%
255 EMA Strategy by tweakerIDema atr lowest highest valuewhenv4 strategy−218.4%11186.1%
Richard's Strategy by Deepak8369highest lowest atr emav4 strategy+34.6%7026.3%
Classic Long Term Trend Following System by Robrecht99ema highest lowest atrv5 strategy+2.9%51.1%
EMA Bounce Strategy by tweakerIDlowest highest valuewhen emav4 strategy−48.8%4856.6%
Positive Bars - Strategy by tweakerIDlowest highest valuewhen atrv4 strategy−40.3%754.7%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 33 msYes 1,000 bars in 135 msNot measured
PineTSNo v5 and v6 only—Not measured

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

Source

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

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © tweakerID// To understand this strategy first we need to look into the Modulo (%) operator. The modulo returns the remainder numerator // of a division's quotient (the result). If we do 5 / 3, we get 1 and 2/3 as a result, where the remainder is 2 (two thirds, in this case). This can be// used for many things, for example to determine when a number divides evenly into another number. If we divide 3/3, our result is 1,// with no remainder numerator, hence our modulo result is 0. In this strategy, we compare a given number (divisor, user defined) with the// the closing price of every candle (dividend, modifiable from the inputs panel) to determine if the result between their division is an even number. // If the answer is true, we have an entry signal. If this signal occurs below the EMA (length is defined by the user) we go short and// viceversa for longs. This logic can be reversed. In this case, the modulo works as a random-like filter for a moving average strategy// that usually struggles when the market is ranging.//@version=4//@version=4strategy("Modulo Logic + EMA Strat",      overlay=true,      default_qty_type=strategy.percent_of_equity,      default_qty_value=100,      initial_capital=10000,      commission_value=0.04,      calc_on_every_tick=false,      slippage=0)direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))/////////////////////// STRATEGY INPUTS ////////////////////////////////////////title1=input(true, "-----------------Strategy Inputs-------------------")  a=input(close, title="Dividend")b=input(4, title="Divisor")usemod=input(true, title="Use Modulo Logic")MALen=input(70, title="EMA Length")/////////////////////// BACKTESTER /////////////////////////////////////////////title2=input(true, "-----------------General Inputs-------------------")  // Backtester General Inputsi_SL=input(true, title="Use Stop Loss and Take Profit")i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])i_SPL=input(defval=10, title="Swing Point Lookback")i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01i_ATR = input(14, title="ATR Length")i_ATRMult = input(4, step=.1, title="ATR Multiple")i_TPRRR = input(1, step=.1, title="Take Profit Risk Reward Ratio")TS=input(false, title="Trailing Stop")// Bought and Sold Boolean Signalbought = strategy.position_size > strategy.position_size[1]  or strategy.position_size < strategy.position_size[1]// Price Action Stop and Take ProfitLL=(lowest(i_SPL))*(1-i_PercIncrement)HH=(highest(i_SPL))*(1+i_PercIncrement)LL_price = valuewhen(bought, LL, 0)HH_price = valuewhen(bought, HH, 0)entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRRstp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR// ATR StopATR=atr(i_ATR)*i_ATRMultATRLong = ohlc4 - ATRATRShort = ohlc4 + ATRATRLongStop = valuewhen(bought, ATRLong, 0)ATRShortStop = valuewhen(bought, ATRShort, 0)LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRRATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR// Strategy Stopfloat LongStop = nafloat ShortStop = nafloat StratTP = nafloat StratSTP = na/////////////////////// STRATEGY LOGIC /////////////////////////////////////////modulo=a%bevennumber=modulo==0MA=ema(close, MALen)plot(MA)BUY=usemod ? evennumber and close > MA : close > MASELL=usemod ? evennumber and close < MA : close < MA//Trading InputsDPR=input(true, "Allow Direct Position Reverse")reverse=input(false, "Reverse Trades")// Entriesif reverse    if not DPR        strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0)        strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0)    else             strategy.entry("long", strategy.long, when=SELL)        strategy.entry("short", strategy.short, when=BUY)else    if not DPR         strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0)        strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0)    else        strategy.entry("long", strategy.long, when=BUY)        strategy.entry("short", strategy.short, when=SELL)SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStopSSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStopTP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTPSTP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP//TrailingStopdif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_pricetrailOffset     = strategy.position_avg_price - SLvar tstop = float(na)if strategy.position_size > 0    tstop := high- trailOffset - dif    if tstop<tstop[1]        tstop:=tstop[1]else    tstop := naStrailOffset     = SSL - strategy.position_avg_pricevar Ststop = float(na)Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0  and strategy.position_size[1]>=0, low,0))if strategy.position_size < 0    Ststop := low+ StrailOffset + Sdif    if Ststop>Ststop[1]        Ststop:=Ststop[1]else    Ststop := nastrategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL, when=i_SL)strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL, when=i_SL)/////////////////////// PLOTS //////////////////////////////////////////////////plot(i_SL and strategy.position_size > 0 and not TS ? SL : i_SL and strategy.position_size > 0 and TS ? tstop : na , title='SL', style=plot.style_cross, color=color.red)plot(i_SL and strategy.position_size < 0 and not TS ? SSL : i_SL and strategy.position_size < 0 and TS ? Ststop : na , title='SSL', style=plot.style_cross, color=color.red)plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green)plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green)// Draw price action setup arrowsplotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar,  color=color.green, title="Bullish Setup", size=size.auto)plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar,  color=color.red, title="Bearish Setup", size=size.auto)