Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Risk Reduction Ultimate Template

A Pine Script v4 strategy built on TSI (close, 5), EMA (erg, 5) and SMA (close, 20). It has 9 order rules, 2 entries among them, and trades long and short with the default settings. Exits wait for a signal; there is no stop loss. Each trade commits 10% of equity and pays 0.1 commission. 23 settings; defaults include Source close, Long Length 20 and Short Length 5.

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 Risk Reduction Ultimate Template repaint?
Yes
At least one pattern in the source can repaint: intrabar recalculation.
How did Risk Reduction Ultimate Template do on BTCUSDT 1D with default settings?
Not measured
It closed no trades there from 26 Jan 2024 to 21 Oct 2026 with the default settings, so there is no result to report. Its code limits trading to a date window, which can leave this period out. It closed no trades on the other markets either. A backtest, not investment advice.
Can Risk Reduction Ultimate Template be converted to Pine Script v5?
Not tested
The steps are shown below, but neither version placed a trade on any market tested, so there was nothing to compare and no download is offered.
Does Risk Reduction Ultimate Template use a stop loss?
No
Every exit waits for a signal; nothing limits a losing trade before it fires.
Does Risk Reduction Ultimate Template run in Zeal Terminal?
Yes
It compiles in 22 ms and runs 1,000 bars in 56 ms, in the browser.

BTCUSDT · 1D · default settings

  • SMI
  • Signal
  • Bollinger Bands %B
  • Overbought
  • Oversold
  • 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 (23)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOctSMI$1,000$2,025Equity from $1,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 long = true as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (line 93) so the engine trades the way the script says. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
Net profit
0.00%
$0.00
Buy and hold
+102.5%
same period
Closed trades
0
0 won · 0 lost
Profitable
0.0%
of closed trades
Profit factor
—
gross profit ÷ gross loss
Max drawdown
0.00%
$0.00

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

    No stop loss

    Every exit waits for a signal. Nothing limits a losing trade before the exit condition fires.

  • Note

    5 settings have no label

    In the settings dialog length (line 16), buy (line 24), sellonce (line 25), sellall (line 26), commission (line 72) show an empty name. The labels on this page come from the variable names.

  • Note

    Uses long =, which v5 renamed line 93

    long = on line 93. v5 writes it as direction = strategy.long or strategy.short.

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 tsi → ta.tsi, ema → ta.ema, sma → ta.sma, stdev → ta.stdev, crossover → ta.crossover, crossunder → ta.crossunder.

v4 → v5

Not verified

Neither version placed a trade on any of the 8 markets, so there was nothing to compare.

  • Line 3: //@version=4 → //@version=5
  • Line 11: tsi → ta.tsi
  • Line 12: ema → ta.ema
  • Line 18: sma → ta.sma
  • Line 19: stdev → ta.stdev
  • Line 66: crossover → ta.crossover
  • Line 68: crossunder → ta.crossunder
  • Line 93: long = true → direction = strategy.long
⋯// © burgercrisis-//@version=4+//@version=5strategy(title="Risk Reduction Ultimate Template", overlay=false, pyramiding=10, calc_on_every_tick=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10, initial_capital=1000, slippage=10, commission_value=0.1)⋯siglen = input(5, minval=1, title="Signal Line Length")-erg = tsi(src, shortlen, longlen)+erg = ta.tsi(src, shortlen, longlen)-sig = ema(erg, siglen)+sig = ta.ema(erg, siglen)plot(erg, color=#0094FF, title="SMI")⋯mult = input(2.0, minval=0.001, maxval=50, step=0.1, title="StdDev")-basis = sma(src, length)+basis = ta.sma(src, length)-dev = mult * stdev(src, length)+dev = mult * ta.stdev(src, length)upper = basis + dev⋯//-longtrigger=crossover(erg,sig)                                          ////Put your trigger for buys here+longtrigger=ta.crossover(erg,sig)                                          ////Put your trigger for buys herelongcondition1=bbr<buy                                                  ////Put your buy filter signals here-shorttrigger=crossunder(erg,sig)                                        ////Put your sell trigger here+shorttrigger=ta.crossunder(erg,sig)                                        ////Put your sell trigger hereshortcondition1=bbr>sellonce                                            ////This is your filters for partial exits⋯    if longcondition1 and longtrigger-        strategy.entry(id="EL", comment="Buy", long=true)                                           //Buy signal+        strategy.entry(id="EL", comment="Buy", direction = strategy.long)                                           //Buy signal        ⋯

Clean v5

Not verified

Neither version placed a trade on any of the 8 markets, so there was nothing to compare.

  • Line 6: input() → input.source()
  • Line 8: input() → input.int()
  • Line 9: input() → input.int()
  • Line 10: input() → input.int()
  • Line 16: input() → input.int()
  • Line 17: input() → input.float()
17 more edits
  • Line 24: input() → input.float()
  • Line 25: input() → input.float()
  • Line 26: input() → input.float()
  • Line 35: input() → input.int()
  • Line 36: input() → input.int()
  • Line 37: input() → input.int()
  • Line 39: input() → input.int()
  • Line 40: input() → input.int()
  • Line 41: input() → input.int()
  • Line 72: input() → input.float()
  • Line 76: input() → input.float()
  • Line 78: input() → input.float()
  • Line 80: input() → input.float()
  • Line 83: input() → input.float()
  • Line 85: input() → input.float()
  • Line 87: input() → input.float()
  • Line 89: input() → input.float()
⋯//This is just to make this template work and publishable.-src = input(close, title="Source")+src = input.source(close, title="Source")//SMII-longlen = input(20, minval=1, title="Long Length")+longlen = input.int(20, minval=1, title="Long Length")-shortlen = input(5, minval=1, title="Short Length")+shortlen = input.int(5, minval=1, title="Short Length")-siglen = input(5, minval=1, title="Signal Line Length")+siglen = input.int(5, minval=1, title="Signal Line Length")erg = ta.tsi(src, shortlen, longlen)⋯//%Blength = input(20, minval=1)-length = input(20, minval=1)+length = input.int(20, minval=1)-mult = input(2.0, minval=0.001, maxval=50, step=0.1, title="StdDev")+mult = input.float(2.0, minval=0.001, maxval=50, step=0.1, title="StdDev")basis = ta.sma(src, length)⋯plot(bbr, "Bollinger Bands %B", color=color.teal)-buy=input(0.0,step=0.1)+buy=input.float(0.0,step=0.1)-sellonce=input(1.0,step=0.1)+sellonce=input.float(1.0,step=0.1)-sellall=input(1.1,step=0.1)+sellall=input.float(1.1,step=0.1)band1 = hline(sellonce, "Overbought", color=#606060, linestyle=hline.style_dashed)⋯//* Modifications made *//-testStartYear = input(2020, "Backtest Start Year") +testStartYear = input.int(2020, "Backtest Start Year") -testStartMonth = input(1, "Backtest Start Month")+testStartMonth = input.int(1, "Backtest Start Month")-testStartDay = input(1, "Backtest Start Day")+testStartDay = input.int(1, "Backtest Start Day")testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)-testStopYear = input(999999, "Backtest Stop Year")+testStopYear = input.int(999999, "Backtest Stop Year")-testStopMonth = input(9, "Backtest Stop Month")+testStopMonth = input.int(9, "Backtest Stop Month")-testStopDay = input(26, "Backtest Stop Day")+testStopDay = input.int(26, "Backtest Stop Day")testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)⋯//This gets multiplied to your sale thresholds to make sure they account for commission properly.-commission=input(0.1)+commission=input.float(0.1)comms=(100+commission)/100⋯//StopLosses-stopLossFear=input(100.0, step=0.2, title="Hard Stop Loss")     //Hard stop loss triggers immediately when a drop from your assumed average position price occurs equal to set percentage+stopLossFear=input.float(100.0, step=0.2, title="Hard Stop Loss")     //Hard stop loss triggers immediately when a drop from your assumed average position price occurs equal to set percentagesl1=(100-stopLossFear)/100*comms-stopLossSafe=input(100.0, step=0.2, title="Soft Stop Loss")     //Soft stop loss triggers when your shorttrigger occurs after a drop from position price equal to set percentage+stopLossSafe=input.float(100.0, step=0.2, title="Soft Stop Loss")     //Soft stop loss triggers when your shorttrigger occurs after a drop from position price equal to set percentagesl2=(100-stopLossSafe)/100*comms-stopLossSafest=input(100.0, step=0.2, title="Safe Stop Loss")   //Safe stop loss triggers when both shorttrigger and shortcondition1 occur after a drop from position price equal to set percentage+stopLossSafest=input.float(100.0, step=0.2, title="Safe Stop Loss")   //Safe stop loss triggers when both shorttrigger and shortcondition1 occur after a drop from position price equal to set percentagesl3=(100-stopLossSafest)/100*comms//TakeProfits-TakeProfit1=input(100.0, step=0.2, title="Hard Take Profit")        //Hard Take Profit occurs after a rise from position price equal to set percentage+TakeProfit1=input.float(100.0, step=0.2, title="Hard Take Profit")        //Hard Take Profit occurs after a rise from position price equal to set percentagetp1=(100+TakeProfit1)/100*comms-TakeProfit2=input(100.0, step=0.2, title="Soft Take Profit")        //Soft Take Profit occurs when your shorttrigger occurs after a rise from position price equal to set percentage+TakeProfit2=input.float(100.0, step=0.2, title="Soft Take Profit")        //Soft Take Profit occurs when your shorttrigger occurs after a rise from position price equal to set percentagetp2=(100+TakeProfit2)/100*comms-TakeProfit3=input(0.0, step=0.2, title="Minimum Sale Profit")       //This is the standard single sell signal, it occurs when shorttrigger and shortcondition1 occur after a rise from position price equal to set percentage to filter bad signals+TakeProfit3=input.float(0.0, step=0.2, title="Minimum Sale Profit")       //This is the standard single sell signal, it occurs when shorttrigger and shortcondition1 occur after a rise from position price equal to set percentage to filter bad signalstp3=(100+TakeProfit3)/100*comms-TakeProfit4=input(0.0, step=0.2, title="Sell All Profit")           //This sells all positions when shorttrigger and shortcondition1 occur after a rise from position price equal to set percentage+TakeProfit4=input.float(0.0, step=0.2, title="Sell All Profit")           //This sells all positions when shorttrigger and shortcondition1 occur after a rise from position price equal to set percentagetp4=(100+TakeProfit4)/100*comms⋯

Does it run in Pine Script v6?

Not tested

Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// © burgercrisis-//@version=5+//@version=6strategy(title="Risk Reduction Ultimate Template", overlay=false, pyramiding=10, calc_on_every_tick=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10, initial_capital=1000, slippage=10, commission_value=0.1)⋯

Settings

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

SettingDefaultType and rangeFeeds
Sourceclosesourceerg basis dev bbr
Long Length20int · min 1erg
Short Length5int · min 1erg
Signal Line Length5int · min 1sig
Length (no label in the script)20int · min 1basis dev
StdDev2.0float · min 0.001 · max 50 · step 0.1dev
Buy (no label in the script)0.0float · step 0.1band0 longcondition1 hline
Sellonce (no label in the script)1.0float · step 0.1band1 shortcondition1 hline
Sellall (no label in the script)1.1float · step 0.1shortcondition2
Backtest Start Year2020inttestPeriodStart
Backtest Start Month1inttestPeriodStart
Backtest Start Day1inttestPeriodStart
Backtest Stop Year999999inttestPeriodStop
Backtest Stop Month9inttestPeriodStop
Backtest Stop Day26inttestPeriodStop
Commission (no label in the script)0.1floatcomms
Hard Stop Loss100.0float · step 0.2sl1
Soft Stop Loss100.0float · step 0.2sl2
Safe Stop Loss100.0float · step 0.2sl3
Hard Take Profit100.0float · step 0.2tp1
Soft Take Profit100.0float · step 0.2tp2
Minimum Sale Profit0.0float · step 0.2tp3
Sell All Profit0.0float · step 0.2tp4

What it calculates

  • TSI (tsi, ta.tsi in v5)Source (close), Short Length (5), Long Length (20)erg · line 11
  • EMA (ema, ta.ema in v5)erg, Signal Line Length (5)sig · line 12
  • SMA (sma, ta.sma in v5)Source (close), Length (20)basis · line 18
  • Stdev (stdev, ta.stdev in v5)Source (close), Length (20)dev · line 19
  • Crossover (crossover, ta.crossover in v5)erg, siglongtrigger · line 66
  • Crossunder (crossunder, ta.crossunder in v5)erg, sigshorttrigger · line 68

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.

