Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Hammers & Stars Strategy

A Pine Script v4 strategy built on ATR (14) and EMA (close). It has 4 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 is one contract and pays no commission. 25 settings; defaults include >= ATR Filter 0.0, <= ATR Filter 3.0 and Stop Loss ATR 1.0.

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 Hammers & Stars Strategy repaint?
No
No repainting patterns were found in the source. The live replay was not measured: the script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script.
How did Hammers & Stars Strategy do on BTCUSDT 1D with default settings?
+32.56%
From 26 Jan 2024 to 21 Oct 2026, over 47 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can Hammers & Stars Strategy be converted to Pine Script v5?
Yes
The upgrade takes 1 step, from v4; each was run before and after on the same candles with identical results, and the v5 script can be downloaded below.
What alerts does Hammers & Stars Strategy have?
8
Bullish Hammer Detected!; alertString; "e=" + broker + " b=long q=" + tostring(tradePositionSize) + " s=" + pair + " t=" + (av_limitOrder ? "limit fp=" + tostring(close) : "market") + " fsl=" + tostring(t_stop) + " ftp=" + tostring(t_target) + (av_gtdOrder != 0 and av_limitOrder ? gtdString : ""); Bearish Hammer Detected!; and more.
Does Hammers & Stars Strategy use a stop loss?
Yes
strategy.exit sets a stop on line 194, 195.

BTCUSDT · 1D · default settings

  • Trade Stop Price
  • Trade Target Price
  • AutoView Position Size
  • Bullish Setup
  • Bearish Setup
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
0.0050,000100,000AprJulOct2025AprJulOct2026AprJulOct$131,051$202,527Equity from $100,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots. Zeal Terminal's engine currently reads an order side written as long = strategy.long, long = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 135, 161) so the engine trades the way the script says. The live re-run is not offered here: the script requests AUDUSD D, which this page cannot load in your browser.

Needs AUDUSD D data, not available: AUDUSD is not on Binance Values that depend on it are empty on this chart.

Table drawn by the script, as it stood on the last bar
Total Trades: 47Starting: $10000Return: $488.05Return: +4.88%
Win Rate: 55.31%Ending: $10488.05Pips: +32393.02Max DD: -5.91%
Net profit
+32.56%
$32,556.30
Buy and hold
+102.5%
same period
Closed trades
47
26 won · 21 lost
Profitable
55.3%
of closed trades
Profit factor
1.30
gross profit ÷ gross loss
Max drawdown
19.81%
−$31,155.20

One run with the author's default settings, $100,000 starting capital, commission as the script sets it. A long position was still open at the last bar. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.

Review

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

  • Check

    No commission

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

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

  • Note

    Uses an argument v6 removed

    when = on line 135, 161, 194, 195. The upgraded version below moves each call inside an if block.

  • Note

    Uses long =, which v5 renamed line 135

    long = on line 135, 161. v5 writes it as direction = strategy.long or strategy.short.

Upgrade and export

Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.

  • Upgrading to v5 renames tostring → str.tostring, atr → ta.atr, ema → ta.ema, pow → math.pow, abs → math.abs, security → request.security, round → math.round.
  • 4 strategy calls use the when = argument (line 135, 161, 194, 195). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Verified

Same 47 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 4: //@version=4 → //@version=5
  • Line 8: input(type = input.float) → input.float()
  • Line 9: input(type = input.float) → input.float()
  • Line 10: input(type = input.float) → input.float()
  • Line 11: input(type = input.float) → input.float()
  • Line 12: input(type = input.float) → input.float()
58 more edits
  • Line 15: input(type = input.integer) → input.int()
  • Line 16: input(type = input.time) → input.time()
  • Line 17: input(type = input.time) → input.time()
  • Line 20: input(type = input.float) → input.float()
  • Line 21: input(type = input.float) → input.float()
  • Line 22: input(type = input.bool) → input.bool()
  • Line 25: input(type = input.bool) → input.bool()
  • Line 26: input(type = input.bool) → input.bool()
  • Line 27: input(type = input.bool) → input.bool()
  • Line 28: input(type = input.integer) → input.int()
  • Line 29: input(type = input.float) → input.float()
  • Line 30: input(type = input.string) → input.string()
  • Line 31: input(type = input.float) → input.float()
  • Line 34: input(type = input.bool) → input.bool()
  • Line 35: input(type = input.string) → input.string()
  • Line 36: input(type = input.float) → input.float()
  • Line 37: input(type = input.float) → input.float()
  • Line 38: input(type = input.string) → input.string()
  • Line 39: input(type = input.string) → input.string()
  • Line 40: input(type = input.bool) → input.bool()
  • Line 48: tostring → str.tostring
  • Line 49: tostring → str.tostring
  • Line 49: tostring → str.tostring
  • Line 49: tostring → str.tostring
  • Line 53: atr → ta.atr
  • Line 54: ema → ta.ema
  • Line 57: return is reserved in v5: renamed return_
  • Line 67: pow → math.pow
  • Line 74: abs → math.abs
  • Line 75: abs → math.abs
  • Line 100: security → request.security
  • Line 100: security(resolution = …) → timeframe = …
  • Line 106: round → math.round
  • Line 113: tostring → str.tostring
  • Line 113: tostring → str.tostring
  • Line 113: tostring → str.tostring
  • Line 135: long = strategy.long → direction = strategy.long
  • Line 135: tostring → str.tostring
  • Line 146: tostring → str.tostring
  • Line 148: tostring → str.tostring
  • Line 149: tostring → str.tostring
  • Line 150: tostring → str.tostring
  • Line 161: long = strategy.short → direction = strategy.short
  • Line 161: tostring → str.tostring
  • Line 172: tostring → str.tostring
  • Line 174: tostring → str.tostring
  • Line 175: tostring → str.tostring
  • Line 176: tostring → str.tostring
  • Line 217: abs → math.abs
  • Line 225: abs → math.abs
  • Line 244: tostring → str.tostring
  • Line 245: tostring → str.tostring
  • Line 246: tostring → str.tostring
  • Line 247: tostring → str.tostring
  • Line 248: tostring → str.tostring
  • Line 249: tostring → str.tostring
  • Line 250: tostring → str.tostring
  • Line 251: tostring → str.tostring
⋯// Last Updated: 5th October, 2021-// @version=4+// @version=5strategy("Hammers & Stars Strategy [v1.1]", shorttitle="HSS[v1.1]", overlay=true)⋯var g_strategy      = "Strategy Settings"-atrMinFilterSize    = input(title=">= ATR Filter", type=input.float, defval=0.0, minval=0.0, group=g_strategy, tooltip="Minimum size of entry candle compared to ATR")+atrMinFilterSize    = input.float(title=">= ATR Filter", defval=0.0, minval=0.0, group=g_strategy, tooltip="Minimum size of entry candle compared to ATR")-atrMaxFilterSize    = input(title="<= ATR Filter", type=input.float, defval=3.0, minval=0.0, group=g_strategy, tooltip="Maximum size of entry candle compared to ATR")+atrMaxFilterSize    = input.float(title="<= ATR Filter", defval=3.0, minval=0.0, group=g_strategy, tooltip="Maximum size of entry candle compared to ATR")-stopMultiplier      = input(title="Stop Loss ATR", type=input.float, defval=1.0, group=g_strategy, tooltip="Stop loss multiplier (x ATR)")+stopMultiplier      = input.float(title="Stop Loss ATR", defval=1.0, group=g_strategy, tooltip="Stop loss multiplier (x ATR)")-rr                  = input(title="R:R", type=input.float, defval=1.0, group=g_strategy, tooltip="Risk:Reward profile")+rr                  = input.float(title="R:R", defval=1.0, group=g_strategy, tooltip="Risk:Reward profile")-fibLevel            = input(title="Fib Level", type=input.float, defval=0.333, group=g_strategy, tooltip="Used to calculate upper/lower third of candle. (For example, setting it to 0.5 will mean hammers must close >= 50% mark of the total candle size)")+fibLevel            = input.float(title="Fib Level", defval=0.333, group=g_strategy, tooltip="Used to calculate upper/lower third of candle. (For example, setting it to 0.5 will mean hammers must close >= 50% mark of the total candle size)")// Filter Settingsvar g_filter        = "Filter Settings"-emaFilter           = input(title="EMA Filter", type=input.integer, defval=0, group=g_filter, tooltip="EMA length to filter trades - set to zero to disable")+emaFilter           = input.int(title="EMA Filter", defval=0, group=g_filter, tooltip="EMA length to filter trades - set to zero to disable")-i_startTime         = input(title="Start Date Filter", defval=timestamp("01 Jan 2000 13:30 +0000"), type=input.time, group=g_filter, tooltip="Date & time to begin trading from")+i_startTime         = input.time(title="Start Date Filter", defval=timestamp("01 Jan 2000 13:30 +0000"), group=g_filter, tooltip="Date & time to begin trading from")-i_endTime           = input(title="End Date Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), type=input.time, group=g_filter, tooltip="Date & time to stop trading")+i_endTime           = input.time(title="End Date Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), group=g_filter, tooltip="Date & time to stop trading")// Backtester Settingsvar g_tester        = "Backtester Settings"-startBalance        = input(title="Starting Balance", type=input.float, defval=10000.0, group=g_tester, tooltip="Your starting balance for the custom inbuilt tester system")+startBalance        = input.float(title="Starting Balance", defval=10000.0, group=g_tester, tooltip="Your starting balance for the custom inbuilt tester system")-riskPerTrade        = input(title="Risk Per Trade", type=input.float, defval=1.0, group=g_tester, tooltip="Your desired % risk per trade (as a whole number)")+riskPerTrade        = input.float(title="Risk Per Trade", defval=1.0, group=g_tester, tooltip="Your desired % risk per trade (as a whole number)")-drawTester          = input(title="Draw Backtester", type=input.bool, defval=true, group=g_tester, tooltip="Turn on/off inbuilt backtester display")+drawTester          = input.bool(title="Draw Backtester", defval=true, group=g_tester, tooltip="Turn on/off inbuilt backtester display")// AutoView Settingsvar g_av            = "AutoView Settings [OANDA]"-av_use              = input(title="Use AutoView?", type=input.bool, defval=false, group=g_av, tooltip="If turned on then the alerts this script generates will use AutoView syntax for auto-trading (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS)")+av_use              = input.bool(title="Use AutoView?", defval=false, group=g_av, tooltip="If turned on then the alerts this script generates will use AutoView syntax for auto-trading (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS)")-av_oandaDemo        = input(title="Use Oanda Demo?", type=input.bool, defval=false, group=g_av, tooltip="If turned on then oandapractice broker prefix will be used for AutoView alerts (demo account). If turned off then live account will be used")+av_oandaDemo        = input.bool(title="Use Oanda Demo?", defval=false, group=g_av, tooltip="If turned on then oandapractice broker prefix will be used for AutoView alerts (demo account). If turned off then live account will be used")-av_limitOrder       = input(title="Use Limit Order?", type=input.bool, defval=true, group=g_av, tooltip="If turned on then AutoView will use limit orders. If turned off then market orders will be used")+av_limitOrder       = input.bool(title="Use Limit Order?", defval=true, group=g_av, tooltip="If turned on then AutoView will use limit orders. If turned off then market orders will be used")-av_gtdOrder         = input(title="Days To Leave Limit Order", type=input.integer, minval=0, defval=2, group=g_av, tooltip="This is your GTD setting (good til day)")+av_gtdOrder         = input.int(title="Days To Leave Limit Order", minval=0, defval=2, group=g_av, tooltip="This is your GTD setting (good til day)")-av_accountBalance   = input(title="Account Balance", type=input.float, defval=1000.0, step=100, group=g_av, tooltip="Your account balance (used for calculating position size)")+av_accountBalance   = input.float(title="Account Balance", defval=1000.0, step=100, group=g_av, tooltip="Your account balance (used for calculating position size)")-av_accountCurrency  = input(title="Account Currency", type=input.string, defval="USD", options=["AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "NZD", "USD"], group=g_av, tooltip="Your account balance currency (used for calculating position size)")+av_accountCurrency  = input.string(title="Account Currency", defval="USD", options=["AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "NZD", "USD"], group=g_av, tooltip="Your account balance currency (used for calculating position size)")-av_riskPerTrade     = input(title="Risk Per Trade %", type=input.float, defval=2.0, step=0.5, group=g_av, tooltip="Your risk per trade as a % of your account balance")+av_riskPerTrade     = input.float(title="Risk Per Trade %", defval=2.0, step=0.5, group=g_av, tooltip="Your risk per trade as a % of your account balance")// PineConnector Settingsvar g_pc            = "PineConnector Settings"-pc_use              = input(title="Use PineConnector?", type=input.bool, defval=false, group=g_pc, tooltip="Use PineConnector Alerts? (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS)")+pc_use              = input.bool(title="Use PineConnector?", defval=false, group=g_pc, tooltip="Use PineConnector Alerts? (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS)")-pc_id               = input(title="License ID", type=input.string, defval="ID", group=g_pc, tooltip="This is your PineConnector license ID")+pc_id               = input.string(title="License ID", defval="ID", group=g_pc, tooltip="This is your PineConnector license ID")-pc_spread           = input(title="Spread", type=input.float, defval=0.5, group=g_pc, tooltip="Enter your average spread for this pair (used for offsetting entry limit order from closing price)")+pc_spread           = input.float(title="Spread", defval=0.5, group=g_pc, tooltip="Enter your average spread for this pair (used for offsetting entry limit order from closing price)")-pc_risk             = input(title="Risk Per Trade", type=input.float, defval=1, step=0.5, group=g_pc, tooltip="This is how much to risk per trade (% of balance or lots - based on PC settings)")+pc_risk             = input.float(title="Risk Per Trade", defval=1, step=0.5, group=g_pc, tooltip="This is how much to risk per trade (% of balance or lots - based on PC settings)")-pc_prefix           = input(title="MetaTrader Prefix", type=input.string, defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol prefix (leave blank if there is none)")+pc_prefix           = input.string(title="MetaTrader Prefix", defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol prefix (leave blank if there is none)")-pc_suffix           = input(title="MetaTrader Suffix", type=input.string, defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol suffix (leave blank if there is none)")+pc_suffix           = input.string(title="MetaTrader Suffix", defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol suffix (leave blank if there is none)")-pc_limit            = input(title="Use Limit Order?", type=input.bool, defval=true, group=g_pc, tooltip="If true a limit order will be used, if false a market order will be used")+pc_limit            = input.bool(title="Use Limit Order?", defval=true, group=g_pc, tooltip="If true a limit order will be used, if false a market order will be used")// Generate PineConnector alert string & prepare OANDA broker string⋯    limit_price = direction == "buy" ? close - spread : close + spread-    price = pc_limit ? "price=" + tostring(limit_price) + "," : ""+    price = pc_limit ? "price=" + str.tostring(limit_price) + "," : ""-    pc_id + "," + direction + limit + "," + symbol + "," + price + "sl=" + tostring(sl) + ",tp=" + tostring(tp) + ",risk=" + tostring(pc_risk)+    pc_id + "," + direction + limit + "," + symbol + "," + price + "sl=" + str.tostring(sl) + ",tp=" + str.tostring(tp) + ",risk=" + str.tostring(pc_risk)// See if this bar's time happened within date filter⋯// Get indicator values-atr = atr(14)+atr = ta.atr(14)-ema = ema(close, emaFilter == 0 ? 1 : emaFilter)+ema = ta.ema(close, emaFilter == 0 ? 1 : emaFilter)// Custom function to convert pips into whole numberstoWhole(number) =>-    return = atr < 1.0 ? (number / syminfo.mintick) / (10 / syminfo.pointvalue) : number+    return_ = atr < 1.0 ? (number / syminfo.mintick) / (10 / syminfo.pointvalue) : number-    return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return * 100 : return+    return_ := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return_ * 100 : return_    ⋯toPips(number) =>-    return = atr >= 1.0 ? number : (number * syminfo.mintick) * (10 / syminfo.pointvalue)+    return_ = atr >= 1.0 ? number : (number * syminfo.mintick) * (10 / syminfo.pointvalue)-    return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return / 100 : return+    return_ := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return_ / 100 : return_    ⋯truncate(_number, _decimalPlaces) =>-    _factor = pow(10, _decimalPlaces)+    _factor = math.pow(10, _decimalPlaces)    int(_number * _factor) / _factor⋯// Check ATR filter-atrMinFilter = abs(high - low) >= (atrMinFilterSize * atr) or atrMinFilterSize == 0.0+atrMinFilter = math.abs(high - low) >= (atrMinFilterSize * atr) or atrMinFilterSize == 0.0-atrMaxFilter = abs(high - low) <= (atrMaxFilterSize * atr) or atrMaxFilterSize == 0.0+atrMaxFilter = math.abs(high - low) <= (atrMaxFilterSize * atr) or atrMaxFilterSize == 0.0atrFilter = atrMinFilter and atrMaxFilter⋯conversionCurrencyPair = accountSameAsCounterCurrency ? syminfo.tickerid : accountNeitherCurrency ? av_accountCurrency + syminfo.currency : av_accountCurrency + syminfo.currency-conversionCurrencyRate = security(symbol=syminfo.type == "forex" ? conversionCurrencyPair : "AUDUSD", resolution="D", expression=close)+conversionCurrencyRate = request.security(symbol=syminfo.type == "forex" ? conversionCurrencyPair : "AUDUSD", timeframe="D", expression=close)// Calculate position size⋯    positionSize = (riskAmount / riskPerPoint) / syminfo.mintick-    round(positionSize)+    math.round(positionSize)    ⋯gtdDay = dayofmonth(gtdTime)-gtdString = " dt=" + tostring(gtdYear) + "-" + tostring(gtdMonth) + "-" + tostring(gtdDay)+gtdString = " dt=" + str.tostring(gtdYear) + "-" + str.tostring(gtdMonth) + "-" + str.tostring(gtdDay)//------------- END POSITION SIZE CODE -------------//⋯    tradePositionSize := getPositionSize(toWhole(longStopDistance) * 10)-    strategy.entry(id="Long", long=strategy.long, when=validLong, comment="(SL=" + tostring(truncate(toWhole(longStopDistance),2)) + " pips)")+    strategy.entry(id="Long", direction = strategy.long, when=validLong, comment="(SL=" + str.tostring(truncate(toWhole(longStopDistance),2)) + " pips)")    // Fire alerts⋯        alert(message="e=" + broker + " b=long q="-         + tostring(tradePositionSize) +         + str.tostring(tradePositionSize)          + " s=" + pair-         + " t=" + (av_limitOrder ? "limit fp=" + tostring(close) : "market")+         + " t=" + (av_limitOrder ? "limit fp=" + str.tostring(close) : "market")-         + " fsl=" + tostring(t_stop)+         + " fsl=" + str.tostring(t_stop)-         + " ftp=" + tostring(t_target)+         + " ftp=" + str.tostring(t_target)         + (av_gtdOrder != 0 and av_limitOrder ? gtdString : ""), ⋯    tradePositionSize := getPositionSize(toWhole(shortStopDistance) * 10)-    strategy.entry(id="Short", long=strategy.short, when=validShort, comment="(SL=" + tostring(truncate(toWhole(shortStopDistance),2)) + " pips)")+    strategy.entry(id="Short", direction = strategy.short, when=validShort, comment="(SL=" + str.tostring(truncate(toWhole(shortStopDistance),2)) + " pips)")    // Fire alerts⋯        alert(message="e=" + broker + " b=short q="-         + tostring(tradePositionSize)+         + str.tostring(tradePositionSize)         + " s=" + pair-         + " t=" + (av_limitOrder ? "limit fp=" + tostring(close) : "market")+         + " t=" + (av_limitOrder ? "limit fp=" + str.tostring(close) : "market")-         + " fsl=" + tostring(t_stop)+         + " fsl=" + str.tostring(t_stop)-         + " ftp=" + tostring(t_target)+         + " ftp=" + str.tostring(t_target)         + (av_gtdOrder != 0 and av_limitOrder ? gtdString : ""),⋯    balance := balance + ((riskPerTrade / 100) * balance) * rr-    totalPips := totalPips + abs(t_entry - t_target)+    totalPips := totalPips + math.abs(t_entry - t_target)    totalWins := totalWins + 1⋯    balance := balance - ((riskPerTrade / 100) * balance)-    totalPips := totalPips - abs(t_entry - t_stop)+    totalPips := totalPips - math.abs(t_entry - t_stop)    totalLoss := totalLoss + 1⋯        dollarReturn = balance - startBalance-        f_fillCell(testTable, 0, 0, "Total Trades:", tostring(strategy.closedtrades), bgcolor, color.white)+        f_fillCell(testTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)-        f_fillCell(testTable, 0, 1, "Win Rate:", tostring(truncate((strategy.wintrades/strategy.closedtrades)*100,2)) + "%", bgcolor, color.white)+        f_fillCell(testTable, 0, 1, "Win Rate:", str.tostring(truncate((strategy.wintrades/strategy.closedtrades)*100,2)) + "%", bgcolor, color.white)-        f_fillCell(testTable, 1, 0, "Starting:", "$" + tostring(startBalance), bgcolor, color.white)+        f_fillCell(testTable, 1, 0, "Starting:", "$" + str.tostring(startBalance), bgcolor, color.white)-        f_fillCell(testTable, 1, 1, "Ending:", "$" + tostring(truncate(balance,2)), bgcolor, color.white)+        f_fillCell(testTable, 1, 1, "Ending:", "$" + str.tostring(truncate(balance,2)), bgcolor, color.white)-        f_fillCell(testTable, 2, 0, "Return:", "$" + tostring(truncate(dollarReturn,2)), dollarReturn > 0 ? color.green : color.red, color.white)+        f_fillCell(testTable, 2, 0, "Return:", "$" + str.tostring(truncate(dollarReturn,2)), dollarReturn > 0 ? color.green : color.red, color.white)-        f_fillCell(testTable, 2, 1, "Pips:", (totalPips > 0 ? "+" : "") + tostring(truncate(toWhole(totalPips),2)), bgcolor, color.white)+        f_fillCell(testTable, 2, 1, "Pips:", (totalPips > 0 ? "+" : "") + str.tostring(truncate(toWhole(totalPips),2)), bgcolor, color.white)-        f_fillCell(testTable, 3, 0, "Return:", (dollarReturn > 0 ? "+" : "") + tostring(truncate((dollarReturn / startBalance)*100,2)) + "%", dollarReturn > 0 ? color.green : color.red, color.white)+        f_fillCell(testTable, 3, 0, "Return:", (dollarReturn > 0 ? "+" : "") + str.tostring(truncate((dollarReturn / startBalance)*100,2)) + "%", dollarReturn > 0 ? color.green : color.red, color.white)-        f_fillCell(testTable, 3, 1, "Max DD:", tostring(truncate(maxDrawdown*100,2)) + "%", color.red, color.white)+        f_fillCell(testTable, 3, 1, "Max DD:", str.tostring(truncate(maxDrawdown*100,2)) + "%", color.red, color.white)// --- END TESTER CODE --- //

Clean v5

VerifiedDownload the v5 script

Same 47 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 135: when = validLong → if block
  • Line 161: when = validShort → if block
  • Line 194: when = strategy.position_size > 0 → if block
  • Line 195: when = strategy.position_size < 0 → if block
⋯    tradePositionSize := getPositionSize(toWhole(longStopDistance) * 10)-    strategy.entry(id="Long", direction = strategy.long, when=validLong, comment="(SL=" + str.tostring(truncate(toWhole(longStopDistance),2)) + " pips)")+    if validLong+        strategy.entry(id="Long", direction = strategy.long, comment="(SL=" + str.tostring(truncate(toWhole(longStopDistance),2)) + " pips)")    // Fire alerts⋯    tradePositionSize := getPositionSize(toWhole(shortStopDistance) * 10)-    strategy.entry(id="Short", direction = strategy.short, when=validShort, comment="(SL=" + str.tostring(truncate(toWhole(shortStopDistance),2)) + " pips)")+    if validShort+        strategy.entry(id="Short", direction = strategy.short, comment="(SL=" + str.tostring(truncate(toWhole(shortStopDistance),2)) + " pips)")    // Fire alerts⋯// Exit trades whenever our stop or target is hit-strategy.exit(id="Long Exit", from_entry="Long", limit=t_target, stop=t_stop, when=strategy.position_size > 0)+if strategy.position_size > 0+    strategy.exit(id="Long Exit", from_entry="Long", limit=t_target, stop=t_stop)-strategy.exit(id="Short Exit", from_entry="Short", limit=t_target, stop=t_stop, when=strategy.position_size < 0)+if strategy.position_size < 0+    strategy.exit(id="Short Exit", from_entry="Short", limit=t_target, stop=t_stop)// Draw trade data⋯

Does it run in Pine Script v6?

No

The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 47 before, 51 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// Last Updated: 5th October, 2021-// @version=5+// @version=6strategy("Hammers & Stars Strategy [v1.1]", shorttitle="HSS[v1.1]", overlay=true)⋯

Settings

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

SettingDefaultType and rangeFeeds
Strategy Settings
>= ATR FilterMinimum size of entry candle compared to ATR0.0float · min 0.0atrMinFilter
<= ATR FilterMaximum size of entry candle compared to ATR3.0float · min 0.0atrMaxFilter
Stop Loss ATRStop loss multiplier (x ATR)1.0floatstopSize
R:RRisk:Reward profile1.0floatlongTargetPrice shortTargetPrice balance
Fib LevelUsed to calculate upper/lower third of candle. (For example, setting it to 0.5 will mean hammers must close >= 50% mark of the total candle size)0.333floatbullFib bearFib
Filter Settings
EMA FilterEMA length to filter trades - set to zero to disable0int (written input.integer)ema emaFilterLong emaFilterShort EMA
Start Date FilterDate & time to begin trading fromtimestamp("01 Jan 2000 13:30 +0000")timedateFilter
End Date FilterDate & time to stop tradingtimestamp("1 Jan 2099 19:30 +0000")timedateFilter
Backtester Settings
Starting BalanceYour starting balance for the custom inbuilt tester system10000.0floatbalance dollarReturn line 246 line 250
Risk Per TradeYour desired % risk per trade (as a whole number)1.0floatbalance
Draw BacktesterTurn on/off inbuilt backtester displaytrueboolline 240
AutoView Settings [OANDA]
Use AutoView?If turned on then the alerts this script generates will use AutoView syntax for auto-trading (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS)falseboolline 137 line 144 line 163 line 170
Use Oanda Demo?If turned on then oandapractice broker prefix will be used for AutoView alerts (demo account). If turned off then live account will be usedfalseboolbroker
Use Limit Order?If turned on then AutoView will use limit orders. If turned off then market orders will be usedtrueboolalert
Days To Leave Limit OrderThis is your GTD setting (good til day)2int (written input.integer) · min 0gtdTime alert
Account BalanceYour account balance (used for calculating position size)1000.0float · step 100riskAmount
Account CurrencyYour account balance currency (used for calculating position size)USDstring · options ["AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "NZD", "USD"]accountSameAsCounterCurrency accountSameAsBaseCurrency conversionCurrencyPair
Risk Per Trade %Your risk per trade as a % of your account balance2.0float · step 0.5riskAmount
PineConnector Settings
Use PineConnector?Use PineConnector Alerts? (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS)falseboolline 137 line 140 line 163 line 166 line 184 line 191
License IDThis is your PineConnector license IDIDstringline 49 alert
SpreadEnter your average spread for this pair (used for offsetting entry limit order from closing price)0.5floatspread
Risk Per TradeThis is how much to risk per trade (% of balance or lots - based on PC settings)1float · step 0.5line 49
MetaTrader PrefixThis is your broker's MetaTrader symbol prefix (leave blank if there is none)stringsymbol
MetaTrader SuffixThis is your broker's MetaTrader symbol suffix (leave blank if there is none)stringsymbol
Use Limit Order?If true a limit order will be used, if false a market order will be usedtrueboollimit price line 184 line 191

What it calculates

  • ATR (atr, ta.atr in v5)14atr · line 53
  • EMA (ema, ta.ema in v5)close, emaFilter == 0 ? 1 : emaFilterema · line 54

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

Order rules

OrderFires whenBy defaultLine
Open Long longvalidLongvalidHammer and strategy.position_size == 0 and dateFilter and barstate.isconfirmedOn135
Open Short shortvalidShortvalidStar and strategy.position_size == 0 and dateFilter and barstate.isconfirmedOn161
Exit Long Exit stop and limitstrategy.position_size > 0On194
Exit Short Exit stop and limitstrategy.position_size < 0On195

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

Alerts

AlertCallMessageLine
(no title)alertBullish Hammer Detected!138
(no title)alertalertString142
(no title)alert"e=" + broker + " b=long q=" + tostring(tradePositionSize) + " s=" + pair + " t=" + (av_limitOrder ? "limit fp=" + tostring(close) : "market") + " fsl=" + tostring(t_stop) + " ftp=" + tostring(t_target) + (av_gtdOrder != 0 and av_limitOrder ? gtdString : "")145
(no title)alertBearish Hammer Detected!164
(no title)alertalertString168
(no title)alert"e=" + broker + " b=short q=" + tostring(tradePositionSize) + " s=" + pair + " t=" + (av_limitOrder ? "limit fp=" + tostring(close) : "market") + " fsl=" + tostring(t_stop) + " ftp=" + tostring(t_target) + (av_gtdOrder != 0 and av_limitOrder ? gtdString : "")171
(no title)alertpc_id + ",cancellong," + symbol185
(no title)alertpc_id + ",cancelshort," + symbol192

Does it repaint?

No

No repainting patterns in the source.

Not measuredAn engine gap, not the scriptThe script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script. The answer comes from the checks on the source alone.
  • ClearHigher-timeframe data1 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 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

Not run on other markets: the script requests AUDUSD D, and that data is not available here (AUDUSD is not on Binance). Its results would rest on empty values.

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market1958%$22,347.00
Sideways market1856%$11,890.20
Falling market1050%−$1,680.93

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

How bad could the drawdown be?

30.5%

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

0%35%
All 47 trades
SideEntryExitBarsP&L
long14 Feb 2024 49,699.6026 Feb 2024 53,168.9012$3,469.32
short24 Mar 2024 63,990.0025 Mar 2024 70,618.901−$6,628.89
short27 Mar 2024 69,988.003 Apr 2024 64,520.407$5,467.62
long28 Apr 2024 63,462.0030 Apr 2024 59,318.902−$4,143.11
short12 May 2024 60,826.0015 May 2024 66,279.403−$5,453.39
short21 Jun 2024 64,870.0024 Jun 2024 61,297.303$3,572.68
short2 Jul 2024 62,900.003 Jul 2024 60,017.401$2,882.64
long6 Jul 2024 56,628.8015 Jul 2024 61,999.509$5,370.70
long17 Jul 2024 65,044.004 Aug 2024 58,125.7018−$6,918.30
short21 Aug 2024 59,013.8023 Aug 2024 64,316.002−$5,302.19
short30 Aug 2024 59,359.006 Sep 2024 54,791.507$4,567.51
long12 Sep 2024 57,338.0018 Sep 2024 61,636.106$4,298.13
short8 Oct 2024 62,224.0014 Oct 2024 66,486.506−$4,262.51
long4 Nov 2024 68,776.006 Nov 2024 72,166.702$3,390.75
long10 Nov 2024 76,677.5011 Nov 2024 80,370.001$3,692.55
long25 Nov 2024 97,900.1026 Nov 2024 92,412.601−$5,487.42
long4 Dec 2024 95,849.705 Dec 2024 101,420.001$5,570.74
short18 Dec 2024 106,134.0019 Dec 2024 99,973.101$6,160.64
long21 Dec 2024 97,805.4020 Jan 2025 107,835.0030$10,030.00
short21 Jan 2025 102,260.0025 Feb 2025 90,525.7035$11,734.30
long1 Mar 2025 84,349.902 Mar 2025 94,393.801$10,043.90
long21 Apr 2025 85,179.2022 Apr 2025 89,558.701$4,379.47
long25 Apr 2025 93,980.508 May 2025 99,602.8013$5,622.28
long16 May 2025 103,764.0021 May 2025 109,009.005$5,245.60
long3 Jun 2025 105,858.005 Jun 2025 100,850.002−$5,008.38
long11 Jun 2025 110,274.0020 Jun 2025 102,398.009−$7,875.92
short15 Jul 2025 119,841.001 Aug 2025 113,648.0017$6,192.71
short10 Aug 2025 116,462.0011 Aug 2025 120,516.001−$4,053.63
short12 Aug 2025 118,686.0021 Aug 2025 112,324.009$6,361.84
short6 Sep 2025 110,660.0012 Sep 2025 116,372.006−$5,711.67
long14 Sep 2025 115,918.0022 Sep 2025 112,188.008−$3,729.98
long28 Sep 2025 109,636.0029 Sep 2025 112,930.001$3,294.37
short28 Oct 2025 114,108.0030 Oct 2025 108,087.002$6,021.03
long20 Nov 2025 91,555.0021 Nov 2025 84,420.201−$7,134.74
short1 Dec 2025 90,360.0018 Dec 2025 85,140.4017$5,219.58
short23 Dec 2025 88,620.805 Jan 2026 93,949.0013−$5,328.24
long7 Jan 2026 93,748.0020 Jan 2026 88,720.5013−$5,027.49
short29 Jan 2026 89,300.0030 Jan 2026 84,650.201$4,649.84
long31 Jan 2026 84,260.501 Feb 2026 78,421.201−$5,839.30
long4 Mar 2026 68,338.0016 Mar 2026 74,845.8012$6,507.83
short15 Apr 2026 74,131.6022 Apr 2026 78,610.107−$4,478.58
long24 Apr 2026 78,257.5028 May 2026 73,604.7034−$4,652.82
long5 Jun 2026 63,886.0025 Jun 2026 59,031.5020−$4,854.46
short28 Jun 2026 60,029.004 Jul 2026 63,233.206−$3,204.15
long7 Jul 2026 64,042.9019 Aug 2026 69,021.1043$4,978.19
long3 Sep 2026 77,340.004 Sep 2026 81,270.401$3,930.36
short12 Sep 2026 77,225.7021 Sep 2026 82,228.709−$5,003.02

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
Hammers & Stars Strategy this page—v4 strategy+32.6%4719.8%
Trend Reversal - Potential pressure by BardiaB2atr emav4 strategy+133,960.0%51,504.8%
Simple Ema_ATR Strategy HulkTrading by TheHulkTradingema atrv4 strategy+2.2%1415.6%
Keltner Breakout Strategy by Zeal Terminalema atrv5 strategy+3.5%212.3%
[EKIN] ATR Exit Strategy by ekinbasarkomurema atrv5 strategy+781.7%302,960.8%
DEMA-EMA & VOLATILITY (VAMS) by Qorbanjfema atrv4 strategy+2,833,450.0%1915,721.0%

Where it runs

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

Zeal Terminal's engine currently reads an order side written as long = strategy.long, long = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 135, 161) 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. PineTS runs Pine Script v5 and v6 only.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © ZenAndTheArtOfTrading / PineScriptMastery// Last Updated: 5th October, 2021// @version=4strategy("Hammers & Stars Strategy [v1.1]", shorttitle="HSS[v1.1]", overlay=true)// Strategy Settingsvar g_strategy      = "Strategy Settings"atrMinFilterSize    = input(title=">= ATR Filter", type=input.float, defval=0.0, minval=0.0, group=g_strategy, tooltip="Minimum size of entry candle compared to ATR")atrMaxFilterSize    = input(title="<= ATR Filter", type=input.float, defval=3.0, minval=0.0, group=g_strategy, tooltip="Maximum size of entry candle compared to ATR")stopMultiplier      = input(title="Stop Loss ATR", type=input.float, defval=1.0, group=g_strategy, tooltip="Stop loss multiplier (x ATR)")rr                  = input(title="R:R", type=input.float, defval=1.0, group=g_strategy, tooltip="Risk:Reward profile")fibLevel            = input(title="Fib Level", type=input.float, defval=0.333, group=g_strategy, tooltip="Used to calculate upper/lower third of candle. (For example, setting it to 0.5 will mean hammers must close >= 50% mark of the total candle size)")// Filter Settingsvar g_filter        = "Filter Settings"emaFilter           = input(title="EMA Filter", type=input.integer, defval=0, group=g_filter, tooltip="EMA length to filter trades - set to zero to disable")i_startTime         = input(title="Start Date Filter", defval=timestamp("01 Jan 2000 13:30 +0000"), type=input.time, group=g_filter, tooltip="Date & time to begin trading from")i_endTime           = input(title="End Date Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), type=input.time, group=g_filter, tooltip="Date & time to stop trading")// Backtester Settingsvar g_tester        = "Backtester Settings"startBalance        = input(title="Starting Balance", type=input.float, defval=10000.0, group=g_tester, tooltip="Your starting balance for the custom inbuilt tester system")riskPerTrade        = input(title="Risk Per Trade", type=input.float, defval=1.0, group=g_tester, tooltip="Your desired % risk per trade (as a whole number)")drawTester          = input(title="Draw Backtester", type=input.bool, defval=true, group=g_tester, tooltip="Turn on/off inbuilt backtester display")// AutoView Settingsvar g_av            = "AutoView Settings [OANDA]"av_use              = input(title="Use AutoView?", type=input.bool, defval=false, group=g_av, tooltip="If turned on then the alerts this script generates will use AutoView syntax for auto-trading (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS)")av_oandaDemo        = input(title="Use Oanda Demo?", type=input.bool, defval=false, group=g_av, tooltip="If turned on then oandapractice broker prefix will be used for AutoView alerts (demo account). If turned off then live account will be used")av_limitOrder       = input(title="Use Limit Order?", type=input.bool, defval=true, group=g_av, tooltip="If turned on then AutoView will use limit orders. If turned off then market orders will be used")av_gtdOrder         = input(title="Days To Leave Limit Order", type=input.integer, minval=0, defval=2, group=g_av, tooltip="This is your GTD setting (good til day)")av_accountBalance   = input(title="Account Balance", type=input.float, defval=1000.0, step=100, group=g_av, tooltip="Your account balance (used for calculating position size)")av_accountCurrency  = input(title="Account Currency", type=input.string, defval="USD", options=["AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "NZD", "USD"], group=g_av, tooltip="Your account balance currency (used for calculating position size)")av_riskPerTrade     = input(title="Risk Per Trade %", type=input.float, defval=2.0, step=0.5, group=g_av, tooltip="Your risk per trade as a % of your account balance")// PineConnector Settingsvar g_pc            = "PineConnector Settings"pc_use              = input(title="Use PineConnector?", type=input.bool, defval=false, group=g_pc, tooltip="Use PineConnector Alerts? (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS)")pc_id               = input(title="License ID", type=input.string, defval="ID", group=g_pc, tooltip="This is your PineConnector license ID")pc_spread           = input(title="Spread", type=input.float, defval=0.5, group=g_pc, tooltip="Enter your average spread for this pair (used for offsetting entry limit order from closing price)")pc_risk             = input(title="Risk Per Trade", type=input.float, defval=1, step=0.5, group=g_pc, tooltip="This is how much to risk per trade (% of balance or lots - based on PC settings)")pc_prefix           = input(title="MetaTrader Prefix", type=input.string, defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol prefix (leave blank if there is none)")pc_suffix           = input(title="MetaTrader Suffix", type=input.string, defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol suffix (leave blank if there is none)")pc_limit            = input(title="Use Limit Order?", type=input.bool, defval=true, group=g_pc, tooltip="If true a limit order will be used, if false a market order will be used")// Generate PineConnector alert string & prepare OANDA broker stringvar broker = av_oandaDemo ? "oandapractice" : "oanda"var symbol = pc_prefix + syminfo.ticker + pc_suffixvar limit = pc_limit ? "limit" : ""var spread = syminfo.mintick * 10 * pc_spreadpc_entry_alert(direction, sl, tp) =>    limit_price = direction == "buy" ? close - spread : close + spread    price = pc_limit ? "price=" + tostring(limit_price) + "," : ""    pc_id + "," + direction + limit + "," + symbol + "," + price + "sl=" + tostring(sl) + ",tp=" + tostring(tp) + ",risk=" + tostring(pc_risk)// See if this bar's time happened within date filterdateFilter = time >= i_startTime and time <= i_endTime// Get indicator valuesatr = atr(14)ema = ema(close, emaFilter == 0 ? 1 : emaFilter)// Custom function to convert pips into whole numberstoWhole(number) =>    return = atr < 1.0 ? (number / syminfo.mintick) / (10 / syminfo.pointvalue) : number    return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return * 100 : return    // Custom function to convert whole numbers back into pipstoPips(number) =>    return = atr >= 1.0 ? number : (number * syminfo.mintick) * (10 / syminfo.pointvalue)    return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return / 100 : return    // Custom function to truncate (cut) excess decimal placestruncate(_number, _decimalPlaces) =>    _factor = pow(10, _decimalPlaces)    int(_number * _factor) / _factor    // Check EMA FilteremaFilterLong = emaFilter == 0 or close > emaemaFilterShort = emaFilter == 0 or close < ema// Check ATR filteratrMinFilter = abs(high - low) >= (atrMinFilterSize * atr) or atrMinFilterSize == 0.0atrMaxFilter = abs(high - low) <= (atrMaxFilterSize * atr) or atrMaxFilterSize == 0.0atrFilter = atrMinFilter and atrMaxFilter// Calculate 33.3% fibonacci level for current candlebullFib = (low - high) * fibLevel + highbearFib = (high - low) * fibLevel + low// Determine which price source closes or opens highest/lowestlowestBody = close < open ? close : openhighestBody = close > open ? close : open// Determine if we have a valid setupvalidHammer = lowestBody >= bullFib and atrFilter and close != open and not na(atr) and emaFilterLongvalidStar = highestBody <= bearFib and atrFilter and close != open and not na(atr) and emaFilterShort// Check if we have confirmation for our setupvalidLong = validHammer and strategy.position_size == 0 and dateFilter and barstate.isconfirmedvalidShort = validStar and strategy.position_size == 0 and dateFilter and barstate.isconfirmed//------------- DETERMINE POSITION SIZE -------------//// Get account inputsvar tradePositionSize = 0.0var pair = syminfo.basecurrency + "/" + syminfo.currency// Check if our account currency is the same as the base or quote currency (for risk $ conversion purposes)accountSameAsCounterCurrency = av_accountCurrency == syminfo.currencyaccountSameAsBaseCurrency = av_accountCurrency == syminfo.basecurrency// Check if our account currency is neither the base or quote currency (for risk $ conversion purposes)accountNeitherCurrency = not accountSameAsCounterCurrency and not accountSameAsBaseCurrency// Get currency conversion rates if applicableconversionCurrencyPair = accountSameAsCounterCurrency ? syminfo.tickerid : accountNeitherCurrency ? av_accountCurrency + syminfo.currency : av_accountCurrency + syminfo.currencyconversionCurrencyRate = security(symbol=syminfo.type == "forex" ? conversionCurrencyPair : "AUDUSD", resolution="D", expression=close)// Calculate position sizegetPositionSize(stopLossSizePoints) =>    riskAmount = (av_accountBalance * (av_riskPerTrade / 100)) * (accountSameAsBaseCurrency or accountNeitherCurrency ? conversionCurrencyRate : 1.0)    riskPerPoint = (stopLossSizePoints * syminfo.pointvalue)    positionSize = (riskAmount / riskPerPoint) / syminfo.mintick    round(positionSize)    // Set up our GTD (good-til-day) order infogtdTime = time + (av_gtdOrder * 1440 * 60 * 1000) // 86,400,000ms per daygtdYear = year(gtdTime)gtdMonth = month(gtdTime)gtdDay = dayofmonth(gtdTime)gtdString = " dt=" + tostring(gtdYear) + "-" + tostring(gtdMonth) + "-" + tostring(gtdDay)//------------- END POSITION SIZE CODE -------------//// Calculate our stop distance & size for the current barstopSize = atr * stopMultiplierlongStopPrice = low < low[1] ? low - stopSize : low[1] - stopSizelongStopDistance = close - longStopPricelongTargetPrice = close + (longStopDistance * rr)shortStopPrice = high > high[1] ? high + stopSize : high[1] + stopSizeshortStopDistance = shortStopPrice - closeshortTargetPrice = close - (shortStopDistance * rr)// Save trade stop & target & position size if a valid setup is detectedvar t_entry = 0.0var t_stop = 0.0var t_target = 0.0var t_direction = 0// Detect valid long setups & trigger alertif validLong    t_entry := close    t_stop := longStopPrice    t_target := longTargetPrice    t_direction := 1    tradePositionSize := getPositionSize(toWhole(longStopDistance) * 10)    strategy.entry(id="Long", long=strategy.long, when=validLong, comment="(SL=" + tostring(truncate(toWhole(longStopDistance),2)) + " pips)")    // Fire alerts    if not av_use and not pc_use        alert(message="Bullish Hammer Detected!", freq=alert.freq_once_per_bar_close)    // Trigger PineConnector long alert    if pc_use        alertString = pc_entry_alert("buy", t_stop, t_target)        alert(alertString, alert.freq_once_per_bar_close)    // Trigger AutoView long alert    if av_use        alert(message="e=" + broker + " b=long q="         + tostring(tradePositionSize)          + " s=" + pair         + " t=" + (av_limitOrder ? "limit fp=" + tostring(close) : "market")         + " fsl=" + tostring(t_stop)         + " ftp=" + tostring(t_target)         + (av_gtdOrder != 0 and av_limitOrder ? gtdString : ""),          freq=alert.freq_once_per_bar_close)   // Detect valid short setups & trigger alertif validShort    t_entry := close    t_stop := shortStopPrice    t_target := shortTargetPrice    t_direction := -1    tradePositionSize := getPositionSize(toWhole(shortStopDistance) * 10)    strategy.entry(id="Short", long=strategy.short, when=validShort, comment="(SL=" + tostring(truncate(toWhole(shortStopDistance),2)) + " pips)")    // Fire alerts    if not av_use and not pc_use        alert(message="Bearish Hammer Detected!", freq=alert.freq_once_per_bar_close)    // Trigger PineConnector short alert    if pc_use        alertString = pc_entry_alert("sell", t_stop, t_target)        alert(alertString, alert.freq_once_per_bar_close)    // Trigger AutoView short alert    if av_use        alert(message="e=" + broker + " b=short q="         + tostring(tradePositionSize)         + " s=" + pair         + " t=" + (av_limitOrder ? "limit fp=" + tostring(close) : "market")         + " fsl=" + tostring(t_stop)         + " ftp=" + tostring(t_target)         + (av_gtdOrder != 0 and av_limitOrder ? gtdString : ""),         freq=alert.freq_once_per_bar_close)         // Check if price has hit long stop loss or targetif t_direction == 1 and (low <= t_stop or high >= t_target)    t_direction := 0    // Cancel limit order if it hasn't been filled yet    if pc_limit and pc_use        alert(pc_id + ",cancellong," + symbol)    // Check if price has hit short stop loss or targetif t_direction == -1 and (high >= t_stop or low <= t_target)    t_direction := 0    // Cancel limit order if it hasn't been filled yet    if pc_limit and pc_use        alert(pc_id + ",cancelshort," + symbol)// Exit trades whenever our stop or target is hitstrategy.exit(id="Long Exit", from_entry="Long", limit=t_target, stop=t_stop, when=strategy.position_size > 0)strategy.exit(id="Short Exit", from_entry="Short", limit=t_target, stop=t_stop, when=strategy.position_size < 0)// Draw trade dataplot(strategy.position_size != 0 or validLong or validShort ? t_stop : na, title="Trade Stop Price", color=color.red, style=plot.style_linebr)plot(strategy.position_size != 0 or validLong or validShort ? t_target : na, title="Trade Target Price", color=color.green, style=plot.style_linebr)plot(strategy.position_size != 0 or validLong or validShort ? tradePositionSize : na, color=color.purple, display=display.none, title="AutoView Position Size")// Draw EMA if it's enabledplot(emaFilter == 0 ? na : ema, color=emaFilterLong ? color.green : color.red, linewidth=2, title="EMA")// Draw price action setup arrowsplotshape(validLong ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup")plotshape(validShort ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup")// --- BEGIN TESTER CODE --- //// Declare performance tracking variablesvar balance = startBalancevar drawdown = 0.0var maxDrawdown = 0.0var maxBalance = 0.0var totalPips = 0.0var totalWins = 0var totalLoss = 0// Detect winning tradesif strategy.wintrades != strategy.wintrades[1]    balance := balance + ((riskPerTrade / 100) * balance) * rr    totalPips := totalPips + abs(t_entry - t_target)    totalWins := totalWins + 1    if balance > maxBalance        maxBalance := balance        // Detect losing tradesif strategy.losstrades != strategy.losstrades[1]    balance := balance - ((riskPerTrade / 100) * balance)    totalPips := totalPips - abs(t_entry - t_stop)    totalLoss := totalLoss + 1    // Update drawdown    drawdown := (balance / maxBalance) - 1    if drawdown < maxDrawdown        maxDrawdown := drawdown        // Prepare stats tablevar table testTable = table.new(position.top_right, 5, 2, border_width=1)f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>    _cellText = _title + "\n" + _value    table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor)    // Draw stats tablevar bgcolor = color.new(color.black,0)if drawTester    if barstate.islastconfirmedhistory        // Update table        dollarReturn = balance - startBalance        f_fillCell(testTable, 0, 0, "Total Trades:", tostring(strategy.closedtrades), bgcolor, color.white)        f_fillCell(testTable, 0, 1, "Win Rate:", tostring(truncate((strategy.wintrades/strategy.closedtrades)*100,2)) + "%", bgcolor, color.white)        f_fillCell(testTable, 1, 0, "Starting:", "$" + tostring(startBalance), bgcolor, color.white)        f_fillCell(testTable, 1, 1, "Ending:", "$" + tostring(truncate(balance,2)), bgcolor, color.white)        f_fillCell(testTable, 2, 0, "Return:", "$" + tostring(truncate(dollarReturn,2)), dollarReturn > 0 ? color.green : color.red, color.white)        f_fillCell(testTable, 2, 1, "Pips:", (totalPips > 0 ? "+" : "") + tostring(truncate(toWhole(totalPips),2)), bgcolor, color.white)        f_fillCell(testTable, 3, 0, "Return:", (dollarReturn > 0 ? "+" : "") + tostring(truncate((dollarReturn / startBalance)*100,2)) + "%", dollarReturn > 0 ? color.green : color.red, color.white)        f_fillCell(testTable, 3, 1, "Max DD:", tostring(truncate(maxDrawdown*100,2)) + "%", color.red, color.white)// --- END TESTER CODE --- //