Pine Script v5 · Strategy
BT-SAR Ema, Squeeze, Volatility
A Pine Script v5 strategy built on SAR (0.02, 0.02), Barssince (check) and EMA or SMA (close, 100). It has 3 order rules, 1 entry among them, and trades long only with the default settings. Exits use a stop loss and a profit target. Each trade commits 300 in cash and pays no commission. 32 settings; defaults include Start 0.02, Increment 0.02 and Maximo 0.2.
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 BT-SAR Ema, Squeeze, Volatility 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 BT-SAR Ema, Squeeze, Volatility do on BTCUSDT 1D with default settings?
- +3.52%
- From 26 Jan 2024 to 21 Oct 2026, over 14 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Does BT-SAR Ema, Squeeze, Volatility run in Pine Script v6?
- No
- The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L116:C0: a 'bool' cannot be 'na' in Pine Script v6 — declare it as true or false. The v6 version is shown for reference and is not offered as a download.
- Does BT-SAR Ema, Squeeze, Volatility use a stop loss?
- Yes
- strategy.exit sets a stop on line 154.
- Does BT-SAR Ema, Squeeze, Volatility run in Zeal Terminal?
- Yes
- It compiles in 54 ms and runs 1,000 bars in 119 ms, in the browser.
BTCUSDT · 1D · default settings
- ParabolicSAR
- EMA Filter
- Position
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- +3.52%
- $35.21
- Buy and hold
- +102.5%
- same period
- Closed trades
- 14
- 7 won · 7 lost
- Profitable
- 50.0%
- of closed trades
- Profit factor
- 1.28
- gross profit ÷ gross loss
- Max drawdown
- 11.55%
- −$125.85
One run with the author's default settings, $1,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.
-
Likely bug
ta.sma(close, keltnerLength) ignores the settings line 86
Line 86 hard-codes close where line 53 uses “ Source”. Changing those settings moves one band but not this one.
ta.sma(close, keltnerLength)ta.sma(emaSource, keltnerLength) -
Likely bug
ta.lowest(low, 5) ignores the settings line 142
Line 142 hard-codes 5 where line 86 uses “Keltner Channel Length”. Changing those settings moves one band but not this one.
ta.lowest(low,5)ta.lowest(low, keltnerLength) -
Check
1 setting does nothing
“Boliinger Bands Mult” is declared but never read.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Note
2 settings have no label
In the settings dialog initialDate (line 26), finalDate (line 28) show an empty name. The labels on this page come from the variable names.
-
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 Filters | |||
| Start date | true | bool | inTradeWindow |
| Initial Date (no label in the script)This start date is in the time zone of the exchange | timestamp('01 Jan 2022 00:00 UTC') | time | inTradeWindow |
| End date | true | bool | inTradeWindow |
| Final Date (no label in the script)This end date is in the time zone of the exchange | timestamp('31 Dec 2029 23:59 UTC') | time | inTradeWindow |
| SAR PARABOLIC | |||
| Start | 0.02 | float | out |
| Increment | 0.02 | float | out |
| Maximo | 0.2 | float | out |
| SAR TRADE SIGNAL | |||
| SAR Trade SignalSAR Flip: Once the parabolic SAR flips it will send a signal, SAR Breakout: Will wait the price cross last Sar Value before it flips. | SAR Flip | string · options ['SAR Flip','SAR Breakout'] | BreakoutPrice openLongPosition Breakout line |
| BarsDefine the number of bars for a entry when the price cross breakout point | 4 | int | BreakoutPrice limitEntryNumbers |
| Show Breakout Point | false | bool | Breakout line |
| Moving Average | |||
| Moving Average FilterThis will enable or disable Exponential Moving Average Filter on Strategy | true | bool | emaFilterBuy EMA Filter |
| Type | Ema | string · options ['Ema','Sma'] | ema |
| Source | close | source | ema |
| Length | 100 | int · min 0 | ema |
| VOLATILITY OSCILLATOR | |||
| Volatility Oscillator FilterThis will enable or disable Volatility Oscillator filter on Strategy | true | bool | volatilityFilterBuy |
| Volatility Oscillator | 100 | int | vltFilterX vltFilterY |
| SQUEEZE MOMENTUM | |||
| Squeeze Momentum FilterThis will enable or disable Squeeze Momentum filter on Strategy | true | bool | sqzFilterBuy |
| Bollinger Bands Length | 20 | int | basis dev |
| Boliinger Bands Mult | 2.0 | float | unused |
| Keltner Channel Length | 20 | int | sma rangema val |
| Keltner Channel Mult | 1.5 | float | dev upperKC lowerKC |
| Use TrueRange (KC) | true | bool | range_1 |
| Take Profit | |||
| Take Profit and Stop Loss | SAR Flip | string · options ['SAR Flip','Fixed % TP/SL', 'Risk Reward TP/SL'] | closeLongPosition exit Long Take Profit Fixed TP Fixed SL Risk Reward TP |
| Fixed TP %The percentage increase to set the take profit price target. | 1.5 | float · min 0.05 · step 0.5 | longTakeProfitPrice |
| Fixed Long SL %The percentage increase to set the Long Stop Loss price target. | 1.0 | float · min 0.1 · step 0.5 | longStopPrice |
| Risk Reward TPThe Risk Reward parameter. | 1 | float · min 0.25 · step 0.25 | takeProfitRR |
| Show RR Stop Loss | false | bool | Last Bottom |
| Traling Profit | |||
| Enable TrailingEnable or disable the trailing for take profit. | false | bool | exit Long Take Profit |
| Trailing Take Profit Deviation %The step to follow the price when the take profit limit is reached. | 0.1 | float · min 0.01 · max 100 · step 0.01 | longTrailingTakeProfitStepTicks |
| Alert Message For Bot | |||
| Strategy Entry Message | | string | entry Long Entry |
| Strategy Exit Message | | string | exit Long Take Profit |
| Strategy Close Message | | string | close Long Entry |
What it calculates
- SARStart (0.02), Increment (0.02), Maximo (0.2)
out · line 37 - Barssincecheck · chosen by SAR Trade Signal
BreakoutPrice · line 44 - EMA / SMA Source (close), Length (100) · chosen by Type
ema · line 53 - StdevvltFilterSpike, Volatility Oscillator (100)
vltFilterX · line 59 - StdevvltFilterSpike, Volatility Oscillator (100)
vltFilterY · line 60 - SMAsqzFilterSrc, Bollinger Bands Length (20)
basis · line 71 - StdevsqzFilterSrc, Bollinger Bands Length (20)
dev · line 72 - SMAsqzFilterSrc, Keltner Channel Length (20)
sma · line 76 - TR
range_1 · line 77 - SMArange_1, Keltner Channel Length (20)
rangema · line 78 - Linreg / Highest / Lowest / SMAsqzFilterSrc - math.avg(math.avg(ta.highest(high, keltnerLength), ta.lowest(low, keltnerLength)),ta.sma(close, keltnerLength)), Keltner Channel Length (20), 0
val · line 86
Signal flow
How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.
The script has 72 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long Entry long | (openLongPosition) and (inTradeWindow) | On | 151 |
| Exit Long Take Profit stop and limit | (longIsActive) and (inTradeWindow) | On | 154 |
| Close Long Entry | (closeLongPosition) | On | 156 |
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 timingprocess_orders_on_close = true: orders fill at the signal bar's close.
The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.
Other markets
The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | +3.5% | +102.5% | 14 | 50% | 1.28 | 11.5% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +1.3% | +5.5% | 13 | 23% | 1.33 | 1.5% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +4.3% | +9.8% | 12 | 42% | 1.23 | 11.6% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +5.5% | +8.4% | 11 | 27% | 2.18 | 2.4% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +8.0% | +16.7% | 13 | 69% | 1.43 | 8.7% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +5.7% | +21.5% | 12 | 58% | 3.48 | 1.9% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −2.1% | +148.3% | 13 | 46% | 0.83 | 7.6% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +6.9% | +17.1% | 12 | 33% | 3.90 | 1.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 | 6 | 33% | $10.35 |
| Sideways market | 8 | 63% | $24.86 |
| Falling market | 0 | — | $0.00 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
9.8%
The 95th percentile of the worst drawdown when the same 14 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 4.2% to 9.8%; the tick is what actually happened, 9.0%. Order luck alone moves it this much.
All 14 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 15 Jul 2024 64,724.10 | 25 Jul 2024 65,799.90 | 10 | $4.99 |
| long | 14 Oct 2024 66,084.00 | 1 Nov 2024 69,496.00 | 18 | $15.49 |
| long | 6 Nov 2024 75,572.00 | 25 Nov 2024 93,010.00 | 19 | $69.22 |
| long | 15 Dec 2024 104,464.00 | 20 Dec 2024 97,805.40 | 5 | −$19.12 |
| long | 6 Jan 2025 102,236.00 | 9 Jan 2025 92,552.50 | 3 | −$28.41 |
| long | 17 Jan 2025 104,077.00 | 27 Jan 2025 102,083.00 | 10 | −$5.75 |
| long | 2 Mar 2025 94,270.00 | 9 Mar 2025 80,734.40 | 7 | −$43.08 |
| long | 8 May 2025 103,262.00 | 25 May 2025 109,004.00 | 17 | $16.68 |
| long | 9 Jun 2025 110,263.00 | 18 Jun 2025 104,887.00 | 9 | −$14.63 |
| long | 7 Aug 2025 117,472.00 | 15 Aug 2025 117,342.00 | 8 | −$0.33 |
| long | 2 Sep 2025 111,240.00 | 21 Sep 2025 115,232.00 | 19 | $10.77 |
| long | 1 Oct 2025 118,595.00 | 10 Oct 2025 112,775.00 | 9 | −$14.72 |
| long | 19 Aug 2026 69,334.80 | 1 Sep 2026 77,439.00 | 13 | $35.07 |
| long | 18 Sep 2026 80,883.90 | 7 Oct 2026 83,321.80 | 19 | $9.04 |
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 |
|---|---|---|---|---|---|
| BT-SAR Ema, Squeeze, Volatility this page | — | v5 strategy | +3.5% | 14 | 11.5% |
| CHOP Zone Entry Strategy + DMI-PSAR Exit by IronCasper | highest lowest sma linreg sar ema | v4 strategy | +17.1% | 8 | 20.0% |
| [fpemehd] SSL Baseline Strategy by DuDu95 | ema sma highest lowest stdev tr | v5 strategy | +2.3% | 71 | 3.7% |
| SSL + Wave Trend Strategy by kevinmck100 | ema sma highest lowest stdev tr | v5 strategy | −1.0% | 1 | 1.0% |
| PSAR BBPT ZLSMA BTC 1min by Rolan_Kruger | sar linreg lowest highest sma stdev ema | v5 strategy | No trades on this market | ||
| VixFixLinReg-Strategy by Trendoscope | highest stdev sma lowest linreg | v4 strategy | −49.3% | 12 | 51.1% |
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.
- 1 setting uses the untyped input() (line 68). It still compiles in v6; input.int, input.float or input.source state the type.
- No v6-only features. v6 is not needed to run this script.
Same 14 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 68: input() → input.bool()
⋯keltnerMult = input.float(defval=1.5, title='Keltner Channel Mult',inline='',group= sqzgroup)-useTrueRange = input(true, title='Use TrueRange (KC)', inline='',group= sqzgroup)+useTrueRange = input.bool(true, title='Use TrueRange (KC)', inline='',group= sqzgroup)// CALCULATE BOLLINGER BANDS⋯Does it run in Pine Script v6?
No
The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L116:C0: a 'bool' cannot be 'na' in Pine Script v6 — declare it as true or false. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
//VERSION =================================================================================================================-//@version=5+//@version=6// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 54 ms | With a workaround 1,000 bars in 119 ms | Not measured |
| PineTS | Not tested | Not tested | Not measured |
Zeal Terminal's engine currently reads an order side written as direction = strategy.long as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (line 151) 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.
//VERSION =================================================================================================================//@version=5// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// This strategy is intended to study.// It can also be used to signal a bot to open a deal by providing the Bot ID, email token and trading pair in the strategy settings screen.// As currently written, this strategy uses a SAR PARABOLIC to send signal, and EMA, Squeeze Momentum, Volatility Oscilator as filter.// There are two enter point, when SAR Flips, or Breakout Point - the last SAR Value before it Flips.// There are tree options for exit: SAR Flips, Fixed Stop Loss ande Fixed Take Profit in % and Risk Reward tha can be set, 0.5/1, 1/1 etc.//Autor M4TR1X_BR//▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒//STRATEGY ================================================================================================================strategy(title = 'BT-SAR Ema, Squeeze, Voltatility', shorttitle = 'SAR ESV', overlay = true, pyramiding = 0, default_qty_type = strategy.cash, default_qty_value = 300, initial_capital = 1000, max_lines_count = 150, process_orders_on_close=true, max_labels_count = 150)//▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒// INPUTS =================================================================================================================// TIME INPUTSusefromDate = input.bool(defval = true, title = 'Start date', inline = '0', group = "Time Filters")initialDate = input.time(defval = timestamp('01 Jan 2022 00:00 UTC'), title = '', inline = "0",group = 'Time Filters',tooltip="This start date is in the time zone of the exchange ")usetoDate = input.bool(defval = true, title = 'End date', inline = '1', group = "Time Filters")finalDate = input.time(defval = timestamp('31 Dec 2029 23:59 UTC'), title = '', inline = "1",group = 'Time Filters',tooltip="This end date is in the time zone of the exchange")// TIME LOGIC inTradeWindow = not usefromDate and not usetoDate or (time >= initialDate and time < finalDate)// SAR PARABOLIC INPUTS ==================================================================================================string sargroup= "SAR PARABOLIC ========================================="start = input.float(defval=0.02,title='Start',inline='',group = sargroup)increment = input.float(defval=0.02,title='Increment',inline='',group = sargroup)maximum = input.float(defval=0.2,title='Maximo',inline='',group = sargroup)// SAR PARABOLIC LOGIC out = ta.sar(start, increment, maximum)// SAR FLIP OR BREAKOUT OPTIONSstring bkgroup ='SAR TRADE SIGNAL ====================================== 'sarTradeSignal =input.string(defval='SAR Flip',title='SAR Trade Signal', options= ['SAR Flip','SAR Breakout'],group=bkgroup, tooltip='SAR Flip: Once the parabolic SAR flips it will send a signal, SAR Breakout: Will wait the price cross last Sar Value before it flips.')nBars = input.int(defval=4,title='Bars',group=bkgroup, tooltip ='Define the number of bars for a entry when the price cross breakout point')float sarBreakoutPoint= ta.valuewhen((close[1] < out[1]) and (close > out),out[1],0) //Get Sar Breakout Pointbool check = (close[1] < out[1]) and (close > out) //Verify when sar flipsbool BreakoutPrice = sarTradeSignal=='SAR Breakout'? (ta.barssince(check) < nBars) and ((open < sarBreakoutPoint) and (close > sarBreakoutPoint)): (ta.barssince(check) < nBars) and (close > out)barcolor (check? color.yellow:na,title="Signal Bar color" )// MOVING AVERAGES INPUTS ================================================================================================string magroup = "Moving Average ========================================"useEma = input.bool(defval = true, title = 'Moving Average Filter',inline='', group= magroup,tooltip='This will enable or disable Exponential Moving Average Filter on Strategy')emaType=input.string (defval='Ema',title='Type',options=['Ema','Sma'],inline='', group= magroup)emaSource = input.source(defval=close,title=" Source",inline="", group= magroup)emaLength = input.int(defval=100,title="Length",minval=0,inline='', group= magroup)// MOVING AVERAGE LOGICfloat ema = emaType=='Ema'? ta.ema(emaSource,emaLength): ta.sma(emaSource,emaLength)// VOLATILITY OSCILLATOR =================================================================================================string vogroup = "VOLATILITY OSCILLATOR ================================="useVltFilter=input.bool(defval=true,title="Volatility Oscillator Filter",inline='',group= vogroup,tooltip='This will enable or disable Volatility Oscillator filter on Strategy')vltFilterLength = input.int(defval=100,title="Volatility Oscillator",inline='',group=vogroup)vltFilterSpike = close - openvltFilterX = ta.stdev(vltFilterSpike,vltFilterLength)vltFilterY = ta.stdev(vltFilterSpike,vltFilterLength) * -1// SQUEEZE MOMENTUM INPUTS ==============================================================================================string sqzgroup = "SQUEEZE MOMENTUM =====================================" useSqzFilter=input.bool(defval=true,title="Squeeze Momentum Filter",inline='',group= sqzgroup, tooltip='This will enable or disable Squeeze Momentum filter on Strategy')sqzFilterlength = input.int(defval=20, title='Bollinger Bands Length',inline='',group= sqzgroup)sqzFiltermult = input.float(defval=2.0, title='Boliinger Bands Mult',inline='',group= sqzgroup)keltnerLength = input.int(defval=20, title='Keltner Channel Length',inline='',group= sqzgroup)keltnerMult = input.float(defval=1.5, title='Keltner Channel Mult',inline='',group= sqzgroup)useTrueRange = input(true, title='Use TrueRange (KC)', inline='',group= sqzgroup)// CALCULATE BOLLINGER BANDSsqzFilterSrc = closebasis = ta.sma(sqzFilterSrc, sqzFilterlength)dev = keltnerMult * ta.stdev(sqzFilterSrc, sqzFilterlength)upperBB = basis + devlowerBB = basis - dev// CALCULATE KELTNER CHANNEL sma = ta.sma(sqzFilterSrc, keltnerLength)range_1 = useTrueRange ? ta.tr : high - lowrangema = ta.sma(range_1, keltnerLength)upperKC = sma + rangema * keltnerMultlowerKC = sma - rangema * keltnerMult// CHECK IF BOLLINGER BANDS IS IN OR OUT OF KELTNER CHANNELsqzOn = lowerBB > lowerKC and upperBB < upperKCsqzOff = lowerBB < lowerKC and upperBB > upperKCnoSqz = sqzOn == false and sqzOff == false// SQUEEZE MOMENTUM LOGICval = ta.linreg(sqzFilterSrc - math.avg(math.avg(ta.highest(high, keltnerLength), ta.lowest(low, keltnerLength)),ta.sma(close, keltnerLength)), keltnerLength, 0)// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒// TAKE PROFIT STOP LOSS INPUTS =========================================================================================string tkpgroup='Take Profit =================================================='tpType = input.string(defval = 'SAR Flip', title='Take Profit and Stop Loss', options=['SAR Flip','Fixed % TP/SL', 'Risk Reward TP/SL'], group=tkpgroup )longTakeProfitPerc = input.float(defval = 1.5, title = 'Fixed TP %', minval = 0.05, step = 0.5, group=tkpgroup, tooltip = 'The percentage increase to set the take profit price target.')/100longLossPerc = input.float(defval=1.0, title="Fixed Long SL %", minval=0.1, step=0.5, group = tkpgroup, tooltip = 'The percentage increase to set the Long Stop Loss price target.') * 0.01//shortLossPerc = input.float(defval=1.5, title="Fixed Short SL (%)", minval=0.1, step=0.5, group = tkpgroup, tooltip = 'The percentage increase to set the Short Stop Loss price target.') * 0.01longTakeProfitRR = input.float(defval = 1, title = 'Risk Reward TP', minval = 0.25, step = 0.25, group=tkpgroup, tooltip = 'The Risk Reward parameter.')var plotStopLossRR = input.bool(defval=false, title='Show RR Stop Loss', group=tkpgroup)//enableStopLossRR = input.bool(defval = false, title = 'Enable Risk Reward TP',group=tkpgroup, tooltip = 'Enable Variable Stop Loss.')string trpgroup='Traling Profit ==============================================='enableTrailing = input.bool(defval = false, title = 'Enable Trailing',group=trpgroup, tooltip = 'Enable or disable the trailing for take profit.')trailingTakeProfitDeviationPerc = input.float(defval = 0.1, title = 'Trailing Take Profit Deviation %', minval = 0.01, maxval = 100, step = 0.01, group=trpgroup, tooltip = 'The step to follow the price when the take profit limit is reached.') / 100// BOT MESSAGESstring msgroup='Alert Message For Bot ========================================='messageEntry = input.string("", title="Strategy Entry Message",group=msgroup)messageExit =input.string("",title="Strategy Exit Message",group=msgroup)messageClose = input.string("", title="Strategy Close Message",group=msgroup)// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒// POSITIONS =============================================================================================================//VERIFY IF THE BUY FILTERS ARE ON OR OFF bool emaFilterBuy = useEma? (close > ema):(close >= ema) or (close <= ema) bool volatilityFilterBuy = useVltFilter? (vltFilterSpike > vltFilterX) : (vltFilterSpike >= 0) or (vltFilterSpike <= 0) bool sqzFilterBuy = useSqzFilter? (val > val[1]): (val >= val[1] or val <=val[1]) bool sarflip = (close > out)//LONG / SHORT POSITIONS LOGIC//Var 'check' will verify if the SAR flips and if the exit price occurs it will limit in bars number a new entry on the same signal.bool limitEntryNumbers = (ta.barssince(check) < nBars) bool openLongPosition = sarTradeSignal == 'SAR Flip'? (sarflip and emaFilterBuy and volatilityFilterBuy and sqzFilterBuy and limitEntryNumbers) :sarTradeSignal=='SAR Breakout'? (BreakoutPrice and emaFilterBuy and volatilityFilterBuy and sqzFilterBuy): nabool openShortPosition = nabool closeLongPosition= tpType=='SAR Flip'? (close < out):nabool closeShortPosition=na// CHEK OPEN POSITONS =====================================================================================================// open signal when not already into a positionbool validOpenLongPosition = openLongPosition and strategy.opentrades.size(strategy.opentrades - 1) <= 0bool longIsActive = validOpenLongPosition or strategy.opentrades.size(strategy.opentrades - 1) > 0// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒// TAKE PROFIT STOP LOSS CONFIG ==========================================================================================// FIXED TAKE PROFIT IN %float posSize = strategy.opentrades.entry_price(strategy.opentrades - 1) //Get the entry pricevar float longTakeProfitPrice = nalongTakeProfitPrice := if (longIsActive) if (openLongPosition and not (strategy.opentrades.size(strategy.opentrades - 1) > 0)) posSize * (1 + longTakeProfitPerc) else nz(longTakeProfitPrice[1], close * (1 + longTakeProfitPerc))else nalongTrailingTakeProfitStepTicks = longTakeProfitPrice * trailingTakeProfitDeviationPerc / syminfo.mintick// FIXED STOP LOSS IN %longStopPrice = strategy.position_avg_price * (1 - longLossPerc)//shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc)// TAKE PROFIT BY RISK/REWARD// Set stop losstta = not (strategy.opentrades.size(strategy.opentrades - 1) > 0)float lastb = ta.valuewhen(check and tta,ta.lowest(low,5),0) - (10 * syminfo.mintick)// TAKE PROFIT CALCULATIONfloat stopLossRisk = (posSize - lastb)float takeProfitRR = posSize + (longTakeProfitRR * stopLossRisk)// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒// POSITION ORDERS =====================================================================================================// LOGIC ===============================================================================================================// getting into LONG positionif (openLongPosition) and (inTradeWindow) strategy.entry(id = 'Long Entry', direction = strategy.long, alert_message=messageEntry)//submit exit orders for trailing take profit price if (longIsActive) and (inTradeWindow) strategy.exit(id = 'Long Take Profit', from_entry = 'Long Entry', limit = enableTrailing ? na : tpType=='Fixed % TP/SL'? longTakeProfitPrice: tpType == 'Risk Reward TP/SL'? takeProfitRR:na, trail_price = enableTrailing ? longTakeProfitPrice : na, trail_offset = enableTrailing ? longTrailingTakeProfitStepTicks : na, stop = tpType =='Fixed % TP/SL' ? longStopPrice: tpType == 'Risk Reward TP/SL'? lastb:na, alert_message=messageExit) if (closeLongPosition) strategy.close(id = 'Long Entry', alert_message=messageClose) // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒// PLOTS ===============================================================================================================// TRADE WINDOW ========================================================================================================bgcolor(color = inTradeWindow ? color.new(#089981,90):na, title = 'Time Window')// SAR PARABOLICvar sarColor = color.new(#00bcd4,0)plot(out, "ParabolicSAR", color=sarColor, linewidth=1,style=plot.style_cross)//BREAKOUT LINEvar plotBkPoint = input.bool(defval=false, title='Show Breakout Point', group=bkgroup)plot(series = (sarTradeSignal=='SAR Breakout' and plotBkPoint == true)? sarBreakoutPoint:na, title = 'Breakout line', color =color.new(#ffeb3b,50) , linewidth = 1, style = plot.style_linebr, offset = 0)// EMA/SMA var emafilterColor = color.new(color.white, 0)plot(series=useEma? ema:na, title = 'EMA Filter', color = emafilterColor, linewidth = 2, style = plot.style_line)// ENTRY PRICEvar posColor = color.new(#2962ff, 0)plot(series = strategy.opentrades.entry_price(strategy.opentrades - 1), title = 'Position', color = posColor, linewidth = 1, style = plot.style_linebr,offset=0)// FIXED TAKE PROFIT var takeProfitColor = color.new(#ba68c8, 0)plot(series = tpType=='Fixed % TP/SL'? longTakeProfitPrice:na, title = 'Fixed TP', color = takeProfitColor, linewidth = 1, style = plot.style_linebr, offset = 0)// FIXED STOP LOSSvar stopLossColor = color.new(#ff0000, 0)plot(series = tpType=='Fixed % TP/SL' ? longStopPrice:na, title = 'Fixed SL', color = stopLossColor, linewidth = 1, style = plot.style_linebr, offset = 0)// RISK REWARD TAKE PROFITvar takeProfitRRColor = color.new(#ba68c8, 0)plot(series=tpType == 'Risk Reward TP/SL'? takeProfitRR:na,title='Risk Reward TP',color=takeProfitRRColor,linewidth=1,style=plot.style_linebr)// STOP LOSS RISK REWARDplot(series = (check and plotStopLossRR)? lastb:na, title = 'Last Bottom', color =color.new(#ff0000,0), linewidth = 2, style = plot.style_linebr, offset = 0)// ======================================================================================================================