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
- 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
VerifiedSame 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))⋯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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Strategy Direction | 0 | int (written input.integer) · min -1 · max 1 | line 22 |
| -----------------Strategy Inputs------------------- | true | bool | unused |
| Dividend | close | source | modulo |
| Divisor | 4 | int | modulo |
| Use Modulo Logic | true | bool | BUY SELL |
| EMA Length | 70 | int | MA |
| -----------------General Inputs------------------- | true | bool | unused |
| Use Stop Loss and Take Profit | true | bool | exit TP & SL SL SSL TP STP |
| Type Of Stop | ATR Stop | string · options ["Strategy Stop", "Swing Lo/Hi", "ATR Stop"] | SL SSL TP STP |
| Swing Point Lookback | 10 | int | LL HH |
| Swing Point SL Perc Increment | 3 | int · step .1 | LL HH |
| ATR Length | 14 | int | ATR |
| ATR Multiple | 4 | int · step .1 | ATR |
| Take Profit Risk Reward Ratio | 1 | int · step .1 | tp stp ATRtp ATRstp |
| Trailing Stop | false | bool | exit TP & SL SL SSL |
| Allow Direct Position Reverse | true | bool | entry long entry short entry long entry short entry long entry short entry long entry short line 79 line 86 |
| Reverse Trades | false | bool | line 78 |
What it calculates
- Lowest (
lowest,ta.lowestin v5)Swing Point Lookback (10)LL · line 44 - Highest (
highest,ta.highestin v5)Swing Point Lookback (10)HH · line 45 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, LL, 0LL_price · line 46 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, HH, 0HH_price · line 47 - ATR (
atr,ta.atrin v5)ATR Length (14)ATR · line 53 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, ATRLong, 0ATRLongStop · line 56 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, ATRShort, 0ATRShortStop · line 57 - EMA (
ema,ta.emain 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open long long | SELL and strategy.position_size == 0 | On | 80 |
| Open short short | BUY and strategy.position_size == 0 | On | 81 |
| Open long long | SELL | On | 83 |
| Open short short | BUY | On | 84 |
| Open long long | BUY and strategy.position_size == 0 | On | 87 |
| Open short short | SELL and strategy.position_size == 0 | On | 88 |
| Open long long | BUY | On | 90 |
| Open short short | SELL | On | 91 |
| Exit TP & SL stop and limit | i_SL | On | 117 |
| Exit TP & SL stop and limit | i_SL | On | 118 |
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 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.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | −50.8% | +102.5% | 16 | 31% | 0.40 | 54.7% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −31.6% | +5.5% | 20 | 25% | 0.33 | 36.0% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +66.0% | +9.8% | 6 | 67% | 2.78 | 21.4% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −5.9% | +8.4% | 6 | 50% | 0.68 | 12.1% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −23.2% | +16.7% | 4 | 50% | 0.55 | 53.1% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −2.5% | +21.5% | 2 | 50% | 0.75 | 13.7% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +28.5% | +148.3% | 4 | 75% | 2.67 | 21.1% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −4.4% | +17.1% | 1 | 0% | 0.00 | 4.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 | 5 | 0% | −$3,734.44 |
| Sideways market | 8 | 50% | −$214.51 |
| Falling market | 3 | 33% | −$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.
All 16 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 7 Apr 2024 68,896.00 | 1 May 2024 60,672.00 | 24 | −$1,200.72 |
| short | 1 May 2024 60,672.00 | 6 May 2024 64,012.00 | 5 | −$491.63 |
| long | 6 May 2024 64,012.00 | 5 Aug 2024 51,618.70 | 91 | −$1,614.52 |
| long | 26 Aug 2024 64,220.00 | 6 Sep 2024 56,180.00 | 11 | −$842.63 |
| short | 6 Sep 2024 56,180.00 | 26 Sep 2024 65,648.60 | 20 | −$991.12 |
| long | 8 Oct 2024 62,224.00 | 28 Oct 2024 69,929.10 | 20 | $597.36 |
| long | 23 Nov 2024 98,892.00 | 18 Feb 2025 95,780.00 | 87 | −$175.94 |
| short | 18 Feb 2025 95,780.00 | 26 Feb 2025 82,673.80 | 8 | $718.67 |
| short | 14 Apr 2025 83,760.00 | 27 Apr 2025 94,628.00 | 13 | −$783.24 |
| long | 27 Apr 2025 94,628.00 | 19 May 2025 107,065.00 | 22 | $681.22 |
| long | 13 Jul 2025 117,420.00 | 22 Aug 2025 112,500.00 | 40 | −$251.63 |
| short | 22 Aug 2025 112,500.00 | 11 Sep 2025 113,960.00 | 20 | −$77.82 |
| long | 11 Sep 2025 113,960.00 | 5 Oct 2025 124,191.00 | 24 | $495.25 |
| short | 1 Dec 2025 90,360.00 | 31 Jan 2026 77,819.00 | 61 | $836.66 |
| long | 18 Apr 2026 77,072.00 | 2 Jun 2026 66,199.40 | 45 | −$978.12 |
| short | 2 Jul 2026 60,024.00 | 20 Aug 2026 70,145.90 | 49 | −$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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Modulo Logic + EMA Strat this page | — | v4 strategy | −50.8% | 16 | 54.7% |
| 255 EMA Strategy by tweakerID | ema atr lowest highest valuewhen | v4 strategy | −218.4% | 11 | 186.1% |
| Richard's Strategy by Deepak8369 | highest lowest atr ema | v4 strategy | +34.6% | 70 | 26.3% |
| Classic Long Term Trend Following System by Robrecht99 | ema highest lowest atr | v5 strategy | +2.9% | 5 | 1.1% |
| EMA Bounce Strategy by tweakerID | lowest highest valuewhen ema | v4 strategy | −48.8% | 48 | 56.6% |
| Positive Bars - Strategy by tweakerID | lowest highest valuewhen atr | v4 strategy | −40.3% | 7 | 54.7% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 33 ms | Yes 1,000 bars in 135 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.
Source
Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © 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)