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
Needs AUDUSD D data, not available: AUDUSD is not on Binance Values that depend on it are empty on this chart.
| Total Trades: 47 | Starting: $10000 | Return: $488.05 | Return: +4.88% |
| Win Rate: 55.31% | Ending: $10488.05 | Pips: +32393.02 | Max 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
VerifiedSame 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 --- //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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Strategy Settings | |||
| >= ATR FilterMinimum size of entry candle compared to ATR | 0.0 | float · min 0.0 | atrMinFilter |
| <= ATR FilterMaximum size of entry candle compared to ATR | 3.0 | float · min 0.0 | atrMaxFilter |
| Stop Loss ATRStop loss multiplier (x ATR) | 1.0 | float | stopSize |
| R:RRisk:Reward profile | 1.0 | float | longTargetPrice 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.333 | float | bullFib bearFib |
| Filter Settings | |||
| EMA FilterEMA length to filter trades - set to zero to disable | 0 | int (written input.integer) | ema emaFilterLong emaFilterShort EMA |
| Start Date FilterDate & time to begin trading from | timestamp("01 Jan 2000 13:30 +0000") | time | dateFilter |
| End Date FilterDate & time to stop trading | timestamp("1 Jan 2099 19:30 +0000") | time | dateFilter |
| Backtester Settings | |||
| Starting BalanceYour starting balance for the custom inbuilt tester system | 10000.0 | float | balance dollarReturn line 246 line 250 |
| Risk Per TradeYour desired % risk per trade (as a whole number) | 1.0 | float | balance |
| Draw BacktesterTurn on/off inbuilt backtester display | true | bool | line 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) | false | bool | line 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 used | false | bool | broker |
| Use Limit Order?If turned on then AutoView will use limit orders. If turned off then market orders will be used | true | bool | alert |
| Days To Leave Limit OrderThis is your GTD setting (good til day) | 2 | int (written input.integer) · min 0 | gtdTime alert |
| Account BalanceYour account balance (used for calculating position size) | 1000.0 | float · step 100 | riskAmount |
| Account CurrencyYour account balance currency (used for calculating position size) | USD | string · options ["AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "NZD", "USD"] | accountSameAsCounterCurrency accountSameAsBaseCurrency conversionCurrencyPair |
| Risk Per Trade %Your risk per trade as a % of your account balance | 2.0 | float · step 0.5 | riskAmount |
| PineConnector Settings | |||
| Use PineConnector?Use PineConnector Alerts? (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS) | false | bool | line 137 line 140 line 163 line 166 line 184 line 191 |
| License IDThis is your PineConnector license ID | ID | string | line 49 alert |
| SpreadEnter your average spread for this pair (used for offsetting entry limit order from closing price) | 0.5 | float | spread |
| Risk Per TradeThis is how much to risk per trade (% of balance or lots - based on PC settings) | 1 | float · step 0.5 | line 49 |
| MetaTrader PrefixThis is your broker's MetaTrader symbol prefix (leave blank if there is none) | | string | symbol |
| MetaTrader SuffixThis is your broker's MetaTrader symbol suffix (leave blank if there is none) | | string | symbol |
| Use Limit Order?If true a limit order will be used, if false a market order will be used | true | bool | limit price line 184 line 191 |
What it calculates
- ATR (
atr,ta.atrin v5)14atr · line 53 - EMA (
ema,ta.emain 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
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long long | validLongvalidHammer and strategy.position_size == 0 and dateFilter and barstate.isconfirmed | On | 135 |
| Open Short short | validShortvalidStar and strategy.position_size == 0 and dateFilter and barstate.isconfirmed | On | 161 |
| Exit Long Exit stop and limit | strategy.position_size > 0 | On | 194 |
| Exit Short Exit stop and limit | strategy.position_size < 0 | On | 195 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| (no title) | alert | Bullish Hammer Detected! | 138 |
| (no title) | alert | alertString | 142 |
| (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) | alert | Bearish Hammer Detected! | 164 |
| (no title) | alert | alertString | 168 |
| (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) | alert | pc_id + ",cancellong," + symbol | 185 |
| (no title) | alert | pc_id + ",cancelshort," + symbol | 192 |
Does it repaint?
No
No repainting patterns in the source.
- 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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 19 | 58% | $22,347.00 |
| Sideways market | 18 | 56% | $11,890.20 |
| Falling market | 10 | 50% | −$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.
All 47 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 14 Feb 2024 49,699.60 | 26 Feb 2024 53,168.90 | 12 | $3,469.32 |
| short | 24 Mar 2024 63,990.00 | 25 Mar 2024 70,618.90 | 1 | −$6,628.89 |
| short | 27 Mar 2024 69,988.00 | 3 Apr 2024 64,520.40 | 7 | $5,467.62 |
| long | 28 Apr 2024 63,462.00 | 30 Apr 2024 59,318.90 | 2 | −$4,143.11 |
| short | 12 May 2024 60,826.00 | 15 May 2024 66,279.40 | 3 | −$5,453.39 |
| short | 21 Jun 2024 64,870.00 | 24 Jun 2024 61,297.30 | 3 | $3,572.68 |
| short | 2 Jul 2024 62,900.00 | 3 Jul 2024 60,017.40 | 1 | $2,882.64 |
| long | 6 Jul 2024 56,628.80 | 15 Jul 2024 61,999.50 | 9 | $5,370.70 |
| long | 17 Jul 2024 65,044.00 | 4 Aug 2024 58,125.70 | 18 | −$6,918.30 |
| short | 21 Aug 2024 59,013.80 | 23 Aug 2024 64,316.00 | 2 | −$5,302.19 |
| short | 30 Aug 2024 59,359.00 | 6 Sep 2024 54,791.50 | 7 | $4,567.51 |
| long | 12 Sep 2024 57,338.00 | 18 Sep 2024 61,636.10 | 6 | $4,298.13 |
| short | 8 Oct 2024 62,224.00 | 14 Oct 2024 66,486.50 | 6 | −$4,262.51 |
| long | 4 Nov 2024 68,776.00 | 6 Nov 2024 72,166.70 | 2 | $3,390.75 |
| long | 10 Nov 2024 76,677.50 | 11 Nov 2024 80,370.00 | 1 | $3,692.55 |
| long | 25 Nov 2024 97,900.10 | 26 Nov 2024 92,412.60 | 1 | −$5,487.42 |
| long | 4 Dec 2024 95,849.70 | 5 Dec 2024 101,420.00 | 1 | $5,570.74 |
| short | 18 Dec 2024 106,134.00 | 19 Dec 2024 99,973.10 | 1 | $6,160.64 |
| long | 21 Dec 2024 97,805.40 | 20 Jan 2025 107,835.00 | 30 | $10,030.00 |
| short | 21 Jan 2025 102,260.00 | 25 Feb 2025 90,525.70 | 35 | $11,734.30 |
| long | 1 Mar 2025 84,349.90 | 2 Mar 2025 94,393.80 | 1 | $10,043.90 |
| long | 21 Apr 2025 85,179.20 | 22 Apr 2025 89,558.70 | 1 | $4,379.47 |
| long | 25 Apr 2025 93,980.50 | 8 May 2025 99,602.80 | 13 | $5,622.28 |
| long | 16 May 2025 103,764.00 | 21 May 2025 109,009.00 | 5 | $5,245.60 |
| long | 3 Jun 2025 105,858.00 | 5 Jun 2025 100,850.00 | 2 | −$5,008.38 |
| long | 11 Jun 2025 110,274.00 | 20 Jun 2025 102,398.00 | 9 | −$7,875.92 |
| short | 15 Jul 2025 119,841.00 | 1 Aug 2025 113,648.00 | 17 | $6,192.71 |
| short | 10 Aug 2025 116,462.00 | 11 Aug 2025 120,516.00 | 1 | −$4,053.63 |
| short | 12 Aug 2025 118,686.00 | 21 Aug 2025 112,324.00 | 9 | $6,361.84 |
| short | 6 Sep 2025 110,660.00 | 12 Sep 2025 116,372.00 | 6 | −$5,711.67 |
| long | 14 Sep 2025 115,918.00 | 22 Sep 2025 112,188.00 | 8 | −$3,729.98 |
| long | 28 Sep 2025 109,636.00 | 29 Sep 2025 112,930.00 | 1 | $3,294.37 |
| short | 28 Oct 2025 114,108.00 | 30 Oct 2025 108,087.00 | 2 | $6,021.03 |
| long | 20 Nov 2025 91,555.00 | 21 Nov 2025 84,420.20 | 1 | −$7,134.74 |
| short | 1 Dec 2025 90,360.00 | 18 Dec 2025 85,140.40 | 17 | $5,219.58 |
| short | 23 Dec 2025 88,620.80 | 5 Jan 2026 93,949.00 | 13 | −$5,328.24 |
| long | 7 Jan 2026 93,748.00 | 20 Jan 2026 88,720.50 | 13 | −$5,027.49 |
| short | 29 Jan 2026 89,300.00 | 30 Jan 2026 84,650.20 | 1 | $4,649.84 |
| long | 31 Jan 2026 84,260.50 | 1 Feb 2026 78,421.20 | 1 | −$5,839.30 |
| long | 4 Mar 2026 68,338.00 | 16 Mar 2026 74,845.80 | 12 | $6,507.83 |
| short | 15 Apr 2026 74,131.60 | 22 Apr 2026 78,610.10 | 7 | −$4,478.58 |
| long | 24 Apr 2026 78,257.50 | 28 May 2026 73,604.70 | 34 | −$4,652.82 |
| long | 5 Jun 2026 63,886.00 | 25 Jun 2026 59,031.50 | 20 | −$4,854.46 |
| short | 28 Jun 2026 60,029.00 | 4 Jul 2026 63,233.20 | 6 | −$3,204.15 |
| long | 7 Jul 2026 64,042.90 | 19 Aug 2026 69,021.10 | 43 | $4,978.19 |
| long | 3 Sep 2026 77,340.00 | 4 Sep 2026 81,270.40 | 1 | $3,930.36 |
| short | 12 Sep 2026 77,225.70 | 21 Sep 2026 82,228.70 | 9 | −$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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Hammers & Stars Strategy this page | — | v4 strategy | +32.6% | 47 | 19.8% |
| Trend Reversal - Potential pressure by BardiaB2 | atr ema | v4 strategy | +133,960.0% | 5 | 1,504.8% |
| Simple Ema_ATR Strategy HulkTrading by TheHulkTrading | ema atr | v4 strategy | +2.2% | 14 | 15.6% |
| Keltner Breakout Strategy by Zeal Terminal | ema atr | v5 strategy | +3.5% | 21 | 2.3% |
| [EKIN] ATR Exit Strategy by ekinbasarkomur | ema atr | v5 strategy | +781.7% | 30 | 2,960.8% |
| DEMA-EMA & VOLATILITY (VAMS) by Qorbanjf | ema atr | v4 strategy | +2,833,450.0% | 19 | 15,721.0% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 81 ms | With a workaround 1,000 bars in 114 ms | Not measured |
| PineTS | No 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 --- //