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
- 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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Time | |||
| Start DateChoose Backtest Start Date | timestamp("20 Jan 1990 00:00 +0900") | time | c_timeCond |
| End DateChoose Backtest End Date | timestamp("20 Dec 2030 00:00 +0900") | time | c_timeCond |
| Long / Short | |||
| Long?Enable Long Position Trade? | true | bool | openLong closeLong |
| Short?Enable Short Position Trade? | true | bool | openShort closeShort |
| Filters | |||
| ATR Filter On?ATR Filter On? | true | bool | openLong openShort |
| SMA Length for ATR SMAATR should be bigger than this | 40 | int · min 1 · max 100000 · step 1 | i_ATRFilter |
| Shared Inputs | |||
| Enable SL & TP? | true | bool | exit 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? | false | bool | c_longSLPrice c_stopPrice c_shortSLPrice |
| Stop Loss TypeStop Loss based on %? ATR? | ATR | string · options ["Percent", "ATR"] | line 119 line 136 |
| ATR Length | 14 | int · min 1 · max 200 · step 1 | i_ATRFilter openAtr |
| Take Profit TypeTake Profit based on %? ATR? R-R ratio? | R:R | string · options ["Percent", "ATR", "R:R"] | line 153 line 171 |
| Take Profit Quantity %% of position when tp target is met. | 50 | float · min 0.0 · max 100 · step 1.0 | exit Long Take Profit / Stop Loss exit Short Take Profit / Stop Loss |
| Long Stop Loss / Take Profit | |||
| SL Percent | 3 | float | line 120 |
| TP PercentLong Stop Loss && Take Profit Percent? | 3 | float | line 154 |
| SL ATR Multiplier | 3 | float · min 1 · max 200 · step 0.1 | line 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) | 3 | float · min 1 · max 200 · step 0.1 | line 155 |
| R:R RatioR:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss | 1.8 | float · min 0.1 · max 200 · step 0.1 | line 156 |
| Short Stop Loss / Take Profit | |||
| SL Percent | 3 | float | line 137 |
| TP PercentShort Stop Loss && Take Profit Percent? | 3 | float | line 172 |
| SL ATR Multiplier | 3 | float · min 1 · max 200 · step 0.1 | line 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) | 3 | float · min 1 · max 200 · step 0.1 | line 173 |
| R:R RatioR:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss | 1.8 | float · min 0.1 · max 200 · step 0.1 | line 174 |
| Strategy | |||
| MA TypeChoose MA Type | RMA | string · options ["SMA", "EMA", "WMA", "HMA", "RMA", "VWMA", "SWMA", "ALMA", "VWAP"] | line 68 |
| MA 1 Length | 5 | int · min 1 | c_MA1 |
| MA 2 Length | 10 | int · min 1 | c_MA2 |
| MA 3 Length | 15 | int · min 1 | c_MA3 |
| MA 4 Length | 25 | int · min 1 | c_MA4 |
| ALMA Offset ValueThe Value of ALMA offset | 0.7 | float | c_MA1 c_MA2 c_MA3 c_MA4 |
| ALMA Sigma ValueThe Value of ALMA sigma | 7 | float | c_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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long Entry long | (enterLong) | On | 190 |
| Open Short Entry short | (enterShort) | On | 192 |
| Close Long Entry | (closeLong) | On | 194 |
| Close Short Entry | (closeShort) | On | 196 |
| Exit Long Take Profit / Stop Loss stop and limit | (longIsActive and i_useSLTP) | On | 198 |
| Exit Long Stop Loss stop | (longIsActive and i_useSLTP) | On | 199 |
| Exit Short Take Profit / Stop Loss stop and limit | (shortIsActive and i_useSLTP) | On | 202 |
| Exit Short Stop Loss stop | (shortIsActive and i_useSLTP) | On | 203 |
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 | −4.7% | +102.5% | 29 | 41% | 0.93 | 46.4% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +3.1% | +5.5% | 26 | 31% | 1.11 | 9.8% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +149.5% | +9.8% | 23 | 65% | 4.36 | 33.3% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +2.1% | +8.4% | 24 | 46% | 1.07 | 16.9% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +14.3% | +16.7% | 27 | 44% | 1.15 | 51.3% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +14.3% | +21.5% | 26 | 42% | 1.41 | 20.7% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −28.3% | +148.3% | 29 | 34% | 0.63 | 48.6% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −2.2% | +17.1% | 32 | 38% | 0.92 | 16.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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 4 | 25% | −$8,609.07 |
| Sideways market | 20 | 45% | $4,774.37 |
| Falling market | 5 | 40% | −$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.
All 29 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 19 Mar 2024 67,610.00 | 14 Apr 2024 63,924.50 | 26 | −$5,640.00 |
| short | 6 Jul 2024 56,628.80 | 15 Jul 2024 63,312.30 | 9 | −$5,662.61 |
| short | 6 Jul 2024 56,628.80 | 15 Jul 2024 63,312.30 | 9 | −$5,662.61 |
| short | 16 Jul 2024 64,724.10 | 17 Jul 2024 65,044.00 | 1 | −$576.36 |
| long | 27 Jul 2024 67,908.00 | 3 Aug 2024 60,615.30 | 7 | −$4,501.20 |
| long | 27 Jul 2024 67,908.00 | 3 Aug 2024 60,615.30 | 7 | −$4,501.20 |
| short | 6 Aug 2024 54,018.80 | 23 Aug 2024 63,494.20 | 17 | −$6,515.80 |
| short | 6 Aug 2024 54,018.80 | 23 Aug 2024 63,494.20 | 17 | −$6,515.80 |
| long | 30 Oct 2024 72,736.40 | 11 Nov 2024 84,232.00 | 12 | $4,704.97 |
| long | 30 Oct 2024 72,736.40 | 24 Dec 2024 94,881.50 | 55 | $9,119.56 |
| long | 20 Jan 2025 101,332.00 | 5 Feb 2025 97,763.10 | 16 | −$2,757.83 |
| short | 3 Mar 2025 94,270.00 | 27 Mar 2025 86,909.20 | 24 | $5,439.35 |
| short | 10 Apr 2025 82,615.20 | 16 Apr 2025 83,644.00 | 6 | −$1,111.69 |
| long | 24 May 2025 107,318.00 | 6 Jun 2025 101,509.00 | 13 | −$4,247.69 |
| long | 10 Jun 2025 110,263.00 | 19 Jun 2025 104,887.00 | 9 | −$3,625.71 |
| long | 27 Jun 2025 106,947.00 | 3 Aug 2025 112,546.00 | 37 | $3,414.47 |
| long | 14 Aug 2025 123,306.00 | 18 Aug 2025 114,851.00 | 4 | −$2,513.05 |
| long | 14 Aug 2025 123,306.00 | 18 Aug 2025 114,851.00 | 4 | −$2,513.05 |
| short | 1 Sep 2025 108,246.00 | 12 Sep 2025 115,483.00 | 11 | −$4,566.99 |
| long | 4 Oct 2025 122,232.00 | 10 Oct 2025 114,157.00 | 6 | −$2,097.86 |
| long | 4 Oct 2025 122,232.00 | 10 Oct 2025 114,157.00 | 6 | −$2,097.86 |
| long | 11 Oct 2025 112,774.00 | 14 Oct 2025 115,166.00 | 3 | $1,103.39 |
| short | 19 Oct 2025 107,185.00 | 21 Nov 2025 84,966.80 | 33 | $6,022.66 |
| short | 19 Oct 2025 107,185.00 | 4 Jan 2026 90,628.00 | 77 | $4,473.14 |
| short | 30 Jan 2026 84,650.20 | 5 Feb 2026 70,470.00 | 6 | $5,724.41 |
| short | 30 Jan 2026 84,650.20 | 12 Mar 2026 70,191.90 | 41 | $5,838.06 |
| short | 3 Jun 2026 66,760.80 | 10 Jul 2026 63,230.00 | 37 | $4,108.47 |
| long | 21 Aug 2026 73,027.00 | 21 Sep 2026 82,689.10 | 31 | $5,516.74 |
| long | 21 Aug 2026 73,027.00 | 15 Oct 2026 81,682.00 | 55 | $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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| MA Simple Strategy with SL & TP & ATR Filters this page | — | v5 strategy | −4.7% | 29 | 46.4% |
| I11L - Better Buy Low Volatility or High Volatility- by I11L | atr sma | v5 strategy | +19.2% | 83 | 37.4% |
| Vortex Cross w-MA Confirmation by DraftVenture | atr sma | v5 strategy | +2.4% | 52 | 4.7% |
| Configurable Multi MA Crossover Voting System by levieux | sma atr | v5 strategy | +28.5% | 5 | 39.4% |
| Swing Trend Strategy by Inkedlau | sma atr | v5 strategy | +11.2% | 5 | 16.2% |
| SSL Backtester With ATR SL TP and Money Management by JBTrippin | sma atr | v4 strategy | +8.5% | 55 | 3.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
VerifiedNothing 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
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 61 ms | With a workaround 1,000 bars in 150 ms | Not measured |
| PineTS | Not tested | Not tested | Not 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)