Strategy · Pine Script v4 · On the chart

Hammers & Stars Strategy YouTube

by amico1234· code credited to ZenAndTheArtOfTrading / www.PineScriptMastery.com

The Hammers & Stars Strategy identifies hammer and star candlestick patterns on the price chart to generate buy and sell signals.

View on GitHub

GitHub stars1on the repository
Pine versionv4older, still runs
Lines of code168
Settings16inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago2 Mar 2024

Add It to Your TradingView Chart

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

Source Code

168 lines of Pine Script v4 from strategysample.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

strategysample.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading / www.PineScriptMastery.com
// Last Updated: 26th May, 2021
// @version=4
strategy("Hammers & Stars Strategy YouTube", shorttitle="HSS", overlay=true)

// Get user input
stopMultiplier   = input(title="Stop Loss ATR", type=input.float, defval=1.0, tooltip="Stop loss multiplier (x ATR)", group="Strategy Settings")
rr               = input(title="R:R", type=input.float, defval=1.0, tooltip="Risk:Reward profile", group="Strategy Settings")
fibLevel         = input(title="Fib Level", type=input.float, defval=0.333, 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)", group="Strategy Settings")
oandaDemo        = input(title="Use Oanda Demo?", type=input.bool, defval=false, 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", group="AutoView Oanda Settings")
limitOrder       = input(title="Use Limit Order?", type=input.bool, defval=true, tooltip="If turned on then AutoView will use limit orders. If turned off then market orders will be used", group="AutoView Oanda Settings")
gtdOrder         = input(title="Days To Leave Limit Order", type=input.integer, minval=0, defval=2, tooltip="This is your GTD setting (good til day)", group="AutoView Oanda Settings")
accountBalance   = input(title="Account Balance", type=input.float, defval=1000.0, step=100, tooltip="Your account balance (used for calculating position size)", group="AutoView Oanda Settings")
accountCurrency  = input(title="Account Currency", type=input.string, defval="USD", options=["AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "NZD", "USD"], tooltip="Your account balance currency (used for calculating position size)", group="AutoView Oanda Settings")
riskPerTrade     = input(title="Risk Per Trade %", type=input.float, defval=2.0, step=0.5, tooltip="Your risk per trade as a % of your account balance", group="AutoView Oanda Settings")

// Filter Settings
// ATR Filter
atrMinFilterSize = input(title=">= ATR Filter", type=input.float, defval=0.0, minval=0.0, tooltip="Minimum size of entry candle compared to ATR", group="Filters")
atrMaxFilterSize = input(title="<= ATR Filter", type=input.float, defval=3.0, minval=0.0, tooltip="Maximum size of entry candle compared to ATR", group="Filters")
// EMA Filter
emaFilterLength = input(title="EMA Filter Length", type=input.integer, defval=0, tooltip="EMA Length for filtering trades (set to zero to disable)", group="Filters")
// Date Filter
startTime = input(title="Start Date Filter", defval=timestamp("01 Jan 1000 13:30 +0000"), type=input.time, tooltip="Date & time to begin trading from", group="Filters")
endTime = input(title="End Date Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), type=input.time, tooltip="Date & time to stop trading", group="Filters")
// Time Filter
timeSession = input(title="Time Session To Ignore Trades", type=input.session, defval="0600-0915", group="Filters", tooltip="Time session to ignore trades")
useTimeFilter = input(title="Use Time Session Filter", type=input.bool, defval=false, group="Filters", tooltip="Turns on/off time session filter")

// Get ATR
atr = atr(14)

// Check ATR Filter
atrMinFilter = high - low >= (atrMinFilterSize * atr) or atrMinFilterSize == 0.0
atrMaxFilter = high - low <= (atrMaxFilterSize * atr) or atrMaxFilterSize == 0.0
atrFilter = atrMinFilter and atrMaxFilter

// Check EMA Filter
ema = emaFilterLength == 0 ? na : ema(close, emaFilterLength)
emaLongFilter = emaFilterLength == 0 or (close > ema and not na(ema))
emaShortFilter = emaFilterLength == 0 or (close < ema and not na(ema))

// Check Date Filter
dateFilter = time >= startTime and time <= endTime

// Check Time Filter
isInSession(sess) => na(time(timeframe.period, sess)) == false
timeFilter = (useTimeFilter and not isInSession(timeSession)) or not useTimeFilter

// Merge Filters
longFilters = atrFilter and emaLongFilter and dateFilter and timeFilter
shortFilters = atrFilter and emaShortFilter and dateFilter and timeFilter
bgcolor(color=(useTimeFilter and isInSession(timeSession)) or not dateFilter or not atrFilter ? color.red : na, transp=70, title="Filter Colorr")

// Calculate the 33.3% fibonacci level for current candle
bullFib = (low - high) * fibLevel + high
bearFib = (high - low) * fibLevel + low

// Determine which price source closes or opens highest/lowest
lowestBody = close < open ? close : open
highestBody = close > open ? close : open

// Determine if we have a valid setup
validHammer = lowestBody >= bullFib and close != open and not na(atr) and longFilters
validStar = highestBody <= bearFib and close != open and not na(atr) and shortFilters

// Check if we have confirmation for our setup
validLong = validHammer and strategy.position_size == 0 and barstate.isconfirmed
validShort = validStar and strategy.position_size == 0 and barstate.isconfirmed

//------------- DETERMINE POSITION SIZE -------------//
// Get account inputs
var broker = oandaDemo ? "oandapractice" : "oanda"
var tradePositionSize = 0.0
var pair = syminfo.basecurrency + "/" + syminfo.currency

// Check if our account currency is the same as the base or quote currency (for risk $ conversion purposes)
accountSameAsCounterCurrency = accountCurrency == syminfo.currency
accountSameAsBaseCurrency = 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 applicable
conversionCurrencyPair = accountSameAsCounterCurrency ? syminfo.tickerid : accountNeitherCurrency ? accountCurrency + syminfo.currency : accountCurrency + syminfo.currency
conversionCurrencyRate = security(symbol=syminfo.type == "forex" ? conversionCurrencyPair : "AUDUSD", resolution="D", expression=close)

// Calculate position size
getPositionSize(stopLossSizePoints) =>
    riskAmount = (accountBalance * (riskPerTrade / 100)) * (accountSameAsBaseCurrency or accountNeitherCurrency ? conversionCurrencyRate : 1.0)
    riskPerPoint = (stopLossSizePoints * syminfo.pointvalue)
    positionSize = syminfo.type == "forex" ? ((riskAmount / riskPerPoint) / syminfo.mintick) : 0
    round(positionSize)
    
// Custom function to convert pips into whole numbers
toWhole(number) =>
    return = atr(14) < 1.0 ? (number / syminfo.mintick) / (10 / syminfo.pointvalue) : number
    return := atr(14) >= 1.0 and atr(14) < 100.0 and syminfo.currency == "JPY" ? return * 100 : return
//------------- END POSITION SIZE CODE -------------//

// Set up our GTD (good-til-date) order info
gtdTime = time + (gtdOrder * 1440 * 60 * 1000) // 86,400,000ms per day
gtdYear = year(gtdTime)
gtdMonth = month(gtdTime)
gtdDay = dayofmonth(gtdTime)
gtdString = " dt=" + tostring(gtdYear) + "-" + tostring(gtdMonth) + "-" + tostring(gtdDay)

// Calculate our stops & targets
stopSize = atr * stopMultiplier
longStopPrice = low < low[1] ? low - stopSize : low[1] - stopSize
longStopDistance = close - longStopPrice
longTargetPrice = close + (longStopDistance * rr)
shortStopPrice = high > high[1] ? high + stopSize : high[1] + stopSize
shortStopDistance = shortStopPrice - close
shortTargetPrice = close - (shortStopDistance * rr)

// Save stops & targets for the current trade
var tradeStopPrice = 0.0
var tradeTargetPrice = 0.0

// Detect valid long setups & trigger alerts
if validLong
    tradeStopPrice := longStopPrice
    tradeTargetPrice := longTargetPrice
    tradePositionSize := getPositionSize(toWhole(longStopDistance) * 10)
    // Trigger AutoView long alert
    alert(message="e=" + broker + " b=long"
     + " q=" + tostring(tradePositionSize) 
     + " s=" + pair
     + " t=" + (limitOrder ? "limit fp=" + tostring(close) : "market")
     + " fsl=" + tostring(tradeStopPrice)
     + " ftp=" + tostring(tradeTargetPrice)
     + (gtdOrder != 0 and limitOrder ? gtdString : ""),
     freq=alert.freq_once_per_bar_close)

// Detect valid short setups & trigger alerts
if validShort
    tradeStopPrice := shortStopPrice
    tradeTargetPrice := shortTargetPrice
    tradePositionSize := getPositionSize(toWhole(shortStopDistance) * 10)
    // Trigger AutoView short alert
    alert(message="e=" + broker + " b=short"
     + " q=" + tostring(tradePositionSize) 
     + " s=" + pair
     + " t=" + (limitOrder ? "limit fp=" + tostring(close) : "market")
     + " fsl=" + tostring(tradeStopPrice)
     + " ftp=" + tostring(tradeTargetPrice) 
     + (gtdOrder != 0 and limitOrder ? gtdString : ""),
     freq=alert.freq_once_per_bar_close)

// Enter trades whenever a valid setup is detected
strategy.entry(id="Long", long=strategy.long, when=validLong)
strategy.entry(id="Short", long=strategy.short, when=validShort)

// Exit trades whenever our stop or target is hit
strategy.exit(id="Long Exit", from_entry="Long", limit=tradeTargetPrice, stop=tradeStopPrice, when=strategy.position_size > 0)
strategy.exit(id="Short Exit", from_entry="Short", limit=tradeTargetPrice, stop=tradeStopPrice, when=strategy.position_size < 0)

// Draw trade data
plot(emaFilterLength == 0 ? na : ema, color=close > ema ? color.green : color.red, title="EMA Filter")
plot(strategy.position_size != 0 or validLong or validShort ? tradeStopPrice : na, title="Trade Stop Price", color=color.red, style=plot.style_linebr, transp=0)
plot(strategy.position_size != 0 or validLong or validShort ? tradeTargetPrice : na, title="Trade Target Price", color=color.green, style=plot.style_linebr, transp=0)
//plot(strategy.position_size != 0 or validLong or validShort ? tradePositionSize : na, title="Trade Position Size", color=color.purple, style=plot.style_linebr, transp=100)

// Draw price action setup arrows
plotshape(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")

Overview

Hammers & Stars Strategy YouTube calculates stop loss as ATR multiplied by a user-defined multiplier and sets take profit using the risk-reward ratio. Fib level determines pattern confirmation thresholds. Filters adjust for ATR size, EMA length, trading dates, and time sessions. The strategy draws signals directly on the price chart. Main settings change pattern confirmation and trading filters. It supports limit orders for alerts and has no exit rules beyond take profit.

Details

Published by

amico1234 on GitHub

Code credit

ZenAndTheArtOfTrading / www.PineScriptMastery.com, as written in the script's header

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Candlestick patterns

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

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

Settings

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

SettingTypeDefaultVariable
Stop Loss ATRfloat1.0stopMultiplier
R:Rfloat1.0rr
Fib Levelfloat0.333fibLevel
Use Oanda Demo?boolfalseoandaDemo
Use Limit Order?booltruelimitOrder
Days To Leave Limit Orderint2gtdOrder
Account Balancefloat1000.0accountBalance
Account CurrencystringUSDaccountCurrency
Risk Per Trade %float2.0riskPerTrade
>= ATR Filterfloat0.0atrMinFilterSize
<= ATR Filterfloat3.0atrMaxFilterSize
EMA Filter Lengthint0emaFilterLength
Show all 16 settings
SettingTypeDefaultVariable
Start Date Filtertimetimestamp("01 Jan 1000 13:30 +0000")startTime
End Date Filtertimetimestamp("1 Jan 2099 19:30 +0000")endTime
Time Session To Ignore Tradessession0600-0915timeSession
Use Time Session FilterboolfalseuseTimeFilter
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

Exceeded Candle [Alorse] is a mean-reversion strategy that identifies candlestick engulfing patterns combined with Bollinger Bands filters. It enters a long position when a green candle surpasses the body of the previous red candle while price is below the mid

Strategy v4 Mean reversionCandlestick patterns
Updated 2 months ago · None stated GitHub repository of Exceeded candle [Alorse]
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy

ESU2023-10M - V1

by dearvn
257 stars

ESU2023-10M - V1 is an intraday trend-reversal strategy designed for index futures contracts on the price chart. It calculates a 3-period moving average of candle highs and lows alongside specific three-bar price action patterns to detect short-term swing high

Strategy v5 TrendCandlestick patterns
Updated 6 weeks ago · None stated GitHub repository of ESU2023-10M - V1

STRG One Bar Pursuit

by harryguiacorn
219 stars

The STRG One Bar Pursuit strategy identifies single-bar momentum reversals by monitoring shifts between bullish and bearish candlesticks starting from the year 2024. It enters a long position when a bullish candle follows a bearish candle and enters a short po

Strategy v5 Candlestick patternsMean reversion
Updated 1 year ago · None stated GitHub repository of STRG One Bar Pursuit
218 stars

This strategy identifies trade opportunities based on candlestick wick imbalances relative to the Average True Range. It enters positions when candle wicks exceed defined thresholds and filters out doji candles using a minimum body ATR requirement. Exits are h

Strategy v6 Candlestick patternsVolatility & bands Repaints
Updated 3 months ago · None stated GitHub repository of Super Negative R:R Wick Strategy

More strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers