Strategy · Pine Script v5 · On the chart

Pinbar Strategy

by Web3Degenerate

This strategy identifies pin bar candlestick patterns, specifically hammer and shooting star candles, to trigger trade entries.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code95
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago13 Sep 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

95 lines of Pine Script v5 from advanced-pine-script/9.Strategy-Scripts/8.Pinbar-Strategy-Example.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

8.Pinbar-Strategy-Example.pine
// Strategy trades from Steven Hart (youtube) around an investopedia article
// Uses hammer and star candle
// expands on some of the things we've learned so far by creating a profitable hammer & shooting star strategy!
// Investopedia Video: https://www.youtube.com/watch?v=R7cXkvztdKY

// More for forex markets

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// Last Updated: 2nd February 2022
// @version=5
strategy("Pinbar Strategy", shorttitle="PBS", overlay=true)

// Import Zen library
import ZenAndTheArtOfTrading/ZenLibrary/3 as zen

// Strategy Settings
var g_strategy      = "Strategy Settings"
stopMultiplier      = input.float(title="Stop Loss ATR", defval=1.0, group=g_strategy, tooltip="Stop loss multiplier (x ATR)")
rr                  = input.float(title="R:R", defval=1.0, group=g_strategy, tooltip="Risk:Reward profile")
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 Settings
var g_filter        = "Filter Settings"
atrMinFilterSize    = input.float(title=">= ATR Filter", defval=0.0, minval=0.0, group=g_filter, tooltip="Minimum size of entry candle compared to ATR")
atrMaxFilterSize    = input.float(title="<= ATR Filter", defval=3.0, minval=0.0, group=g_filter, tooltip="Maximum size of entry candle compared to ATR")
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.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.time(title="End Date Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), group=g_filter, tooltip="Date & time to stop trading")

// See if this bar's time happened within date filter
dateFilter = time >= i_startTime and time <= i_endTime

// Get indicator values
atr = ta.atr(14)
ema = ta.ema(close, emaFilter == 0 ? 1 : emaFilter)

// Check EMA Filter
emaFilterLong = emaFilter == 0 or close > ema
emaFilterShort = emaFilter == 0 or close < ema

// 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 and not na(atr)

// Determine if we have a valid setup
validHammer = zen.isHammer(fibLevel) and atrFilter and emaFilterLong and dateFilter and close != open
validStar   = zen.isStar(fibLevel) and atrFilter and emaFilterShort and dateFilter and close != open

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

// Calculate our stops & targets for the current bar
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 trade stop & target if a valid setup is detected
var t_entry = 0.0
var t_stop = 0.0
var t_target = 0.0

// Detect valid long setups & trigger alert
if validLong
    t_entry := close
    t_stop := longStopPrice
    t_target := longTargetPrice
    strategy.entry(id="Long", direction=strategy.long, comment="(SL=" + str.tostring(zen.truncate(zen.toWhole(longStopDistance))) + " pips)")

// Detect valid short setups & trigger alert
if validShort
    t_entry := close
    t_stop := shortStopPrice
    t_target := shortTargetPrice
    strategy.entry(id="Short", direction=strategy.short, comment="(SL=" + str.tostring(zen.truncate(zen.toWhole(shortStopDistance))) + " pips)")

// 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)
strategy.exit(id="Short Exit", from_entry="Short", limit=t_target, stop=t_stop, when=strategy.position_size < 0)

// Draw trade data
plot(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)

// Draw EMA if it's enabled
plot(emaFilter == 0 ? na : ema, color=emaFilterLong ? color.green : color.red, linewidth=2, title="EMA")

// 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

Pinbar Strategy detects candle shapes based on a customizable Fibonacci threshold. Signals can be filtered using minimum and maximum ATR candle size bounds, an optional EMA trend direction filter, and a date range filter. When a valid setup is confirmed at bar close, trades are entered with ATR-based stop losses and dynamic profit targets set by a customizable risk-to-reward ratio. It draws directly on the price chart.

Details

Published by

Web3Degenerate on GitHub

Draws

On the price chart

Markets

Forex

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
>= ATR Filterfloat0.0atrMinFilterSize
<= ATR Filterfloat3.0atrMaxFilterSize
EMA Filterint0emaFilter
Start Date Filtertimetimestamp("01 Jan 2000 13:30 +0000")i_startTime
End Date Filtertimetimestamp("1 Jan 2099 19:30 +0000")i_endTime
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

106 stars

This strategy plots modified Bollinger Bands and an exponential moving average on the price chart. It watches for closes crossing the upper or lower band, optionally filtered by the EMA trend and extra crossover or crossunder checks. Long stops use the recent

Strategy v5 Volatility & bandsMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of Bollinger Bands Modified (Stormer)

Heikin Ashi Trend

by Basant1Saini
1 stars

Heikin Ashi Trend is a trend-following strategy that calculates Heikin Ashi candle values and moving averages directly on the main price chart. It generates long and short entry signals when a user-defined number of consecutive Heikin Ashi bars align with fast

Strategy v5 TrendMoving averages
Updated 8 months ago · None stated GitHub repository of Heikin Ashi Trend
1 stars

This Pine Script strategy detects pin bar patterns on the price chart using body size relative to ATR and shadow conditions for long and short signals. It applies engulfing candle confirmation and filters by EMA trend direction with volatility bands. Multiple

Strategy v6 TrendVolatility & bands
Updated 3 weeks ago · None stated GitHub repository of Pin Bar Strategy Developed

Tweezer Lyfe

by RobACurtis
1 stars

Tweezer Lyfe is a TradingView strategy that identifies Tweezer reversal patterns on the price chart. It plots Bollinger Bands with RSI and stochastic indicators for momentum confirmation. Bullish signals require a prior bearish candle closing near the lower ba

Strategy v5 TrendOscillators & momentum
Updated 2 years ago · None stated GitHub repository of Tweezer Lyfe
330 stars

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

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger bands + Aroon [Alorse]
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

More Candlestick patterns scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers