Strategy · Pine Script v5 · On the chart

Heikin Ashi Supertrend

by wynnforthework· code credited to jordanfray

This strategy applies a Supertrend calculation to Heikin Ashi price data to identify trend direction and potential market reversals.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code357
Settings23inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago7 Oct 2025

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

357 lines of Pine Script v5 from 策略/新建文件夹 (2)/eth4小时趋势/Heikin Ashi 超级趋势.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Heikin Ashi 超级趋势.txt
// 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 bot
import 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)


//  Tooltips
alertatronSecretTip                 = "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 Automation
enableWebhookMessages               = 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 States
currentlyInLongPosition = strategy.position_size > 0
currentlyInShortPosition = strategy.position_size < 0
currentlyInAPosition = strategy.position_size != 0

//  Heikin Ashi Candles
haOpen = 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 Supertrend
haTrueRange = 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 = na
float trendingDown = na
direction = 0

trendingUp := haClose[1] > trendingUp[1] ? math.max(haSupertrendUp,trendingUp[1]) : haSupertrendUp
trendingDown := haClose[1] < trendingDown[1] ? math.min(haSupertrendDown,trendingDown[1]) : haSupertrendDown
direction := haClose > trendingDown[1] ? 1: haClose < trendingUp[1]? -1: nz(direction[1],1)
supertrend = direction == 1 ? trendingUp : trendingDown

supertrendUp = ta.change(direction) < 0
supertrendDown = ta.change(direction) > 0

//  Average Entry Price
float averageEntryPrice = currentlyInAPosition ? strategy.position_avg_price : close
justClosedPosition = ta.change(averageEntryPrice)
barsSinceOpen = currentlyInAPosition ? (bar_index - strategy.opentrades.entry_bar_index(0)) : 0

//  Profit and Loss
profitAndLoss = strategy.opentrades.profit(0)
profitAndLossPercent = math.round(((close - averageEntryPrice) / averageEntryPrice) * 100,2)

//  Profit Target
profitTarget = currentlyInLongPosition ? averageEntryPrice + (averageEntryPrice * (profitTargetPercent/100)) : averageEntryPrice - (averageEntryPrice * (profitTargetPercent/100))

//  Stop Loss Criteria
float stopLossLimitPrice        = currentlyInLongPosition ? math.round(averageEntryPrice - (averageEntryPrice * stopLimitTrigger/100),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(averageEntryPrice + (averageEntryPrice * stopLimitTrigger/100),exchangeQtyDecimals) : na
float stopLossTriggerPrice      = currentlyInLongPosition ? math.round(stopLossLimitPrice + (stopLossLimitPrice * stopLimitOffset/100),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(stopLossLimitPrice - (stopLossLimitPrice * stopLimitOffset/100),exchangeQtyDecimals) : na 

//  Move Stop Loss
float moveStopLossAfter = currentlyInLongPosition ? math.round(averageEntryPrice + (averageEntryPrice * (moveAfter/100)),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(averageEntryPrice - (averageEntryPrice * (moveAfter/100)),exchangeQtyDecimals) : na
var bool moveStopTriggered = false

moveStopLossTo = currentlyInLongPosition ? math.round(averageEntryPrice + (averageEntryPrice * (moveTo/100)),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(averageEntryPrice - (averageEntryPrice * (moveTo/100)),exchangeQtyDecimals) : na

if currentlyInLongPosition and high > moveStopLossAfter and enableMoveStopToBreakEven and moveStopTriggered == false
    moveStopTriggered := true

if 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 Criteria
bool openLong = supertrendDown
bool openShort = supertrendUp
bool exitLong = currentlyInLongPosition and close > profitTarget
bool exitShort = currentlyInShortPosition and close < profitTarget
bool longStopLoss = currentlyInLongPosition and close < stopLossTriggerPrice and barsSinceOpen > 2
bool shortStopLoss = currentlyInShortPosition and close > stopLossTriggerPrice and barsSinceOpen > 2
bool manuallyCloseShort = currentlyInShortPosition and manuallyCloseTrade and time == dateTimeClosed
bool 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 Labels
bodyMiddle = 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 = red
color stopLossBackgroundColor = red

if currentlyInLongPosition and stopLossLimitPrice > averageEntryPrice
    stopLossColor := green
    stopLossBackgroundColor := lightGreen
else
    if currentlyInShortPosition and stopLossLimitPrice < averageEntryPrice
        stopLossColor := green
        stopLossBackgroundColor := lightGreen
    else
        stopLossColor := red
        stopLossBackgroundColor := lightRed

var label stopLossLabel = na
var label moveStopAfterLabel = na
var label averageEntryLabel = na
var label profitAndLossLabel = na
var label profitTargetLabel = na

var line stopLossTriggerLine = na
var line moveStopAfterLine = na
var line stopLossLimitLine = na
var line averageEntryLine = na
var line profitTargetLine = na

var linefill stopLossBackground = na
var linefill profitTargetBackground = na

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)

string stopLossLabelText = na

if 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 Message
warning_color = enableWebhookMessages == true ? red : green
var table status = table.new(position=position.top_right, columns=2, rows=100, bgcolor=warning_color, border_color=warning_color, border_width=1)
rowCount2 = 0

table.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 += 1

table.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 += 1

table.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 += 1

table.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 += 1

table.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 += 1

table.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 += 1

lotSizeDisplay = 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 += 1

table.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)

Overview

Heikin Ashi Supertrend executes trades based on Supertrend trend shifts and incorporates an On-Balance Volume filter. Risk management includes a configurable percentage profit target, a stop-limit trigger, and an optional trailing break-even stop mechanism. Position sizing defaults to a fixed dollar amount. Plots appear directly on the price chart, and settings include webhook automation parameters for third-party execution.

Details

Published by

wynnforthework on GitHub

Code credit

jordanfray, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Volatility & bands

Markets

Crypto

Timeframes

H4 and above, M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Strategy IdentifierstringHASTXXXUSDT (Nm)strategyIdentifier
ATR Lengthint10supertrendAtrPeriod
ATR Multiplierfloat2.7supertrendAtrMultiplier
Lot Sizefloat100lotSize
Lot Size TypestringDollarslotSizeType
Profit Target (%)float47.0profitTargetPercent
Stop Limit Trigger (%)float21stopLimitTrigger
Stop Limit Offset (%)float0.10stopLimitOffset
Move Stop LossbooltrueenableMoveStopToBreakEven
to (%)float1.0moveTo
after (%)float4.0moveAfter
Manullay Close Trade?boolfalsemanuallyCloseTrade
Show all 23 settings
SettingTypeDefaultVariable
Date/Time When Trade Was Closedtimetimestamp("01 Jan 2022 00:00")dateTimeClosed
Price Trade Was Closed Atprice0.0priceClosed
Enable Webook MessagesboolfalseenableWebhookMessages
ExchangestringByBittradeAutomationExchange
Alertatron API SecretstringhaStEthUsdttradeAutomationSecret
Leverage Amountint1tradeAutomationLeverage
Leverage TypestringCrosstradeAutomationLeverageType
Currency OverridestringtradeAutomationCurrencyOverride
Symbol OverridestringtradeAutomationSymbolOverride
Order QTY Decimal Roundingint3exchangeQtyDecimals
Show Debug TableboolfalseshowDebugTable
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

This strategy calculates Bollinger Bands and Aroon oscillator values to identify mean-reversion opportunities. It enters a long position using full equity when the closing price crosses below the lower Bollinger Band while Aroon Up remains above a user-specifi

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger bands + Aroon [Alorse]
257 stars

This overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades

Strategy v6 Moving averagesVolatility & bands
Updated 6 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint

STRG-BBForce

by harryguiacorn
219 stars

STRG-BBForce is a Bollinger Bands trend-following strategy. It calculates standard Bollinger Bands and tracks directional alignment across the upper, lower, and basis lines. When all three lines slope upward, it opens a long position and closes short positions

Strategy v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of STRG-BBForce

Nasdaq Prop Firm Strategy

by TradersPost
218 stars

This strategy uses multiple VWAP anchors and a custom Lull indicator to generate buy and sell signals on the Nasdaq price chart. It plots the VWAP trend line and three VWAP anchors with customizable colors and mitigation methods. The Lull indicator produces si

Strategy v6 TrendSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Nasdaq Prop Firm Strategy

This strategy implements a single-layer perceptron machine learning model built from scratch to generate trading signals directly on the price chart. It calculates predictions based on sample size, threshold settings, and optional volatility or volume filters.

Strategy v5 AI / machine learningTrend
Updated 1 year ago · None stated GitHub repository of Machine Learning: Perceptron-Based Strategy [5] (v.3)
106 stars

This overlay strategy plots a two-timeframe Ichimoku setup on the price chart, with Tenkan, Kijun, Chikou, and Kumo from a base higher timeframe and an optional highest-timeframe cloud. It allows two entries in the same direction and uses ATR-based trailing st

Strategy v4 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of 2Tier Ichimoku Pyramiding [Takazudo]

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers