Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

MA Simple Strategy with SL & TP & ATR Filters

A Pine Script v5 strategy built on ATR or SMA (14). It has 8 order rules, 2 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.1% commission. 29 settings; defaults include SMA Length for ATR SMA 40, Stop Loss Type ATR and ATR Length 14.

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 MA Simple Strategy with SL & TP & ATR Filters repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 5 of 5 trades.
How did MA Simple Strategy with SL & TP & ATR Filters do on BTCUSDT 1D with default settings?
−4.71%
From 26 Jan 2024 to 21 Oct 2026, over 29 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does MA Simple Strategy with SL & TP & ATR Filters 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: 29 before, 130 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download.
Does MA Simple Strategy with SL & TP & ATR Filters use a stop loss?
Yes
strategy.exit sets a stop on line 198, 199, 202, 203.
Does MA Simple Strategy with SL & TP & ATR Filters run in Zeal Terminal?
Yes
It compiles in 61 ms and runs 1,000 bars in 150 ms, in the browser.

BTCUSDT · 1D · default settings

  • SMA 1
  • SMA 2
  • SMA 3
  • SMA 4
  • Position
  • Long Stop Loss
  • Short Stop Loss
  • Long Take Profit
  • Short Take Profit
  • 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 (29)
50,00075,000100,000125,000AprJulOct2025AprJulOct2026AprJulOct$95,287$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 direction = strategy.long, direction = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 190, 192) so the engine trades the way the script says.
Net profit
−4.71%
−$4,709.14
Buy and hold
+102.5%
same period
Closed trades
29
12 won · 17 lost
Profitable
41.4%
of closed trades
Profit factor
0.93
gross profit ÷ gross loss
Max drawdown
46.42%
−$46,423.50

One run with the author's default settings, $100,000 starting capital, commission as the script sets it. 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

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

Settings

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

SettingDefaultType and rangeFeeds
Time
Start DateChoose Backtest Start Datetimestamp("20 Jan 1990 00:00 +0900")timec_timeCond
End DateChoose Backtest End Datetimestamp("20 Dec 2030 00:00 +0900")timec_timeCond
Long / Short
Long?Enable Long Position Trade?trueboolopenLong closeLong
Short?Enable Short Position Trade?trueboolopenShort closeShort
Filters
ATR Filter On?ATR Filter On?trueboolopenLong openShort
SMA Length for ATR SMAATR should be bigger than this40int · min 1 · max 100000 · step 1i_ATRFilter
Shared Inputs
Enable SL & TP?trueboolexit Long Take Profit / Stop Loss exit Long Stop Loss exit Short Take Profit / Stop Loss exit Short Stop Loss line 197 line 201
Enable Trailing SL?Enable Stop Loss & Take Profit? \n\Enable Trailing SL?falseboolc_longSLPrice c_stopPrice c_shortSLPrice
Stop Loss TypeStop Loss based on %? ATR?ATRstring · options ["Percent", "ATR"]line 119 line 136
ATR Length14int · min 1 · max 200 · step 1i_ATRFilter openAtr
Take Profit TypeTake Profit based on %? ATR? R-R ratio?R:Rstring · options ["Percent", "ATR", "R:R"]line 153 line 171
Take Profit Quantity %% of position when tp target is met.50float · min 0.0 · max 100 · step 1.0exit Long Take Profit / Stop Loss exit Short Take Profit / Stop Loss
Long Stop Loss / Take Profit
SL Percent3floatline 120
TP PercentLong Stop Loss && Take Profit Percent?3floatline 154
SL ATR Multiplier3float · min 1 · max 200 · step 0.1line 121
TP ATR MultiplierATR > Long Stop Loss && Take Profit ATR Multiplier? \n\Stop Loss = i_slATRMultLong * ATR (i_slATRLen) \n\Take Profit = i_tpATRMultLong * ATR (i_tpATRLen)3float · min 1 · max 200 · step 0.1line 155
R:R RatioR:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss1.8float · min 0.1 · max 200 · step 0.1line 156
Short Stop Loss / Take Profit
SL Percent3floatline 137
TP PercentShort Stop Loss && Take Profit Percent?3floatline 172
SL ATR Multiplier3float · min 1 · max 200 · step 0.1line 138
TP ATR MultiplierATR > Short Stop Loss && Take Profit ATR Multiplier? \n\Stop Loss = i_slATRMultShort * ATR (i_slATRLen) \n\Take Profit = i_tpATRMultShort * ATR (i_tpATRLen)3float · min 1 · max 200 · step 0.1line 173
R:R RatioR:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss1.8float · min 0.1 · max 200 · step 0.1line 174
Strategy
MA TypeChoose MA TypeRMAstring · options ["SMA", "EMA", "WMA", "HMA", "RMA", "VWMA", "SWMA", "ALMA", "VWAP"]line 68
MA 1 Length5int · min 1c_MA1
MA 2 Length10int · min 1c_MA2
MA 3 Length15int · min 1c_MA3
MA 4 Length25int · min 1c_MA4
ALMA Offset ValueThe Value of ALMA offset0.7floatc_MA1 c_MA2 c_MA3 c_MA4
ALMA Sigma ValueThe Value of ALMA sigma7floatc_MA1 c_MA2 c_MA3 c_MA4

What it calculates

  • ATR / SMAlength = ATR Length (14)i_ATRFilter · line 65

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.

high · low · closehigh · low · closeprice datai_slATRLenATR Lengthsetting · 14i_ATRSMALenSMA Length for ATR SMAsetting · 40closecloseprice datai_MA1LenMA 1 Lengthsetting · 5i_ALMAOffsetALMA Offset Valuesetting · 0.7i_ALMASigmaALMA Sigma Valuesetting · 7i_MA2LenMA 2 Lengthsetting · 10i_MA3LenMA 3 Lengthsetting · 15i_MA4LenMA 4 Lengthsetting · 25highhighprice datalowlowprice datatimetimeprice datai_startStart Datesetting · timestamp("20 Jan 1…i_endEnd Datesetting · timestamp("20 Dec 2…i_ATRFilterATR / SMA→ i_ATRFilterc_MA1c_MA1valuec_MA2c_MA2valuec_MA3c_MA3valuec_MA4c_MA4valuec_longSLPricec_longSLPricevaluec_stopPricec_stopPricevaluec_shortSLPricec_shortSLPricevalueenterLongenterLongconditionenterShortenterShortconditioncloseLongcloseLongconditioncloseShortcloseShortconditionlongIsActivelongIsActiveconditionshortIsActiveshortIsActiveconditionc_timeCondc_timeCondconditionopenLongCond, openShortCondopenLongCond · openShor…2 conditionsopenLongopenLongconditionopenShortopenShortconditionlongTPExecutedlongTPExecutedconditionshortTPExecutedshortTPExecutedconditionopenAtropenAtrconditionc_longTPPricec_longTPPriceconditionc_shortTPPricec_shortTPPriceconditionma1Color, ma2Color, ma3Color, ma4Color, openLongCondColor, ATRFilterColor, posColor, stopLossColor, longTPExecutedColor, shortTPExecutedColor, takeProfitColorColourma1Color · ma2Color +9entry:Long EntryOpen Long Entrystrategy.entryentry:Short EntryOpen Short Entrystrategy.entryclose:Long EntryClose Long Entrystrategy.closeclose:Short EntryClose Short Entrystrategy.closeexit:Long Take Profit / Stop Lossexit Long Take Profit /…strategy.exitexit:Long Stop Lossexit Long Stop Lossstrategy.exitexit:Short Take Profit / Stop Lossexit Short Take Profit …strategy.exitexit:Short Stop Lossexit Short Stop Lossstrategy.exitplot:85SMA 1plotplot:87SMA 2plotplot:89SMA 3plotplot:91SMA 4plotbgcolor:97bgcolorbgcolorbgcolor:99bgcolorbgcolorplot:208Positionplotplot:210Long Stop Lossplotplot:211Short Stop Lossplotplot:219Long Take Profitplotplot:220Short Take Profitplot

Order rules

OrderFires whenBy defaultLine
Open Long Entry long(enterLong)On190
Open Short Entry short(enterShort)On192
Close Long Entry(closeLong)On194
Close Short Entry(closeShort)On196
Exit Long Take Profit / Stop Loss stop and limit(longIsActive and i_useSLTP)On198
Exit Long Stop Loss stop(longIsActive and i_useSLTP)On199
Exit Short Take Profit / Stop Loss stop and limit(shortIsActive and i_useSLTP)On202
Exit Short Stop Loss stop(shortIsActive and i_useSLTP)On203

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.

5/5trades 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−4.7%+102.5%2941%0.9346.4%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+3.1%+5.5%2631%1.119.8%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+149.5%+9.8%2365%4.3633.3%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+2.1%+8.4%2446%1.0716.9%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+14.3%+16.7%2744%1.1551.3%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+14.3%+21.5%2642%1.4120.7%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−28.3%+148.3%2934%0.6348.6%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−2.2%+17.1%3238%0.9216.0%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 market425%−$8,609.07
Sideways market2045%$4,774.37
Falling market540%−$874.43

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

How bad could the drawdown be?

40.3%

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

0%47%
All 29 trades
SideEntryExitBarsP&L
long19 Mar 2024 67,610.0014 Apr 2024 63,924.5026−$5,640.00
short6 Jul 2024 56,628.8015 Jul 2024 63,312.309−$5,662.61
short6 Jul 2024 56,628.8015 Jul 2024 63,312.309−$5,662.61
short16 Jul 2024 64,724.1017 Jul 2024 65,044.001−$576.36
long27 Jul 2024 67,908.003 Aug 2024 60,615.307−$4,501.20
long27 Jul 2024 67,908.003 Aug 2024 60,615.307−$4,501.20
short6 Aug 2024 54,018.8023 Aug 2024 63,494.2017−$6,515.80
short6 Aug 2024 54,018.8023 Aug 2024 63,494.2017−$6,515.80
long30 Oct 2024 72,736.4011 Nov 2024 84,232.0012$4,704.97
long30 Oct 2024 72,736.4024 Dec 2024 94,881.5055$9,119.56
long20 Jan 2025 101,332.005 Feb 2025 97,763.1016−$2,757.83
short3 Mar 2025 94,270.0027 Mar 2025 86,909.2024$5,439.35
short10 Apr 2025 82,615.2016 Apr 2025 83,644.006−$1,111.69
long24 May 2025 107,318.006 Jun 2025 101,509.0013−$4,247.69
long10 Jun 2025 110,263.0019 Jun 2025 104,887.009−$3,625.71
long27 Jun 2025 106,947.003 Aug 2025 112,546.0037$3,414.47
long14 Aug 2025 123,306.0018 Aug 2025 114,851.004−$2,513.05
long14 Aug 2025 123,306.0018 Aug 2025 114,851.004−$2,513.05
short1 Sep 2025 108,246.0012 Sep 2025 115,483.0011−$4,566.99
long4 Oct 2025 122,232.0010 Oct 2025 114,157.006−$2,097.86
long4 Oct 2025 122,232.0010 Oct 2025 114,157.006−$2,097.86
long11 Oct 2025 112,774.0014 Oct 2025 115,166.003$1,103.39
short19 Oct 2025 107,185.0021 Nov 2025 84,966.8033$6,022.66
short19 Oct 2025 107,185.004 Jan 2026 90,628.0077$4,473.14
short30 Jan 2026 84,650.205 Feb 2026 70,470.006$5,724.41
short30 Jan 2026 84,650.2012 Mar 2026 70,191.9041$5,838.06
short3 Jun 2026 66,760.8010 Jul 2026 63,230.0037$4,108.47
long21 Aug 2026 73,027.0021 Sep 2026 82,689.1031$5,516.74
long21 Aug 2026 73,027.0015 Oct 2026 81,682.0055$4,932.92

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
MA Simple Strategy with SL & TP & ATR Filters this page—v5 strategy−4.7%2946.4%
I11L - Better Buy Low Volatility or High Volatility- by I11Latr smav5 strategy+19.2%8337.4%
Vortex Cross w-MA Confirmation by DraftVentureatr smav5 strategy+2.4%524.7%
Configurable Multi MA Crossover Voting System by levieuxsma atrv5 strategy+28.5%539.4%
Swing Trend Strategy by Inkedlausma atrv5 strategy+11.2%516.2%
SSL Backtester With ATR SL TP and Money Management by JBTrippinsma atrv4 strategy+8.5%553.9%

Upgrade and export

Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.

  • No v6-only features. v6 is not needed to run this script.

Clean v5

Verified

Nothing to change.

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: 29 before, 130 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.

⋯// © fpemehd-// @version=5+// @version=6// # ========================================================================= #⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 61 msWith a workaround 1,000 bars in 150 msNot measured
PineTSNot testedNot testedNot measured

Zeal Terminal's engine currently reads an order side written as direction = strategy.long, direction = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 190, 192) so the engine trades the way the script says.

“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.

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/// © fpemehd// @version=5// # ========================================================================= #// #                   |   STRATEGY  |// # ========================================================================= #strategy(title = 'MA Simple Strategy with SL & TP & ATR Filters',      shorttitle = 'MA Strategy',      overlay = true,      pyramiding = 0,      default_qty_type = strategy.percent_of_equity,      default_qty_value = 100,      commission_type  = strategy.commission.percent,      commission_value = 0.1,      initial_capital = 100000,      max_lines_count = 150,      max_labels_count = 300)// # ========================================================================= #// #                          Inputs// # ========================================================================= #// 1. Timei_start = input.time (defval = timestamp("20 Jan 1990 00:00 +0900"), title = "Start Date", tooltip = "Choose Backtest Start Date", inline = "Start Date", group = "Time" ) i_end = input.time (defval = timestamp("20 Dec 2030 00:00 +0900"), title = "End Date", tooltip = "Choose Backtest End Date", inline = "End Date", group = "Time" ) c_timeCond = time >= i_start and time <= i_end// 2. Inputs for direction: Long? Short? Both? i_longEnabled = input.bool(defval = true , title = "Long?", tooltip = "Enable Long Position Trade?", inline = "Long / Short", group = "Long / Short" )i_shortEnabled = input.bool(defval = true , title = "Short?", tooltip = "Enable Short Position Trade?", inline = "Long / Short", group = "Long / Short" )// 3. Use Filters? What Filters?i_ATRFilterOn = input.bool(defval = true , title = "ATR Filter On?", tooltip = "ATR Filter On?", inline = "ATR Filter", group =  "Filters") i_ATRSMALen = input.int(defval = 40 , title = "SMA Length for ATR SMA", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ATR should be bigger than this", inline = "ATR Filter", group = "Filters") // 3. Shared inputs for Long and Short//// 3-1. Inputs for Stop Loss Type: normal? or trailing? //// If trailing, always trailing or trailing after take profit order executed?i_useSLTP = input.bool(defval =  true, title = "Enable SL & TP?", tooltip = "", inline = "Enable SL & TP & SL Type", group = "Shared Inputs") i_tslEnabled = input.bool(defval = false , title = "Enable Trailing SL?", tooltip = "Enable Stop Loss & Take Profit? \n\Enable Trailing SL?", inline = "Enable SL & TP & SL Type", group = "Shared Inputs") // i_tslAfterTP = input.bool(defval = true , title = "Enable Trailing SL after TP?", tooltip = "Enable Trailing SL after TP?", inline = "Trailing SL Execution", group = "Shared Inputs") i_slType = input.string(defval = "ATR", title = "Stop Loss Type", options = ["Percent", "ATR"], tooltip = "Stop Loss based on %? ATR?", inline = "Stop Loss Type", group = "Shared Inputs") i_slATRLen = input.int(defval = 14, title = "ATR Length", minval = 1 , maxval = 200 , step = 1, inline = "Stop Loss ATR", group = "Shared Inputs")  i_tpType = input.string(defval = "R:R", title = "Take Profit Type", options = ["Percent", "ATR", "R:R"], tooltip = "Take Profit based on %? ATR? R-R ratio?", inline = "Take Profit Type", group = "Shared Inputs") //// 3-2. Inputs for Quantityi_tpQuantityPerc = input.float(defval = 50, title = 'Take Profit Quantity %', minval = 0.0, maxval = 100, step = 1.0, tooltip = '% of position when tp target is met.', group = 'Shared Inputs')// 4. Inputs for Long Stop Loss & Long Take Profiti_slPercentLong = input.float(defval = 3, title = "SL Percent", tooltip = "", inline = "Percent > Long Stop Loss / Take Profit Percent", group = "Long Stop Loss / Take Profit") i_tpPercentLong = input.float(defval = 3, title = "TP Percent", tooltip = "Long Stop Loss && Take Profit Percent?", inline = "Percent > Long Stop Loss / Take Profit Percent", group = "Long Stop Loss / Take Profit") i_slATRMultLong = input.float(defval = 3, title = "SL ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "", inline = "Long Stop Loss / Take Profit ATR", group = "Long Stop Loss / Take Profit") i_tpATRMultLong = input.float(defval = 3, title = "TP ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "ATR > Long Stop Loss && Take Profit ATR Multiplier? \n\Stop Loss = i_slATRMultLong * ATR (i_slATRLen) \n\Take Profit = i_tpATRMultLong * ATR (i_tpATRLen)", inline = "Long Stop Loss / Take Profit ATR", group = "Long Stop Loss / Take Profit") i_tpRRratioLong = input.float(defval = 1.8, title = "R:R Ratio", minval = 0.1 , maxval = 200 , step = 0.1, tooltip = "R:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss", inline = "R:R Ratio", group = "Long Stop Loss / Take Profit") // 5. Inputs for Short Stop Loss & Short Take Profiti_slPercentShort = input.float(defval = 3, title = "SL Percent", tooltip = "", inline = "Percent > Short Stop Loss / Take Profit Percent", group = "Short Stop Loss / Take Profit") i_tpPercentShort = input.float(defval = 3, title = "TP Percent", tooltip = "Short Stop Loss && Take Profit Percent?", inline = "Percent > Short Stop Loss / Take Profit Percent", group = "Short Stop Loss / Take Profit") i_slATRMultShort = input.float(defval = 3, title = "SL ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "", inline = "ATR > Short Stop Loss / Take Profit ATR", group = "Short Stop Loss / Take Profit") i_tpATRMultShort = input.float(defval = 3, title = "TP ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "ATR > Short Stop Loss && Take Profit ATR Multiplier? \n\Stop Loss = i_slATRMultShort * ATR (i_slATRLen) \n\Take Profit = i_tpATRMultShort * ATR (i_tpATRLen)", inline = "ATR > Short Stop Loss / Take Profit ATR", group = "Short Stop Loss / Take Profit") i_tpRRratioShort = input.float(defval = 1.8, title = "R:R Ratio", minval = 0.1 , maxval = 200 , step = 0.1, tooltip = "R:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss", inline = "R:R Ratio", group = "Short Stop Loss / Take Profit") // 6. Inputs for logici_MAType = input.string(defval = "RMA", title = "MA Type", options = ["SMA", "EMA", "WMA", "HMA", "RMA", "VWMA", "SWMA", "ALMA", "VWAP"], tooltip = "Choose MA Type", inline = "MA Type", group = 'Strategy') i_MA1Len = input.int(defval = 5, title = 'MA 1 Length', minval = 1, inline = 'MA Length', group = 'Strategy')i_MA2Len = input.int(defval = 10, title = 'MA 2 Length', minval = 1, inline = 'MA Length', group = 'Strategy')i_MA3Len = input.int(defval = 15, title = 'MA 3 Length', minval = 1, inline = 'MA Length', group = 'Strategy')i_MA4Len = input.int(defval = 25, title = 'MA 4 Length', minval = 1, inline = 'MA Length', group = 'Strategy')i_ALMAOffset = input.float(defval = 0.7 , title = "ALMA Offset Value", tooltip = "The Value of ALMA offset", inline = "ALMA Input", group = 'Strategy')i_ALMASigma = input.float(defval = 7 , title = "ALMA Sigma Value", tooltip = "The Value of ALMA sigma", inline = "ALMA Input", group = 'Strategy')// # ========================================================================= #// #                          Entry, Close Logic// # ========================================================================= #bool i_ATRFilter = ta.atr(length = i_slATRLen) >= ta.sma(source = ta.atr(length = i_slATRLen), length = i_ATRSMALen) ? true : false// calculate Technical Indicators for the LogicgetMAValue (source, length, almaOffset, almaSigma) =>     switch i_MAType         'SMA' => ta.sma(source = source, length = length)         'EMA' => ta.ema(source = source, length = length)         'WMA' => ta.wma(source = source, length = length)         'HMA' => ta.hma(source = source, length = length)         'RMA' => ta.rma(source = source, length = length)         'SWMA' => ta.swma(source = source)         'ALMA' => ta.alma(series = source, length = length, offset = almaOffset, sigma = almaSigma)         'VWMA' => ta.vwma(source = source, length = length)         'VWAP' => ta.vwap(source = source)        => na float c_MA1 = getMAValue(close, i_MA1Len, i_ALMAOffset, i_ALMASigma)float c_MA2 = getMAValue(close, i_MA2Len, i_ALMAOffset, i_ALMASigma)float c_MA3 = getMAValue(close, i_MA3Len, i_ALMAOffset, i_ALMASigma)float c_MA4 = getMAValue(close, i_MA4Len, i_ALMAOffset, i_ALMASigma)// Logic: 정배열 될 떄 들어가var ma1Color = color.new(color.red, 0)plot(series = c_MA1, title = 'SMA 1', color = ma1Color, linewidth = 1, style = plot.style_line)var ma2Color = color.new(color.orange, 0)plot(series = c_MA2, title = 'SMA 2', color = ma2Color, linewidth = 1, style = plot.style_line)var ma3Color = color.new(color.yellow, 0)plot(series = c_MA3, title = 'SMA 3', color = ma3Color, linewidth = 1, style = plot.style_line)var ma4Color = color.new(color.green, 0)plot(series = c_MA4, title = 'SMA 4', color = ma4Color, linewidth = 1, style = plot.style_line)bool openLongCond = (c_MA1 >= c_MA2 and c_MA2 >= c_MA3 and c_MA3 >= c_MA4) bool openShortCond = (c_MA1 <= c_MA2 and c_MA2 <= c_MA3 and c_MA3 <= c_MA4)bool openLong = i_longEnabled and openLongCond and (not i_ATRFilterOn or i_ATRFilter)bool openShort = i_shortEnabled and openShortCond and (not i_ATRFilterOn or i_ATRFilter)openLongCondColor = openLongCond ? color.new(color = color.blue, transp = 80) : nabgcolor(color = openLongCondColor)ATRFilterColor = i_ATRFilter ? color.new(color = color.orange, transp = 80) : na bgcolor(color = ATRFilterColor)bool enterLong = openLong and not (strategy.opentrades.size(strategy.opentrades-1) > 0)bool enterShort = openShort and not (strategy.opentrades.size(strategy.opentrades-1) < 0)bool closeLong = i_longEnabled and (c_MA1[1] >= c_MA2[1] and c_MA2[1] >= c_MA3[1] and c_MA3[1] >= c_MA4[1]) and not (c_MA1 >= c_MA2 and c_MA2 >= c_MA3 and c_MA3 >= c_MA4) bool closeShort = i_shortEnabled and (c_MA1[1] <= c_MA2[1] and c_MA2[1] <= c_MA3[1] and c_MA3[1] <= c_MA4[1]) and not (c_MA1 <= c_MA2 and c_MA2 <= c_MA3 and c_MA3 <= c_MA4)// # ========================================================================= #// #                          Position, Status Conrtol// # ========================================================================= #// longisActive: New Long || Already Long && not closeLong, short is the samebool longIsActive = enterLong or strategy.opentrades.size(strategy.opentrades - 1) > 0 and not closeLongbool shortIsActive = enterShort or strategy.opentrades.size(strategy.opentrades - 1) < 0 and not closeShort// before longTPExecution: no trailing SL && after longTPExecution: trailing SL starts// longTPExecution qunatity should be less than 100% bool longTPExecuted = falsebool shortTPExecuted = false// # ========================================================================= #// #                          Long Stop Loss Logic// # ========================================================================= #float openAtr = ta.valuewhen(enterLong or enterShort, ta.atr(i_slATRLen), 0)f_getLongSL (source) =>     switch i_slType        'Percent' => source * (1 - (i_slPercentLong/100))        'ATR' => source - i_slATRMultLong * openAtr        => navar float c_longSLPrice = nac_longSLPrice := if (longIsActive)    if (enterLong)        f_getLongSL(close)    else        c_stopPrice = f_getLongSL(i_tslEnabled ? high : strategy.opentrades.entry_price(trade_num = strategy.opentrades - 1))        math.max(c_stopPrice, nz(c_longSLPrice[1]))else    na// # ========================================================================= #// #                          Short Stop Loss Logic// # ========================================================================= #f_getShortSL (source) =>     switch i_slType        'Percent' => source * (1 + (i_slPercentShort)/100)        'ATR' => source + i_slATRMultShort * openAtr        => navar float c_shortSLPrice = nac_shortSLPrice := if (shortIsActive)    if (enterShort)        f_getShortSL (close)    else        c_stopPrice = f_getShortSL(i_tslEnabled ? low : strategy.opentrades.entry_price(strategy.opentrades - 1))        math.min(c_stopPrice, nz(c_shortSLPrice[1], 999999.9))else    na// # ========================================================================= #// #                          Long Take Profit Logic// # ========================================================================= #f_getLongTP () =>     switch i_tpType        'Percent' => close * (1 + (i_tpPercentLong/100))        'ATR' => close + i_tpATRMultLong * openAtr        'R:R' => close + i_tpRRratioLong * (close - f_getLongSL(close))        => navar float c_longTPPrice = nac_longTPPrice := if (longIsActive and not longTPExecuted)    if (enterLong)        f_getLongTP()    else         nz(c_longTPPrice[1], f_getLongTP())else    nalongTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) > 0 and (longTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) < strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and high >= c_longTPPrice)// # ========================================================================= #// #                          Short Take Profit Logic// # ========================================================================= #f_getShortTP () =>     switch i_tpType        'Percent' => close * (1 - (i_tpPercentShort/100))        'ATR' => close - i_tpATRMultShort * openAtr        'R:R' => close - i_tpRRratioShort * (close - f_getLongSL(close))        => navar float c_shortTPPrice = nac_shortTPPrice := if (shortIsActive and not shortTPExecuted)    if (enterShort)        f_getShortTP()    else        nz(c_shortTPPrice[1], f_getShortTP())else    nashortTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) < 0 and (shortTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) > strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and low <= c_shortTPPrice)// # ========================================================================= #// #                          Make Orders// # ========================================================================= #if (c_timeCond)    if (enterLong)        strategy.entry(id = "Long Entry", direction = strategy.long , comment = 'Long(' + syminfo.ticker + '): Started', alert_message = 'Long(' + syminfo.ticker + '): Started')    if (enterShort)        strategy.entry(id = "Short Entry", direction = strategy.short , comment = 'Short(' + syminfo.ticker + '): Started', alert_message = 'Short(' + syminfo.ticker + '): Started')    if (closeLong)        strategy.close(id = 'Long Entry', comment = 'Close Long', alert_message = 'Long: Closed at market price')    if (closeShort)        strategy.close(id = 'Short Entry', comment = 'Close Short', alert_message = 'Short: Closed at market price')    if (longIsActive and i_useSLTP)        strategy.exit(id = 'Long Take Profit / Stop Loss', from_entry = 'Long Entry', qty_percent = i_tpQuantityPerc, limit = c_longTPPrice, stop = c_longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Take Profit or Stop Loss executed')        strategy.exit(id = 'Long Stop Loss', from_entry = 'Long Entry', stop = c_longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Stop Loss executed')        if (shortIsActive and i_useSLTP)        strategy.exit(id = 'Short Take Profit / Stop Loss', from_entry = 'Short Entry', qty_percent = i_tpQuantityPerc, limit = c_shortTPPrice, stop = c_shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Take Profit or Stop Loss executed')        strategy.exit(id = 'Short Stop Loss', from_entry = 'Short Entry', stop = c_shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Stop Loss executed')// # ========================================================================= #// #                          Plot// # ========================================================================= #var posColor = color.new(color.white, 0)plot(series = strategy.opentrades.entry_price(strategy.opentrades - 1), title = 'Position', color = posColor, linewidth = 1, style = plot.style_linebr)var stopLossColor = color.new(color.maroon, 0)plot(series = c_longSLPrice, title = 'Long Stop Loss', color = stopLossColor, linewidth = 1, style = plot.style_linebr, offset = 1)plot(series = c_shortSLPrice, title = 'Short Stop Loss', color = stopLossColor, linewidth = 1, style = plot.style_linebr, offset = 1)longTPExecutedColor = longTPExecuted ? color.new(color = color.green, transp = 80) : na //bgcolor(color = longTPExecutedColor) shortTPExecutedColor = shortTPExecuted ? color.new(color = color.red, transp = 80) : na //bgcolor(color = shortTPExecutedColor) // isPositionOpenedColor = strategy.opentrades.size(strategy.opentrades-1) != 0 ? color.new(color = color.yellow, transp = 90) : na // bgcolor(color = isPositionOpenedColor) var takeProfitColor = color.new(color.teal, 0)plot(series = c_longTPPrice, title = 'Long Take Profit', color = takeProfitColor, linewidth = 1, style = plot.style_linebr, offset = 1)plot(series = c_shortTPPrice, title = 'Short Take Profit', color = takeProfitColor, linewidth = 1, style = plot.style_linebr, offset = 1)