Strategy · Pine Script v5 · On the chart

NoSKi Hammer Star Backtester %

by hasnocool· code credited to noski1

This strategy backtests hammer and star candlestick patterns on the price chart.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code120
Settings24inputs
LicenceGPL-3.0
Last update2 years ago18 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

120 lines of Pine Script v5 from -NoSKi Hammer-Star -w angle of ema Backtester -.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

-NoSKi Hammer-Star -w angle of ema Backtester -.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © noski1
//@version=5
strategy(title='"NoSKi Hammer Star Backtester %', shorttitle='Noski HnS BT %', overlay=true, 
 commission_type=strategy.commission.percent, commission_value=0.075, initial_capital = 10000, currency=currency.USD, default_qty_type= strategy.percent_of_equity, default_qty_value=100)
// Import Zen library
import ZenAndTheArtOfTrading/ZenLibrary/5 as zen
// --------------------------------------------------------------------------------
//------- Inputs--------//
// --------------------------------------------------------------------------------
//Time Period
FromMonth = input.int(defval=1, title='From Month', minval=1, maxval=12)
FromDay = input.int(defval=9, title='From Day', minval=1, maxval=31)
FromYear = input.int(defval=2019, title='From Year', minval=2018)
ToMonth = input.int(defval=1, title='To Month', minval=1, maxval=12)
ToDay = input.int(defval=1, title='To Day', minval=1, maxval=31)
ToYear = input.int(defval=9999, title='To Year', minval=2017)
start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
window() =>
    time >= start and time <= finish ? true : false
    
// Take Profit SL inputs
tp_inp = input.int(14, title='Take Profit %', group = "Take Profit/Stop Loss Settings")/100 //input.int(defval = 1, title = "Take Profit %", minval = 1)/100
sl_inp = input.int(2, title='Stop Loss %', group = "Take Profit/Stop Loss Settings")/100 //input.int(defval = 1, title = "Stop Loss %", minval = 1)/100    
//Once order at a time
order = input.bool(title="One Position at a time", defval=true, group="Order Sizing")
//Hammer and star inputs
fibLevel    = input.float(title="Fib Level", defval=0.333, group="Hammer and Stars")
colorFilter = input.bool(title="Color Filter", defval=false, group="Hammer and Stars")
aatrFilter   = input.float(title="ATR Filter", defval=0.1, group="Hammer and Stars")
//angle inputs
src = input(title='Source', defval=close, group="Angle of EMA")
guide_pos = input.float(title='Guides Position', defval=45, group="Angle of EMA")
guide_neg = input(title='Guides Position', defval=-45, group="Angle of EMA")
//price2bar_ratio = input(title='Price To Bar Ratio', defval=20.0, group="Angle of EMA")  // Should be the same as that of the Chart
p2br = input(title='Price To Bar Ratio', defval=20.0, group="Angle of EMA")  // Should be the same as that of the Chart
threshold = input(title='Threshold', defval=1.0, group="Angle of EMA")
show_bg = input(title='Show Negative Slope Zone', defval=true, group="Angle of EMA")
smal = input(title='Average angle over how many bars', defval=20, group="Angle of EMA")
emafilter   = input.int(title="EMA length", defval=20, group= "EMA")
//Swing High/Low filter
var g_hl     = "High/Low Filter"
lookback     = input.int(title="Swing High/Low Lookback", defval=10, tooltip="How many bars to look back for swing high/low", group=g_hl)
useHlFilter  = input.bool(title="Use Swing High/Low Filter?", defval=false, tooltip="Turns on/off the swing high/low filter", group=g_hl)
// Filter Settings
var g_filter        = "Entry Candle ATR Size"
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")
price2bar_ratio = request.security(syminfo.tickerid, "D", close) * 0.000025 * p2br
// --------------------------------------------------------------------------------
// Hammer and Candles
// --------------------------------------------------------------------------------
// Check our ATR filter
atr = ta.atr(14)
candleSize = high - low
atrFilterCheck = candleSize >= atr * aatrFilter
// Calculate 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 hammer or shooting star candle
hammerCandle = lowestBody >= bullFib and (not colorFilter or close > open) and atrFilterCheck
starCandle   = highestBody <= bearFib and (not colorFilter or close < open) and atrFilterCheck
// Get swing high/low filter
swingHighFilter = not useHlFilter or (high == ta.highest(high, lookback) or high[1] == ta.highest(high, lookback))
swingLowFilter  = not useHlFilter or (low == ta.lowest(low, lookback) or low[1] == ta.lowest(low, lookback))
// --------------------------------------------------------------------------------
// EMA Angle Functions
// --------------------------------------------------------------------------------
ema = ta.ema(close, emafilter)
get_slope(ema, price2bar_ratio) =>
    180.0 / (2 * math.asin(1)) * math.atan(ta.change(ema) / price2bar_ratio)
// Logic
slope = get_slope(ema, price2bar_ratio)
rise = false
rise := slope - slope[1] > threshold ? true : slope - slope[1] < -threshold ? false : nz(rise[1])
prefall = false
prefall := not rise or slope - slope[1] > 0 ? false : rise and slope - slope[1] < 0 ? true : nz(prefall[1])
prerise = false
prerise := rise or slope - slope[1] < 0 ? false : not rise and slope - slope[1] > 0 ? true : nz(prerise[1])
sma = ta.sma(slope, smal)
// Angle Buy Sell Filter
emapos = sma > guide_pos
emaneg = sma < guide_neg
// --------------------------------------------------------------------------------
// ATR Settings
// --------------------------------------------------------------------------------
// 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)
var int inTrade = 0
order1 = not order or inTrade ==0 
// --------------------------------------------------------------------------------
// Combined Buy and Sell signals
// --------------------------------------------------------------------------------
buy = hammerCandle and emapos and atrFilter and swingLowFilter and barstate.isconfirmed and order1// inTrade == 0
sell = starCandle and emaneg and atrFilter and swingHighFilter and barstate.isconfirmed and order1//inTrade == 0
inpStopLoss = strategy.position_avg_price * (1 - sl_inp)
inpTakeProfit = strategy.position_avg_price * (1 + tp_inp)
if strategy.position_size < 0
    inpStopLoss := strategy.position_avg_price * (1 + sl_inp)
    inpTakeProfit := strategy.position_avg_price * (1 - tp_inp)    
// --------------------------------------------------------------------------------
// View
// --------------------------------------------------------------------------------
plotshape(buy, style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), text = "Long", title='Long', textcolor = color.green)
plotshape(sell, style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), text = "Short", title='Short', textcolor = color.red)
bgcolor(sma > guide_pos ? color.new(color.green, 85) : na)  // highlighting bg when ema angle > 45
bgcolor(sma < guide_neg ? color.new(color.red, 85) : na)
plot(ema, title="EMA", color=color.yellow, linewidth=2)
strategy.entry("Long", direction= strategy.long, when= buy and window())
strategy.entry("Short", direction= strategy.short, when= sell and window())
strategy.exit("Long Exit", from_entry="Long", when=strategy.position_size > 0, limit = inpTakeProfit, stop = inpStopLoss)
strategy.exit("Short Exit", from_entry="Short", when=strategy.position_size < 0, limit = inpTakeProfit, stop = inpStopLoss)
Expand (156 lines)

Overview

NoSKi Hammer Star Backtester % filters setups with an exponential moving average slope angle, optional swing high and low checks, and entry-candle size versus ATR. It opens one position at a time inside a user-defined date window and exits with percentage take profit and stop loss. Settings change the pattern fib level, color filter, EMA length, angle guides, and ATR limits. The script does not document repainting or higher-timeframe lookahead.

Details

Published by

hasnocool on GitHub

Code credit

noski1, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Candlestick patterns, Trend, Volatility & bands

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.

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
From Monthint1FromMonth
From Dayint9FromDay
From Yearint2019FromYear
To Monthint1ToMonth
To Dayint1ToDay
To Yearint9999ToYear
Take Profit %int14tp_inp
Stop Loss %int2sl_inp
One Position at a timebooltrueorder
Fib Levelfloat0.333fibLevel
Color FilterboolfalsecolorFilter
ATR Filterfloat0.1aatrFilter
Show all 24 settings
SettingTypeDefaultVariable
Sourcesourceclosesrc
Guides Positionfloat45guide_pos
Guides Positionint-45guide_neg
Price To Bar Ratiofloat20.0p2br
Thresholdfloat1.0threshold
Show Negative Slope Zonebooltrueshow_bg
Average angle over how many barsint20smal
EMA lengthint20emafilter
Swing High/Low Lookbackint10lookback
Use Swing High/Low Filter?boolfalseuseHlFilter
>= ATR Filterfloat0.0atrMinFilterSize
<= ATR Filterfloat3.0atrMaxFilterSize
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

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

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

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

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

STRG-BBForce

by harryguiacorn
219 stars

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

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

Nasdaq Prop Firm Strategy

by TradersPost
218 stars

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

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

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

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

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