Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Risk Management Strategy Template

A Pine Script v5 strategy built on EMA (close, 200), RSI (close, 10) and Crossover (rsi, 40). It has 3 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 1 in cash and pays no commission. 16 settings; defaults include EMA Length 200, RSI Length 10 and RSI Overbought 60.

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 Management Strategy Template 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 Risk Management Strategy Template do on BTCUSDT 1D with default settings?
−0.35%
From 26 Jan 2024 to 21 Oct 2026, over 7 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does Risk Management Strategy Template run in Pine Script v6?
Yes
Same 7 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. The v6 script can be downloaded below.
Does Risk Management Strategy Template use a stop loss?
Yes
strategy.exit sets a stop on line 197.
Does Risk Management Strategy Template run in Zeal Terminal?
Yes
It compiles in 57 ms and runs 1,000 bars in 93 ms, in the browser.

BTCUSDT · 1D · default settings

  • EMA Trend Line
  • Stop Loss Price
  • Take Profit Price
  • 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 (16)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$997$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. Lines, boxes and labels are the script's own drawings, the most recent ones its limits keep.
Net profit
−0.35%
−$3.47
Buy and hold
+102.5%
same period
Closed trades
7
2 won · 5 lost
Profitable
28.6%
of closed trades
Profit factor
0.92
gross profit ÷ gross loss
Max drawdown
3.60%
−$36.58

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 commission

    The backtest assumes free trading. Results on any real exchange will be lower.

  • Note

    4 settings have no label

    In the settings dialog startMonth (line 72), startDate (line 73), endMonth (line 75), endDate (line 76) 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.

SettingDefaultType and rangeFeeds
Indicators: Settings
EMA Length EMA line to identify trend direction. Above EMA trend line is bullish. Below EMA trend line is bearish200int · min 1ema
RSI Length 10int · min 1rsi
Strategy: Conditions
RSI Overbought RSI overbought level used to identify pullbacks within the main trend. RSI crossing BELOW this level triggers a SHORT when in a DOWN trend60int · min 50 · max 100bearRsi
RSI Oversold RSI overbought level used to identify pullbacks within the main trend. RSI crossing ABOVE this level triggers a LONG when in an UP trend40int · min 0 · max 50bullRsi
Strategy: Exit Conditions
Stop Loss ATR Length Length of ATR used to calculate Stop Loss.14int · min 0atr
Stop Loss ATR Multiplier Size of StopLoss is determined by multiplication of ATR value. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.4float · min 0 · step 0.1slAmount
Strategy: Risk Management
Risk : Reward 1 :Previous high or low (long/short dependant) is used to determine TP level. 'Risk : Reward' ratio is then used to calculate SL based of previous high/low level.\n\nIn short, the higher the R:R ratio, the smaller the SL since TP target is fixed by previous high/low price data.2float · min 0 · step 0.1tpPercent
Portfolio Risk % Percentage of portfolio you lose if trade hits SL.\n\nYou then stand to gain\n Portfolio Risk % * Risk : Reward\nif trade hits TP.1float · min 0 · step 0.1riskAmt
Strategy: Date Range
Start Date 2022int · min 1900 · max 2100inDateRange
Start Month (no label in the script)1int · options [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]inDateRange
Start Date (no label in the script)1int · options [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]inDateRange
End Date 2100int · min 1900 · max 2100inDateRange
End Month (no label in the script)1int · options [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]inDateRange
End Date (no label in the script)1int · options [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]inDateRange
Strategy: Drawings
Show TP / SL BoxesShow or hide TP and SL position boxes.\n\nNote: TradingView limits the maximum number of boxes that can be displayed to 500 so they may not appear for all price data under test.trueboolline 117 line 125
Show Trade Exit LabelsUseful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.falseboolline 133

