Ramisegal
Active member
The strategy will allow settings which will have unrealistic P&L results.
I keep it that way to assist me with my entry in the active trader tab.
Set the EntryOrderOffset to zero or the signal delay to 1 to avoid repainting the signaled trigger bar.
In this video I used the strategy as is in a live market to illustrate it (this is not a recommendation).
The alerts don't get triggered, I am not sure why.
I keep it that way to assist me with my entry in the active trader tab.
Set the EntryOrderOffset to zero or the signal delay to 1 to avoid repainting the signaled trigger bar.
In this video I used the strategy as is in a live market to illustrate it (this is not a recommendation).
The alerts don't get triggered, I am not sure why.
Code:
## HILOTrailStrategy
## START STRATEGY
##
input EnableStrategy = yes;
input UseMarketTime = no; #hint UseMarketTime: Use Trading hours?
input TradeTimeStart = 0930;
input TradeTimeEnd = 1555;
input UseTradeOffTradeTime = no;
input UseMarketTradeTimeToExitPositions = no; #hint UseMarketTradeTimeToExitPositions: Exit/Close open trades based on the market hours selected
input UseDateRange = no; #hint UseDateRange: Trade Signals within the date range specified
input ActiveStartDate = 20230101;
input ActiveEndDate = 20240101;
def activedaterange = GetYYYYMMDD() >= ActiveStartDate and GetYYYYMMDD() <= ActiveEndDate;
def activerange = if UseDateRange then activedaterange else 1;
AddLabel(UseDateRange, if activerange then "Range " + AsPrice(ActiveStartDate) + " - " + AsPrice(ActiveEndDate) else "" , Color.WHITE );
def Active = if GetDay() != GetDay()[1]
then 0
else if SecondsTillTime(TradeTimeStart) <= 0 and
SecondsTillTime(TradeTimeEnd) >= 0
then 1
else 0;
def ActiveTradeTime = if UseTradeOffTradeTime then !Active else if UseMarketTime then if SecondsTillTime(TradeTimeStart) <= 0 and
SecondsTillTime(TradeTimeEnd) >= 0 then 1 else 0
else 1;
def closeallmarket = ( if UseMarketTime and UseTradeOffTradeTime then !Active[1] and Active and UseMarketTradeTimeToExitPositions else !ActiveTradeTime and ActiveTradeTime[1]) and UseMarketTradeTimeToExitPositions;
input ShowTime = yes;
input TimeZone = 10.5;
def Hours = Floor(TimeZone + SecondsFromTime(0930) / 60 / 60) - 1;
def Minutes = ((TimeZone + SecondsFromTime(930) / 60 / 60) % 1) * 60;
AddLabel(ShowTime, "HILOTrailStrategy: Market Time: " + GetMonth() + "/" + GetDayOfMonth(GetYYYYMMDD()) + "/" + (AsPrice(GetYear())) + ":" + Hours + ":" + Minutes ,
if !IsNaN(GetTime())
then Color.LIME
else if IsNaN(GetTime())
then Color.PINK
else Color.WHITE);
#hint: Entry signals are taken when price sufficiently crosses the HILO lines that are constructed by previous highest highs and lowest lows over the input periods. Exit signals are taken when price touches the Trail plots after a percentage gain is met.
input nFast = 13; #hint nFast: HILO Trail fast period.
input nSlow = 34; #hint nSlow: HILO Trail slow period.
input trailType = {default AVG, FAST, SLOW}; #hint trailType: AVG uses the average of the fast and slow HILO lines; FAST uses the fast HILO line; SLOW uses the slow HILO line.
input price = close; #hint price: Fundamental price type for calculating HILO lines. Also used in constructing signals and Trail plots.
input bandType = {default BB, KC}; #hint bandType: Set the Trail adjust band type. (BB is BollingerBands, KC is KeltnerChannels)
input bandAvgType = AverageType.SIMPLE; #hint bandAvgType: Moving average type for BB or KC.
input bandLength = 20; #hint bandLength: BB or KC average period, and smoothing length for Stdev or ATR respectively.
input bandFactor = 2.0; #hint bandFactor: BB or KC multiplier to offet upper and lower bands. (BB is 2.0 by default, KC is 1.5 by default)
input tradeSize = 1; #hint tradeSize: Number of shares/contracts per order.
input targetPercent = 5.0; #hint targetPercent: Close orders on Trail touches after this percentage gain.
input EntryOrderPrice = open; #hint orderPrice: Enter orders at this price, used with orderOffset.
input EntryOrderOffset = -1; #hint orderOffset: Offset orderPrice forward (if negative) or back (if positive). Also offsets the order arrows.
input paintBars = {default OFF, ORDER, PRICE}; #hint paintBars: ORDER colors the price bars by entry direction; PRICE colors the price bars with Heikin Ashi and price; OFF uses the default price bar colors.
def haDiff = HeikinAshiDiff();
def HHF = Highest(high[1], nFast);
def LLF = Lowest(low[1], nFast);
def HHS = Highest(high[1], nSlow);
def LLS = Lowest(low[1], nSlow);
def HH;
def LL;
switch (trailType){
case AVG:
HH = (HHS + HHF) / 2;
LL = (LLS + LLF) / 2;
case FAST:
HH = HHF;
LL = LLF;
case SLOW:
HH = HHS;
LL = LLS;
}
def signal = if IsNaN(close) then signal[1]
else if high > HH and price > HHF
and low > LLF then 1
else if low < LL and price < LLF
and high < HHF then -1
else if signal[1] < 0
and low > HH then 2
else if signal[1] > 0
and high < LL then -2
else signal[1];
def Avg = MovingAverage(bandAvgType, price, bandLength);
def shift = if bandType == bandType.BB
then StDev(price, bandLength)
else MovingAverage(bandAvgType,
TrueRange(high, close, low), bandLength);
plot TrailU;
plot TrailD;
def UB = Avg + shift * bandFactor;
def LB = Avg - shift * bandFactor;
def prDir =
if haDiff > 0 and price > price[1] then 1
else if haDiff < 0 and price < price[1] then -1
else prDir[1];
def Trail_;
def adjHH =
if prDir > 0 or low < LB
then (HH + high) / 2
else HH;
def adjLL =
if prDir < 0 or high > UB
then (LL + low) / 2
else LL;
Trail_ =
if IsNaN(close[0]) then
Trail_[1] + (Trail_[1] - Trail_[2])
else if signal crosses 0 then
if signal > 0 then
if LL < LB then LB else LL
else if HH > UB then UB else HH
else if signal > 0 and adjLL > Trail_[1] then adjLL
else if signal < 0 and adjHH < Trail_[1] then adjHH
else Trail_[1];
TrailU = if Trail_ == 0 or IsNaN(close[1]) or signal <= 0 then Double.NaN else Trail_;
#TrailU.SetDefaultColor(CreateColor(51, 255, 255));
TrailU.SetDefaultColor(color.lime);
TrailU.SetLineWeight(2);
TrailU.HideBubble();
TrailU.HideTitle();
TrailD = if Trail_ == 0 or IsNaN(close[1]) or signal >= 0 then Double.NaN else Trail_;
#TrailD.SetDefaultColor(CreateColor(255, 51, 204));
TrailD.SetDefaultColor(color.magenta);
TrailD.SetLineWeight(2);
TrailD.HideBubble();
TrailD.HideTitle();
def orderAuto;
def exitToClose;
orderAuto = CompoundValue(1,
if IsNaN(close) then orderAuto[1]
else if signal crosses above 0 then 1
else if signal crosses below 0 then -1
else if exitToClose[1] crosses 0 then 0
else orderAuto[1]
, 0);
def entry = EntryorderPrice[EntryorderOffset];
def exit = EntryorderPrice[EntryorderOffset];
def entryPrice = EntryPrice();
def exitTarget = targetPercent * entryPrice / 100;
exitToClose = if IsNaN(entryPrice) then exitToClose[1]
else if orderAuto crosses 0 then 0
else if high > Trail_ and entry <= entryPrice - exitTarget then 1
else if low < Trail_ and entry >= entryPrice + exitTarget then -1
else exitToClose[1];
def Buy = tradeSize > 0 and orderAuto[EntryorderOffset] == 1 and orderAuto[EntryorderOffset + 1] != 1;
def Sell = tradeSize > 0 and orderAuto[EntryorderOffset] == -1 and orderAuto[EntryorderOffset + 1] != -1;
def BuyTC = tradeSize > 0 and exitToClose[EntryorderOffset] crosses above 0;
def SellTC = tradeSize > 0 and exitToClose[EntryorderOffset] crosses below 0;
input ShowVerticalEntryExitSignals = yes;
addverticalLine(ShowVerticalEntryExitSignals and Buy,"B",color.green);
addverticalLine(ShowVerticalEntryExitSignals and Sell,"S",color.red);
addverticalLine(ShowVerticalEntryExitSignals and BuyTC,"Bx",color.white);
addverticalLine(ShowVerticalEntryExitSignals and SellTC,"Sx",color.white);
input ShowEntryExitBubbles = yes;
AddChartBubble(ShowEntryExitBubbles and ( Buy or Sell), if Buy then lowest(close,nFast)[1] else highest(high,nFast)[1], if Buy then "Risk On" else if Sell then "Risk Off" else "", if Buy then Color.GREEN else Color.RED, if Buy then 0 else 1);
AddChartBubble(ShowEntryExitBubbles and (BuyTC or SellTC),if Buy then lowest(close,nFast)[1] else highest(high,nFast)[1], if BuyTC then "Risk On Chopp" else "Risk Off Chopp", if BuyTC then Color.light_GREEN else Color.light_RED, if BuyTC then 0 else 1);
AssignPriceColor(
if !paintBars then Color.CURRENT
else if paintBars == paintBars.PRICE then
if prDir > 0 and price > Avg then Color.UPTICK
else if prDir < 0 and price < Avg then Color.DOWNTICK
else Color.GRAY
else if !IsNaN(Trail_) then
if IsNaN(close[-1]) or IsNaN(close[EntryorderOffset]) then
if signal > 0 then
if prDir > 0 then Color.UPTICK else Color.DARK_GREEN
else if signal < 0 then
if prDir < 0 then Color.DOWNTICK else Color.DARK_RED
else Color.GRAY
else if orderAuto[EntryorderOffset] > 0 then
if prDir > 0 then Color.UPTICK else Color.DARK_GREEN
else if orderAuto[EntryorderOffset] < 0 then
if prDir < 0 then Color.DOWNTICK else Color.DARK_RED
else Color.GRAY
else Color.DARK_GRAY
);
input FractalCalculationsLength = 13; #hint FractalCalculationsLength: Periods or Length for the fractal calculations
input Periods_for_the_Smoothed_Signal_Line = 5; #hint Periods_for_the_Smoothed_Signal_Line: Periods for the Smoothed Signal Line.
def IV = if IsNaN(imp_volatility(period = AggregationPeriod.DAY))
then IV[1]
else imp_volatility(period = AggregationPeriod.DAY);
def HTH = Highest(Max(high, close[1]), FractalCalculationsLength);
def LTL = Lowest(Min(low, close[1]), FractalCalculationsLength);
def CIb = (((close * IV) / (HTH - LTL)) / Log(10));
def CI = WildersAverage(CIb, Periods_for_the_Smoothed_Signal_Line);
AddLabel(1, if CI < CI[1] then "Trending" else "Choppy", if CI < CI[1] then Color.GREEN else Color.RED);
input PaintFractalCalculationsBars = no;
AssignPriceColor( if PaintFractalCalculationsBars then if CI < CI[1]
then if signal > 0 then if close > open then Color.LIME else color.white else if signal < 0
then if close < open then Color.MAGENTA else color.white else Color.CURRENT else Color.GRAY else Color.CURRENT ) ;
Input UseFractal = no;
Input UseFractalStops = no;
input OrderSimbol = no;
input SignalDelay = 0;
input useStops = yes;
input useEntryAlerts = no;
input useSignalAlerts = no;
input showSignalLines = yes;
input showSignals = yes;
def BuyStop_ind = ( usestops and ( (BuyTC and if !UseFractal then 1 else CI < CI[1]) or ( if UseFractalStops then BuyTC and CI[1] > CI[0] else UseFractalStops)));
def SellStop_ind = (closeAllmarket or !activerange) or (usestops and ( (SellTC and if !UseFractal then 1 else CI < CI[1]) or ( if UseFractalStops then SellTC and CI[1] > CI[0] else UseFractalStops)) );
def buysignal_ind = Buy and if !UseFractal then 1 else CI < CI[1] ;
def SellSignal_ind = Sell and if !UseFractal then 1 else CI < CI[1] ;
def BuySignal = buysignal_ind[SignalDelay];
def SellSignal = SellSignal_ind[SignalDelay] ;
def BuyStop = BuyStop_ind[SignalDelay] or (closeAllmarket or !activerange) ;
def SellStop = SellStop_ind[SignalDelay] or (closeAllmarket or !activerange) ;
#######################################
## Maintain the position of trades
#######################################
def CurrentPosition; # holds whether flat = 0 long = 1 short = -1
if (BarNumber() == 1) or IsNaN(CurrentPosition[1]) {
CurrentPosition = 0;
} else {
if CurrentPosition[1] == 0 { # FLAT
if (BuySignal) {
CurrentPosition = 1;
} else if (SellSignal) {
CurrentPosition = -1;
} else {
CurrentPosition = CurrentPosition[1];
}
} else if CurrentPosition[1] == 1 { # LONG
if (SellSignal) {
CurrentPosition = -1;
} else if (BuyStop) {
CurrentPosition = 0;
} else {
CurrentPosition = CurrentPosition[1];
}
} else if CurrentPosition[1] == -1 { # SHORT
if (BuySignal) {
CurrentPosition = 1;
} else if (SellStop) {
CurrentPosition = 0;
} else {
CurrentPosition = CurrentPosition[1];
}
} else {
CurrentPosition = CurrentPosition[1];
}
}
def isLong = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;
def isFlat = if CurrentPosition == 0 then 1 else 0;
def isOrder = if CurrentPosition == CurrentPosition[1] then 0 else 1; # Status changed so it's a new order
# If not already long and get a BuySignal
plot BuySig = if (!isLong[1] and BuySignal and showSignals) then 1 else 0;
BuySig.AssignValueColor(Color.CYAN);
BuySig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySig.SetLineWeight(5);
# If not already short and get a SellSignal
plot SellSig = if (!isShort[1] and SellSignal and showSignals) then 1 else 0;
SellSig.AssignValueColor(Color.CYAN);
SellSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSig.SetLineWeight(5);
# If long and get a BuyStop
plot BuyStpSig = if (CurrentPosition == 0 and isLong[1] and showSignals and useStops) then 1 else 0;
BuyStpSig.AssignValueColor(Color.LIGHT_GRAY);
BuyStpSig.SetPaintingStrategy(if showSignalLines then PaintingStrategy.dASHES else PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig.SetLineWeight(3);
# If short and get a SellStop
plot SellStpSig = if (CurrentPosition == 0 and isShort[1] and showSignals and useStops) then 1 else 0;
SellStpSig.AssignValueColor(Color.LIGHT_GRAY);
SellStpSig.SetPaintingStrategy(if showSignalLines then PaintingStrategy.dASHES else PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig.SetLineWeight(3);
def SignalEntryorderPrice = if (isOrder and (BuySignal or SellSignal)) then open[-1] else SignalEntryorderPrice[1];
def pricelevel = SignalEntryorderPrice;
def buypricelevel = if Buy then pricelevel else buypricelevel[1];
def sellpricelevel = if Sell then pricelevel else sellpricelevel[1];
def pbp = if buypricelevel <> buypricelevel[1] then buypricelevel[1] else pbp[1];
def psp = if sellpricelevel <> sellpricelevel[1] then sellpricelevel[1] else psp[1];
def riskon = close > buypricelevel and signal > 0 and buypricelevel > pbp and sellpricelevel > psp and buypricelevel > sellpricelevel;
def riskoff = close < sellpricelevel and signal < 0 and buypricelevel < pbp and sellpricelevel < psp and sellpricelevel < buypricelevel;
addverticalLine(riskon and !riskon[1], "Risk On", color.green);
addverticalLine(riskoff and !riskoff[1], "Risk Off", color.red);
plot OrderBlock = pricelevel;
OrderBlock.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
OrderBlock.SetDefaultColor(color.cyan);
OrderBlock.SetPaintingStrategy(PaintingStrategy.DASHES);
OrderBlock.assignValueColor(if signal > 0 then color.green else if ( ( signal < 0 )) then color.red else color.white);
def buyalert = (BuySignal);
def sellalert = ( SellSignal);
def alertprice = if IsNaN(EntryPrice()) then 0 else EntryPrice();
def alertposchange = ( alertprice <> alertprice[1] and alertprice == 0 ) or ( alertprice <> alertprice[1] and alertprice[1] == 0 ) or ( alertprice <> alertprice[1] and alertprice[1] > 0 and alertprice[0] > 0 );
def Activealert = (useEntryAlerts and alertposchange and absValue(alertprice-alertprice[1] )>0) or ( useSignalAlerts and (sellalert or buyalert)) ;
Alert(Activealert and buyalert, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(Activealert and sellalert, "Sell Signal" , Alert.BAR, Sound.Ding);
def highestclosehigh = if close > if isnan(highestclosehigh[1]) then high else highestclosehigh[1] then high else if signal < 0 and signal[1] > 0 then high else highestclosehigh[1];
def highestclosehighlow = if highestclosehigh <> highestclosehigh[1] then low else highestclosehighlow[1];
plot hcl = if signal > 0 then highestclosehighlow else double.nan;
hcl.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
hcl.SetDefaultColor(color.yellow);
hcl.assignvalueColor(if close < highestclosehighlow then color.gRAY else color.current);
def lowestcloselow = if close < if isnan(lowestcloselow[1]) then low else lowestcloselow[1] then low else if signal > 0 and signal[1] < 0 then low else lowestcloselow[1];
def lowestcloselowhigh = if lowestcloselow <> lowestcloselow[1] then high else lowestcloselowhigh[1];
plot lch = if signal < 0 then lowestcloselowhigh else double.nan;
lch.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
lch.SetDefaultColor(color.magenta);
lch.assignvalueColor(if close > lowestcloselowhigh then color.gRAY else color.current);
input ShowRiskFadeBubble = no;
AddChartBubble(ShowRiskFadeBubble and (high < Trail_ and signal < 0 and low crosses above lowestcloselowhigh ) or (low > Trail_ and signal > 0 and high crosses below highestclosehighlow) , if signal > 0 then lowest(close,nFast)[1] else highest(high,nFast)[1], if signal > 0 then "Risk On" else if signal < 0 then "Risk Off" else "", if signal > 0 then Color.gray else Color.gray, if signal > 0 then 0 else 1);
def bar = barNumber();
def Today = getDay() == getLastDay();
def RTH = if SecondsFromTime(0930) >= 0 and SecondsTillTime(1600) >= 0 then 1 else 0;
def RTH_Bar1 = if RTH and !RTH[1] then bar else double.nan;
Script T{
def RTH = if SecondsFromTime(0930) >= 0 and
SecondsTillTime(1600) >= 0
then 1
else 0;
def cT = if RTH and !RTH[1]
then 1
else if RTH
then cT[1] + 1
else cT[1];
plot Data = if RTH then cT else double.nan;
}
AddVerticalLine(T().RTH and !t().RTH[1], "Open", Color.light_Gray, Curve.Long_Dash);
AddVerticalLine(SecondsTillTime(1030) == 0 and
SecondsFromTime(1030) == 0, "EU", Color.light_Gray, Curve.Long_Dash);
AddVerticalLine(SecondsTillTime(1200) == 0 and
SecondsFromTime(1200) == 0, "Noon", Color.light_Gray, Curve.Long_Dash);
AddVerticalLine(SecondsTillTime(1500) == 0 and
SecondsFromTime(1500) == 0, "Last H", Color.light_Gray, Curve.Long_Dash);
AddVerticalLine(!T().RTH and T().RTH[1], "Close", Color.light_Gray, Curve.Long_Dash);
AddOrder(OrderType.BUY_AUTO, EnableStrategy and activerange and ActiveTradeTime and BuySignal, name = if OrderSimbol then "B" else "B(*)@ " +open[-1], price = open[-1], tradesize = tradesize, tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO, EnableStrategy and activerange and ActiveTradeTime and SellSignal, name = if OrderSimbol then "S" else "S(*)@ " + open[-1], price = open[-1], tradesize = tradesize, tickcolor = GetColor(4), arrowcolor = GetColor(4));
AddOrder(OrderType.BUY_to_close,EnableStrategy and activerange and ActiveTradeTime and BuyStop, name = if OrderSimbol then "Bx" else "B(x)@ " + open[-1], price = open[-1], tradesize = tradesize,tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_to_close,EnableStrategy and activerange and ActiveTradeTime and SellStop, name = if OrderSimbol then "Sx" else "S(x)@ " + open[-1], price = open[-1], tradesize = tradesize,tickcolor = GetColor(4), arrowcolor = GetColor(4));
## END STRATEGY
Last edited by a moderator: