Zeal Terminal Open Zeal Terminal

Pine Script v5 · Strategy

Heikin Ashi Supertrend

A Pine Script v5 strategy built on ATR (10) and Change (averageEntryPrice). It has 8 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss. Each trade commits 100 in cash and pays 0.035% commission. 23 settings; defaults include Strategy Identifier HASTXXXUSDT (Nm), ATR Length 10 and ATR Multiplier 2.7.

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 Heikin Ashi Supertrend repaint?
No
No repainting patterns were found in the source.
Does Heikin Ashi Supertrend run in Pine Script v6?
Not tested
The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L9:C0: no source was supplied for the library 'jordanfray/threengine_global_automation_library/89'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download.
Does Heikin Ashi Supertrend use a stop loss?
Yes
strategy.exit sets a stop on line 135, 137, 144, 146.
Does Heikin Ashi Supertrend run in Zeal Terminal?
No
Not yet: it imports the library jordanfray/threengine_global_automation_library/89 and the library jordanfray/obvFilter/2, whose source is not available here, so it does not run here
Does not run in Zeal Terminal yetIt imports the library jordanfray/threengine_global_automation_library/89 and the library jordanfray/obvFilter/2, whose source is not available here, so it does not run here. The settings, logic and review below are read from the source, which does not need a run.

Review

What a careful reader of this script would point out, found by checking the source.

  • 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
Strategy Information
Strategy IdentifierHASTXXXUSDT (Nm)stringline 228
Supertrend
ATR Length10int · step 1haTrueRange
ATR Multiplier2.7float · step 0.1haSupertrendUp haSupertrendDown
Entry Settings
Lot Size100floatcontractCount entryAmount enterLongAlertMessage enterShortAlertMessage lotSizeDisplay
Lot Size TypeDollarsstring · options ["Percent Of Account","Dollars", "Contracts"]contractCount entryAmount enterLongAlertMessage enterShortAlertMessage lotSizeDisplay
Exit Settings
Profit Target (%)47.0float · step .25profitTarget
Stop Limit Trigger (%)21float · step 0.25stopLossLimitPrice enterLongAlertMessage enterShortAlertMessage
Stop Limit Offset (%)0.10float · step 0.01stopLossTriggerPrice enterLongAlertMessage enterShortAlertMessage
Move Stop Loss
Move Stop Losstrueboolline 103 line 105 line 108 line 205
to (%)If enabled, the stop loss will be moved to a price relative to the average entry price using a percentange as an offset after the price reaches the 'after' threshold. \n 0 = break even.\n \n Default: .11.0floatmoveStopLossTo
after (%)If enabled, the stop loss will be moved to a price relative to the average entry price using a percentange as an offset after the price reaches the 'after' threshold. \n 0 = break even.\n \n Default: .14.0floatmoveStopLossAfter moveStopAfterLabel stopLossLabelText
Manually Close Trade
Manullay Close Trade?falseboolmanuallyCloseShort manuallyCloseLong
Date/Time When Trade Was Closedtimestamp("01 Jan 2022 00:00")timemanuallyCloseShort manuallyCloseLong
Price Trade Was Closed At0.0priceexit Manually Close Long exit Manually Close Short
Automation Settings
Enable Webook MessagesfalseboolenterLongAlertMessage enterShortAlertMessage exitLongAlertMessage exitShortAlertMessage warning_color line 232
ExchangePick the exchange that your Alertatron API Secret is configured to. This is used to get the right divider between the pair and the base currency.ByBitstring · options ["ByBit", "FTX.us"]enterLongAlertMessage enterShortAlertMessage exitLongAlertMessage exitShortAlertMessage line 235 line 244
Alertatron API SecretThe key that is configured in Alertatron that selects which exchange integration you want to use.haStEthUsdtstringenterLongAlertMessage enterShortAlertMessage exitLongAlertMessage exitShortAlertMessage line 238
Leverage Amount1intcontractCount entryAmount enterLongAlertMessage enterShortAlertMessage line 241
Leverage TypeCrossstring · options ["Cross", "Isolated"]enterLongAlertMessage enterShortAlertMessage line 241
Currency OverrideIf you want to use a different base currency than the current chart, you can override it here. Be sure it matches the exchange base currency. \n \n Do not include the currency/symbol divider in this.stringsymbol baseCurrency
Symbol OverrideIf you want to use a different symbol than the current chart, you can override it here. Be sure it matches the exchange symbol. \n \n Do not include the currency/symbol divider in this.stringsymbol baseCurrency
Order QTY Decimal Rounding3intstopLossLimitPrice stopLossTriggerPrice moveStopLossAfter moveStopLossTo contractCount entryAmount enterLongAlertMessage enterShortAlertMessage
Testing
Show Debug Tablefalseboolline 256

What it calculates

  • ATRATR Length (10)haTrueRange · line 75
  • ChangeaverageEntryPricejustClosedPosition · line 89

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 97 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open Long longopenLongOn131
Close LongexitLongOn133
Exit moveStopTriggered ? "Moved Stop" : "Stop Loss" stoplongStopLossOn135
Exit Manually Close Long stopmanuallyCloseLongOn137
Open Short shortopenShortOn140
Close ShortexitShortOn142
Exit moveStopTriggered ? "Moved Stop" : "Stop Loss" stopshortStopLossOn144
Exit Manually Close Short stopmanuallyCloseShortOn146

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.

The live replay needs a run, and this script does not run in Zeal Terminal yet; the answer comes from the checks on the source alone.

  • ClearHigher-timeframe data5 request.security call(s), none with lookahead on.
  • 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.

Similar scripts

Indicators and strategies built from the same calculations.

ScriptSharesTypeNetTradesMax drawdown
SOJA PIVOT by ParaBellum68atrv4 strategy+3.3%918.2%
Volatility System by EduardoMattjeatrv5 strategy+150.2%221.5%
ATR Stop Buy Strategy by phobo3satrv4 strategyNo trades on this market
VBand Strategy by Saravanan_Ragavanatrv4 strategyNo trades on this market
Volatility Breakout Strategy [Angel Algo] by AngelAlgoatrv5 strategy+3.1%183.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?

Not tested

The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L9:C0: no source was supplied for the library 'jordanfray/threengine_global_automation_library/89'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// © jordanfray-//@version=5+//@version=6//  About This Indicator⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2No It imports the library jordanfray/threengine_global_automation_library/89 and the library jordanfray/obvFilter/2, whose source is not available here, so it does not run hereNot measured
PineTSNot testedNot testedNot measured

Zeal Terminal's engine currently reads an order side written as direction = strategy.long, direction = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 131, 140) 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/// © jordanfray//@version=5//  About This Indicator//  The default settings for this indicator are for BTC/USDT and intended to be used on the 3D timeframe to identify market trends. //  This indicator does a great job identifying whether the market is bullish, bearish, or consolidating. //  This can also work well on lower time frames to help identify when a trend is strong or when it's reversing. strategy("Heikin Ashi Supertrend", overlay=true, max_bars_back=5000, default_qty_type=strategy.cash, default_qty_value=100, initial_capital=100, commission_type=strategy.commission.percent, close_entries_rule="ANY", commission_value=0.035, backtest_fill_limits_assumption=0, process_orders_on_close=true)import jordanfray/threengine_global_automation_library/89 as botimport jordanfray/obvFilter/2 as obv//  Colors - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -green                               = color.new(#2DBD85,0)lightGreen                          = color.new(#2DBD85,90)red                                 = color.new(#E02A4A,0)lightRed                            = color.new(#E02A4A,90)yellow                              = color.new(#FFED00,0)lightYellow                         = color.new(#FFED00,90)purple                              = color.new(#5A00FF,0)blue                                = color.new(#0C6090,0)oceanBlue                           = color.new(#0C6090,0)skyBlue                             = color.new(#00A5FF,0)lightBlue                           = color.new(#00A5FF,80)black                               = color.new(#000000,0)gray                                = color.new(#AAAAAA,0)white                               = color.new(#ffffff,0)transparent                         = color.new(#000000,100)//  TooltipsalertatronSecretTip                 = "The key that is configured in Alertatron that selects which exchange integration you want to use."exchangeTooltip                     = "Pick the exchange that your Alertatron API Secret is configured to. This is used to get the right divider between the pair and the base currency."exchangeCurrencyOverrideTip         = "If you want to use a different base currency than the current chart, you can override it here. Be sure it matches the exchange base currency. \n \n Do not include the currency/symbol divider in this."exchangeCurrencySymbolTip           = "If you want to use a different symbol than the current chart, you can override it here. Be sure it matches the exchange symbol. \n \n Do not include the currency/symbol divider in this."moveStopToolTip                     = "If enabled, the stop loss will be moved to a price relative to the average entry price using a percentange as an offset after the price reaches the 'after' threshold. \n 0 = break even.\n \n Default: .1"//  Strategy Settings - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - strategyIdentifier                  = input.string(defval="HASTXXXUSDT (Nm)", title="Strategy Identifier", group="Strategy Information")supertrendAtrPeriod                 = input.int(defval = 10, step = 1, title = "ATR Length", group = "Supertrend")supertrendAtrMultiplier             = input.float(defval = 2.7, step = 0.1, title = "ATR Multiplier", group = "Supertrend")lotSize                             = input.float(defval=100, title="Lot Size", group="Entry Settings")lotSizeType                         = input.string(defval="Dollars", title="Lot Size Type", options=["Percent Of Account","Dollars", "Contracts"], group="Entry Settings") profitTargetPercent                 = input.float(defval = 47.0, title = "Profit Target (%)", step = .25, group="Exit Settings")stopLimitTrigger                    = input.float(defval=21, title="Stop Limit Trigger (%)", step=0.25, group="Exit Settings")stopLimitOffset                     = input.float(defval=0.10, title="Stop Limit Offset (%)", step=0.01, group="Exit Settings")enableMoveStopToBreakEven           = input.bool(defval=true, title="Move Stop Loss", group="Move Stop Loss")moveTo                              = input.float(defval=1.0, title="to (%)", tooltip=moveStopToolTip)moveAfter                           = input.float(defval=4.0, title="after (%)", tooltip=moveStopToolTip)manuallyCloseTrade                  = input.bool(defval=false, title="Manullay Close Trade?", group="Manually Close Trade")dateTimeClosed                      = input.time(defval=timestamp("01 Jan 2022 00:00"), title="Date/Time When Trade Was Closed", group="Manually Close Trade")priceClosed                         = input.price(defval=0.0, title="Price Trade Was Closed At", group="Manually Close Trade")//  Trade AutomationenableWebhookMessages               = input.bool(defval=false, title="Enable Webook Messages", group="Automation Settings")tradeAutomationExchange             = input.string(defval="ByBit", options=["ByBit", "FTX.us"], title="Exchange", group="Automation Settings", tooltip=exchangeTooltip)tradeAutomationSecret               = input.string(defval="haStEthUsdt", title="Alertatron API Secret", group="Automation Settings", tooltip=alertatronSecretTip)tradeAutomationLeverage             = input.int(defval=1, title="Leverage Amount", group="Automation Settings")tradeAutomationLeverageType         = input.string(defval="Cross", title="Leverage Type", options=["Cross", "Isolated"], group="Automation Settings")tradeAutomationCurrencyOverride     = input.string(defval="", title="Currency Override", group="Automation Settings", tooltip=exchangeCurrencyOverrideTip)tradeAutomationSymbolOverride       = input.string(defval="", title="Symbol Override", group="Automation Settings", tooltip=exchangeCurrencySymbolTip)exchangeQtyDecimals                 = input.int(defval=3, title="Order QTY Decimal Rounding", group="Automation Settings")showDebugTable                      = input.bool(defval=false, title="Show Debug Table", group="Testing")//  Position StatescurrentlyInLongPosition = strategy.position_size > 0currentlyInShortPosition = strategy.position_size < 0currentlyInAPosition = strategy.position_size != 0//  Heikin Ashi CandleshaOpen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)haHigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)haLow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)haClose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)plotcandle(haOpen < haClose ? haOpen : na, haHigh, haLow, haClose, title='Green Candles', color=green, wickcolor=green, bordercolor=green, display=display.pane)plotcandle(haOpen >= haClose ? haOpen : na, haHigh, haLow, haClose, title='Red Candles', color=red, wickcolor=red, bordercolor=red, display=display.pane)plot(display=display.status_line, series=haOpen, color=green)plot(display=display.status_line, series=haHigh, color=green)plot(display=display.status_line, series=haLow, color=red)plot(display=display.status_line, series=haClose, color=red)//  HA SupertrendhaTrueRange = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ta.atr(supertrendAtrPeriod)) // math.max(haHigh - haLow, math.abs(haHigh - haClose[1]), math.abs(haLow - haClose[1]))haSupertrendUp = ((haHigh + haLow) / 2) - (supertrendAtrMultiplier * haTrueRange)haSupertrendDown = ((haHigh + haLow) / 2) + (supertrendAtrMultiplier * haTrueRange)float trendingUp = nafloat trendingDown = nadirection = 0trendingUp := haClose[1] > trendingUp[1] ? math.max(haSupertrendUp,trendingUp[1]) : haSupertrendUptrendingDown := haClose[1] < trendingDown[1] ? math.min(haSupertrendDown,trendingDown[1]) : haSupertrendDowndirection := haClose > trendingDown[1] ? 1: haClose < trendingUp[1]? -1: nz(direction[1],1)supertrend = direction == 1 ? trendingUp : trendingDownsupertrendUp = ta.change(direction) < 0supertrendDown = ta.change(direction) > 0//  Average Entry Pricefloat averageEntryPrice = currentlyInAPosition ? strategy.position_avg_price : closejustClosedPosition = ta.change(averageEntryPrice)barsSinceOpen = currentlyInAPosition ? (bar_index - strategy.opentrades.entry_bar_index(0)) : 0//  Profit and LossprofitAndLoss = strategy.opentrades.profit(0)profitAndLossPercent = math.round(((close - averageEntryPrice) / averageEntryPrice) * 100,2)//  Profit TargetprofitTarget = currentlyInLongPosition ? averageEntryPrice + (averageEntryPrice * (profitTargetPercent/100)) : averageEntryPrice - (averageEntryPrice * (profitTargetPercent/100))//  Stop Loss Criteriafloat stopLossLimitPrice        = currentlyInLongPosition ? math.round(averageEntryPrice - (averageEntryPrice * stopLimitTrigger/100),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(averageEntryPrice + (averageEntryPrice * stopLimitTrigger/100),exchangeQtyDecimals) : nafloat stopLossTriggerPrice      = currentlyInLongPosition ? math.round(stopLossLimitPrice + (stopLossLimitPrice * stopLimitOffset/100),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(stopLossLimitPrice - (stopLossLimitPrice * stopLimitOffset/100),exchangeQtyDecimals) : na //  Move Stop Lossfloat moveStopLossAfter = currentlyInLongPosition ? math.round(averageEntryPrice + (averageEntryPrice * (moveAfter/100)),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(averageEntryPrice - (averageEntryPrice * (moveAfter/100)),exchangeQtyDecimals) : navar bool moveStopTriggered = falsemoveStopLossTo = currentlyInLongPosition ? math.round(averageEntryPrice + (averageEntryPrice * (moveTo/100)),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(averageEntryPrice - (averageEntryPrice * (moveTo/100)),exchangeQtyDecimals) : naif currentlyInLongPosition and high > moveStopLossAfter and enableMoveStopToBreakEven and moveStopTriggered == false    moveStopTriggered := trueif currentlyInShortPosition and low < moveStopLossAfter and enableMoveStopToBreakEven and moveStopTriggered == false    moveStopTriggered := true    if enableMoveStopToBreakEven and moveStopTriggered    stopLossLimitPrice := moveStopLossTo    stopLossTriggerPrice := currentlyInLongPosition ? math.round(stopLossLimitPrice + (stopLossLimitPrice * stopLimitOffset/100),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(stopLossLimitPrice - (stopLossLimitPrice * stopLimitOffset/100),exchangeQtyDecimals) : na if not currentlyInAPosition or justClosedPosition    moveStopTriggered := false//  Entry/Exit Criteriabool openLong = supertrendDownbool openShort = supertrendUpbool exitLong = currentlyInLongPosition and close > profitTargetbool exitShort = currentlyInShortPosition and close < profitTargetbool longStopLoss = currentlyInLongPosition and close < stopLossTriggerPrice and barsSinceOpen > 2bool shortStopLoss = currentlyInShortPosition and close > stopLossTriggerPrice and barsSinceOpen > 2bool manuallyCloseShort = currentlyInShortPosition and manuallyCloseTrade and time == dateTimeClosedbool manuallyCloseLong = currentlyInLongPosition and manuallyCloseTrade and time == dateTimeClosed//  Alertatron Webhook Messages - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [symbol,baseCurrency] = bot.getPairOverrides(tradeAutomationSymbolOverride,tradeAutomationCurrencyOverride)[contractCount,entryAmount] = bot.getLotSize(lotSizeType, lotSize, tradeAutomationLeverage, exchangeQtyDecimals)string enterLongAlertMessage    = enableWebhookMessages ? bot.getAlertatronMarketEntryMessage(secret=tradeAutomationSecret, symbol=symbol, baseCurrency=baseCurrency, pairDivider=bot.getPairDividerForExchange(tradeAutomationExchange), side="buy", symbolMaxDecimals=exchangeQtyDecimals, leverage=tradeAutomationLeverage, leverageType=tradeAutomationLeverageType, entryPrice=close, amount=lotSize, amountType=lotSizeType, stopTrigger=stopLimitTrigger, stopTriggerType="percent", stopLimitOffset=stopLimitOffset) : "Webhooks disabled by strategy."string enterShortAlertMessage   = enableWebhookMessages ? bot.getAlertatronMarketEntryMessage(secret=tradeAutomationSecret, symbol=symbol, baseCurrency=baseCurrency, pairDivider=bot.getPairDividerForExchange(tradeAutomationExchange), side="sell", symbolMaxDecimals=exchangeQtyDecimals, leverage=tradeAutomationLeverage, leverageType=tradeAutomationLeverageType, entryPrice=close, amount=lotSize, amountType=lotSizeType, stopTrigger=stopLimitTrigger, stopTriggerType="percent", stopLimitOffset=stopLimitOffset) : "Webhooks disabled by strategy."string exitLongAlertMessage     = enableWebhookMessages ? bot.getAlertatronMarketExitMessage(secret=tradeAutomationSecret, symbol=symbol, baseCurrency=baseCurrency, pairDivider=bot.getPairDividerForExchange(tradeAutomationExchange), side="sell") : "Webhooks disabled by strategy."string exitShortAlertMessage    = enableWebhookMessages ? bot.getAlertatronMarketExitMessage(secret=tradeAutomationSecret, symbol=symbol, baseCurrency=baseCurrency, pairDivider=bot.getPairDividerForExchange(tradeAutomationExchange), side="buy") : "Webhooks disabled by strategy."//  Long Entries/Exits - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -if openLong    strategy.entry(id="Long", direction=strategy.long, qty=contractCount, alert_message=enterLongAlertMessage)if exitLong    strategy.close(id="Long", qty_percent=100, comment="Exit Long", alert_message=exitLongAlertMessage)if longStopLoss    strategy.exit(id=moveStopTriggered ? "Moved Stop" : "Stop Loss", from_entry="Long", qty_percent=100, stop=stopLossLimitPrice)if manuallyCloseLong    strategy.exit(id="Manually Close Long", from_entry="Long", qty_percent=100, stop=priceClosed)//  Short Entries/Exits - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -if openShort    strategy.entry(id="Short", direction=strategy.short, qty=contractCount, alert_message=enterShortAlertMessage)if exitShort    strategy.close(id="Short", qty_percent=100, comment="Exit Short", alert_message=exitShortAlertMessage)if shortStopLoss    strategy.exit(id=moveStopTriggered ? "Moved Stop" : "Stop Loss", from_entry="Short", qty_percent=100, stop=stopLossLimitPrice)if manuallyCloseShort    strategy.exit(id="Manually Close Short", from_entry="Short", qty_percent=100, stop=priceClosed)//  Plots, Lines, and LabelsbodyMiddle = plot((haOpen + haClose) / 2, display=display.none)downTrend = plot(direction < 0 ? supertrend : na, "Down Trend", color = red, style=plot.style_linebr)upTrend = plot(direction < 0? na : supertrend, "Up Trend", color = green, style=plot.style_linebr)fill(bodyMiddle, upTrend, lightGreen, fillgaps=false)fill(bodyMiddle, downTrend, lightRed, fillgaps=false)color stopLossColor = redcolor stopLossBackgroundColor = redif currentlyInLongPosition and stopLossLimitPrice > averageEntryPrice    stopLossColor := green    stopLossBackgroundColor := lightGreenelse    if currentlyInShortPosition and stopLossLimitPrice < averageEntryPrice        stopLossColor := green        stopLossBackgroundColor := lightGreen    else        stopLossColor := red        stopLossBackgroundColor := lightRedvar label stopLossLabel = navar label moveStopAfterLabel = navar label averageEntryLabel = navar label profitAndLossLabel = navar label profitTargetLabel = navar line stopLossTriggerLine = navar line moveStopAfterLine = navar line stopLossLimitLine = navar line averageEntryLine = navar line profitTargetLine = navar linefill stopLossBackground = navar linefill profitTargetBackground = nalabel.delete(stopLossLabel)label.delete(moveStopAfterLabel)label.delete(averageEntryLabel)label.delete(profitAndLossLabel)label.delete(profitTargetLabel)line.delete(stopLossTriggerLine)line.delete(moveStopAfterLine)line.delete(stopLossLimitLine)line.delete(averageEntryLine)line.delete(profitTargetLine)linefill.delete(stopLossBackground)linefill.delete(profitTargetBackground)string stopLossLabelText = naif moveStopLossAfter and not moveStopTriggered    stopLossLabelText           := " Stop Trigger | " + str.format("{0,number,currency}", stopLossTriggerPrice) + "\n" + " Stop Limit | " + str.format("{0,number,currency}" + " ", stopLossLimitPrice) + "\n" +  " Moving to " + str.format("{0,number,currency}", moveStopLossTo) + " after " + str.tostring(moveAfter) + "% "else    stopLossLabelText           := " Stop Trigger | " + str.format("{0,number,currency}", stopLossTriggerPrice) + "\n" + " Stop Limit | " + str.format("{0,number,currency}" + " ", stopLossLimitPrice)xOffset = 2 * timeframe.in_seconds(timeframe.period) * 1000 profitAndLossLabel              := label.new(x=time + xOffset, xloc=xloc.bar_time, y=close, style=label.style_label_left, size=size.normal, color=profitAndLoss > 0 ? green : red, textcolor=white, text=" P&L | " + str.format("{0,number,currency}", profitAndLoss) + " (" + str.tostring(profitAndLossPercent) + "%) ")averageEntryLabel               := label.new(x=time + xOffset, xloc=xloc.bar_time, y=averageEntryPrice, style=label.style_label_left, size=size.normal, color=oceanBlue, textcolor=white, text=" Entry | " + str.format("{0,number,currency}" + " ", averageEntryPrice))stopLossLabel                   := label.new(x=time + xOffset, xloc=xloc.bar_time, y=stopLossLimitPrice, style=label.style_label_left, textalign=text.align_left, size=size.normal, color=stopLossColor, textcolor=white, text=stopLossLabelText)averageEntryLine                := line.new(x1=strategy.opentrades.entry_bar_index(0), y1=averageEntryPrice, x2=bar_index, y2=averageEntryPrice, color=oceanBlue, width=2, xloc=xloc.bar_index, style=line.style_solid)profitTargetLine                := line.new(x1=strategy.opentrades.entry_bar_index(0), y1=profitTarget, x2=bar_index, y2=profitTarget, color=green, width=1, xloc=xloc.bar_index, style=line.style_solid)profitTargetLabel               := label.new(x=time + xOffset, xloc=xloc.bar_time, y=profitTarget, style=label.style_label_left, size=size.normal, color=red, textcolor=white, text=" ProfitTarget | " + str.format("{0,number,currency}" + " ", profitTarget))stopLossTriggerLine             := line.new(x1=strategy.opentrades.entry_bar_index(0), y1=stopLossTriggerPrice, x2=bar_index, y2=stopLossTriggerPrice, color=stopLossColor, width=1, xloc=xloc.bar_index, style=line.style_solid)stopLossLimitLine               := line.new(x1=strategy.opentrades.entry_bar_index(0), y1=stopLossLimitPrice, x2=bar_index, y2=stopLossLimitPrice, color=stopLossColor, width=1, xloc=xloc.bar_index, style=line.style_solid)stopLossBackground              := linefill.new(averageEntryLine, stopLossLimitLine, stopLossBackgroundColor)profitTargetBackground          := linefill.new(averageEntryLine, profitTargetLine, lightGreen)if enableMoveStopToBreakEven    moveStopAfterLabel          := label.new(x=time + xOffset, xloc=xloc.bar_time, y=moveStopLossAfter, style=label.style_label_left, size=size.normal, color=purple, textcolor=white, text=" Move Stop After " + str.tostring(moveAfter) + "% | " + str.format("{0,number,currency}" + " ", moveStopLossAfter))    moveStopAfterLine           := line.new(x1=strategy.opentrades.entry_bar_index(0), y1=moveStopLossAfter, x2=bar_index, y2=moveStopLossAfter, color=purple, width=1, xloc=xloc.bar_index, style=line.style_solid)stopLimitStatus                 = plot(stopLossLimitPrice, color=stopLossColor, display=display.price_scale)stopTriggerStatus               = plot(stopLossTriggerPrice, color=stopLossColor, display=display.price_scale)averageEntryStatus              = plot(averageEntryPrice, color=oceanBlue, display=display.price_scale)if not currentlyInAPosition    label.delete(stopLossLabel)    label.delete(moveStopAfterLabel)    label.delete(averageEntryLabel)    label.delete(profitAndLossLabel)    label.delete(profitTargetLabel)    line.delete(stopLossTriggerLine)    line.delete(moveStopAfterLine)    line.delete(stopLossLimitLine)    line.delete(averageEntryLine)    line.delete(profitTargetLine)    linefill.delete(stopLossBackground)    linefill.delete(profitTargetBackground)// Alertatron Automation Status Messagewarning_color = enableWebhookMessages == true ? red : greenvar table status = table.new(position=position.top_right, columns=2, rows=100, bgcolor=warning_color, border_color=warning_color, border_width=1)rowCount2 = 0table.cell(status, 0, rowCount2, text=" " + strategyIdentifier, text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)table.cell(status, 1, rowCount2, text=" ", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)rowCount2 += 1table.cell(status, 0, rowCount2, text=" " + "Webhook Enabled", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)table.cell(status, 1, rowCount2, text=str.tostring(enableWebhookMessages) + " ", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)rowCount2 += 1table.cell(status, 0, rowCount2, text=" " + "Exchange", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)table.cell(status, 1, rowCount2, text=tradeAutomationExchange + " ", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)rowCount2 += 1table.cell(status, 0, rowCount2, text=" " + "Code", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)table.cell(status, 1, rowCount2, text=tradeAutomationSecret == "" ? "N/A" : tradeAutomationSecret + " ", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)rowCount2 += 1table.cell(status, 0, rowCount2, text=" " + "Leverage", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)table.cell(status, 1, rowCount2, text=str.tostring(tradeAutomationLeverageType) + " " + str.tostring(tradeAutomationLeverage) + "x", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)rowCount2 += 1table.cell(status, 0, rowCount2, text=" " + "Pair", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)table.cell(status, 1, rowCount2, text=str.tostring(symbol) + bot.getPairDividerForExchange(tradeAutomationExchange) + str.tostring(baseCurrency), text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)rowCount2 += 1lotSizeDisplay = lotSizeType == "Percent Of Account" ? str.format("{0,number,percent}" + " of account ", lotSize/100): str.format("{0,number,currency}", lotSize)table.cell(status, 0, rowCount2, text=" " + "Lot Size", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)table.cell(status, 1, rowCount2, text=lotSizeDisplay + " ", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)rowCount2 += 1table.cell(status, 0, rowCount2, text=" " + "Account Size", text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)table.cell(status, 1, rowCount2, text=str.format("{0,number,currency}" + " ", strategy.initial_capital), text_color=white, text_halign=text.align_left,  bgcolor=warning_color, text_size=size.small)rowCount2 += 1//  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //  D E B U G   M O D E - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if showDebugTable    var table debug = table.new(position=position.bottom_left, columns=2, rows=100, bgcolor=gray, border_color=gray, border_width=2)        rowCount = 0    table.cell(debug, 0, rowCount, text="enterLongAlertMessage: ", text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    table.cell(debug, 1, rowCount, text=str.tostring(enterLongAlertMessage), text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    rowCount += 1    table.cell(debug, 0, rowCount, text="enterShortAlertMessage: ", text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    table.cell(debug, 1, rowCount, text=str.tostring(enterShortAlertMessage), text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    rowCount += 1    table.cell(debug, 0, rowCount, text="exitLongAlertMessage: ", text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    table.cell(debug, 1, rowCount, text=str.tostring(exitLongAlertMessage), text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    rowCount += 1    table.cell(debug, 0, rowCount, text="exitShortAlertMessage: ", text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    table.cell(debug, 1, rowCount, text=str.tostring(exitShortAlertMessage), text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    rowCount += 1    table.cell(debug, 0, rowCount, text="moveStopTriggered: ", text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    table.cell(debug, 1, rowCount, text=str.tostring(moveStopTriggered), text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    rowCount += 1    table.cell(debug, 0, rowCount, text="longStopLoss (stopLossTriggerPrice): ", text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    table.cell(debug, 1, rowCount, text=str.tostring(longStopLoss) + " | " + str.tostring(stopLossTriggerPrice), text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    rowCount += 1    table.cell(debug, 0, rowCount, text="barsSinceOpen", text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)    table.cell(debug, 1, rowCount, text=str.tostring(barsSinceOpen), text_color=white, text_halign=text.align_left,  bgcolor=gray, text_size=size.small)