What it calculates

  • EMAclose, EMA Length (200)ema · line 89
  • RSIclose, RSI Length (10)rsi · line 94
  • Crossoverrsi, RSI Oversold (40)bullRsi · line 145
  • Crossunderrsi, RSI Overbought (60)bearRsi · line 146
  • ATRStop Loss ATR Length (14)atr · line 167

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 dataemaLengthEMA Length setting · 200rsiLengthRSI Length setting · 10rsiOversoldRSI Oversold setting · 40rsiOverboughtRSI Overbought setting · 60high · low · closehigh · low · closeprice dataatrLengthStop Loss ATR Length …setting · 14slAtrMultiplierStop Loss ATR Multiplie…setting · 4riskRewardRisk : Reward 1 :setting · 2accountRiskPercentPortfolio Risk % …setting · 1timetimeprice datastartYearStart Date setting · 2022startMonthStart Monthsetting · 1startDateStart Datesetting · 1endYearEnd Date setting · 2100endMonthEnd Monthsetting · 1endDateEnd Datesetting · 1lowlowprice datahighhighprice dataemaEMA→ emarsiRSI→ rsibullRsiCrossover→ bullRsibearRsiCrossunder→ bearRsiatrATR→ atrpriceOffset, tradeEntryBar, entryPrice, pnl, posSizepriceOffset · tradeEntr…5 valueslabelStrlabelStrvalueprofitPointsprofitPointsvaluelossPointslossPointsvalueslPriceslPricevaluetpPricetpPricevalueslAmountslAmountvalueslPercentslPercentvaluetpPercenttpPercentvalueriskAmtriskAmtvalueentryQtyentryQtyvalueopenLongopenLongconditionopenShortopenShortconditioninDateRangeinDateRangeconditionbullEma, bearEmabullEma · bearEma2 conditionsgoLonggoLongconditiongoShortgoShortconditionflippingSidesflippingSidesconditionenteringTradeenteringTradeconditioninTradeinTradeconditionslHitslHitconditiontpHittpHitconditionexitTriggeredexitTriggeredconditionentry:LongOpen Longstrategy.entryentry:ShortOpen Shortstrategy.entryexit:TP/SLexit TP/SLstrategy.exitplot:90EMA Trend Lineplotplotchar:224plotcharplotcharplotchar:225plotcharplotchar

Order rules

OrderFires whenBy defaultLine
Open Long longopenLongOn179
Open Short shortopenShortOn187
Exit TP/SL stop and limitevery barOn197

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.

2/2trades 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−0.3%+102.5%729%0.923.6%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−1.6%+5.5%617%0.553.3%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−1.1%+9.8%729%0.783.6%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+6.0%+8.4%667%3.901.3%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+0.9%+16.7%838%1.182.2%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+0.5%+21.5%838%1.163.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−0.1%+148.3%633%0.982.5%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+4.6%+17.1%4100%864.100.8%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 market20%−$20.19
Sideways market333%$7.11
Falling market250%$9.62

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

How bad could the drawdown be?

4.2%

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

0%5%
All 7 trades
SideEntryExitBarsP&L
short15 Sep 2024 59,993.0012 Oct 2024 62,540.0027−$2.71
long12 Oct 2024 62,540.0010 Nov 2024 79,366.3029$19.91
long25 Dec 2024 98,663.6028 Feb 2025 81,144.8065−$10.19
long3 Mar 2025 94,270.0011 Mar 2025 77,070.208−$10.09
long7 Jun 2025 104,288.0017 Nov 2025 92,363.00163−$10.00
short8 Jan 2026 91,364.205 Feb 2026 70,721.7028$19.71
short6 Mar 2026 70,891.0021 Sep 2026 85,314.20199−$10.09

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 Management Strategy Template this page—v5 strategy−0.3%73.6%
Mathias & Christer Timeframe RSI by mattehalenrsi ema atrv4 strategy−0.7%180.7%
Dashboard table by Zeal Terminalrsi atr emav5 indicatorindicator
3 x EMA + Stochastic RSI + ATR by tomimarsonema rsi atrv4 strategy−42.3%1844.8%
Atrend by OTS by prim722ema rsi atrv4 strategy+12.1%7634.4%
EMA crossover (daily TF) by tradeswithashishema rsi atrv5 strategy+11.0%1211.6%

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?

Yes

Same 7 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. It differs from the v5 version by 1 edit.

Download the v6 script

⋯// It was not designed to be traded in its current form.-//@version=5+//@version=6INITIAL_CAPITAL = 1000⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 57 msYes 1,000 bars in 93 msNot measured
PineTSNot testedNot testedNot measured

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report.

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/// © kevinmck100// @description// This strategy is intended to be used as a base template for building new strategies.//// It incorporates the following features:////      - Risk management:  Configurable X% loss per stop loss//                          Configurable R:R ratio////      - Trade entry:      Calculated position size based on risk tolerance////      - Trade exit:       Stop Loss currently configurable ATR multiplier but can be replaced based on strategy//                          Take Profit calculated from Stop Loss using R:R ratio////      - Backtesting:      Configurable backtesting range by date////      - Trade drawings:   TP/SL boxes drawn for all trades. Can be turned on and off//                          Trade exit information labels. Can be turned on and off//                          NOTE: Trade drawings will only be applicable when using overlay strategies////      - Debugging:        Includes section with useful debugging techniques//// Strategy conditions:////      - Trade entry:      LONG:   C1: Price is above EMA line//                                  C2: RSI is crossing out of oversold area//                          SHORT:  C1: Price is below EMA line//                                  C2: RSI is crossing out of overbought area////      - Trade exit:       Stop Loss:      Stop Loss ATR multiplier is hit//                          Take Profit:    R:R multiplier * Stop Loss is hit//// The idea is to use RSI to catch pullbacks within the main trend. Note that// this strategy is intended to be a simple base strategy for building upon.// It was not designed to be traded in its current form.//@version=5INITIAL_CAPITAL = 1000DEFAULT_COMMISSION = 0.02MAX_DRAWINGS = 500IS_OVERLAY = truestrategy("Risk Management Strategy Template", "Strategy Template", overlay = IS_OVERLAY, initial_capital = INITIAL_CAPITAL, currency = currency.NONE, max_labels_count = MAX_DRAWINGS, max_boxes_count = MAX_DRAWINGS, max_lines_count = MAX_DRAWINGS, default_qty_type = strategy.cash, commission_type = strategy.commission.percent, commission_value = DEFAULT_COMMISSION)// =============================================================================// INPUTS// =============================================================================// ------------------------ Replacable section - Start -------------------------// ------------------// Indicator Settings// ------------------emaLength           = input.int (200,   "EMA Length          ",             group = "Indicators: Settings",         inline = "IS1", minval = 1,                 tooltip = "EMA line to identify trend direction. Above EMA trend line is bullish. Below EMA trend line is bearish")rsiLength           = input.int (10,    "RSI Length            ",           group = "Indicators: Settings",         inline = "IS2", minval = 1)// ----------------------// Trade Entry Conditions// ----------------------rsiOverbought       = input.int (60,    "RSI Overbought        ",           group = "Strategy: Conditions",         inline = "SC1", minval = 50, maxval = 100,  tooltip = "RSI overbought level used to identify pullbacks within the main trend. RSI crossing BELOW this level triggers a SHORT when in a DOWN trend")rsiOversold         = input.int (40,    "RSI Oversold          ",           group = "Strategy: Conditions",         inline = "SC2", minval = 0,  maxval = 50,   tooltip = "RSI overbought level used to identify pullbacks within the main trend. RSI crossing ABOVE this level triggers a LONG when in an UP trend")// ---------------------// Trade Exit Conditions// ---------------------atrLength           = input.int  (14,   "Stop Loss ATR Length      ",       group = "Strategy: Exit Conditions",    inline = "EC1", minval = 0,                 tooltip = "Length of ATR used to calculate Stop Loss.")slAtrMultiplier     = input.float(4,    "Stop Loss ATR Multiplier     ",    group = "Strategy: Exit Conditions",    inline = "EC2", minval = 0, step = 0.1,     tooltip = "Size of StopLoss is determined by multiplication of ATR value. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.")// ------------------------- Replacable section - End --------------------------// ---------------// Risk Management// ---------------riskReward          = input.float(2,    "Risk : Reward        1 :",         group = "Strategy: Risk Management",    inline = "RM1", minval = 0, step = 0.1,     tooltip = "Previous high or low (long/short dependant) is used to determine TP level. 'Risk : Reward' ratio is then used to calculate SL based of previous high/low level.\n\nIn short, the higher the R:R ratio, the smaller the SL since TP target is fixed by previous high/low price data.")accountRiskPercent  = input.float(1,    "Portfolio Risk %         ",        group = "Strategy: Risk Management",    inline = "RM1", minval = 0, step = 0.1,     tooltip = "Percentage of portfolio you lose if trade hits SL.\n\nYou then stand to gain\n  Portfolio Risk % * Risk : Reward\nif trade hits TP.")// ----------// Date Range// ----------startYear           = input.int (2022,  "Start Date       ",                group = 'Strategy: Date Range',         inline = 'DR1', minval    = 1900, maxval = 2100)startMonth          = input.int (1,     "",                                 group = 'Strategy: Date Range',         inline = 'DR1', options   = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])startDate           = input.int (1,     "",                                 group = 'Strategy: Date Range',         inline = 'DR1', options   = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])endYear             = input.int (2100,  "End Date      ",                   group = 'Strategy: Date Range',         inline = 'DR2', minval    = 1900, maxval = 2100)endMonth            = input.int (1,     "",                                 group = 'Strategy: Date Range',         inline = 'DR2', options   = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])endDate             = input.int (1,     "",                                 group = 'Strategy: Date Range',         inline = 'DR2', options   = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])// ----------------// Drawing Settings// ----------------showTpSlBoxes       = input.bool(true,  "Show TP / SL Boxes",               group = "Strategy: Drawings",           inline = "D1",  tooltip = "Show or hide TP and SL position boxes.\n\nNote: TradingView limits the maximum number of boxes that can be displayed to 500 so they may not appear for all price data under test.")showLabels          = input.bool(false, "Show Trade Exit Labels",           group = "Strategy: Drawings",           inline = "D2",  tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.")// =============================================================================// INDICATORS// =============================================================================// ------------------------ Replacable section - Start -------------------------// ---// EMA// ---ema = ta.ema(close, emaLength)plot(ema, "EMA Trend Line", color.white)// ---// RSI// ---rsi = ta.rsi(close, rsiLength)// ------------------------- Replacable section - End --------------------------// =============================================================================// STRATEGY LOGIC// =============================================================================// ---------// FUNCTIONS// ---------percentAsPoints(pcnt) =>    math.round(pcnt / 100 * close / syminfo.mintick)    calcStopLossPrice(pointsOffset, isLong) =>    priceOffset = pointsOffset * syminfo.mintick    if isLong        close - priceOffset    else         close + priceOffsetcalcProfitTrgtPrice(pointsOffset, isLong) =>    calcStopLossPrice(-pointsOffset, isLong)            printLabel(barIndex, msg) => label.new(barIndex, close, msg)printTpSlHitBox(left, right, slHit, tpHit, entryPrice, slPrice, tpPrice) =>     if showTpSlBoxes        box.new (left = left,   top = entryPrice,   right = right,  bottom = slPrice,   bgcolor = slHit ? color.new(color.red, 60)   : color.new(color.gray, 90), border_width = 0)        box.new (left = left,   top = entryPrice,   right = right,  bottom = tpPrice,   bgcolor = tpHit ? color.new(color.green, 60) : color.new(color.gray, 90), border_width = 0)        line.new(x1 = left,     y1 = entryPrice,    x2 = right,     y2 = entryPrice,    color = color.new(color.yellow, 20))        line.new(x1 = left,     y1 = slPrice,       x2 = right,     y2 = slPrice,       color = color.new(color.red, 20))        line.new(x1 = left,     y1 = tpPrice,       x2 = right,     y2 = tpPrice,       color = color.new(color.green, 20))        printTpSlNotHitBox(left, right, entryPrice, slPrice, tpPrice) =>     if showTpSlBoxes        box.new (left = left,   top = entryPrice,   right = right,  bottom = slPrice,   bgcolor = color.new(color.gray, 90), border_width = 0)        box.new (left = left,   top = entryPrice,   right = right,  bottom = tpPrice,   bgcolor = color.new(color.gray, 90), border_width = 0)        line.new(x1 = left,     y1 = entryPrice,    x2 = right,     y2 = entryPrice,    color = color.new(color.yellow, 20))        line.new(x1 = left,     y1 = slPrice,       x2 = right,     y2 = slPrice,       color = color.new(color.red, 20))        line.new(x1 = left,     y1 = tpPrice,       x2 = right,     y2 = tpPrice,       color = color.new(color.green, 20))        printTradeExitLabel(x, y, posSize, entryPrice, pnl) =>     if showLabels        labelStr = "Position Size: " + str.tostring(math.abs(posSize), "#.##") + "\nPNL: " + str.tostring(pnl, "#.##") + "\nCapital: " + str.tostring(strategy.equity, "#.##") + "\nEntry Price: " + str.tostring(entryPrice, "#.##")        label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : color.new(color.red, 60), textcolor = color.white, style = label.style_label_down)// ----------// CONDITIONS// ----------inDateRange         = time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0) and time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0)// ------------------------ Replacable section - Start -------------------------// Condition 1: Price above EMA indicates bullish trend, price below EMA indicates bearish trendbullEma             = close > emabearEma             = close < ema// Condition 2: RSI crossing back from overbought/oversold indicates pullback within trendbullRsi             = ta.crossover  (rsi, rsiOversold)bearRsi             = ta.crossunder (rsi, rsiOverbought)// Combine all entry conditionsgoLong              = inDateRange and bullEma and bullRsigoShort             = inDateRange and bearEma and bearRsi// ------------------------- Replacable section - End --------------------------// Trade entry and exit variablesvar tradeEntryBar   = bar_indexvar profitPoints    = 0.var lossPoints      = 0.var slPrice         = 0.var tpPrice         = 0.var inLong          = falsevar inShort         = false// Entry decisionsopenLong            = (goLong and not inLong)openShort           = (goShort and not inShort)flippingSides       = (goLong and inShort) or (goShort and inLong)enteringTrade       = openLong or openShortinTrade             = inLong or inShort// ------------------------ Replacable section - Start -------------------------// Exit calculationsatr                 = ta.atr(atrLength)slAmount            = atr * slAtrMultiplierslPercent           = math.abs((1 - (close - slAmount) / close) * 100)tpPercent           = slPercent * riskReward// ------------------------- Replacable section - End --------------------------// Risk calculationsriskAmt             = strategy.equity * accountRiskPercent / 100entryQty            = math.abs(riskAmt / slPercent * 100)  / closeif openLong    if strategy.position_size < 0        printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice)        printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit)    strategy.entry("Long", strategy.long, qty = entryQty, alert_message = "Long Entry")    enteringTrade   := true    inLong          := true    inShort         := falseif openShort    if strategy.position_size > 0        printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice)        printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit)    strategy.entry("Short", strategy.short, qty = entryQty, alert_message = "Short Entry")    enteringTrade   := true    inShort         := true    inLong          := falseif enteringTrade    profitPoints    := percentAsPoints(tpPercent)    lossPoints      := percentAsPoints(slPercent)    slPrice         := calcStopLossPrice(lossPoints, openLong)    tpPrice         := calcProfitTrgtPrice(profitPoints, openLong)    tradeEntryBar   := bar_indexstrategy.exit("TP/SL", profit = profitPoints, loss = lossPoints, comment_profit = "TP Hit", comment_loss = "SL Hit", alert_profit = "TP Hit Alert", alert_loss = "SL Hit Alert")// =============================================================================// DRAWINGS// =============================================================================// -----------// TP/SL Boxes// -----------slHit           = (inShort and high >= slPrice) or (inLong  and low <= slPrice)tpHit           = (inLong  and high >= tpPrice) or (inShort and low <= tpPrice)exitTriggered   = slHit or tpHitentryPrice      = strategy.closedtrades.entry_price (strategy.closedtrades - 1)pnl             = strategy.closedtrades.profit      (strategy.closedtrades - 1)posSize         = strategy.closedtrades.size        (strategy.closedtrades - 1)// Print boxes for trades closed at profit or lossif (inTrade and exitTriggered)     inShort    := false    inLong     := false     printTpSlHitBox(tradeEntryBar + 1, bar_index, slHit, tpHit, entryPrice, slPrice, tpPrice)    printTradeExitLabel(bar_index, math.max(tpPrice, slPrice), posSize, entryPrice, pnl)// Print TP/SL box for current open tradeif barstate.islastconfirmedhistory and strategy.position_size != 0    printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice)    // =============================================================================// DEBUGGING// =============================================================================// Data window plotsplotchar(slPrice,    "Stop Loss Price",     "")plotchar(tpPrice,    "Take Profit Price",   "")// Label plotsplotDebugLabels = falseif plotDebugLabels    if bar_index == tradeEntryBar         printLabel(bar_index, "Position size: " + str.tostring(entryQty * close, "#.##"))