Strategy · Pine Script v5 · On the chart

Regime HA on EMA strategy

by aofwittawat

This overlay strategy classifies trend from a higher-timeframe Heikin Ashi close and an exponential moving average of that close.

View on GitHub

GitHub stars4on the repository
Pine versionv5runs as is
Lines of code85
Settings7inputs
LicenceNone statedfile: MPL-2.0
Last update4 years ago8 Jun 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

85 lines of Pine Script v5 from Regime HA on EMA strategy.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Regime HA on EMA strategy.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © aofwittawat

//@version=5
strategy("Regime HA on EMA strategy", overlay=true)

//Get User Input
var g_regime        = "--------------------- Regime filter settings ---------------------"
res                 = input.timeframe(title = "Timeframe", defval ="240" , group = g_regime)
ema_HA_len          = input.int(title="EMA length calculate with HA", defval = 25, step =10, group =g_regime)
var g_filter        = "--------------------- Backtest settings --------------------- "
startBalance        = input.float(title="Starting Balance", defval=10000.0, group=g_filter, tooltip="Your starting balance for the inbuilt tester system")
i_startTime         = input.time(title="Start Date Filter", defval=timestamp("01 Jan 2019 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")
useRegime           = input.bool(title= "Show Regime in Chart", defval = true)
showEMA             = input.bool(title="Show EMA in chart", defval = true)


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

//Define custom security function
f_sec(_market ,_res, _exp) 
     => request.security(ticker.heikinashi(syminfo.tickerid),_res,_exp[barstate.isconfirmed ? 0 : 1])

//HA calculate close price
HA_close    = f_sec(ticker.heikinashi(syminfo.tickerid), res, close)

//Get EMA value filter
atr         = ta.atr(14)
ema_HA      = ta.ema(HA_close,ema_HA_len)
emaValue    = f_sec(ticker.heikinashi(syminfo.tickerid), res, ema_HA)


//Check marketprice is above or below EMA_HA filter
marketPrice     = f_sec(syminfo.tickerid, res, HA_close)
regimeFilter    = marketPrice > emaValue 

//Entry
validLong   = false
validShort  = false

//Detect trade setup
if regimeFilter and barstate.isconfirmed and dateFilter 
    validLong  := true
    validShort := false
    strategy.entry(id="Long", direction = strategy.long, comment = "Long")
    strategy.close(id="Short",when=strategy.position_size < 0)
if regimeFilter == false and barstate.isconfirmed and dateFilter 
    validShort := true
    validLong  := false
    strategy.entry(id="Short", direction = strategy.short, comment = "Short")
    strategy.close(id="Long", when=strategy.position_size > 0)
    

//Draw indicators
plotshape(useRegime, style=shape.square, size =size.normal, location = location.bottom, color = regimeFilter ? color.green : color.red, title = "Regime Filter")
plot(showEMA ? ema_HA : na)

plotchar(validLong, color = color.new(color.green,100))
plotchar(validShort, color = color.new(color.red,100))

// =============================================================================
// START BACKTEST CODE
// =============================================================================

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

// Prepare stats table
var 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 table
var bgcolor = color.black
if barstate.islastconfirmedhistory
    if true
        f_fillCell(testTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
        f_fillCell(testTable, 0, 1, "Win Rate:", str.tostring(zen.truncate(strategy.wintrades / strategy.closedtrades * 100)) + "%", bgcolor, color.white)
     
// =============================================================================
// END BACKTEST CODE
// =============================================================================

Overview

When the confirmed price is above the average it enters long and closes any short; when price is below it enters short and closes any long. Entries are limited to a user date range. The default regime timeframe and EMA length are adjustable, and optional squares plus the EMA can be shown on the chart. It has no stop loss or take profit.

Details

Published by

aofwittawat on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages

Markets

Any symbol

Timeframes

H4 and above

Risk Notes

  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
Timeframetimeframe240res
EMA length calculate with HAint25ema_HA_len
Starting Balancefloat10000.0startBalance
Start Date Filtertimetimestamp("01 Jan 2019 13:30 +0000")i_startTime
End Date Filtertimetimestamp("1 Jan 2099 19:30 +0000")i_endTime
Show Regime in ChartbooltrueuseRegime
Show EMA in chartbooltrueshowEMA
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

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated today · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
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
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 6 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar

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