Strategy · Pine Script v4 · On the chart

Backtest Custom HiLo Strategy

by hasnocool· code credited to luyikaibr

Backtest Custom HiLo Strategy overlays a high-low trailing line on the price chart calculated from moving averages of highs and lows.

View on GitHub

GitHub stars106on the repository
Pine versionv4older, still runs
Lines of code102
Settings15inputs
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

102 lines of Pine Script v4 from Backtest Custom HiLo Strategy.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

Backtest Custom HiLo Strategy.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © luyikaibr
//@version=4
strategy("Backtest Custom HiLo Strategy", "BTCHiLoS", overlay=true, precision=2,
         process_orders_on_close=true,
         pyramiding=1,
         close_entries_rule="FIFO",
         initial_capital=100000, 
         default_qty_type=strategy.percent_of_equity,
         default_qty_value=100.0)
// Configure backtest start date with inputs
startDay = input(title="Start Day", type=input.integer,
     defval=2, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer,
     defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer,
     defval=2020, minval=1800, maxval=2100)
// Set backtest end date with inputs
endDay = input(title="End Day", type=input.integer,
     defval=31, minval=1, maxval=31)
endMonth = input(title="End Month", type=input.integer,
     defval=10, minval=1, maxval=12)
endYear = input(title="End Year", type=input.integer,
     defval=2020, minval=1800, maxval=2100)
     
endHour = input(title="End Hour", type=input.integer,
     defval=17, minval=0, maxval=23)
endMin = input(title="End Minute", type=input.integer,
     defval=0, minval=0, maxval=59)
startAtOrigin = input(false, title="Start at Origin")
endNow = input(false, title="End Now")
len = input(34, title="Length", minval=0)
offset = input(0, title="Offset", minval=0)
hiloType = input(title="Type", defval="HiLo", options=["HiLo", "HiLo Activator"])
simpleHiLo = (hiloType == "HiLo")
maType = input(title="MA Type", defval="SMA", options=["SMA", "EMA"])
useEMA = (maType == "EMA")
opType = input(title="Operation Type", defval="Long", options=["Long", "Short", "Both"])
opShort = (opType != "Long")
opLong  = (opType != "Short")
opBoth  = (opType == "Both")
hima = (useEMA ? ema(high, len) : sma(high, len))
loma = (useEMA ? ema(low, len) : sma(low, len))
hihi = (simpleHiLo ? na: highest(high, len))
lolo = (simpleHiLo ? na: lowest(low, len))
hilo = close
hilo := if simpleHiLo
    (close < loma[offset] ? hima : (close > hima[offset] ? loma : hilo[1]))
else
    (close < loma[offset] ? hihi : (close > hima[offset] ? lolo : hilo[1]))
hlColor = color.red
hlColor := (close < loma[offset] ? color.red : (close > hima[offset] ? color.green : hlColor[1]))
buyArith  = sign(close - hima[offset])
sellArith = sign(close - loma[offset])
buyCond = (close > hima[offset])
sellCond = (close < loma[offset])
buy = crossover(buyArith, 0.5)
sell = crossunder(sellArith, -0.5)
buyState = false
buyState :=  buy ? true : (sell ? false : buyState[1])
sellState = false
sellState :=  buy ? false : (sell ? true : sellState[1])
enterBuyState  = buyState[0]  and not buyState[1]
enterSellState = sellState[0] and not sellState[1]
 
plot(hilo, color=hlColor, linewidth=2, style=plot.style_cross, transp=0, title="HiLo")
plotshape(enterBuyState,  title = "Buy", text = 'Buy', style = shape.labelup, location = location.belowbar, color= color.green,textcolor = color.white, transp = 0, size = size.tiny)
plotshape(enterSellState, title = "Sell", text = 'Sell', style = shape.labeldown, location = location.abovebar, color= color.maroon,textcolor = color.white, transp = 0, size = size.tiny)
// See if this bar's time happened on/after start date
startDate = timestamp(syminfo.timezone, startYear, startMonth, startDay, 0, 0)
afterStartDate = if startAtOrigin
    true
else
    (time >= startDate)
atStartDate = if startAtOrigin
    false
else
    (time >= startDate and time < (startDate + time_close[1]-time_close[2]))
     
// See if bar's close time is before end date
endTS = if endNow
    timenow - 2*(time_close[1]-time_close[2]) // 86400
else
    timestamp(syminfo.timezone, endYear, endMonth, endDay, endHour, endMin, 0)
beforeEndDate = (time < endTS)
// Only submit enter long orders
strategy.risk.allow_entry_in(opBoth ? strategy.direction.all : (opLong ? strategy.direction.long : strategy.direction.short))
// Submit entry orders, but only on/after start date
if (atStartDate and beforeEndDate and buyCond)
    strategy.entry(id="EL", long=true)
if (atStartDate and beforeEndDate and sellCond)
    strategy.entry(id="ES", long=false)
if (afterStartDate and beforeEndDate and enterBuyState)
    strategy.entry(id="EL", long=true)
if (afterStartDate and beforeEndDate and enterSellState)
    strategy.entry(id="ES", long=false)
              
// if (barstate.islast or not beforeEndDate)
if (not beforeEndDate and strategy.position_size != 0)
    strategy.close_all(comment="End")
    
Expand (131 lines)

Overview

Backtest Custom HiLo Strategy establishes upper and lower bounds using simple or exponential moving averages along with optional period extremes. Signal entries occur when the closing price crosses above the high average or below the low average. The script allows backtesting long, short, or both trade directions within customizable date ranges. There are no built-in stop loss or take profit rules.

Details

Published by

hasnocool on GitHub

Code credit

luyikaibr, as written in the script's header

Type

Strategy, Pine Script v4

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
Start Dayint2startDay
Start Monthint1startMonth
Start Yearint2020startYear
End Dayint31endDay
End Monthint10endMonth
End Yearint2020endYear
End Hourint17endHour
End Minuteint0endMin
Start at OriginboolfalsestartAtOrigin
End NowboolfalseendNow
Lengthint34len
Offsetint0offset
Show all 15 settings
SettingTypeDefaultVariable
TypestringHiLohiloType
MA TypestringSMAmaType
Operation TypestringLongopType
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 yesterday · 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

EMA Crossover Strategy

by TradersPost
228 stars

EMA Crossover Strategy plots a fast and a slow exponential moving average on the price chart. It treats a confirmed fast-over-slow cross as a long condition and a confirmed cross under as a short condition. Position size is a percentage of equity. Optional per

Strategy v6 TrendMoving averages
Updated 3 months ago · None stated GitHub repository of EMA Crossover Strategy

More Moving averages 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