Strategy · Pine Script v5 · On the chart

HG Strat

by benso87

This strategy implements an ADX trend-following system with moving average pullbacks.

View on GitHub

GitHub stars24on the repository
Pine versionv5runs as is
Lines of code160
Settings9inputs
LicenceMPL-2.0
Last update4 years ago5 Oct 2022

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

160 lines of Pine Script v5 from Holy Grail Strategy.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

Holy Grail Strategy.pine
//@version=5
//
// Author: benso87
// benso87.com
//
//
strategy("Holy Grail Strat", overlay=true, initial_capital=100, default_qty_value=100, default_qty_type=strategy.percent_of_equity, process_orders_on_close=true, backtest_fill_limits_assumption=1, pyramiding=0, max_bars_back=500)

noColor = color.new(color.white, transp=100)
////////////////////////////////////////////////////////////
// Inputs

//Dates
startDate = input.time(timestamp('1 Jan 2022 00:00'), title='Start', group='Dates')
endDate = input.time(timestamp('1 Jan 2100 00:00'), title='End', group='Dates')

// Moving Average
maLength = input.int(20, title='MA Length', minval=1, group='Moving Average')
maType = input.string('EMA', title='MA Type', options=['SMA', 'EMA'], group='Moving Average')
maSource = input.source(close, title='MA Source', group='Moving Average')

// ADX
adxLength = input.int(14, title='ADK Length', minval=1, group='ADX')
adxLevel = input.float(30, title='Signal Level', minval=0, maxval=100, group='ADX')

// Swings
pvtLenL = input.int(3, minval=1, title='Pivot Length Left')
pvtLenR = input.int(3, minval=1, title='Pivot Length Right')

////////////////////////////////////////////////////////////
// Calculations

// Moving Average
ma = maType == 'EMA' ? ta.ema(maSource, maLength) : ta.sma(maSource, maLength)

// ADX
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, adxLength)
plus = fixnan(100 * ta.rma(plusDM, adxLength) / trur)
minus = fixnan(100 * ta.rma(minusDM, adxLength) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxLength)

var bool adxWindow = na
adxWindow := ta.crossover(adx,adxLevel) ? true : ta.crossunder(adx,adxLevel) ? false : adxWindow

// MA tests
maTestLong = open > ma and close >= ma and low <= ma and adxWindow
maTestShort = open < ma and close <= ma and high >= ma and adxWindow

var bool testWindowLong = na
var float testHigh = na
var float testLow = na
var bool testWindowShort = na

if maTestLong or maTestShort
    testHigh := high
    testLow := low

if maTestLong
    testWindowLong := true

if maTestShort
    testWindowShort := true

if close < ma or adx < adxLevel
    testWindowLong := false

if close > ma or adx < adxLevel
    testWindowShort := false

maSignalLong = testWindowLong and close >= testHigh and time >= startDate and time <= endDate
maSignalShort = testWindowShort and close <= testLow and time >= startDate and time <= endDate

// Get High and Low Pivot Points
pvthi_ = ta.pivothigh(high, pvtLenL, pvtLenR)
pvtlo_ = ta.pivotlow(low, pvtLenL, pvtLenR)

// Force Pivot completion before plotting.
Shunt = 1  //Wait for close before printing pivot? 1 for true 0 for flase
maxLvlLen = 0  //Maximum Extension Length
pvthi = pvthi_[Shunt]
pvtlo = pvtlo_[Shunt]

// Count How many candles for current Pivot Level, If new reset.
counthi = ta.barssince(not na(pvthi))
countlo = ta.barssince(not na(pvtlo))

pvthis = fixnan(pvthi)
pvtlos = fixnan(pvtlo)
hipc = ta.change(pvthis) != 0 ? na : #ff0014
lopc = ta.change(pvtlos) != 0 ? na : #0bff00

// Entries
longEntry = adxWindow and maSignalLong and close <= pvthis
shortEntry = adxWindow and maSignalShort and close >= pvtlos

// Trade variables
var float entryPrice = na
var float slLong = na
var float slShort = na
var float tpLong = na
var float tpShort = na
var float testHighVar = na
var float testLowVar = na
var string tradeType = na

if longEntry and strategy.position_size == 0
    entryPrice := close
    slLong := testLow
    tpLong := pvthis
    tradeType := 'long'
    adxWindow := false

if shortEntry and strategy.position_size == 0
    entryPrice := close
    slShort := testHigh
    tpShort := pvtlos
    tradeType := 'short'
    adxWindow := false

stopLoss = tradeType == 'long' ? slLong : tradeType == 'short' ? slShort : na
takeProfit = tradeType == 'long' ? tpLong : tradeType == 'short' ? tpShort : na
trailSize = tradeType == 'long' ? (close - ma) * syminfo.mintick : tradeType == 'short' ? (ma - close) * syminfo.mintick : na


//////////////////////////////////////////////////////////////
// Strategy

// Entries
if strategy.position_size == 0
    strategy.entry('Long', strategy.long, when=longEntry)
    strategy.entry('Short', strategy.short, when=shortEntry)

// Exits
strategy.exit('Long Exit', from_entry='Long', stop=slLong, trail_price=tpLong, trail_points=trailSize)
strategy.exit('Short Exit', from_entry='Short', stop=slShort, trail_price=tpShort, trail_points=trailSize)


////////////////////////////////////////////////////////////
// Plots

plot(ma, title='MA', color=color.yellow, linewidth=2)
plotchar(maTestLong, color=#0bff00, char='·', location=location.abovebar, size=size.normal)
plotchar(maTestShort, color=#ff0014, char='·', location=location.belowbar, size=size.normal)

// Trades
sl = plot(strategy.position_size != 0 or strategy.position_size[1] != 0 ? stopLoss : na, title='Stop Loss', color=color.red, style=plot.style_linebr)
e = plot(strategy.position_size != 0 or strategy.position_size[1] != 0 ? entryPrice : na, title='Entry', color=color.yellow, style=plot.style_linebr)
tp = plot(strategy.position_size != 0 or strategy.position_size[1] != 0 ? takeProfit : na, title='Take Profit', color=color.green, style=plot.style_linebr)

fill(sl, e, color=color.new(color.red, transp=80))
fill(tp, e, color=color.new(color.green, transp=80))


//////////////////////////////////////////////////////////////
// Testing

Overview

HG Strat identifies strong market momentum when the Average Directional Index exceeds a chosen threshold, then monitors price retests of an exponential or simple moving average. Long entries trigger when price touches the average from above and subsequently breaks above the pullback candle high while below recent pivot highs. Short entries mirror this behavior below the average. Users can configure the moving average type, period, ADX threshold, and pivot swing lengths. The strategy plots trade signals directly on the price chart.

Details

Published by

benso87 on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Oscillators & momentum, Moving averages

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
Starttimetimestamp('1 Jan 2022 00:00')startDate
Endtimetimestamp('1 Jan 2100 00:00')endDate
MA Lengthint20maLength
MA TypestringEMAmaType
MA SourcesourceclosemaSource
ADK Lengthint14adxLength
Signal Levelfloat30adxLevel
Pivot Length Leftint3pvtLenL
Pivot Length Rightint3pvtLenR
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

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy

This strategy combines Arnaud Legoux Moving Average percentage price change calculations with an adaptive Gaussian Moving Average to generate trend-following signals. Long and short entries are triggered when the ALMA change calculation crosses above or below

Strategy v5 Moving averagesOscillators & momentum
Updated 6 weeks ago · None stated GitHub repository of ESM2024 - ALMA Smoothed Gaussian Moving Average
218 stars

This strategy generates trading signals based on a selectable momentum engine, supporting MACD, RSI, Stochastic, or Rate of Change. Entries trigger on signal crosses, zero-line crosses, or threshold crosses, with an optional moving average trend filter. Risk m

Strategy v6 Oscillators & momentumTrend
Updated 3 months ago · None stated GitHub repository of Momentum Strategy Template

255 EMA Strategy

by hasnocool
106 stars

255 EMA Strategy combines an exponential moving average with Average True Range bands and standard MACD crossovers to generate entry signals. Drawn directly on the price chart, it plots the central 255 EMA along with upper and lower volatility envelopes. Trade

Strategy v4 Moving averagesOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 255 EMA Strategy

SMA RSI Strategy

by PythonForForex
64 stars

This strategy evaluates simple moving averages and the Relative Strength Index to generate trading signals. It calculates a 10-period SMA, a 30-period SMA, and a 14-period RSI. Long positions are entered when the fast SMA crosses above the slow SMA while RSI i

Strategy v5 TrendOscillators & momentum
Updated 4 years ago · None stated GitHub repository of SMA RSI 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