closecloseprice datashortlenShort Lengthsetting · 5longlenLong Lengthsetting · 20siglenSignal Line Lengthsetting · 5lengthLengthsetting · 20multStdDevsetting · 2.0testStartYearBacktest Start Yearsetting · 2020testStartMonthBacktest Start Monthsetting · 1testStartDayBacktest Start Daysetting · 1testStopYearBacktest Stop Yearsetting · 999999testStopMonthBacktest Stop Monthsetting · 9testStopDayBacktest Stop Daysetting · 26commissionCommissionsetting · 0.1stopLossFearHard Stop Losssetting · 100.0stopLossSafeSoft Stop Losssetting · 100.0stopLossSafestSafe Stop Losssetting · 100.0TakeProfit1Hard Take Profitsetting · 100.0TakeProfit2Soft Take Profitsetting · 100.0TakeProfit3Minimum Sale Profitsetting · 0.0TakeProfit4Sell All Profitsetting · 0.0buyBuysetting · 0.0sellonceSelloncesetting · 1.0sellallSellallsetting · 1.1highhighprice dataergTSI→ ergsigEMA→ sigbasisSMA→ basisdevStdev→ devlongtriggerCrossover→ longtriggershorttriggerCrossunder→ shorttriggerupper, lowerupper · lower2 valuesbbrbbrvaluetestPeriodStarttestPeriodStartvaluetestPeriodStoptestPeriodStopvaluecommscommsvaluesl1sl1valuesl2sl2valuesl3sl3valuetp1tp1valuetp2tp2valuetp3tp3valuetp4tp4valuelongcondition1longcondition1conditionshortcondition1shortcondition1conditionshortcondition2shortcondition2conditionentry:ELOpen ELstrategy.entryentry:Sell One OrderOpen Sell One Orderstrategy.entryclose:ELClose ELstrategy.closeplot:13SMIplotplot:14Signalplotplot:23Bollinger Bands %Bplothline:27hlinehlinehline:28hlinehlinefill:BackgroundBackgroundfill

Order rules

OrderFires whenBy defaultLine
Open EL longlongcondition1 and longtriggerOn93
Open Sell One Order shortshortcondition1 and shorttrigger and ((strategy.position_avg_price*tp3 < high) or (strategy.position_avg_price*tp3 < close))On96
Close ELshortcondition2 and shorttrigger and ((strategy.position_avg_price*tp4 < high) or (strategy.position_avg_price*tp4 < close))On99
Close EL((strategy.position_avg_price*tp1 < high) or (strategy.position_avg_price*tp1 < close))On102
Close EL((strategy.position_avg_price*tp2 < high) or (strategy.position_avg_price*tp2 < close)) and shorttriggerOn105
Close EL(strategy.position_avg_price*sl1 > close)On108
Close EL(strategy.position_avg_price*sl2 > close) and shorttriggerOn111
Close EL(strategy.position_avg_price*sl3 > close) and shortcondition1 and shorttriggerOn114
Close EL(strategy.position_avg_price*sl3 > close) and shortcondition2 and shorttriggerOn117

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Does it repaint?

Yes

At least one pattern in the source can repaint; it is marked Check below.

Not measuredNo trades to compareThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, but neither the live nor the historical run produced any trades in them, so the replay says nothing either way.
  • ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • CheckIntrabar recalculationcalc_on_every_tick = true. Live values can differ from history.
  • 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 1D0.0%+102.5%00%—0.0%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h0.0%+5.5%00%—0.0%8 May 2026 – 21 Oct 2026
ETHUSDT 1D0.0%+9.8%00%—0.0%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h0.0%+8.4%00%—0.0%8 May 2026 – 21 Oct 2026
SOLUSDT 1D0.0%+16.7%00%—0.0%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h0.0%+21.5%00%—0.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D0.0%+148.3%00%—0.0%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h0.0%+17.1%00%—0.0%8 May 2026 – 21 Oct 2026

Backtests are simulations on historical data and are not investment advice.

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
Risk Reduction Ultimate Template this page—v4 strategy0.0%00.0%
Volume Weighted Bollinger Bands Strategy by Ankit_1618ema sma stdevv4 strategy+10.0%1527.5%
BB21_MA200_Strategy by mohaneeema sma stdevv4 strategyNo trades on this market
Super Breakout day trading by beststockalertstdev sma emav4 strategyNo trades on this market
Super Auto Breakout Day Trade Volatile stocks by beststockalertstdev sma emav4 strategy−6.1%5129.1%
VFI strategy [based on VFI indicator published by UTS] by mohaneesma stdev emav4 strategy+181.4%8154.2%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 22 msWith a workaround 1,000 bars in 56 msNot measured
PineTSNo v5 and v6 only—Not measured

Zeal Terminal's engine currently reads an order side written as long = true as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (line 93) so the engine trades the way the script says. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.

“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/// © burgercrisis//@version=4strategy(title="Risk Reduction Ultimate Template", overlay=false, pyramiding=10, calc_on_every_tick=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10, initial_capital=1000, slippage=10, commission_value=0.1)//This is just to make this template work and publishable.src = input(close, title="Source")//SMIIlonglen = input(20, minval=1, title="Long Length")shortlen = input(5, minval=1, title="Short Length")siglen = input(5, minval=1, title="Signal Line Length")erg = tsi(src, shortlen, longlen)sig = ema(erg, siglen)plot(erg, color=#0094FF, title="SMI")plot(sig, color=#FF6A00, title="Signal")//%Blength = input(20, minval=1)length = input(20, minval=1)mult = input(2.0, minval=0.001, maxval=50, step=0.1, title="StdDev")basis = sma(src, length)dev = mult * stdev(src, length)upper = basis + devlower = basis - devbbr = (src - lower)/(upper - lower)plot(bbr, "Bollinger Bands %B", color=color.teal)buy=input(0.0,step=0.1)sellonce=input(1.0,step=0.1)sellall=input(1.1,step=0.1)band1 = hline(sellonce, "Overbought", color=#606060, linestyle=hline.style_dashed)band0 = hline(buy, "Oversold", color=#606060, linestyle=hline.style_dashed)fill(band1, band0, color=color.teal, title="Background")//Always include a backtesting period selector. Always always always always or I hate you.//* Backtesting Period Selector | Component *////* https://www.tradingview.com/script/eCC1cvxQ-Backtesting-Period-Selector-Component *////* https://www.tradingview.com/u/pbergden/ *////* Modifications made *//testStartYear = input(2020, "Backtest Start Year") testStartMonth = input(1, "Backtest Start Month")testStartDay = input(1, "Backtest Start Day")testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)testStopYear = input(999999, "Backtest Stop Year")testStopMonth = input(9, "Backtest Stop Month")testStopDay = input(26, "Backtest Stop Day")testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)testPeriod() =>    time >= testPeriodStart and time <= testPeriodStop ? true : false/////////////// END - Backtesting Period Selector | Component /////////////////Whats the point of this?//This is a strategy template for risk reduction. I've found that the main problem with strategies on Tradingview is they do not account for risk and reward management! The ones that do, do so very poorly and rudimentarily!//Utter lack of stop losses, rudimentary and unconditional stop losses with no care for changes in momentum that may indicate the stop loss shouldn't be taken, take profits occurring in the middle of huge rush just because a price was hit//and momentum based signals with no care for whether the sale is profitable or not, or if price had barely even changed!//I thought maybe TA-based bots just aren't possible to actually be any good for a moment. But rather then give up, I decided to try to gear up. And I believe I found a key that can make almost any strategy work. A path to actually beating buy and hold.////How do I use this?//It's actually really simple. It might have a lot of tiny pieces but that is to maximize the users choices in maximizing risk adjusted return and its really simple once you make sense of it.//You have a single buy signal, three stop losses, two take profits and two (roughly) standard sells.//I tend to use a trigger and multiple filter conditions for both my buys and sales. This strategy doesn't need it for the buys but that is how you make the sale system work so for clarity there are two conditions for buys – longtrigger and longcondition1.//The trigger, you want to be something that occurs at a single point in time, such as a crossover of some kind. The filter you want to be more loose and regional, such as an overbought or oversold condition.//The sells conditions are similar. You have a shorttrigger and two shortconditions sets for filtering. The first shortcondition is to sell a single set (depending on your position sizing settings in properties tab).//The second shortcondition is to sell everything at more extreme settings. This is because nobody can perfectly time every top, even with a script, so you want to take profits along the way without completely exiting//and allowing yourself to re-enter when its right and only fully exit at extreme cases. If you want to use just one set of conditions, move to the last line and replace  shortcondition2 with  shortcondition1.//Then you can decide if selling all is truly better then pyramiding things out... Test both % and flat and you will see.////Everything should be pretty clearly labeled.////longtrigger=crossover(erg,sig)                                          ////Put your trigger for buys herelongcondition1=bbr<buy                                                  ////Put your buy filter signals hereshorttrigger=crossunder(erg,sig)                                        ////Put your sell trigger hereshortcondition1=bbr>sellonce                                            ////This is your filters for partial exitsshortcondition2=bbr>sellall                                             ////This is your filter for full sales.//This gets multiplied to your sale thresholds to make sure they account for commission properly.commission=input(0.1)comms=(100+commission)/100//Three stop losses//StopLossesstopLossFear=input(100.0, step=0.2, title="Hard Stop Loss")     //Hard stop loss triggers immediately when a drop from your assumed average position price occurs equal to set percentagesl1=(100-stopLossFear)/100*commsstopLossSafe=input(100.0, step=0.2, title="Soft Stop Loss")     //Soft stop loss triggers when your shorttrigger occurs after a drop from position price equal to set percentagesl2=(100-stopLossSafe)/100*commsstopLossSafest=input(100.0, step=0.2, title="Safe Stop Loss")   //Safe stop loss triggers when both shorttrigger and shortcondition1 occur after a drop from position price equal to set percentagesl3=(100-stopLossSafest)/100*comms//TakeProfitsTakeProfit1=input(100.0, step=0.2, title="Hard Take Profit")        //Hard Take Profit occurs after a rise from position price equal to set percentagetp1=(100+TakeProfit1)/100*commsTakeProfit2=input(100.0, step=0.2, title="Soft Take Profit")        //Soft Take Profit occurs when your shorttrigger occurs after a rise from position price equal to set percentagetp2=(100+TakeProfit2)/100*commsTakeProfit3=input(0.0, step=0.2, title="Minimum Sale Profit")       //This is the standard single sell signal, it occurs when shorttrigger and shortcondition1 occur after a rise from position price equal to set percentage to filter bad signalstp3=(100+TakeProfit3)/100*commsTakeProfit4=input(0.0, step=0.2, title="Sell All Profit")           //This sells all positions when shorttrigger and shortcondition1 occur after a rise from position price equal to set percentagetp4=(100+TakeProfit4)/100*commsif testPeriod()                                                                 //Backtesting period selector component    if longcondition1 and longtrigger        strategy.entry(id="EL", comment="Buy", long=true)                                           //Buy signal            if shortcondition1 and shorttrigger and ((strategy.position_avg_price*tp3 < high) or (strategy.position_avg_price*tp3 < close))     //Sell One signal        strategy.entry("Sell One Order", strategy.short)            if shortcondition2 and shorttrigger and ((strategy.position_avg_price*tp4 < high) or (strategy.position_avg_price*tp4 < close))     //Sell All signal        strategy.close(id="EL", comment="Sell All")            if ((strategy.position_avg_price*tp1 < high) or (strategy.position_avg_price*tp1 < close))                          //Hard Take Profit signal        strategy.close(id="EL", comment="Hard Take Profit")            if ((strategy.position_avg_price*tp2 < high) or (strategy.position_avg_price*tp2 < close)) and shorttrigger                 //Soft Take Profit signal        strategy.close(id="EL", comment="Soft Take Profit")            if (strategy.position_avg_price*sl1 > close)                                                    //Hard Stop Loss Signal        strategy.close(id="EL", comment="Hard Stop Loss")            if (strategy.position_avg_price*sl2 > close) and shorttrigger                                           //Soft Stop Loss signal        strategy.close(id="EL", comment="Soft Stop Loss")            if (strategy.position_avg_price*sl3 > close) and shortcondition1 and shorttrigger                               //Safe Stop Loss from Sell One conditions        strategy.close(id="EL", comment="Safe Stop Loss 1")           if (strategy.position_avg_price*sl3 > close) and shortcondition2 and shorttrigger                               //Safe Stop Loss  from Sell All condition        strategy.close(id="EL", comment="Safe Stop Loss 2")