Projected Move Expected Bounce For ThinkOrSwim

Ramisegal

Active member
Plus
Strategy: Projected Move Expected Bounce

This strategy is using the core concept from Theo trade to calculate the range the option market is pricing the underline and expecting price will be in for the next coming week.

Conditions for entries are based on a price bounce to and from the projected levels.

The strategy can be configured to run in 1 of 2 modes:
Weekly: projections per week
Daily: Intra day projections per period

For lower time frames 2 instances of the strategy can run simultaneously one for each mode (add the strategy twice to the chart), I will share a grid with the setup. The default setup is weekly, change it to daily on one of them. (enable the dashboard to display the trade odds only on 1 of the instances) this option will also allow each instance to operate in a context of the active session
An option to only Long or only short may be suited with the underline
Future versions will have input for sessions, days of the week as conditional entries.
Other than chart aggregation is used with a re-painting safeguard where though the higher aggregation period lookback is optional it will always be set to a minimum of 1 for a higher time frame and all calculations will be done when the period ends.
Options to limit the strategy to a date range and active session, limit number of projection plots, display trades statistics dashboard so when adding other strategies such as stop loss and/or take profit to the chart all are factored in in the dashboard with P&L bubbles on every position change matching the strategy report, additional contracts orders are limited to 1 per period and more…
I have added additional options and conditional orders as I continue to backtest new ideas. I wouldn't feel comfortable trading without having some proof that my trade plan works. Backtests are one way to reach that conviction.
Another requirement for me is that the trade must have an explainable/understandable edge.

Hopefully I documented all the important conditions in the code and tool tips. Let me know if you have any questions.

Please share your ideas on any improvements you see fit.
Daily MES
7_FnmtaEP59XbGit5UKQxB_4Et0FYqriRoYDWR6R5Mqo8kAL75WnSqSGeQMmAvZbyRfnFiEoEM-0-Ifpv44k49oL8oKzM1f5VsfzGfzJqdQFdoFjuR9YkeXa_lREanD3HqyU5kumsntilBh84rl0I7M

Daily MNQ
zg4fXBAowQYoy8Ooi9oGSods6S-K6lSYxToBO5-EiSzaKZu9CRNdfyvI1CnR7TAnvfAu_oN9J-hozkzZC0m-ok7MiAiDdV8W2Llli9HvFgUYsj14XpmiQiau5ZaNXd0ihERBF4qto7cuZSuWb8lfOWA


Hourly MNQ with limiting date range and trade session
TbqYs3ijX4DK9iEvLXp1IzF0E-AYZGBggAFR4r1ES7rxiNcGp-u1zRv554dlalUJRQNMaT3j9bj97MVpVDg0wWT6jM8LFvL5oyd7vkfSWbgYlR6TooGU9MY8CTCd-kq4e4gh8hodXqHhD8mvsJ3sQBU


7gskL2US6p_gJLSAlSzLWuUXNRzw0XTQFzhGOc3aa-P_UOIQXZLWPb1I1K1T5SieBmB-DYSs2bby9rE_9767fMVwGQrhmrNP78Bn3Nsv3ibJvLjsJf7Xfmw3egCcMgnQvG77wTH37bSVmFLrzNc-Cxg





Lower time frames MNQ
jcOMZpebDTgn-6Qtu8shDGz6pa2fO0btI-EAy5ANL6GbkzW743T1o2U22i_uoDkPFLg3zqXs2VJWwnHwzfC2fSmZAm6QkMAM3hrYr-7dNlafjTtHkcgh6Sk8StBHcB8CjtS4tc47rP60mu6og4t10DE


Nu0OhfzEkqkoJUwsOqgRXa-bQqFKMnNoJfPskDAObWUEiZTGJWrQvywMWyNguS7Ufqlw5YFExzz3VhOf1CtUdoghsgXdAusg2nZM6TJnDeV5vUPRZLY6njgvDPR3ONSoFVPsXLCtCwsTPeqj7hHNbq4

PvhrqyWRymmMXEPEwgkTFLZ-WhmVTaJVNvd_lZ2AbnkADHU30Hxmo6p0Sf1zoFyOYICgmHtw9-t1DfKHlqolIj_hKE7v_4yMGCO85upo4qQJZQQ29MKU0zvbhIwUc2Uuppf7Agb5h96j25N6M3a9jq0


BjHqCs-kwlXknSam8k7O_6uQkbtt5sXstOZ7RJX2SDNzW5KT_t9rYvnUuUwspA08nmD-HFMPCcz1XeJxZt-G-mXN-OxqUz0Mxl7wlPDEL2lzT7tdyJF4_K32N8JELnZpw23A2aoOaj3vzWjOUVB5CqM




RamiSegal: ProjectedMovesExpectedBounce
Share link: http://tos.mx/DLJM1wv

01/02/2024 Recent update (cleaned up code, renamed input variables )
Share link: http://tos.mx/Nld04El

Code:
##-------------------------------------------------------------------------------------
## Rami Segal ## https://usethinkscript.com/members/ramisegal.8158/
##---------------------------- ProjectedMoveExpectedBounce ----------------------------
##---- inspired by... ---------------------------------------------------------------------------------
##-------------------------------------------------------------------------------------
# TheoTrade_Weely_Expected_Move
# Copyright TheoTrade LLC
# V08.11.2017
# Free for use. Header credits must be included when any form of the code included in # This package is used.
#
# User assumes all risk. Author not responsible for errors or use of tool.
# scripted by Todd Rind
#
# Thanks to all those who have freely shared ThinkScript concepts over the Web.
#
# The study is used to analyze the DAILY CLOSING performance of an equity against
# the expected move (EM) for any ticker.
# The study works for daily aggregation only.
# Best performance will be against ETF's due to the option and stock implied volatility
# typically being close. When looking at equities, earnings will cause a difference
# between volatility for options and stock. That is, option volatility may be
# elevated as compared to the stock volatility. Since option volatility cannont
# be accessed from ThinkScript, the script EM will be lower than the EM found
# in the option chain.
#
# NEW LOGIC
#
# Drawing line from previous close.
# Completed the daily calculations for inside EM.
# Turn the "dots" for the bars exceeding EM to RED.
# Added logic for "touches". The "dots" for touches are BLUE.
# Touches are a calculated bandwidth around the EM bars. EX:
# High touches occur when either the high or close is within the calculated
# bandwidth of the EM. Default is 90% of EM.
#
# MINOR ISSUES TO MONITOR
#
# Remove the bars not marked with EM levels from the % occurance calculation.
# Fixed by making sure high & low bar > 1.
#
# Note sent to TOS Support about counter issues when checking day number-no response
# from TO. It appears that occasionally a bar out of view is used as the start.
# Seems to sometimes make Friday count one to many.
#
#-------------------- Header End ----------------------------

##-------------------------------------------------------------------------------------
## Rami Segal ## https://usethinkscript.com/members/ramisegal.8158/
##---------------------------- ProjectedMoveExpectedBounce ----------------------------
##-------------------------------------------------------------------------------------

##############################################################################
########################       ProjectedMove User Input     ##################
##############################################################################

input mode = {default "Weekly", "Daily"};#hint mode: Daily for Lower time frames, weekly for daily time frame only.
input EnableStrategy = yes; #hint EnableStrategy: Enable or Disable the strategy
input UseMarketTime = no; #hint UseMarketTime: When UseMarketTime is true the Strategy simulates trades from TradeTimeStart to TradeTimeEnd
Input UseTradeOffTradeTime = no; #hint UseTradeOffTradeTime: When UseTradeOffTradeTime is true the Strategy simulates trades from TradeTimeEnd to TradeTimeStart
input TradeTimeStart = 0930;
input TradeTimeEnd = 1600;
input UseMarketTradeTimeToExitPositions = no;#hint UseMarketTradeTimeToExitPositions: When UseMarketTradeTimeToExitPositions is true the Strategy will close any open positions at TradeTimeEnd
input UseDateRange = no; #hint UseDateRange: Strategy simulate trades within the date range specified
input ActiveStartDate = 20230101;
input ActiveEndDate = 20240101;
input ShowTime = yes; #hint ShowTime: Display time, Time updates based on the chart aggregation period
##-------------------------------------------------------------------------------------
################################################################################## PreMarket  #################
input PreMarketStart = 0400; #hint PreMarketStart: Plot Highs and Lows per PreMarket start time
input PreMarketEnd = 0700; #hint PreMarketEnd: Plot Highs and Lows per PreMarket End time
input ShowPreMarketCloud = no;
input ShowPreMarketLines = no;
##-------------------------------------------------------------------------------------
################################################################################## Look and feel #################

input ShowProjectedMoveCalculations = no;
input ShowProjectedMovePlots= yes;#hint ShowProjectedMovePlots:Hide or show the Projected Move lines
input ShowProjectedMoveClouds= yes;
input showOnlyLastPeriod = no;#hint showOnlyLastPeriod:Limit the Projected Move lines to recent Daily or Weekly mode
input showOnlyLastPeriodLength = 6;#hint showOnlyLastPeriodLength:The number of periods to display the Project Move lines
input ShowDebugVerticalIV = no;#hint ShowDebugVerticalIV:Show verticalHorizontalFilter lines with the implied volatility on period switch
input ProjectedMoveSkewPercent = 70; #hint ProjectedMoveSkewPercent:Projected Move offset percent
input ProjectedMoveExpensionPercent = 110;#hint ProjectedMoveExpensionPercent:Extend the Projected Move to determine the High and Low Bar for the period
input ProjectedMoveTouchesPercent = 80;#hint ProjectedMoveTouchesPercent: Projected Move offset percent to determine the Touch bar offset from the High and Low Bar for the period
##-------------------------------------------------------------------------------------
##################################################################################
################################################################################## For debugging
##################################################################################
input UseCurrentChartClose = yes;#hint UseCurrentChartClose: Use Daily close or current chart close price to project the Move  For debugging
input UseImpVol = yes; #hint UseImpVol:  Use Implied volatility or IV override value  For debugging
input UseDailyIv = no; #hint UseDailyIv: For debugging
input Iv_override = 0.1618; #hint Iv_override:  Value to use for IV  For debugging
##-------------------------------------------------------------------------------------
################################################################################## The square root of time
##################################################################################
input IvWeekdays = 6; #hint UseImpVol:  Number of days per week period to use in the square root of time
input IvYearDays = 365; #hint IvYearDays:  Number of days a year period to use in the square root of time
input UseDaySession = no;#hint UseDaySession: Used in Daily mode to start the projection per DaySessionHour value
input DaySessionHour = 4;#hint DaySessionHour: Used in Daily mode to start the projection per hour value
input UseActiveMarkets = no;#hint UseActiveMarkets: Start intraday projections at DaySessionStartTime and DaySessionCloseTime
input DaySessionStartTime = 0400;#hint DaySessionStartTime: Used in Daily mode
input DaySessionCloseTime = 1800;#hint DaySessionCloseTime: Used in Daily mode
##-------------------------------------------------------------------------------------
################################################################################## Simulate trades
##################################################################################
input useEntryAlerts = no;
input useSignalAlerts = no;
input OrderSimbol = yes; #hint OrderSimbol: Display B or S for Order Entry vs Detail entry price and order source
input useSignalOrderEntry = no;
input UseAutoPmOrBounceTouch = yes; #hint UseAuto: When UseAuto is true, Simulate trades when UsePmAuto or UseTouchAuto and any bounce of the edges of the projected moves lines
input UsePmAuto= yes;#hint UsePmAuto: When UseAuto is true, Simulate trades when price reaches the edges of the High or low projected move lines
input UseTouchAuto= yes;#hint UseTouchAuto: When UseAuto is true, Simulate trades when price bounce of the edges of the High or low projected touch lines
input UsePmShiftingLevels = yes;#hint UsePmShiftingLevels: Levels are set to the most recent projected move lines when the projected moves are shifting direction from period to period. when UseLevels is true, Simulate trades when the close price exceeds the levels
input UseTouchWithinPmEdge = no; #hint UseTouchWithinPmEdge: high or low within the Projected Move and touch lines
input UseTouchBreachPmEdge = yes; #hint UseTouchBreachPmEdge:  high or low Breach the Projected Move touch line

input UseProjectedMove= no;  #hint UseProjectedMove: Simulate trades when price reaches the edges of the projected move line
input UseProjectedMoveTouch= no;  #hint UseProjectedMoveTouch: Simulate trades when price touches the edges of the projected move touch line

input UseBuyBias = no;  #hint UseBuyBias: When UseBuyBias is true and if UseLevels is true the Direction will be included and any bounce of the edges of the projected moves lines, Simulate Long trades only and exit long on a Short signal.
input UseSellBias = no;  #hint UseSellBias: When UseSellBias is true and if UseLevels is true the Direction will include any bounce of the edges of the projected moves lines, , Simulate Short trades only and exit Short on a Long signal.

input UseDirectionMove = no; #hint UseDirectionMove: When UseDirectionMove is true, Simulate trades in the direction of the most recent bounce
input UseMarketShiftPmExit = no;#hint UseMarketShiftPmExit: When UseExit is true, Projections reversals from previous period direction, Close all Simulated trades
input UseeMarketShiftPmAutoExit= yes; #hint UseeMarketShiftPmAutoExit: When UseAutoExit is true, Close Simulated trades as UseExit and Reopen a position in the reverse direction
##-------------------------------------------------------------------------------------
########################    End: ProjectedMove User Input     ##############################################
##########################################################################################################
##-------------------------------------------------------------------------------------
##################################################################################
#############                Time                                  ###############
##-------------------------------------------------------------------------------------
def TimeZone = 10.5;
def activedaterange = GetYYYYMMDD() >= ActiveStartDate and GetYYYYMMDD() <= ActiveEndDate;
def activerange = if UseDateRange then  activedaterange else 1;
def Hours = Floor(TimeZone + SecondsFromTime(0930) / 60 / 60) - 1;
def Minutes = ((TimeZone + SecondsFromTime(930) / 60 / 60) % 1) * 60;

AddLabel(ShowTime, " 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);

AddLabel(UseDateRange, if UseDateRange then "Range " + asPrice(ActiveStartDate) + " - " + asPrice(ActiveEndDate) else ""  , Color.WHITE );

##################################################################################
#######################    ActiveTradeTime            ############################
##-------------------------------------------------------------------------------------

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 ActiveTradeTime[1] and !ActiveTradeTime and UseMarketTradeTimeToExitPositions else  !ActiveTradeTime and ActiveTradeTime[1])  and UseMarketTradeTimeToExitPositions;
AddLabel(UseMarketTime, if ActiveTradeTime then "Active " + asPrice(TradeTimeStart) + " - " + asPrice(TradeTimeEnd) else ""  , Color.WHITE );


##-------------------------------------------------------------------------------------
##################################################################################
AddOrder(OrderType.BUY_TO_CLOSE, EnableStrategy  and  closeallmarket, tickcolor = GetColor(1), arrowcolor = GetColor(1), name =  mode+"BxEdt@ " + open[-1]) ;
AddOrder(OrderType.SELL_TO_CLOSE, EnableStrategy and  closeallmarket, tickcolor = GetColor(1), arrowcolor = GetColor(1), name =  mode+"SxEdt" + open[-1]);
AddOrder(OrderType.BUY_TO_CLOSE, EnableStrategy  and  !activerange, tickcolor = GetColor(1), arrowcolor = GetColor(1), name =  mode+"BxRange@ " + open[-1]) ;
AddOrder(OrderType.SELL_TO_CLOSE, EnableStrategy and  !activerange, tickcolor = GetColor(1), arrowcolor = GetColor(1), name =  mode+"SxRange@" + open[-1]);

##################################################################################
##################################################################################
##################################################################################
##-------------------------------------------------------------------------------------
##-------------------------------------------------------------------------------------
##-------------------------------------------------------------------------------------
##################################################################
#                          Projected Move Mode                   #
##################################################################
###Daily for Lower timeframes, weekly for daily time frame only.

def UseWeekly ;
switch (mode) {
case "Weekly":
    UseWeekly = 1;
case "Daily":
    UseWeekly = 0;
}
##################################################################
#                          Projected Move Price                       #
##################################################################
def AggregationPeriod = AggregationPeriod.DAY;
def PriceHigh = if UseCurrentChartClose then high[0] else high(period = aggregationPeriod)[0];
def PriceLow =  if UseCurrentChartClose then  low[0] else low(period = aggregationPeriod)[0];
def PriceClose =  if UseCurrentChartClose then close[0] else close(period = aggregationPeriod)[0];
def ivPriceClose =  if IsNaN(close(period = aggregationPeriod)[1]) then close[1] else close(period = aggregationPeriod)[1];


def DaySessionActive = if GetDay() != GetDay()[1] then 0  else if SecondsTillTime(DaySessionStartTime) <= 0 and  SecondsTillTime(DaySessionCloseTime) >= 0  then 1 else 0;

##################################################################
#                          # implied volatility                            #
##################################################################

def Dailyiv =  imp_volatility(period = aggregationPeriod)[1];
def iv = if UseDailyIv then Dailyiv else if UseWeekly then impVolatility() else imp_volatility();

##################################################################
#                          Projected Move calculations                        #
##################################################################

## True when weekly period changed
def calcw = if GetDayOfWeek(GetYYYYMMDD()) == 1  or ( (GetDayOfWeek(GetYYYYMMDD()[1]) == 5 and GetDayOfWeek(GetYYYYMMDD()) == 2))
then 1 else 0;

## true when intraday period changed, if day session and hour selected or day session active session or the daily aggregation period changed (based on user INPUT)
def calcpm = if UseWeekly then calcw else if UseDaySession and Hours == DaySessionHour and Hours <> Hours[1] 
then 1 else if UseActiveMarkets then DaySessionActive[1] <> DaySessionActive else if ivPriceClose <> ivPriceClose[1] then 1 else  0;


## declare variables to populate on perriod change
def PojectedMove_IV;
def PojectedMove;
def Pojected_high_bar;
def Pojected_low_bar;
def pm_close;
def weekcnt;
def Pojected_Touch_high_bar;
def Pojected_Touch_low_bar;

if calcpm == 1 and calcpm[1] == 0
then {
    pm_close = if UseWeekly then  ivPriceClose else if UseCurrentChartClose then PriceClose else ivPriceClose;
    PojectedMove_IV =  if UseImpVol then iv else Iv_override;
    PojectedMove = ( if UseWeekly then (pm_close * PojectedMove_IV * Sqrt(IVweekdays) / Sqrt(IvYearDays) * ProjectedMoveSkewPercent / 100 * ProjectedMoveExpensionPercent / 100)  else pm_close * PojectedMove_IV * Sqrt(1 / IVweekdays) / Sqrt(IvYearDays) * ProjectedMoveSkewPercent / 100 * ProjectedMoveExpensionPercent / 100);
    Pojected_high_bar =  (pm_close) + PojectedMove;
    Pojected_Touch_high_bar = (pm_close) + (PojectedMove * ProjectedMoveTouchesPercent / 100);
    Pojected_low_bar = ( pm_close) - PojectedMove;
    Pojected_Touch_low_bar = (pm_close ) - (PojectedMove * ProjectedMoveTouchesPercent / 100);
    weekcnt = weekcnt[1] + 1;
}
else {
    PojectedMove_IV = PojectedMove_IV[1];
    PojectedMove = PojectedMove[1];
    Pojected_high_bar = Pojected_high_bar[1];
    Pojected_Touch_high_bar = Pojected_Touch_high_bar[1];
    Pojected_low_bar = Pojected_low_bar[1];
    Pojected_Touch_low_bar = Pojected_Touch_low_bar[1];
    pm_close = pm_close[1];
    weekcnt = weekcnt[1];
}
## End declare variables to populate on perriod change

##################################################################
#                          # projections Peak and Vally           #
##################################################################

## exceed projections
def peak = if Pojected_high_bar > 1 and PriceClose > Pojected_high_bar then 1 else 0;
def valley = if Pojected_low_bar > 1 and PriceClose < Pojected_low_bar then 1 else 0;

##original theotrade
#def touchpeak = if Pojected_high_bar > 1 and ((high < Pojected_high_bar and high >= Pojected_Touch_high_bar) or (close < Pojected_high_bar and close >= Pojected_Touch_high_bar)) then 1 else 0;
#def touchvalley = if Pojected_low_bar > 1 and ((low > Pojected_low_bar and low <= Pojected_Touch_low_bar) or (close > Pojected_low_bar and close <= Pojected_Touch_low_bar)) then 1 else 0;

## touch stay or bounce
## options for true condition: if UseTouchWithin is true then high or close are between the upper edge and the upper touch projection lines else just the high is higher then the upper projection touch line and if UseTouchBreach is false then low must be under the upper touch line.
## the theotrade original script where the close is in between the projection high touch line and the projection high line
def touchpeak = if Pojected_high_bar > 1 and
(
(if UseTouchWithinPmEdge
then
    PriceHigh < Pojected_high_bar and PriceHigh >= Pojected_Touch_high_bar
else
    PriceHigh >=  Pojected_Touch_high_bar
    and
    if UseTouchBreachPmEdge
    then
        1
    else
        PriceLow < Pojected_Touch_high_bar  )
or
(PriceClose < Pojected_high_bar and PriceClose >= Pojected_Touch_high_bar)
) then 1 else 0;


## options for true condition: if UseTouchWithin is true then low or close are between the lower edge and the lower touch projection lines else just the low is lower then the lower projection touch line and if UseTouchBreach is false then high must be above the lower projection touch line.
def touchvalley = if Pojected_low_bar > 1 and
(
( if UseTouchWithinPmEdge
then
    PriceLow> Pojected_low_bar and PriceLow <= Pojected_Touch_low_bar
else
    PriceLow<= Pojected_Touch_low_bar
    and
    if UseTouchBreachPmEdge then
        1 else
        PriceHigh > Pojected_Touch_low_bar )
or
(PriceClose >     Pojected_low_bar and PriceClose <= Pojected_Touch_low_bar)
) then 1 else 0;


## count all peaks and vallys
def pkcnt =  if  peak then pkcnt[1] + 1 else pkcnt[1] ;
def vcnt = if valley then vcnt[1] + 1 else vcnt[1] ;

def tpkcnt =  if  touchpeak then tpkcnt[1] + 1 else tpkcnt[1] ;
def tvcnt = if touchvalley then tvcnt[1] + 1 else tvcnt[1] ;



## count all touches peaks and vallys per period and reset to 0 on period change
## this is to control one order per perriod per peak or vally
## additional orders on a new period mostly a double down on the position if enabled in global strategy settings
def peakcnt = if weekcnt != weekcnt[1] or valley then 0 else  if  peak then peakcnt[1] + 1 else peakcnt[1] ;
def valleycnt = if weekcnt != weekcnt[1] or peak then 0 else if valley then valleycnt[1] + 1 else valleycnt[1] ;

def touchpeakcnt = if weekcnt != weekcnt[1] or touchvalley   then 0 else if touchpeak then touchpeakcnt[1] + 1 else touchpeakcnt[1] ;
def touchvalleynt = if weekcnt != weekcnt[1] or touchpeak  then 0 else if touchvalley then touchvalleynt[1] + 1 else touchvalleynt[1] ;


## control the number of plots to display per mode
## variable used: weekcnt is the period counter for the strategy mode
def slp = if showOnlyLastPeriod and  if UseWeekly then weekcnt > highestAll(weekcnt)-showOnlyLastPeriodLength else weekcnt > highestAll(weekcnt)-3  then 1 else 0;

plot ProjectionStart ;
plot ProjectionHigh ;
plot ProjectionLow ;
plot ProjectionHighTouch ;
plot ProjectionLowTouch;

if showOnlyLastPeriod  {
    ProjectionHigh = if  Pojected_high_bar < 1 then Double.NaN else if slp then Pojected_high_bar else Double.NaN;
    ProjectionLow = if Pojected_low_bar < 1 then Double.NaN else if slp then Pojected_low_bar else Double.NaN;
    ProjectionStart =  if pm_close < 1 then Double.NaN else if slp then pm_close else Double.NaN;
    ProjectionHighTouch = if  Pojected_high_bar < 1 then Double.NaN else if slp then Pojected_Touch_high_bar else Double.NaN;
    ProjectionLowTouch = if Pojected_low_bar < 1 then Double.NaN else if slp then Pojected_Touch_low_bar else Double.NaN;


} else {
    ProjectionHigh = if  Pojected_high_bar < 1 then Double.NaN else Pojected_high_bar;
    ProjectionLow = if Pojected_low_bar < 1 then Double.NaN else Pojected_low_bar;
    ProjectionStart =  if pm_close < 1 then Double.NaN else pm_close;
    ProjectionHighTouch = if  Pojected_high_bar < 1 then Double.NaN else Pojected_Touch_high_bar;
    ProjectionLowTouch = if Pojected_low_bar < 1 then Double.NaN else Pojected_Touch_low_bar;
}

## clouds will show per showOnlyLastPeriod since they hinge on the plots
## shade between projections and touches
addCloud(if ShowProjectedMoveClouds then ProjectionHigh else double.nan, ProjectionHighTouch,color.pink );
addCloud(if ShowProjectedMoveClouds then ProjectionLowTouch  else double.nan,ProjectionLow , color.light_green);



## hide and show projections plots
ProjectionHigh.SetHiding( !ShowProjectedMovePlots);
ProjectionHigh.SetDefaultColor(Color.GREEN);
ProjectionHigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ProjectionHigh.SetLineWeight(2);

ProjectionLow.SetHiding( !ShowProjectedMovePlots);
ProjectionLow.SetDefaultColor(Color.RED);
ProjectionLow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ProjectionLow.SetLineWeight(2);
ProjectionStart.SetHiding( !ShowProjectedMovePlots);
ProjectionStart.SetDefaultColor(Color.WHITE);
ProjectionStart.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ProjectionStart.SetLineWeight(2);
ProjectionHighTouch.SetHiding( !ShowProjectedMovePlots);
ProjectionHighTouch.SetDefaultColor(Color.LIGHT_GREEN);
ProjectionHighTouch.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ProjectionHighTouch.SetLineWeight(2);
ProjectionLowTouch.SetHiding( !ShowProjectedMovePlots);
ProjectionLowTouch.SetDefaultColor(Color.LIGHT_RED);
ProjectionLowTouch.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ProjectionLowTouch.SetLineWeight(2);


##################################################################
#                          Levels                             #
##################################################################

## capture the previous projections on a new perriod, this is used for the projections trend
def prevPojectedMove = if PojectedMove <> PojectedMove[1] then PojectedMove[1] else  prevPojectedMove[1] ;
def prevhighbar = if Pojected_high_bar <> Pojected_high_bar[1] then Pojected_high_bar[1] else prevhighbar[1];
def prevlowbar = if Pojected_low_bar <> Pojected_low_bar[1] then Pojected_low_bar[1] else prevlowbar[1];


##################################################################
#          ## Show Projections calculations        #
##################################################################
AddLabel(ShowProjectedMoveCalculations, "ProjectedMoveIntraDay: " +mode , Color.WHITE );
AddLabel(UseDateRange, if activerange then "Strategy Range " + AsPrice(ActiveStartDate) + " - " + AsPrice(ActiveEndDate) else ""  , Color.WHITE );
AddLabel(ShowProjectedMoveCalculations, "Recent IV = " + PojectedMove_IV);
AddLabel(ShowProjectedMoveCalculations, "Recent PM = " + PojectedMove, if prevPojectedMove <= PojectedMove then Color.LIGHT_GREEN else Color.PINK);
AddLabel(ShowProjectedMoveCalculations, "Prev PM = " + prevPojectedMove, if prevPojectedMove >= PojectedMove then Color.LIGHT_GREEN else Color.PINK);
AddLabel(ShowProjectedMoveCalculations, "Recent High Bar = " + Pojected_high_bar);
AddLabel(ShowProjectedMoveCalculations, "Recent Low Bar = " + Pojected_low_bar);
AddLabel(ShowProjectedMoveCalculations, "PM Skew%/Std Dev Adj(%)/Touches% = " + ProjectedMoveSkewPercent + "/" + ProjectedMoveExpensionPercent + "/" + ProjectedMoveTouchesPercent);
AddLabel(ShowProjectedMoveCalculations, "Peak = " + pkcnt);
AddLabel(ShowProjectedMoveCalculations, "Vally  = " + vcnt);
AddLabel(ShowProjectedMoveCalculations, "TPeak = " + tpkcnt);
AddLabel(ShowProjectedMoveCalculations, "TVally  = " + tvcnt);

## for debug sometimes the iv from TOS is double.nan "n/a"
AddVerticalLine(ShowDebugVerticalIV and weekcnt <> weekcnt[1] , "EM:" + " (" + PojectedMove_IV  + ")" ,  if Pojected_low_bar > Pojected_low_bar[1] then Color.GREEN else if Pojected_high_bar < Pojected_high_bar[1] then Color.RED else if Pojected_low_bar > Pojected_low_bar[1] and  Pojected_high_bar < Pojected_high_bar[1] then Color.WHITE else Color.CYAN);

##################################################################
#                          PREMARKET                             #
##################################################################
#PREMARKET HIGHS AND LOWS
def PreMarketTimeRange = secondsFromTime(PreMarketStart) >= 0 and secondsTillTime(PreMarketEnd) >= 0;
def PreMarket = PreMarketTimeRange and !PremarketTimeRange[1];
def Pre_Market_High = compoundValue(1, if((high > Pre_Market_High[1] and PremarketTimeRange) or PreMarket, high, Pre_Market_High[1]), high);
def Pre_Market_Low = compoundValue(1, if((low < Pre_Market_Low[1] and PremarketTImeRange) or PreMarket, low, Pre_Market_Low[1]), low);

plot PreMarketHigh = if Pre_Market_High  == Pre_Market_High[1] then Pre_Market_High else double.nan;
PreMarketHigh.SetStyle(curve.short_dash);
PreMarketHigh.SetDefaultColor(color.light_gray);
PreMarketHigh.Sethiding(!ShowPreMarketLines);
plot PreMarketLow = if Pre_Market_Low == Pre_Market_Low[1] then Pre_Market_Low else double.nan;
PreMarketLow.SetStyle(curve.short_dash);
PreMarketLow.SetDefaultColor(color.light_gray);
PreMarketLow.Sethiding(!ShowPreMarketLines);
AddCloud(if ShowPreMarketCloud then PreMarketHigh else double.nan, if ShowPreMarketCloud then PreMarketLow else double.nan, color.light_gray, color.light_gray);


##################################################################
#                       Shifting Levels                          #
##################################################################
##  1 for higher Projections , -1 for lower
def emdir = if  Pojected_high_bar > 1 and Pojected_high_bar >= prevhighbar then 1 else if  Pojected_high_bar > 1 and Pojected_high_bar <= prevhighbar then -1 else 0;

# price level of projections shifting direction
def buylevel = if emdir > 0 and emdir[1] < 0 then prevlowbar else buylevel[1];
def selllevel = if emdir < 0 and emdir[1] > 0  then prevhighbar else selllevel[1];

## plot the levels
plot buylevels = if slp then buylevel else double.nan;
plot selllevels = if slp then  selllevel else double.nan;

buylevels.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
selllevels.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
buylevels.SetDefaultColor(if UseWeekly then Color.CYAN else Color.yellow);
selllevels.SetDefaultColor(if UseWeekly then Color.plum else Color.Dark_orange);
buylevels.SetStyle(curve.short_dash);
selllevels.SetStyle(curve.short_dash);

## conditions for entry based on close above previous perriod Projections
def buyabovelevels = PriceClose >= Max(buylevel , selllevel) ;
def sellunderlevels = PriceClose <= Min(buylevel , selllevel) ;

## condition for entry based on the most recent direction
def leveldir = if Pojected_high_bar > 1 and Pojected_high_bar > prevhighbar then 1 else if  Pojected_high_bar > 1 and Pojected_high_bar < prevhighbar then -1 else leveldir[1];

#condition for entry based on most recent touch or peak
def Dailydirection = if  (valley or touchvalley) then 1 else if  (peak or touchpeak) then -1 else if IsNaN(Dailydirection[1]) then 0 else Dailydirection[1];

##################################################################
#      ProjectedMove and Expected bounce Strategy Orders                             #
##################################################################

AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and UsePmShiftingLevels  and activerange and buyabovelevels and !buyabovelevels[1], price = open[-1], name = if OrderSimbol then "B" else mode+"B(level)@ " + open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(4));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and UsePmShiftingLevels  and activerange and sellunderlevels and !sellunderlevels[1], price = open[-1], name = if OrderSimbol then "S" else  mode+"S(Level)@ " + open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(4));


AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy  and activerange and  UseProjectedMoveTouch and  touchvalley and touchvalleynt == 1 and touchvalleynt[1] == 0, name = if OrderSimbol then "B" else  mode+"B(Tv)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy  and activerange and  UseProjectedMoveTouch and  touchpeak  and  touchpeakcnt == 1 and touchpeakcnt[1] == 0, name = if OrderSimbol then "S" else  mode+"S(Tp)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy  and activerange and  UseProjectedMove and  valley and   valleycnt == 1 and valleycnt[1]== 0  , name = if OrderSimbol then "B" else  mode+"B(V)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy  and activerange and  UseProjectedMove and  peak and peakcnt == 1 and peakcnt[1] == 0, name = if OrderSimbol then "S" else  mode+"S(V)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and UseDirectionMove and  Dailydirection > 0 and leveldir> 0, name = if OrderSimbol then "B" else  mode+"B(>d)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and UseDirectionMove and  Dailydirection < 0 and leveldir < 0, name = if OrderSimbol then "S" else  mode+"S(<d)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and  activerange and UseAutoPmOrBounceTouch and  UseTouchAuto and touchvalleynt == 1 and touchvalleynt[1] == 0, name = if OrderSimbol then "B" else  mode+"B(Atv)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and UseAutoPmOrBounceTouch  and  UseTouchAuto and  touchpeakcnt == 1 and touchpeakcnt[1] == 0, name = if OrderSimbol then "S" else  mode+"S(Atp)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and UseAutoPmOrBounceTouch and UsePmAuto and   valleycnt == 1 and valleycnt[1] == 0, name = if OrderSimbol then "B" else  mode+"B(Av)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and UseAutoPmOrBounceTouch and  UsePmAuto and peakcnt == 1 and peakcnt[1] == 0, name = if OrderSimbol then "S" else  mode+"S(Ap)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and  activerange and usebuybias  and if UsePmShiftingLevels then leveldir > 0 else 1 and  ( ( valleycnt == 1 and valleycnt[1] == 0 ) or (touchvalleynt == 1 and touchvalleynt[1] == 0)), name = if OrderSimbol then "B" else  mode+"B>>>@$ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_TO_CLOSE,!useSignalOrderEntry and  EnableStrategy  and activerange and usebuybias  and  (   touchpeakcnt == 1 and touchpeakcnt[1] == 0 or  peakcnt == 1 and peakcnt[1] == 0 ), name = if OrderSimbol then "Sx" else  mode+"S>x@$ " + Open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and usesellbias   and if UsePmShiftingLevels then leveldir < 0 else 1 and  (   touchpeakcnt == 1 and touchpeakcnt[1] == 0 or  peakcnt == 1 and peakcnt[1] == 0 ), name = if OrderSimbol then "S" else  mode+"S<<<@$ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));
AddOrder(OrderType.BUY_TO_CLOSE,!useSignalOrderEntry and  EnableStrategy  and activerange and usesellbias  and ( ( valleycnt == 1 and valleycnt[1] == 0 ) or (touchvalleynt == 1 and touchvalleynt[1] == 0)), name = if OrderSimbol then "Bx" else  mode+"B<x@$ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));

def pmvalid = Pojected_high_bar > 1;
AddOrder(OrderType.SELL_auto,!useSignalOrderEntry and  EnableStrategy  and activerange and  pmvalid and  UseeMarketShiftPmAutoExit and  Dailydirection > 0 and Pojected_high_bar < Pojected_low_bar[1], name = if OrderSimbol then "S" else  mode+"S(AExit)@ " + Open[-1], price = Open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));
AddOrder(OrderType.BUY_auto,!useSignalOrderEntry and  EnableStrategy  and activerange and  pmvalid and UseeMarketShiftPmAutoExit and Dailydirection < 0 and Pojected_low_bar > Pojected_high_bar[1], name = if OrderSimbol then "B" else  mode+"B(AExit)$ " + Open[-1], price = Open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));


AddOrder(OrderType.SELL_TO_CLOSE,!useSignalOrderEntry and  EnableStrategy  and activerange and  pmvalid and UseMarketShiftPmExit and  Dailydirection > 0 and Pojected_high_bar < Pojected_low_bar[1], name = if OrderSimbol then "S" else  mode+"S(Exit)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));
AddOrder(OrderType.BUY_TO_CLOSE,!useSignalOrderEntry and  EnableStrategy  and activerange and  pmvalid and UseMarketShiftPmExit and Dailydirection < 0 and Pojected_low_bar > Pojected_high_bar[1], name = if OrderSimbol then "Bx" else  mode+"B(Exit)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));


##################################################################
#     End of ProjectedMove and Expected bounce Strategy                             #
##################################################################





##################################################################
#     End of ProjectedMove and Expected bounce Strategy Orders                             #
##################################################################




##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#                                                SUPERTREND
##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
##################################################################
#     Everything below can be removed from the Projected move strategy                             #
##################################################################


input UseSuperTrendRangeBar = yes; #hint UseSuperTrendRangeBar: Modified TrueRange SuperTrend.
input UseInputOtherTimeFrames = yes;
input otf_AggregationPeriod = AggregationPeriod.FIFTEEN_MIN; #hint otf_AggregationPeriod: SuperTrend time frame
input otf_nATR = 5; #hint otf_nATR: Length for Momentum calculations.
input otf_AvgType = AverageType.SimPLE;
input otf_ATRMult = 0.7;
input otf_TMV = 3; #hint TMV: Modified TrueRange SuperTrend periods.
input otf_Aggregation_Periodoffset = 1; #hint Aggregation_Periodoffset : Higher aggregation will always default to 1 to avoid re painting
input otf_AggregationPeriodHighestHighLowestLowOffset = 0;

##########################################################################################################################################################

def otf_timeFrame =  if GetAggregationPeriod() > otf_AggregationPeriod then GetAggregationPeriod()
else if UseInputOtherTimeFrames then otf_AggregationPeriod else GetAggregationPeriod() ;
def AggregationPeriodoffset = if otf_timeFrame > GetAggregationPeriod() then 1 else otf_Aggregation_Periodoffset;

def tmvotf_priceclose = (highest( close( period = otf_timeFrame)[max(AggregationPeriodoffset,0)],otf_TMV)[otf_AggregationPeriodHighestHighLowestLowOffset]+ lowest( close( period = otf_timeFrame)[max(AggregationPeriodoffset,0)],otf_TMV)[otf_AggregationPeriodHighestHighLowestLowOffset])/2;
def tmvotf_pricehigh = highest(high( period = otf_timeFrame)[max(AggregationPeriodoffset,0)],otf_TMV)[otf_AggregationPeriodHighestHighLowestLowOffset];
def tmvotf_pricelow = lowest( low( period = otf_timeFrame)[max(AggregationPeriodoffset,0)], otf_TMV)[otf_AggregationPeriodHighestHighLowestLowOffset];

def otf_priceclose =  close( period = otf_timeFrame)[max(AggregationPeriodoffset,0)];
def otf_pricehigh =  high( period = otf_timeFrame)[max(AggregationPeriodoffset,0)];
def otf_pricelow =  low( period = otf_timeFrame)[max(AggregationPeriodoffset,0)];;

def otf_h =   if UseSuperTrendRangeBar then tmvotf_pricehigh else otf_pricehigh;
def otf_l =   if UseSuperTrendRangeBar then tmvotf_pricelow else otf_pricelow;
def otf_c =   if UseSuperTrendRangeBar then  tmvotf_priceclose else otf_priceclose;

def otf_TrueRange = TrueRange(otf_h, otf_c, otf_l) ;

def otf_ATR = if UseSuperTrendRangeBar then MovingAverage(otf_AvgType, TrueRange(otf_h, otf_c, otf_l), otf_nATR) else otf_TrueRange ;

def otf_UP = otf_c+ (otf_ATRMult * otf_ATR);
def otf_DN = otf_c+ (-otf_ATRMult * otf_ATR);

def otf_lowestup = if otf_UP <= otf_lowestup[1] then otf_UP[0] else if otf_c < otf_lowestup[1] and otf_c < otf_UP[0] then otf_lowestup[1] else otf_UP[0];
def otf_highestdn = if otf_DN >= otf_highestdn[1] then otf_DN[0] else if otf_c > otf_highestdn[1] and otf_c > otf_DN[0]  then otf_highestdn[1] else otf_DN[0];

def otf_trend = if  otf_c[0] crosses below otf_highestdn[1] then -1 else if  otf_c[0] crosses above otf_lowestup[1]  then 1 else otf_trend[1];

def otf_sellmodeprice =  if otf_trend  < 0 and otf_trend <> otf_trend[1] then otf_highestdn[1] else otf_sellmodeprice[1];
def otf_buymodeprice =  if otf_trend  > 0 and otf_trend <> otf_trend[1] then otf_lowestup[1] else otf_buymodeprice[1];

plot otf_sellcrossprice = if  otf_trend  <> 0 then  otf_sellmodeprice else Double.NaN;
plot otf_buycrossprice = if otf_trend  <> 0  then  otf_buymodeprice   else Double.NaN;

otf_sellcrossprice.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
otf_buycrossprice.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

otf_buycrossprice.setdefaultColor(Color.LIGHT_GREEN);
otf_sellcrossprice.setdefaultColor(Color.PINK);

otf_sellcrossprice.SetStyle(Curve.FIRM );
otf_sellcrossprice.SetLineWeight(1);

otf_buycrossprice.SetStyle(Curve.FIRM );
otf_buycrossprice.SetLineWeight(1);


plot otf_sell =  if  otf_trend < 0 then otf_lowestup[0] else Double.NaN ;
plot otf_buy = if  otf_trend > 0  then otf_highestdn[0] else Double.NaN ;

otf_buy .setdefaultColor(Color.lime);
otf_sell.setdefaultColor(Color.magenta);


def otf_barUp = otf_trend > 0 ;
def otf_barDown = otf_trend < 0 ;
def otf_barUpCount = CompoundValue(1, if otf_barUp then (if IsNaN(otf_barUpCount[1]) then 0 else otf_barUpCount[1]) + 1 else 0, 0);

def otf_barDownCount = CompoundValue(1, if otf_barDown then ( if IsNaN( otf_barDownCount[1]) then 0 else otf_barDownCount[1] ) - 1 else 0, 0);

def otf_trendcnt = otf_barDownCount + otf_barUpCount ;

input ShowSuperTrendLabels = yes;
AddLabel(ShowSuperTrendLabels, "SuperTrendRangeStrategy - TF: " +otf_timeFrame/60000, color.white);
AddLabel(ShowSuperTrendLabels, "Trendind Bars " + (otf_trendcnt) ,  if otf_trend > 0  then Color.LIME else  Color.MAGENTA );

input UseMomentumFilter = no;
input TradeFrequecy= {Default "Hold", "Swing", "Scalp"};
def tf;
Switch (TradeFrequecy) {
Case "Swing":
tf = 3;
Case "Scalp":
tf = 2;
Case "Hold":
tf = 1;
}

AddLabel(UseMomentumFilter, "Momentum Filter: " + TradeFrequecy,  color.white);

def otf_trendlowestlow;
def otf_trendhighesthigh;

if otf_trend < 0
then
{
    otf_trendlowestlow = if otf_trend == otf_trend[1] then if (if UseMomentumFilter then (if tf==3 then close else if tf==2 then  low else if tf==1 then high else low) else low) < otf_trendlowestlow[1] then low else otf_trendlowestlow[1] else low[1];
    otf_trendhighesthigh =  otf_trendhighesthigh[1];
}
else
if otf_trend > 0
then
{
    otf_trendlowestlow = otf_trendlowestlow[1];
    otf_trendhighesthigh = if otf_trend == otf_trend[1] then if (if UseMomentumFilter then  (if tf==3 then close else if tf==2 then  high else if tf==1 then low else high) else high) > otf_trendhighesthigh[1] then high else otf_trendhighesthigh[1] else high[1];
}
else
{
    otf_trendlowestlow = otf_trendlowestlow[1];
    otf_trendhighesthigh = otf_trendhighesthigh[1];
}

 
Input ShowSuperTrendHighAndLow = yes;
def trendlowest = if otf_trend<>otf_trend[1] and otf_trend > 0 then otf_trendlowestlow[1] else trendlowest[1];
def trendhighest = if otf_trend<>otf_trend[1] and otf_trend < 0 then otf_trendhighesthigh[1] else trendhighest[1];

plot STrendlowestlow =  if ShowSuperTrendHighAndLow and otf_trend >  0 and otf_trendlowestlow == otf_trendlowestlow[1]then otf_trendlowestlow else double.NaN;
plot STrendhighesthigh =  if ShowSuperTrendHighAndLow and  otf_trend < 0 and otf_trendhighesthigh == otf_trendhighesthigh[1] then otf_trendhighesthigh  else double.NaN;

STrendlowestlow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
STrendhighesthigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
STrendlowestlow.SetDefaultColor(color.red);
STrendhighesthigh.SetDefaultColor(color.green);


##################################################################################################################            
######################################### Trend shifting upper and lower bands #########################################################
##################################################################################################################       
def max1h = max( otf_trendhighesthigh,otf_sellcrossprice );
def min1h = min( otf_trendhighesthigh,otf_sellcrossprice ) ;
def max1l = max(  otf_trendlowestlow,otf_buycrossprice  ) ;
def min1l = min(  otf_trendlowestlow,otf_buycrossprice  ) ;
#################################
input ShowOrderBlockCloud = yes;
#################################
addCloud(if ShowOrderBlockCloud and otf_trendcnt < 0    then min1h  else   double.NaN ,max1h, color.red );
addCloud(if ShowOrderBlockCloud and otf_trendcnt > 0   then max1l  else   double.NaN ,min1l, color.green    );
#################################

input ShowSuperTrendHighAndLowOrderBlockCloud = yes;
addCloud(if ShowSuperTrendHighAndLowOrderBlockCloud and otf_trendcnt < 0   then otf_sellcrossprice  else   double.NaN , strendhighesthigh     );
addCloud(if ShowSuperTrendHighAndLowOrderBlockCloud and otf_trendcnt > 0   then otf_buycrossprice  else   double.NaN ,    strendlowestlow  );

def cloudrange = absValue( if otf_trendcnt < 0 then otf_sellmodeprice - otf_trendhighesthigh else otf_buymodeprice - otf_trendlowestlow);

input useIntraDaySignalsOnDailyMode = no; #hint useIntraDaySignalsOnDailyMode: Strategy simulate intra day trades on daily time frame
input UseCloudRange =  no;#hint UseLessRisk: Strategy simulate when trend momentum is on and new high delta from previous high is less than the cloudrange*RiskFactor
input UseAtrCloudRange =  yes;#hint UseMoreRisk: Strategy simulate when trend momentum is on and new high delta from previous high is less than the ATR*RiskFactor
input RiskFactor = 1.4;#hint RiskFactor: Cloud percentage factor
input RiskBars = 3;#hint RiskBars: Number of bars to calculate for momentum delta

def enableIntraday = if !useIntraDaySignalsOnDailyMode then if getAggregationPeriod() < aggregationPeriod.DAY then 1 else 0 else 1;

def buylIGHTisk =   otf_trendhighesthigh > otf_trendhighesthigh[1]  and close >  otf_trendhighesthigh[RiskBars] ;
def SelllIGHTisk =  otf_trendlowestlow < otf_trendlowestlow[1]  and close < otf_trendlowestlow[RiskBars] ;

def buyLessRisk =   otf_trendhighesthigh > otf_trendhighesthigh[1]  and close >  otf_trendhighesthigh[RiskBars]  and (otf_trendhighesthigh- otf_trendhighesthigh[RiskBars] <= cloudrange*RiskFactor);
def sellLessRisk =  otf_trendlowestlow < otf_trendlowestlow[1]  and close < otf_trendlowestlow[RiskBars]  and ( otf_trendlowestlow- otf_trendlowestlow[RiskBars] <= -cloudrange*RiskFactor);

def buyMoreRisk =  otf_trendhighesthigh > otf_trendhighesthigh[1] and close >  otf_trendhighesthigh[1]  and (otf_trendhighesthigh- otf_trendhighesthigh[RiskBars] <= otf_ATR*RiskFactor);
def sellMoreRisk =  otf_trendlowestlow < otf_trendlowestlow[1] and close < otf_trendlowestlow[1] and ( otf_trendlowestlow- otf_trendlowestlow[RiskBars] <= -otf_ATR*RiskFactor);

AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and enableIntraday and  UseCloudRange and buyLessRisk and !buyLessRisk[1], name = if OrderSimbol then "B" else  mode+"B(lr)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and enableIntraday and UseCloudRange  and sellLessRisk and !sellLessRisk[1], name =  if OrderSimbol then "S" else   mode+"S(lr)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and enableIntraday and UseAtrCloudRange and buyMoreRisk and !buyMoreRisk[1], name =   if OrderSimbol then "B" else   mode+"B(mr)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and enableIntraday and UseAtrCloudRange and sellMoreRisk and !sellMoreRisk[1], name =   if OrderSimbol then "S" else    mode+"S(mr)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

##################################################################
#                          Gandalf Pattern                            #
##################################################################
script gwiz{
 input i_aggregation = aggregationPeriod.DAY;
def aggregation = if i_aggregation < getaggregationPeriod() then getaggregationPeriod() else i_aggregation;


def averagePrice =  ohlc4(period = aggregation)[1];
def medianPrice = hl2(period = aggregation)[1];
def medianBodyPrice = ( open(period = aggregation)[1] +close(period = aggregation)[1]) /2;   # MidBodyVal();

def Long = (averagePrice[1] < medianPrice[1] and
    medianPrice[2] <= averagePrice[1] and
    medianBodyPrice[2] <= averagePrice[3]) or
    (averagePrice[1] < medianPrice[3] and
    medianBodyPrice < medianPrice[2] and
    medianBodyPrice[1] < medianBodyPrice[2]);

plot Exit = (averagePrice[1] < medianBodyPrice[1] and
    medianPrice[2] == medianBodyPrice[3] and
    medianBodyPrice[1] <= medianBodyPrice[4]) or
    (averagePrice[2] < medianBodyPrice and
    medianPrice[4] <= averagePrice[3] and
    medianBodyPrice[1] <= averagePrice[1]);
}

def  gwiztrue = if gwiz(aggregationPeriod.month).Long or  gwiz(aggregationPeriod.week).Long or gwiz(aggregationPeriod.DAY).Long or
 gwiz(AggregationPeriod.FOUR_HOURS).Long or gwiz(AggregationPeriod.HOUR).Long or gwiz(AggregationPeriod.FIFTEEN_MIN) or gwiz(AggregationPeriod.FIVE_MIN).Long or gwiz(AggregationPeriod.MIN).Long then 1
else if  gwiz(aggregationPeriod.month).Exit or  gwiz(aggregationPeriod.week).Exit or gwiz(aggregationPeriod.DAY).Exit or
 gwiz(AggregationPeriod.FOUR_HOURS).Exit or gwiz(AggregationPeriod.HOUR).Exit or gwiz(AggregationPeriod.FIFTEEN_MIN) or gwiz(AggregationPeriod.FIVE_MIN).Exit or gwiz(AggregationPeriod.MIN).Exit then -1 else gwiztrue[1] ;



input UseGwiz =  NO;#hint UseGwiz: Strategy simulate Long orders when Gandelf Long Entry Price Pattern is found on any timeframe and no new lower lows are registered. Exit entries are simulated when the supertrend turns bearish or close price is under the reversing projections levels
AddOrder(OrderType.BUY_to_open,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime  and ( UseGwiz ) and gwiztrue and !SelllIGHTisk, name =  if OrderSimbol then "B" else    mode+"B(Wiz)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_to_close,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime  and UseGwiz and ((SelllIGHTisk )or  (sellunderlevels and !sellunderlevels[1])), name =  if OrderSimbol then "Sx" else   mode+"Sx(mr)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


def buy_ind =
(EnableStrategy  and activerange and UsePmShiftingLevels  and  buyabovelevels and !buyabovelevels[1]) or
(EnableStrategy  and activerange and  UseProjectedMoveTouch and  touchvalley and touchvalleynt == 1 and touchvalleynt[1] == 0) or
(EnableStrategy  and activerange and  UseProjectedMove and  valley and   valleycnt == 1 and valleycnt[1]== 0 ) or
(EnableStrategy and activerange and UseDirectionMove and  Dailydirection > 0 and leveldir> 0) or
(EnableStrategy and  activerange and UseAutoPmOrBounceTouch and  UseTouchAuto and touchvalleynt == 1 and touchvalleynt[1] == 0) or
(EnableStrategy and activerange and UseAutoPmOrBounceTouch and UsePmAuto and   valleycnt == 1 and valleycnt[1] == 0) or
(EnableStrategy and  activerange and usebuybias  and if UsePmShiftingLevels then leveldir > 0 else 1 and  ( ( valleycnt == 1 and valleycnt[1] == 0 ) or (touchvalleynt == 1 and touchvalleynt[1] == 0))) or
(EnableStrategy  and activerange and UseeMarketShiftPmAutoExit and  pmvalid and Dailydirection < 0 and Pojected_low_bar > Pojected_high_bar[1]) or
(EnableStrategy and activerange and ActiveTradeTime and enableIntraday and  UseCloudRange and buyLessRisk and !buyLessRisk[1]) or
(EnableStrategy and activerange and ActiveTradeTime and enableIntraday and UseAtrCloudRange and buyMoreRisk and !buyMoreRisk[1]) or
(EnableStrategy and activerange and ActiveTradeTime  and ( UseGwiz ) and gwiztrue and !SelllIGHTisk);

def sell_ind =
(EnableStrategy  and activerange and UsePmShiftingLevels   and sellunderlevels and !sellunderlevels[1]) or
(EnableStrategy  and activerange and  UseProjectedMoveTouch and  touchpeak  and  touchpeakcnt == 1 and touchpeakcnt[1] == 0) or
(EnableStrategy  and activerange and  UseProjectedMove and  peak and peakcnt == 1 and peakcnt[1] == 0) or
(EnableStrategy and activerange and UseDirectionMove and  Dailydirection < 0 and leveldir < 0) or
(EnableStrategy and activerange and UseAutoPmOrBounceTouch  and  UseTouchAuto and  touchpeakcnt == 1 and touchpeakcnt[1] == 0) or
(EnableStrategy and activerange and UseAutoPmOrBounceTouch and  UsePmAuto and peakcnt == 1 and peakcnt[1] == 0) or
(EnableStrategy and activerange and usesellbias   and if UsePmShiftingLevels then leveldir < 0 else 1 and  (   touchpeakcnt == 1 and touchpeakcnt[1] == 0 or  peakcnt == 1 and peakcnt[1] == 0 )) or
( EnableStrategy  and activerange and UseeMarketShiftPmAutoExit and pmvalid and Dailydirection > 0 and Pojected_low_bar < Pojected_high_bar[1]) or
(EnableStrategy and activerange and ActiveTradeTime and enableIntraday and UseCloudRange  and sellLessRisk and !sellLessRisk[1]) or
(EnableStrategy and activerange and ActiveTradeTime and enableIntraday and UseAtrCloudRange and sellMoreRisk and !sellMoreRisk[1]) or
(EnableStrategy and activerange and ActiveTradeTime  and UseGwiz and ((SelllIGHTisk )or  (sellunderlevels and !sellunderlevels[1])));
##################################################################
#     Alerts                          #
##################################################################


def SellStop = closeallmarket or !activerange or
(EnableStrategy  and activerange and ActiveTradeTime and usebuybias  and  (   touchpeakcnt == 1 and touchpeakcnt[1] == 0 or  peakcnt == 1 and peakcnt[1] == 0)
) or
(EnableStrategy  and activerange and ActiveTradeTime and UseMarketShiftPmExit and  Dailydirection > 0 and Pojected_high_bar < Pojected_low_bar[1]) ;

def BuyStop = closeallmarket or !activerange or
(EnableStrategy and activerange and ActiveTradeTime and usesellbias  and ( ( valleycnt == 1 and valleycnt[1] == 0 ) or (touchvalleynt == 1 and touchvalleynt[1] == 0)))or
(EnableStrategy and activerange and ActiveTradeTime and UseMarketShiftPmExit and Dailydirection < 0 and Pojected_low_bar > Pojected_high_bar[1]) or
(EnableStrategy and activerange and ActiveTradeTime  and UseGwiz and ((SelllIGHTisk )or  (sellunderlevels and sellunderlevels[1])));


def BuySignal = buy_ind;
def SellSignal = sell_ind;
#######################################
##  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
def orderPrice = if (isOrder and (BuySignal or SellSignal)) then open[-1] else orderPrice[1];




def pricelevel = orderPrice;

def prevpricelevel = if pricelevel <> pricelevel[1] then pricelevel[1] else prevpricelevel[1];

plot OrderBlock = pricelevel;
OrderBlock.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
OrderBlock.SetDefaultColor(color.cyan);


def top = if prevpricelevel < pricelevel then pricelevel else prevpricelevel ;
def bottom = if prevpricelevel > pricelevel then pricelevel else prevpricelevel ;

input ShowCloud = no;
def maxlvl = max(prevpricelevel,pricelevel);
def minlvl = min(prevpricelevel,pricelevel);

addCloud(if ShowCloud and islong  then maxlvl else double.nan , minlvl, color.green);
addCloud(if ShowCloud and isshort  then minlvl else double.nan , maxlvl, color.red);


AddOrder(OrderType.BUY_AUTO,useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and buysignal, name = if OrderSimbol then "B" else "B(*)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and sellsignal, name = if OrderSimbol then "S" else  "S(*)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

AddOrder(OrderType.BUY_to_close,useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime  and buystop, name = if OrderSimbol then "Bx" else  "B(x)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_to_close,useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and sellstop, name =  if OrderSimbol then "Sx" else  "S(x)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


def buyalert = islong;
def sellalert =isshort;

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 Activealert and !Activealert[1] and buyalert, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(Activealert and Activealert  and !Activealert[1] and sellalert, "Sell Signal" , Alert.BAR, Sound.Ding);



#######################################
##  START of Strategies DashBoard
####################################
addOrder(OrderType.BUY_AUTO, no); #dont change this line
input enableDashBoard = no;
input ShowStrategyCurrentPnlBubble = yes;
input ShowStrategyPnlBubble = no;
input ShowStrategyPnlEntryBubble = yes;
input ShowStrategyPnlVertical = no;
Input ShowStrategyProfitLossLabels = yes;
def fpl = FPL();
def StrategyEntryprice = if IsNaN(EntryPrice())  then 0 else EntryPrice();
def ep = entryprice();
def poschange = ( StrategyEntryprice <> StrategyEntryprice[1] and StrategyEntryprice == 0 ) or (  StrategyEntryprice <> StrategyEntryprice[1] and StrategyEntryprice[1] == 0  )   or (  StrategyEntryprice <> StrategyEntryprice[1] and StrategyEntryprice[1] > 0   and StrategyEntryprice[0] > 0 );
def pnlentry =  if  poschange  then  fpl[1] else pnlentry[1];
def currentprofit = fpl() - pnlentry[1];
def pnlprofit =  if pnlentry <> pnlentry[1] then  fpl()[1] - pnlentry[1] else 0  ;
def entryprofit = (if pnlprofit> 0 then 1 else -1 )  * absValue( if  poschange  then if StrategyEntryprice == 0 then open[0] - ep[1] else ep-ep[1] else 0) ;
def dollarentryprofitloss = Round(((entryprofit ) / TickSize()) * TickValue());

AddChartBubble(enableDashBoard and ShowStrategyPnlEntryBubble and poschange and absValue(dollarentryprofitloss  )>0, open[0], AsDollars(dollarentryprofitloss[0]), if dollarentryprofitloss[0] > 0 then Color.light_GREEN else if  dollarentryprofitloss[0] < 0 then Color.pink else Color.BLUE);
AddVerticalLine(ShowStrategyPnlVertical and ShowStrategyPnlEntryBubble and poschange, AsDollars(fpl) + " (" + dollarentryprofitloss + ")" ,  if dollarentryprofitloss > 0 then Color.GREEN else if dollarentryprofitloss < 0 then Color.RED else if pnlentry == 0 then Color.WHITE else Color.CYAN);

def fplpnlprofit = pnlprofit;
AddChartBubble(enableDashBoard and ShowStrategyPnlBubble and poschange[0] and absValue(fplpnlprofit  )>0, open[0], AsDollars(fplpnlprofit[0]), if fplpnlprofit[0] > 0 then Color.GREEN else if  fplpnlprofit[0] < 0 then Color.RED else Color.BLUE);
AddVerticalLine(enableDashBoard and ShowStrategyPnlVertical and ShowStrategyPnlBubble and poschange, AsDollars(fpl) + " (" + pnlprofit + ")" ,  if pnlprofit > 0 then Color.GREEN else if pnlprofit < 0 then Color.RED else if pnlentry == 0 then Color.WHITE else Color.CYAN);
def lastentry =if isnan( entryprice()) then lastentry[1] else entryprice() ;
AddChartBubble(enableDashBoard and ShowStrategyCurrentPnlBubble  and !IsNaN(close) and IsNaN(close [-1] ) and HighestAll(BarNumber()) and absValue(currentprofit)> 0, lastentry, AsDollars(currentprofit[0]), if currentprofit[0] > 0 then Color.green else if  currentprofit[0] < 0 then Color.red else Color.BLUE);

def pl = if ShowStrategyPnlEntryBubble then if isnan( dollarentryprofitloss) then 0 else dollarentryprofitloss else if isnan(fplpnlprofit) then 0 else fplpnlprofit;
def StrategyLongprofitLossSum = CompoundValue(1, if BarNumber() == 1 then 0 else if pl > 0 then StrategyLongprofitLossSum[1] + pl[0] else StrategyLongprofitLossSum[1], 0);
def StrategyShortprofitLossSum = CompoundValue(1, if BarNumber() == 1 then 0 else if pl < 0 then StrategyShortprofitLossSum[1] + pl[0] else StrategyShortprofitLossSum[1], 0);
def StrategyProfittradecnt = if  BarNumber() == 1 then 0 else if pl > 0 then StrategyProfittradecnt[1] + 1 else StrategyProfittradecnt[1] ;
def Strategylosstradecnt = if  BarNumber() == 1 then 0 else if pl < 0 then Strategylosstradecnt[1] + 1 else Strategylosstradecnt[1] ;
def Strategytradecnt = StrategyProfittradecnt + Strategylosstradecnt;

# What percent were winners
def StrategyPCTWin = Round(((StrategyProfittradecnt) / (Strategytradecnt)) * 100, 2) ;
def StrategyPCTLoss = Round(((Strategylosstradecnt) / (Strategytradecnt)) * 100, 2) ;
def StrategyPCTWinamt = Round(((absValue(StrategyLongprofitLossSum/StrategyProfittradecnt)) /absValue( (StrategyLongprofitLossSum/StrategyProfittradecnt) + absValue(StrategyShortprofitLossSum/Strategytradecnt))) * 1, 2) ;
def PCTLossamt =  Round(((absValue(StrategyShortprofitLossSum/Strategylosstradecnt)) /absValue( (StrategyLongprofitLossSum/StrategyProfittradecnt) + absValue(StrategyShortprofitLossSum/Strategytradecnt))) * 1, 2) ;
plot PltEntryPrice = if enableDashBoard then  ep else double.nan;
PltEntryPrice.SetPaintingStrategy(PaintingStrategy.DASHES);
PltEntryPrice.SetdefaultColor(color.cyan);
PltEntryPrice.assignValueColor(if currentprofit then color.green else
if entryprofit < 0 then color.red else color.cyan );


def Strategylowestdrawdown =  min(if isnan(currentprofit) then 0 else currentprofit,Strategylowestdrawdown[1]);
def StrategyHigestdrawUp =  max(if isnan(currentprofit) then 0 else currentprofit,StrategyHigestdrawUp[1]);
def Strategylowestloss = min(pl,Strategylowestloss[1]);
def highestwin = max(pl,highestwin[1]);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels,"Last Entry: "+lastentry +"("+currentprofit +")" ,if currentprofit > 0 then color.light_green else if currentprofit < 0 then color.light_red else color.cyan );
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "PNL: " + (FPL()), if FPL() > 0 then Color.LIME else Color.RED);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Winners: " + StrategyPCTWin + "%", if StrategyPCTWin > 50 then Color.GREEN else if StrategyPCTWin > 40 then Color.YELLOW else Color.GRAY);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "ProfitLossSum: " + (StrategyLongprofitLossSum + StrategyShortprofitLossSum), if (StrategyLongprofitLossSum + StrategyShortprofitLossSum) > 0 then Color.LIME else Color.RED);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "ShortprofitLossSum: " + (StrategyShortprofitLossSum), Color.pink);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "LongprofitLossSum: " + (StrategyLongprofitLossSum), Color.LIME);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Trades: " + (Strategytradecnt), Color.WHITE);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Profit Trades: " + (StrategyProfittradecnt), if StrategyProfittradecnt > Strategylosstradecnt then Color.LIME else Color.RED);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Loss Trades: " + (Strategylosstradecnt), if StrategyProfittradecnt < Strategylosstradecnt then Color.LIME else Color.pink);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Profit Factor: " +round(absvalue (StrategyLongprofitLossSum/StrategyShortprofitLossSum)),color.cyan);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Lowest Loss: " + (Strategylowestloss), Color.pink);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Lowest DrawDown: " + (Strategylowestdrawdown), Color.pink);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Highest DrawUp: " + (StrategyHigestdrawUp), Color.LIME);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Highest Win: " + (highestwin), Color.LIME);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "PCTWin Trades: " + (StrategyPCTWin), Color.GREEN);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "PCTLoss Trades: " + (StrategyPCTLoss), Color.PINK);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "PCTWin Amount: " + (StrategyPCTWinamt), Color.GREEN);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "PCTLoss Amount: " + (PCTLossamt), Color.PINK);

def firstentry = if Strategytradecnt ==1 then close[1] else firstentry[1];
def buyandhold = Round(((close - firstentry ) / TickSize()) * TickValue());
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Buy&Hold: " + (buyandhold), if buyandhold > 0 then Color.LIME else Color.RED);



#######################################
##  END of Strategy DashBoard
#######################################

I updated the code above (minor typos) and included a few more examples where the strategy is configured with a Long Entry bias.

rsegal_ProjectedMoveandExpectedBounce_long_bias
Share grid: http://tos.mx/n5FHeWw

Your comments are helpful please provide them.


1703818959722.png


1703819000719.png


1703819031387.png
 
Last edited:
@Ramisegal Thank you for sharing your work.
If it is not too much trouble, could you provide a user manual and/or perhaps add a video demo/tutorial.
I is not easy to take advantage of presented tools without understanding
how to use them ?
covered use cases ? (stocks, options, futures) (day- swing- trading)
what limitation (if any) exist?
thanks again
 
Thank you for inquiring about the strategy.
Do you have any specific questions or interests or general use you want me to focus on?
Documentation can become an overwhelming task specialy with not much interest in the tool.
 
Thank you for inquiring about the strategy.
Do you have any specific questions or interests or general use you want me to focus on?
Documentation can become an overwhelming task specialy with not much interest in the tool.
Sure,
1. Could you explain how (steps to take) to add the value of your backtesting tool(s) by applying (configuring) it to track a user developed strategy.
2. Please explain how to use labels, what to monitor for ?
3. What steps to take for optimizing ?
Many thanks in advance
 
If you are interested in the Dashboard tools you can find the instructions in this post:
https://usethinkscript.com/threads/gandalfprojectresearchsystem-dashboard-for-thinkorswim.17429/

follow the steps and add your custom strategy or any strategy to the chart.
note:
the code for the lower study is extending the standard floating PL study
the code for the upper strategy dash board must be created and saved as a strategy

Some strategy are resource intensive and may take a long time to load and may give the impression all data was loaded and processed so i used the lower study to indicate when all calculations are done. its not perfect there some cases where the entries started after the first bar in the set.
make sure you turn on the market time to display the pnl start date vs 1st bar date.

the optimization is a personal preference, as you start using the tool it will help you identify the impact of your changes on you trade odds.
 
Thank you for rekindling the interest in the options expected move.
I won't have time to contribute until I finish some other tasks, but I do wonder when the EM fails what other oddities occur before that... I wouldn't get bogged down with Macro Economics events which are subjective I think just other market internals might be adequate to confirm expected moves...
https://usethinkscript.com/search/1435069/?q=internals&o=date
Documentation can become an overwhelming task specialy with not much interest in the tool.
Absolutely that is something everyone faces.
 
Thank you for rekindling the interest in the options expected move.
I won't have time to contribute until I finish some other tasks, but I do wonder when the EM fails what other oddities occur before that... I wouldn't get bogged down with Macro Economics events which are subjective I think just other market internals might be adequate to confirm expected moves...
https://usethinkscript.com/search/1435069/?q=internals&o=date

Absolutely that is something everyone faces.

In this strategy the the projected move is a target zone for an entry in the opposite direction when the a projection is reversing trend (next period over or under previous period) the strategy can either exit the trade or reverse direction.
on the lower time frames as an addition to the weekly/daily fractal concept (bounce of the edges and reversals on trend shift) the super trend (modified version of the ATR) to stay with the trend.
The strategy back test well with highly liquid underlines.

With TOS the back testing on the lower time frame is limited and very slow but somewhat extended in the OnDemand mode specially when all the markets are close. lol

I can document all the logic in the strategy line by line but I was hoping the tooltips and comments in the code with very clearly stated variable names will be sufficient.

Is there a module in the forum or a post with strategy/study documentation template to follow ?
 
In this strategy the the projected move is a target zone for an entry in the opposite direction when the a projection is reversing trend (next period over or under previous period) the strategy can either exit the trade or reverse direction.
Okay, that helps me understand where you are coming from.
There were times in the past where those who worked on the original EM used it to understand how often price would be outside of the ER, and how much greater value options might be auctioned to as a result of surpassing the expected move.
I don't think EM was ever a breakout indicator by itself but it was used on the daily to understand the pricing of volatility.

I can document all the logic in the strategy line by line but I was hoping the tooltips and comments in the code with very clearly stated variable names will be sufficient.

Is there a module in the forum or a post with strategy/study documentation template to follow ?
That is absolutely not necessary what you have done is very complete. I was only wondering if you wanted to use internals as a confirmation.

I am a bit surprised that you are using this to trade almost like a mean reversal. Of course the price can return to within the EM but I don't know if it may face resistance as the market adjusts to the abruptness of whatever catalyst created the trend beyond the "expected move" in the first place.
 
It is a mechanical system more that proved to be consistent so it serves as a bias with the self adjusting rules i would have manually apply with my technical analysis.
The projected move are from period to period using the implied volatility which is the earliest predictor in tos.
Other internals such as cumulative tick/advanced/declines across all indexes and overall breadth so far have been hard to work with.
https://usethinkscript.com/threads/cumulative-tick-indicator-for-thinkorswim.603/post-135795

i will update a new chart weekly to monitor if it keeps up the performance.
1704397277323.png
 
Last edited:
It is a mechanical system more that proved to be consistent so it serves as a bias with the self adjusting rules i would have manually apply with my technical analysis.
The projected move are from period to period using the implied volatility which is the earliest predictor in tos.
Other internals such as cumulative tick/advanced/declines across all indexes and overall breadth so far have been hard to work with.
https://usethinkscript.com/threads/cumulative-tick-indicator-for-thinkorswim.603/post-135795

i will update a new chart weekly to monitor if it keeps up the performance.
View attachment 20618
Very good, I will be out awhile but over the weekend I will observe more closely and hopefully I might be able to contribute something that brings you some enjoyment. 😇
 
Very good, I will be out awhile but over the weekend I will observe more closely and hopefully I might be able to contribute something that brings you some enjoyment. 😇

MatthewA

It's been 2 weeks since the lower edge was touched, the image below is an update on the strategy in progress still holding a short position targeting 17,211 for a bounce this week

1706572230011.png
 

MatthewA

It's been 2 weeks since the lower edge was touched, the image below is an update on the strategy in progress still holding a short position targeting 17,211 for a bounce this week

View attachment 20830
Yes my friend, yesterday I slept 12 hours after finishing midterms. I'm going to start releasing the ViewOfVolume indicators and get back to modeling Volatility as Mr. @Welkin taught.
It is good to be back and great to see everyone is doing well. :)
 

@MatthewA​

It's been 2 weeks since the lower edge was touched, the image below is an update on the strategy in progress still holding a short position targeting 17,211 for a bounce this week
That is awesome my brother. If I had been using options data to follow this asset I probably would have gotten short today as that has the first day with retracement potential from my "ViewOfVolume".
I would have gotten short around noon after my "DPLs" were clear.
EntryShortNQ.png


I would love any thoughts or constructive criticisms you may have for me. I haven't relaunched the ViewOfVolume quite yet as it was lagging and repainting for some users and I was terrified of leading others the wrong way with mistakes.
I haven't found any outright bugs in the old code but I am concerned that it was overburdening computers.

DPLs for trailing stops and partial profits.png
 
https://usethinkscript.com/members/matthewa.3104/
I like the hints/comments/labels displayed in your image, could it be displayed in the study programmatically (generated by the script using the "rules/thoughts" you used to write them)?

I would like to incorporate your study with my strategy.
let me know if I have your most recent version.
This shared link of the image below (updated most recent version of the strategy)
http://tos.mx/dVBZSUQ


1706890078019.png


Thanks.
 
https://usethinkscript.com/members/matthewa.3104/
I like the hints/comments/labels displayed in your image, could it be displayed in the study programmatically (generated by the script using the "rules/thoughts" you used to write them)?

I would like to incorporate your study with my strategy.
let me know if I have your most recent version.
This shared link of the image below (updated most recent version of the strategy)
http://tos.mx/dVBZSUQ


View attachment 20883

Thanks.
Hello @Ramisegal ,
I've been so busy at school I haven't had time to visit with you.

Lately I have been thinking it might be less stressful and more forgiving if you do not have to hold single trades from Expected Move positions.

There are many terms which may allow a more graceful "surfing" 🌊🏄‍♀️ experience.
 

Attachments

  • image-2.png
    image-2.png
    169.2 KB · Views: 210
Hello @Ramisegal ,
I've been so busy at school I haven't had time to visit with you.

Lately I have been thinking it might be less stressful and more forgiving if you do not have to hold single trades from Expected Move positions.

There are many terms which may allow a more graceful "surfing" 🏄‍♀️ experience.

Thank you for your kind advice though I am retired enjoying the stress-free life in Hawaii! 🌊Surfing and being close to nature can be incredibly rejuvenating. Remember, trading should complement your lifestyle, not compromise it.

Since the strategy was posted 8 out of 10 signals were profitable.

sseyAKRPGINDXZOoeMhdm8TZXlL-IZ0A26Rj-ohJLDx1UA-PRnlV6vwsk0arHOiPiGzuIEOHuipiXNVS0aqk6rAeSZo06-sM5D-7Q0TGFl1gMuHrn5jXDQEJnXcUqp5zTwVv3eW_5PGjp3sZkEtvJr0


This section of the configuration defines various inputs related to order entry strategies:

JvsklgKWaPETPr-132j7MuNADgK_3XesthwQBo78ff5ro4NAABBH8We4WkXTEDKSZEJyrKiVwkQRVKkzz24EvzxvCVYJLcMmUS3zV_liryAZVPAZr9ORak5m9l8VwBfSj4d5i6xNQYxjoaJKgt2efa4


These inputs allow the user to customize the order entry strategy based on projected moves and touch lines, with options for auto-order, biasing, and directional trading.


Projected Move Strategy Orders:
OrderEntryUseAutoPmOrBounceTouch
: enables auto-trading when price reaches edges of projected move or touch lines and bounces off them (default is yes)
OrderEntryUsePmAuto: enables auto-trading when price reaches edges of high/low projected move lines (default is yes)
OrderEntryUseTouchAuto: enables auto-trading when price bounces off edges of projected touch lines (default is yes)
OrderEntryUsePmShiftingLevels: sets levels to recent projected move lines when direction shifts (default is yes)
OrderEntryUseProjectedMove: enables trading when price reaches edges of projected move line (default is no)
OrderEntryUseProjectedMoveTouch: enables trading when price touches edges of projected move touch line (default is no)
OrderEntryUseBuyBias: biases trading to long positions when levels are touched and direction is considered (default is no)
OrderEntryUseSellBias: biases trading to short positions when levels are touched and direction is considered (default is no)
OrderEntryUseDirectionMove: enables trading in direction of recent bounce (default is no)
OrderEntryUseMarketShiftPmExit: closes all trades when projection reverses from previous period direction (default is no)
OrderEntryUseMarketShiftPmAutoExit: closes and reopens trades in reverse direction when auto-exit is true (default is yes)




OrderSimbol: displays a symbol (B or S) to indicate whether an order is an entry order or a detail order (default is yes)

To display the entry order name with the condition detail
OrderEntryUseAutoPmOrBounceTouch B(Atv)@ , S(Atp)@
OrderEntryUseAutoPmOrBounceTouch B(Av)@ , S(Ap)@

OrderEntryUseProjectedMove B(V)@ , S(V)@
OrderEntryUseProjectedMoveTouch B(Tv)@ , S(Tp)@

OrderEntryUsePmShiftingLevels B(level), S(Level)@
OrderEntryUseDirectionMove B(>d)@ , S(<d)@


OrderEntryUseBuyBias B>>>@$ , S>x@$
OrderEntryUseBuyBias B, Sx

OrderEntryUseSellBias S, B<x@$
OrderEntryUseSellBias S, B<x@$

OrderEntryUseMarketShiftPmAutoExit S(AExit)@
OrderEntryUseMarketShiftPmAutoExit B(AExit)$

OrderEntryUseMarketShiftPmExit S(Exit)@
OrderEntryUseMarketShiftPmExit B(Exit)@

Most recent version of the strategy below:
Code:
##-------------------------------------------------------------------------------------
## Rami Segal ## https://usethinkscript.com/members/ramisegal.8158/
##---------------------------- ProjectedMoveExpectedBounce v2.0 ----------------------------
##---- inspired by... ---------------------------------------------------------------------------------
##-------------------------------------------------------------------------------------
# TheoTrade_Weely_Expected_Move
# Copyright TheoTrade LLC
# V08.11.2017
# Free for use. Header credits must be included when any form of the code included in # This package is used.
#
# User assumes all risk. Author not responsible for errors or use of tool.
# scripted by Todd Rind
#
# Thanks to all those who have freely shared ThinkScript concepts over the Web.
#
# The study is used to analyze the DAILY CLOSING performance of an equity against
# the expected move (EM) for any ticker.
# The study works for daily aggregation only.
# Best performance will be against ETF's due to the option and stock implied volatility
# typically being close. When looking at equities, earnings will cause a difference
# between volatility for options and stock. That is, option volatility may be
# elevated as compared to the stock volatility. Since option volatility cannont
# be accessed from ThinkScript, the script EM will be lower than the EM found
# in the option chain.
#
# NEW LOGIC
#
# Drawing line from previous close.
# Completed the daily calculations for inside EM.
# Turn the "dots" for the bars exceeding EM to RED.
# Added logic for "touches". The "dots" for touches are BLUE.
# Touches are a calculated bandwidth around the EM bars. EX:
# High touches occur when either the high or close is within the calculated
# bandwidth of the EM. Default is 90% of EM.
#
# MINOR ISSUES TO MONITOR
#
# Remove the bars not marked with EM levels from the % occurance calculation.
# Fixed by making sure high & low bar > 1.
#
# Note sent to TOS Support about counter issues when checking day number-no response
# from TO. It appears that occasionally a bar out of view is used as the start.
# Seems to sometimes make Friday count one to many.
#
#-------------------- Header End ----------------------------

##-------------------------------------------------------------------------------------
## Rami Segal ## https://usethinkscript.com/members/ramisegal.8158/
##---------------------------- ProjectedMoveExpectedBounce ----------------------------
##-------------------------------------------------------------------------------------

##############################################################################
########################       ProjectedMove User Input     ##################
##############################################################################

input mode = {default "Weekly", "Daily"};#hint mode: Daily for Lower time frames, weekly for daily time frame only.
input EnableStrategy = yes; #hint EnableStrategy: Enable or Disable the strategy
input UseMarketTime = no; #hint UseMarketTime: When UseMarketTime is true the Strategy simulates trades from TradeTimeStart to TradeTimeEnd
Input UseTradeOffTradeTime = no; #hint UseTradeOffTradeTime: When UseTradeOffTradeTime is true the Strategy simulates trades from TradeTimeEnd to TradeTimeStart
input TradeTimeStart = 0930;
input TradeTimeEnd = 1600;
input UseMarketTradeTimeToExitPositions = no;#hint UseMarketTradeTimeToExitPositions: When UseMarketTradeTimeToExitPositions is true the Strategy will close any open positions at TradeTimeEnd
input UseDateRange = no; #hint UseDateRange: Strategy simulate trades within the date range specified
input ActiveStartDate = 20230101;
input ActiveEndDate = 20240101;
input ShowTime = yes; #hint ShowTime: Display time, Time updates based on the chart aggregation period
##-------------------------------------------------------------------------------------
################################################################################## PreMarket  #################
input PreMarketStart = 0400; #hint PreMarketStart: Plot Highs and Lows per PreMarket start time
input PreMarketEnd = 0700; #hint PreMarketEnd: Plot Highs and Lows per PreMarket End time
input ShowPreMarketCloud = no;
input ShowPreMarketLines = no;
##-------------------------------------------------------------------------------------
################################################################################## Look and feel #################

input ShowProjectedMoveCalculations = no;
input ShowProjectedMovePlots= yes;#hint ShowProjectedMovePlots:Hide or show the Projected Move lines
input ShowProjectedMoveClouds= yes;
input showOnlyLastPeriod = no;#hint showOnlyLastPeriod:Limit the Projected Move lines to recent Daily or Weekly mode
input showOnlyLastPeriodLength = 6;#hint showOnlyLastPeriodLength:The number of periods to display the Project Move lines
input ShowDebugVerticalIV = no;#hint ShowDebugVerticalIV:Show verticalHorizontalFilter lines with the implied volatility on period switch
input ProjectedMoveSkewPercent = 70; #hint ProjectedMoveSkewPercent:Projected Move offset percent
input ProjectedMoveExpensionPercent = 110;#hint ProjectedMoveExpensionPercent:Extend the Projected Move to determine the High and Low Bar for the period
input ProjectedMoveTouchesPercent = 80;#hint ProjectedMoveTouchesPercent: Projected Move offset percent to determine the Touch bar offset from the High and Low Bar for the period
##-------------------------------------------------------------------------------------
##################################################################################
################################################################################## For debugging
##################################################################################
input UseCurrentChartClose = yes;#hint UseCurrentChartClose: Use Daily close or current chart close price to project the Move  For debugging
input UseImpVol = yes; #hint UseImpVol:  Use Implied volatility or IV override value  For debugging
input UseDailyIv = no; #hint UseDailyIv: For debugging
input Iv_override = 0.1618; #hint Iv_override:  Value to use for IV  For debugging
##-------------------------------------------------------------------------------------
################################################################################## The square root of time
##################################################################################
input IvWeekdays = 6; #hint UseImpVol:  Number of days per week period to use in the square root of time
input IvYearDays = 365; #hint IvYearDays:  Number of days a year period to use in the square root of time
input UseDaySession = no;#hint UseDaySession: Used in Daily mode to start the projection per DaySessionHour value
input DaySessionHour = 4;#hint DaySessionHour: Used in Daily mode to start the projection per hour value
input UseActiveMarkets = no;#hint UseActiveMarkets: Start intraday projections at DaySessionStartTime and DaySessionCloseTime
input DaySessionStartTime = 0400;#hint DaySessionStartTime: Used in Daily mode
input DaySessionCloseTime = 1800;#hint DaySessionCloseTime: Used in Daily mode
##-------------------------------------------------------------------------------------
################################################################################## Simulate trades
##################################################################################
input useEntryAlerts = no;
input useSignalAlerts = no;
input OrderSimbol = yes; #hint OrderSimbol: Display B or S for Order Entry vs Detail entry price and order source
input useSignalOrderEntry = no;
input UseTouchWithinPmEdge = no; #hint UseTouchWithinPmEdge: high or low within the Projected Move and touch lines
input UseTouchBreachPmEdge = yes; #hint UseTouchBreachPmEdge:  high or low Breach the Projected Move touch line

input ProjectedMoveStrategyOrders = "**PM Entry Orders**";
input OrderEntryUseAutoPmOrBounceTouch = yes; #hint OrderEntryUseAutoPmOrBounceTouch: When OrderEntryUseAutoPmOrBounceTouch is true, Simulate trades when OrderEntryUsePmAuto or OrderEntryUseTouchAuto and any bounce of the edges of the projected moves lines. a counter is used per bounce to control the entry per period.
input OrderEntryUsePmAuto= yes;#hint OrderEntryUsePmAuto: When OrderEntryUsePmAuto and OrderEntryUseAutoPmOrBounceTouch is true, Simulate trades when price reaches the edges of the High or low projected move lines
input OrderEntryUseTouchAuto= yes;#hint OrderEntryUseTouchAuto: When OrderEntryUseTouchAuto and OrderEntryUsePmAuto is true, Simulate trades when price bounce of the edges of the High or low projected touch lines
input OrderEntryUsePmShiftingLevels = yes;#hint OrderEntryUsePmShiftingLevels: when OrderEntryUsePmShiftingLevels is true the Shifting Levels are set to the most recent projected move lines as the projected moves are shifting direction from period to period. when OrderEntryUsePmShiftingLevels is true, Simulate trades when the close price exceeds the levels

input OrderEntryUseProjectedMove= no;  #hint OrderEntryUseProjectedMove: Simulate trades when price reaches the edges of the projected move line
input OrderEntryUseProjectedMoveTouch= no;  #hint OrderEntryUseProjectedMoveTouch: Simulate trades when price touches the edges of the projected move touch line

input OrderEntryUseBuyBias = no;  #hint OrderEntryUseBuyBias: When OrderEntryUseBuyBias is true and if OrderEntryUsePmShiftingLevels is true the Direction will be included and any bounce of the edges of the projected moves lines, Simulate Long trades only and exit long on a Short signal.
input OrderEntryUseSellBias = no;  #hint OrderEntryUseSellBias: When OrderEntryUseSellBias is true and if OrderEntryUsePmShiftingLevels is true the Direction will include any bounce of the edges of the projected moves lines, , Simulate Short trades only and exit Short on a Long signal.

input OrderEntryUseDirectionMove = no; #hint OrderEntryUseDirectionMove: When OrderEntryUseDirectionMove is true, Simulate trades in the direction of the most recent bounce
input OrderEntryUseMarketShiftPmExit = no;#hint OrderEntryUseMarketShiftPmExit: When OrderEntryUseMarketShiftPmExit is true, Projections reversals from previous period direction, Close all Simulated trades
input OrderEntryUseMarketShiftPmAutoExit= yes; #hint OrderEntryUseMarketShiftPmAutoExit: When OrderEntryUseMarketShiftPmAutoExit is true, Close Simulated trades as UseExit and Reopen a position in the reverse direction
##-------------------------------------------------------------------------------------
########################    End: ProjectedMove User Input     ##############################################
##########################################################################################################
##-------------------------------------------------------------------------------------
##################################################################################
#############                Time                                  ###############
##-------------------------------------------------------------------------------------
def TimeZone = 10.5;
def activedaterange = GetYYYYMMDD() >= ActiveStartDate and GetYYYYMMDD() <= ActiveEndDate;
def activerange = if UseDateRange then  activedaterange else 1;
def Hours = Floor(TimeZone + SecondsFromTime(0930) / 60 / 60) - 1;
def Minutes = ((TimeZone + SecondsFromTime(930) / 60 / 60) % 1) * 60;

AddLabel(ShowTime, " 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);

AddLabel(UseDateRange, if UseDateRange then "Range " + asPrice(ActiveStartDate) + " - " + asPrice(ActiveEndDate) else ""  , Color.WHITE );

##################################################################################
#######################    ActiveTradeTime            ############################
##-------------------------------------------------------------------------------------

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 ActiveTradeTime[1] and !ActiveTradeTime and UseMarketTradeTimeToExitPositions else  !ActiveTradeTime and ActiveTradeTime[1])  and UseMarketTradeTimeToExitPositions;
AddLabel(UseMarketTime, if ActiveTradeTime then "Active " + asPrice(TradeTimeStart) + " - " + asPrice(TradeTimeEnd) else ""  , Color.WHITE );


##-------------------------------------------------------------------------------------
##################################################################################
AddOrder(OrderType.BUY_TO_CLOSE, EnableStrategy  and  closeallmarket, tickcolor = GetColor(1), arrowcolor = GetColor(1), name =  mode+"BxEdt@ " + open[-1]) ;
AddOrder(OrderType.SELL_TO_CLOSE, EnableStrategy and  closeallmarket, tickcolor = GetColor(1), arrowcolor = GetColor(1), name =  mode+"SxEdt" + open[-1]);
AddOrder(OrderType.BUY_TO_CLOSE, EnableStrategy  and  !activerange, tickcolor = GetColor(1), arrowcolor = GetColor(1), name =  mode+"BxRange@ " + open[-1]) ;
AddOrder(OrderType.SELL_TO_CLOSE, EnableStrategy and  !activerange, tickcolor = GetColor(1), arrowcolor = GetColor(1), name =  mode+"SxRange@" + open[-1]);

##################################################################################
##################################################################################
##################################################################################
##-------------------------------------------------------------------------------------
##-------------------------------------------------------------------------------------
##-------------------------------------------------------------------------------------
##################################################################
#                          Projected Move Mode                   #
##################################################################
###Daily for Lower timeframes, weekly for daily time frame only.

def UseWeekly ;
switch (mode) {
case "Weekly":
    UseWeekly = 1;
case "Daily":
    UseWeekly = 0;
}
##################################################################
#                          Projected Move Price                       #
##################################################################
def AggregationPeriod = AggregationPeriod.DAY;
def PriceHigh = if UseCurrentChartClose then high[0] else high(period = aggregationPeriod)[0];
def PriceLow =  if UseCurrentChartClose then  low[0] else low(period = aggregationPeriod)[0];
def PriceClose =  if UseCurrentChartClose then close[0] else close(period = aggregationPeriod)[0];
def ivPriceClose =  if IsNaN(close(period = aggregationPeriod)[1]) then close[1] else close(period = aggregationPeriod)[1];


def DaySessionActive = if GetDay() != GetDay()[1] then 0  else if SecondsTillTime(DaySessionStartTime) <= 0 and  SecondsTillTime(DaySessionCloseTime) >= 0  then 1 else 0;

##################################################################
#                          # implied volatility                            #
##################################################################

def Dailyiv =  imp_volatility(period = aggregationPeriod)[1];
def iv = if UseDailyIv then Dailyiv else if UseWeekly then impVolatility() else imp_volatility();

##################################################################
#                          Projected Move calculations                        #
##################################################################

## True when weekly period changed
def calcw = if GetDayOfWeek(GetYYYYMMDD()) == 1  or ( (GetDayOfWeek(GetYYYYMMDD()[1]) == 5 and GetDayOfWeek(GetYYYYMMDD()) == 2))
then 1 else 0;

## true when intraday period changed, if day session and hour selected or day session active session or the daily aggregation period changed (based on user INPUT)
def calcpm = if UseWeekly then calcw else if UseDaySession and Hours == DaySessionHour and Hours <> Hours[1] 
then 1 else if UseActiveMarkets then DaySessionActive[1] <> DaySessionActive else if ivPriceClose <> ivPriceClose[1] then 1 else  0;


## declare variables to populate on perriod change
def PojectedMove_IV;
def PojectedMove;
def Pojected_high_bar;
def Pojected_low_bar;
def pm_close;
def weekcnt;
def Pojected_Touch_high_bar;
def Pojected_Touch_low_bar;

if calcpm == 1 and calcpm[1] == 0
then {
    pm_close = if UseWeekly then  ivPriceClose else if UseCurrentChartClose then PriceClose else ivPriceClose;
    PojectedMove_IV =  if UseImpVol then iv else Iv_override;
    PojectedMove = ( if UseWeekly then (pm_close * PojectedMove_IV * Sqrt(IVweekdays) / Sqrt(IvYearDays) * ProjectedMoveSkewPercent / 100 * ProjectedMoveExpensionPercent / 100)  else pm_close * PojectedMove_IV * Sqrt(1 / IVweekdays) / Sqrt(IvYearDays) * ProjectedMoveSkewPercent / 100 * ProjectedMoveExpensionPercent / 100);
    Pojected_high_bar =  (pm_close) + PojectedMove;
    Pojected_Touch_high_bar = (pm_close) + (PojectedMove * ProjectedMoveTouchesPercent / 100);
    Pojected_low_bar = ( pm_close) - PojectedMove;
    Pojected_Touch_low_bar = (pm_close ) - (PojectedMove * ProjectedMoveTouchesPercent / 100);
    weekcnt = weekcnt[1] + 1;
}
else {
    PojectedMove_IV = PojectedMove_IV[1];
    PojectedMove = PojectedMove[1];
    Pojected_high_bar = Pojected_high_bar[1];
    Pojected_Touch_high_bar = Pojected_Touch_high_bar[1];
    Pojected_low_bar = Pojected_low_bar[1];
    Pojected_Touch_low_bar = Pojected_Touch_low_bar[1];
    pm_close = pm_close[1];
    weekcnt = weekcnt[1];
}
## End declare variables to populate on perriod change

##################################################################
#                          # projections Peak and Vally           #
##################################################################

## exceed projections
def peak = if Pojected_high_bar > 1 and PriceClose > Pojected_high_bar then 1 else 0;
def valley = if Pojected_low_bar > 1 and PriceClose < Pojected_low_bar then 1 else 0;

##original theotrade
#def touchpeak = if Pojected_high_bar > 1 and ((high < Pojected_high_bar and high >= Pojected_Touch_high_bar) or (close < Pojected_high_bar and close >= Pojected_Touch_high_bar)) then 1 else 0;
#def touchvalley = if Pojected_low_bar > 1 and ((low > Pojected_low_bar and low <= Pojected_Touch_low_bar) or (close > Pojected_low_bar and close <= Pojected_Touch_low_bar)) then 1 else 0;

## touch stay or bounce
## options for true condition: if UseTouchWithin is true then high or close are between the upper edge and the upper touch projection lines else just the high is higher then the upper projection touch line and if UseTouchBreach is false then low must be under the upper touch line.
## the theotrade original script where the close is in between the projection high touch line and the projection high line
def touchpeak = if Pojected_high_bar > 1 and
(
(if UseTouchWithinPmEdge
then
    PriceHigh < Pojected_high_bar and PriceHigh >= Pojected_Touch_high_bar
else
    PriceHigh >=  Pojected_Touch_high_bar
    and
    if UseTouchBreachPmEdge
    then
        1
    else
        PriceLow < Pojected_Touch_high_bar  )
or
(PriceClose < Pojected_high_bar and PriceClose >= Pojected_Touch_high_bar)
) then 1 else 0;


## options for true condition: if UseTouchWithin is true then low or close are between the lower edge and the lower touch projection lines else just the low is lower then the lower projection touch line and if UseTouchBreach is false then high must be above the lower projection touch line.
def touchvalley = if Pojected_low_bar > 1 and
(
( if UseTouchWithinPmEdge
then
    PriceLow> Pojected_low_bar and PriceLow <= Pojected_Touch_low_bar
else
    PriceLow<= Pojected_Touch_low_bar
    and
    if UseTouchBreachPmEdge then
        1 else
        PriceHigh > Pojected_Touch_low_bar )
or
(PriceClose >     Pojected_low_bar and PriceClose <= Pojected_Touch_low_bar)
) then 1 else 0;


## count all peaks and vallys
def pkcnt =  if  peak then pkcnt[1] + 1 else pkcnt[1] ;
def vcnt = if valley then vcnt[1] + 1 else vcnt[1] ;

def tpkcnt =  if  touchpeak then tpkcnt[1] + 1 else tpkcnt[1] ;
def tvcnt = if touchvalley then tvcnt[1] + 1 else tvcnt[1] ;



## count all touches peaks and vallys per period and reset to 0 on period change
## this is to control one order per perriod per peak or vally
## additional orders on a new period mostly a double down on the position if enabled in global strategy settings
def peakcnt = if weekcnt != weekcnt[1] or valley then 0 else  if  peak then peakcnt[1] + 1 else peakcnt[1] ;
def valleycnt = if weekcnt != weekcnt[1] or peak then 0 else if valley then valleycnt[1] + 1 else valleycnt[1] ;




def touchpeakcnt = if weekcnt != weekcnt[1] or touchvalley   then 0 else if touchpeak then touchpeakcnt[1] + 1 else touchpeakcnt[1] ;
def touchvalleycnt = if weekcnt != weekcnt[1] or touchpeak  then 0 else if touchvalley then touchvalleycnt[1] + 1 else touchvalleycnt[1] ;

#addVerticalLine(peakcnt[1] == 0 and peakcnt[0]==1, "Pk "+peakcnt, color.white);
#addVerticalLine(valleycnt[1] == 0 and valleycnt[0]==1, "PV "+valleycnt, color.white);
#addVerticalLine(touchvalleycnt[1] == 0 and touchvalleycnt[0]==1, "PVT "+touchvalleycnt, color.white);
#addVerticalLine(touchpeakcnt[1] == 0 and touchpeakcnt[0]==1, "PkT "+touchpeakcnt, color.white);


## control the number of plots to display per mode
## variable used: weekcnt is the period counter for the strategy mode
def slp = if showOnlyLastPeriod and  if UseWeekly then weekcnt > highestAll(weekcnt)-showOnlyLastPeriodLength else weekcnt > highestAll(weekcnt)-3  then 1 else 0;

plot ProjectionStart ;
plot ProjectionHigh ;
plot ProjectionLow ;
plot ProjectionHighTouch ;
plot ProjectionLowTouch;

if showOnlyLastPeriod  {
    ProjectionHigh = if  Pojected_high_bar < 1 then Double.NaN else if slp then Pojected_high_bar else Double.NaN;
    ProjectionLow = if Pojected_low_bar < 1 then Double.NaN else if slp then Pojected_low_bar else Double.NaN;
    ProjectionStart =  if pm_close < 1 then Double.NaN else if slp then pm_close else Double.NaN;
    ProjectionHighTouch = if  Pojected_high_bar < 1 then Double.NaN else if slp then Pojected_Touch_high_bar else Double.NaN;
    ProjectionLowTouch = if Pojected_low_bar < 1 then Double.NaN else if slp then Pojected_Touch_low_bar else Double.NaN;


} else {
    ProjectionHigh = if  Pojected_high_bar < 1 then Double.NaN else Pojected_high_bar;
    ProjectionLow = if Pojected_low_bar < 1 then Double.NaN else Pojected_low_bar;
    ProjectionStart =  if pm_close < 1 then Double.NaN else pm_close;
    ProjectionHighTouch = if  Pojected_high_bar < 1 then Double.NaN else Pojected_Touch_high_bar;
    ProjectionLowTouch = if Pojected_low_bar < 1 then Double.NaN else Pojected_Touch_low_bar;
}

## clouds will show per showOnlyLastPeriod since they hinge on the plots
## shade between projections and touches
addCloud(if ShowProjectedMoveClouds then ProjectionHigh else double.nan, ProjectionHighTouch,color.pink );
addCloud(if ShowProjectedMoveClouds then ProjectionLowTouch  else double.nan,ProjectionLow , color.light_green);



## hide and show projections plots
ProjectionHigh.SetHiding( !ShowProjectedMovePlots);
ProjectionHigh.SetDefaultColor(Color.GREEN);
ProjectionHigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ProjectionHigh.SetLineWeight(2);

ProjectionLow.SetHiding( !ShowProjectedMovePlots);
ProjectionLow.SetDefaultColor(Color.RED);
ProjectionLow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ProjectionLow.SetLineWeight(2);
ProjectionStart.SetHiding( !ShowProjectedMovePlots);
ProjectionStart.SetDefaultColor(Color.WHITE);
ProjectionStart.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ProjectionStart.SetLineWeight(2);
ProjectionHighTouch.SetHiding( !ShowProjectedMovePlots);
ProjectionHighTouch.SetDefaultColor(Color.LIGHT_GREEN);
ProjectionHighTouch.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ProjectionHighTouch.SetLineWeight(2);
ProjectionLowTouch.SetHiding( !ShowProjectedMovePlots);
ProjectionLowTouch.SetDefaultColor(Color.LIGHT_RED);
ProjectionLowTouch.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ProjectionLowTouch.SetLineWeight(2);


##################################################################
#                          Levels                             #
##################################################################

## capture the previous projections on a new perriod, this is used for the projections trend
def prevPojectedMove = if PojectedMove <> PojectedMove[1] then PojectedMove[1] else  prevPojectedMove[1] ;
def prevhighbar = if Pojected_high_bar <> Pojected_high_bar[1] then Pojected_high_bar[1] else prevhighbar[1];
def prevlowbar = if Pojected_low_bar <> Pojected_low_bar[1] then Pojected_low_bar[1] else prevlowbar[1];


##################################################################
#          ## Show Projections calculations        #
##################################################################
AddLabel(ShowProjectedMoveCalculations, "ProjectedMoveIntraDay: " +mode , Color.WHITE );
AddLabel(UseDateRange, if activerange then "Strategy Range " + AsPrice(ActiveStartDate) + " - " + AsPrice(ActiveEndDate) else ""  , Color.WHITE );
AddLabel(ShowProjectedMoveCalculations, "Recent IV = " + PojectedMove_IV);
AddLabel(ShowProjectedMoveCalculations, "Recent PM = " + PojectedMove, if prevPojectedMove <= PojectedMove then Color.LIGHT_GREEN else Color.PINK);
AddLabel(ShowProjectedMoveCalculations, "Prev PM = " + prevPojectedMove, if prevPojectedMove >= PojectedMove then Color.LIGHT_GREEN else Color.PINK);
AddLabel(ShowProjectedMoveCalculations, "Recent High Bar = " + Pojected_high_bar);
AddLabel(ShowProjectedMoveCalculations, "Recent Low Bar = " + Pojected_low_bar);
AddLabel(ShowProjectedMoveCalculations, "PM Skew%/Std Dev Adj(%)/Touches% = " + ProjectedMoveSkewPercent + "/" + ProjectedMoveExpensionPercent + "/" + ProjectedMoveTouchesPercent);
AddLabel(ShowProjectedMoveCalculations, "Peak = " + pkcnt);
AddLabel(ShowProjectedMoveCalculations, "Vally  = " + vcnt);
AddLabel(ShowProjectedMoveCalculations, "TPeak = " + tpkcnt);
AddLabel(ShowProjectedMoveCalculations, "TVally  = " + tvcnt);

## for debug sometimes the iv from TOS is double.nan "n/a"
AddVerticalLine(ShowDebugVerticalIV and weekcnt <> weekcnt[1] , "EM:" + " (" + PojectedMove_IV  + ")" ,  if Pojected_low_bar > Pojected_low_bar[1] then Color.GREEN else if Pojected_high_bar < Pojected_high_bar[1] then Color.RED else if Pojected_low_bar > Pojected_low_bar[1] and  Pojected_high_bar < Pojected_high_bar[1] then Color.WHITE else Color.CYAN);

##################################################################
#                          PREMARKET                             #
##################################################################
#PREMARKET HIGHS AND LOWS
def PreMarketTimeRange = secondsFromTime(PreMarketStart) >= 0 and secondsTillTime(PreMarketEnd) >= 0;
def PreMarket = PreMarketTimeRange and !PremarketTimeRange[1];
def Pre_Market_High = compoundValue(1, if((high > Pre_Market_High[1] and PremarketTimeRange) or PreMarket, high, Pre_Market_High[1]), high);
def Pre_Market_Low = compoundValue(1, if((low < Pre_Market_Low[1] and PremarketTImeRange) or PreMarket, low, Pre_Market_Low[1]), low);

plot PreMarketHigh = if Pre_Market_High  == Pre_Market_High[1] then Pre_Market_High else double.nan;
PreMarketHigh.SetStyle(curve.short_dash);
PreMarketHigh.SetDefaultColor(color.light_gray);
PreMarketHigh.Sethiding(!ShowPreMarketLines);
plot PreMarketLow = if Pre_Market_Low == Pre_Market_Low[1] then Pre_Market_Low else double.nan;
PreMarketLow.SetStyle(curve.short_dash);
PreMarketLow.SetDefaultColor(color.light_gray);
PreMarketLow.Sethiding(!ShowPreMarketLines);
AddCloud(if ShowPreMarketCloud then PreMarketHigh else double.nan, if ShowPreMarketCloud then PreMarketLow else double.nan, color.light_gray, color.light_gray);


##################################################################
#                       Shifting Levels                          #
##################################################################
##  1 for higher Projections , -1 for lower
#def emdir = if  Pojected_high_bar > 1 and Pojected_high_bar >= prevhighbar then 1 else if  Pojected_high_bar > 1 and Pojected_high_bar <= prevhighbar then -1 else 0;

def emdir;
emdir = CompoundValue(1, 
  if IsNaN(close) then emdir[1]
  else if Pojected_high_bar > 1 and Pojected_high_bar >= prevhighbar then 1
  else if Pojected_high_bar > 1 and Pojected_high_bar <= prevhighbar then -1
  else emdir[1]
, 0);


# price level of projections shifting direction
def buylevel = if emdir > 0 and emdir[1] < 0 then prevlowbar else buylevel[1];
def selllevel = if emdir < 0 and emdir[1] > 0  then prevhighbar else selllevel[1];

## plot the levels
plot buylevels = if slp then buylevel else double.nan;
plot selllevels = if slp then  selllevel else double.nan;

buylevels.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
selllevels.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
buylevels.SetDefaultColor(if UseWeekly then Color.CYAN else Color.yellow);
selllevels.SetDefaultColor(if UseWeekly then Color.plum else Color.Dark_orange);
buylevels.SetStyle(curve.short_dash);
selllevels.SetStyle(curve.short_dash);
addCloud(buylevels, buylevels+tickValue(), color.blue, color.yellow);
addCloud(selllevels, selllevels-tickValue(), Color.blue, Color.orange);

## conditions for entry based on close above previous perriod Projections
def buyabovelevels = PriceClose >= Max(buylevel , selllevel) ;
def sellunderlevels = PriceClose <= Min(buylevel , selllevel) ;


## condition for entry based on the most recent direction
#def leveldir = if Pojected_high_bar > 1 and Pojected_high_bar > prevhighbar then 1 else if  Pojected_high_bar > 1 and Pojected_high_bar < prevhighbar then -1 else leveldir[1];

def leveldir;
leveldir = CompoundValue(1, 
  if IsNaN(close) then leveldir[1]
  else if Pojected_high_bar > 1 and Pojected_high_bar > prevhighbar  then 1
  else if Pojected_high_bar > 1 and Pojected_high_bar < prevhighbar then -1
  else leveldir[1]
, 0);


addverticalLine(OrderEntryUsePmShiftingLevels and leveldir<> leveldir[1], if leveldir>0 then mode+": LvUp" else mode+ ": LvlDn", if leveldir>0 then color.yellow else color.magenta);
AddLabel(ShowProjectedMoveCalculations, mode+": PM Levels Bias: " + if leveldir > 0 then "Up"else"Dn" ,if leveldir > 0 then  color.green else color.red);

#condition for entry based on most recent touch or peak
#def Dailydirection = if  (valleycnt or touchvalleycnt) then 1 else if  (peakcnt or touchpeakcnt) then -1 else if IsNaN(Dailydirection[1]) then 0 else Dailydirection[1];
def Dailydirection;
Dailydirection = CompoundValue(1, 
  if IsNaN(close) then Dailydirection[1]
  else if (valleycnt or touchvalleycnt) then 1
  else if (peakcnt or touchpeakcnt) then -1
  else Dailydirection[1]
, 0);

AddLabel(ShowProjectedMoveCalculations, mode+": PM Direction Bias: " + if Dailydirection > 0 then "Up"else"Dn" ,if Dailydirection > 0 then  color.green else color.red);


##################################################################
#      ProjectedMove and Expected bounce Strategy Orders                             #
##################################################################

AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and OrderEntryUsePmShiftingLevels  and activerange and buyabovelevels and !buyabovelevels[1], price = open[-1], name = if OrderSimbol then "B" else mode+"B(level)@ " + open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(4));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and OrderEntryUsePmShiftingLevels  and activerange and sellunderlevels and !sellunderlevels[1], price = open[-1], name = if OrderSimbol then "S" else  mode+"S(Level)@ " + open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(4));


AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy  and activerange and ActiveTradeTime and  OrderEntryUseProjectedMoveTouch and  touchvalley and touchvalleycnt == 1 and touchvalleycnt[1] == 0, name = if OrderSimbol then "B" else  mode+"B(Tv)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy  and activerange and ActiveTradeTime and  OrderEntryUseProjectedMoveTouch and  touchpeak  and  touchpeakcnt == 1 and touchpeakcnt[1] == 0, name = if OrderSimbol then "S" else  mode+"S(Tp)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy  and activerange and ActiveTradeTime and  OrderEntryUseProjectedMove and  valley and   valleycnt == 1 and valleycnt[1]== 0  , name = if OrderSimbol then "B" else  mode+"B(V)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy  and activerange and ActiveTradeTime and  OrderEntryUseProjectedMove and  peak and peakcnt == 1 and peakcnt[1] == 0, name = if OrderSimbol then "S" else  mode+"S(V)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and OrderEntryUseDirectionMove and  Dailydirection > 0 and leveldir> 0, name = if OrderSimbol then "B" else  mode+"B(>d)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and OrderEntryUseDirectionMove and  Dailydirection < 0 and leveldir < 0, name = if OrderSimbol then "S" else  mode+"S(<d)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and  activerange and ActiveTradeTime and OrderEntryUseAutoPmOrBounceTouch and  OrderEntryUseTouchAuto and touchvalleycnt == 1 and touchvalleycnt[1] == 0, name = if OrderSimbol then "B" else  mode+"B(Atv)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and OrderEntryUseAutoPmOrBounceTouch  and  OrderEntryUseTouchAuto and  touchpeakcnt == 1 and touchpeakcnt[1] == 0, name = if OrderSimbol then "S" else  mode+"S(Atp)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and OrderEntryUseAutoPmOrBounceTouch and OrderEntryUsePmAuto and   valleycnt == 1 and valleycnt[1] == 0, name = if OrderSimbol then "B" else  mode+"B(Av)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and OrderEntryUseAutoPmOrBounceTouch and  OrderEntryUsePmAuto and peakcnt == 1 and peakcnt[1] == 0, name = if OrderSimbol then "S" else  mode+"S(Ap)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and  activerange and ActiveTradeTime and OrderEntryUseBuyBias  and if OrderEntryUsePmShiftingLevels then leveldir > 0 else 1 and  ( ( valleycnt == 1 and valleycnt[1] == 0 ) or (touchvalleycnt == 1 and touchvalleycnt[1] == 0)), name = if OrderSimbol then "B" else  mode+"B>>>@$ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_TO_CLOSE,!useSignalOrderEntry and  EnableStrategy  and activerange and ActiveTradeTime and OrderEntryUseBuyBias  and  (   touchpeakcnt == 1 and touchpeakcnt[1] == 0 or  peakcnt == 1 and peakcnt[1] == 0 ), name = if OrderSimbol then "Sx" else  mode+"S>x@$ " + Open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

def buytoclosebias =  ( ( valleycnt == 1 and valleycnt[1] == 0 ) or (touchvalleycnt == 1 and touchvalleycnt[1] == 0));
def selltoclosebias =  (   touchpeakcnt == 1 and touchpeakcnt[1] == 0 or  peakcnt == 1 and peakcnt[1] == 0 );


AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and OrderEntryUseSellBias   and if OrderEntryUsePmShiftingLevels then leveldir < 0 else 1 and  (   touchpeakcnt == 1 and touchpeakcnt[1] == 0 or  peakcnt == 1 and peakcnt[1] == 0 ), name = if OrderSimbol then "S" else  mode+"S<<<@$ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));
AddOrder(OrderType.BUY_TO_CLOSE,!useSignalOrderEntry and  EnableStrategy  and activerange and ActiveTradeTime and OrderEntryUseSellBias  and ( ( valleycnt == 1 and valleycnt[1] == 0 ) or (touchvalleycnt == 1 and touchvalleycnt[1] == 0)), name = if OrderSimbol then "Bx" else  mode+"B<x@$ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));

def pmvalid = Pojected_high_bar > 1;
def sellMarketShift = pmvalid and Dailydirection > 0 and Pojected_high_bar < Pojected_low_bar[1];
def buyMarketShift = pmvalid and Dailydirection < 0 and Pojected_low_bar > Pojected_high_bar[1];

AddOrder(OrderType.SELL_auto,!useSignalOrderEntry and  EnableStrategy  and activerange and ActiveTradeTime and  pmvalid and  OrderEntryUseMarketShiftPmAutoExit and  Dailydirection > 0 and Pojected_high_bar < Pojected_low_bar[1], name = if OrderSimbol then "S" else  mode+"S(AExit)@ " + Open[-1], price = Open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

AddOrder(OrderType.BUY_auto,!useSignalOrderEntry and  EnableStrategy  and activerange and ActiveTradeTime and  pmvalid and OrderEntryUseMarketShiftPmAutoExit and Dailydirection < 0 and Pojected_low_bar > Pojected_high_bar[1], name = if OrderSimbol then "B" else  mode+"B(AExit)$ " + Open[-1], price = Open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));


AddOrder(OrderType.SELL_TO_CLOSE,!useSignalOrderEntry and  EnableStrategy  and activerange and ActiveTradeTime and  pmvalid and OrderEntryUseMarketShiftPmExit and  Dailydirection > 0 and Pojected_high_bar < Pojected_low_bar[1], name = if OrderSimbol then "S" else  mode+"S(Exit)@ " + open[-1], price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));
AddOrder(OrderType.BUY_TO_CLOSE,!useSignalOrderEntry and  EnableStrategy  and activerange and ActiveTradeTime and  pmvalid and OrderEntryUseMarketShiftPmExit and Dailydirection < 0 and Pojected_low_bar > Pojected_high_bar[1], name = if OrderSimbol then "Bx" else  mode+"B(Exit)@ " + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));


##################################################################
#     End of ProjectedMove and Expected bounce Strategy                             #
##################################################################





##################################################################
#     End of ProjectedMove and Expected bounce Strategy Orders                             #
##################################################################




##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#                                                SUPERTREND
##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
##################################################################
#     Everything below can be removed from the Projected move strategy                             #
##################################################################


input UseSuperTrendRangeBar = yes; #hint UseSuperTrendRangeBar: Modified TrueRange SuperTrend. Set to No to use the standard ATR
input UseInputOtherTimeFrames = yes;
input otf_AggregationPeriod = AggregationPeriod.FIFTEEN_MIN; #hint otf_AggregationPeriod: SuperTrend time frame
input otf_nATR = 5; #hint otf_nATR: Length for Momentum calculations.
input otf_AvgType = AverageType.SimPLE;
input otf_ATRMult = 0.7;
input otf_TMV = 3; #hint TMV: Modified TrueRange SuperTrend periods.
input otf_Aggregation_Periodoffset = 0; #hint Aggregation_Periodoffset : Higher aggregation will always default to 1 to avoid re painting
input otf_AggregationPeriodHighestHighLowestLowOffset = 0;

##########################################################################################################################################################

def otf_timeFrame =  if GetAggregationPeriod() > otf_AggregationPeriod then GetAggregationPeriod()
else if UseInputOtherTimeFrames then otf_AggregationPeriod else GetAggregationPeriod() ;
def AggregationPeriodoffset = if otf_timeFrame > GetAggregationPeriod() then 1 else otf_Aggregation_Periodoffset;

def tmvotf_priceclose = (highest( close( period = otf_timeFrame)[max(AggregationPeriodoffset,0)],otf_TMV)[otf_AggregationPeriodHighestHighLowestLowOffset]+ lowest( close( period = otf_timeFrame)[max(AggregationPeriodoffset,0)],otf_TMV)[otf_AggregationPeriodHighestHighLowestLowOffset])/2;
def tmvotf_pricehigh = highest(high( period = otf_timeFrame)[max(AggregationPeriodoffset,0)],otf_TMV)[otf_AggregationPeriodHighestHighLowestLowOffset];
def tmvotf_pricelow = lowest( low( period = otf_timeFrame)[max(AggregationPeriodoffset,0)], otf_TMV)[otf_AggregationPeriodHighestHighLowestLowOffset];

def otf_priceclose =  close( period = otf_timeFrame)[max(AggregationPeriodoffset,0)];
def otf_pricehigh =  high( period = otf_timeFrame)[max(AggregationPeriodoffset,0)];
def otf_pricelow =  low( period = otf_timeFrame)[max(AggregationPeriodoffset,0)];;

def otf_h =   if UseSuperTrendRangeBar then tmvotf_pricehigh else otf_pricehigh;
def otf_l =   if UseSuperTrendRangeBar then tmvotf_pricelow else otf_pricelow;
def otf_c =   if UseSuperTrendRangeBar then  tmvotf_priceclose else otf_priceclose;


def otf_TrueRange = TrueRange(otf_h, otf_c, otf_l) ;

def otf_ATR =  MovingAverage(otf_AvgType, otf_TrueRange, otf_nATR);

def otf_UP = otf_c+ (otf_ATRMult * otf_ATR);
def otf_DN = otf_c+ (-otf_ATRMult * otf_ATR);

def otf_lowestup = if otf_UP <= otf_lowestup[1] then otf_UP[0] else if otf_c < otf_lowestup[1] and otf_c < otf_UP[0] then otf_lowestup[1] else otf_UP[0];
def otf_highestdn = if otf_DN >= otf_highestdn[1] then otf_DN[0] else if otf_c > otf_highestdn[1] and otf_c > otf_DN[0]  then otf_highestdn[1] else otf_DN[0];

def otf_trend = if  otf_c[0] crosses below otf_highestdn[1] then -1 else if  otf_c[0] crosses above otf_lowestup[1]  then 1 else otf_trend[1];

def otf_sellmodeprice =  if otf_trend  < 0 and otf_trend <> otf_trend[1] then otf_highestdn[1] else otf_sellmodeprice[1];
def otf_buymodeprice =  if otf_trend  > 0 and otf_trend <> otf_trend[1] then otf_lowestup[1] else otf_buymodeprice[1];

plot otf_sellcrossprice = if  otf_trend  <> 0 then  otf_sellmodeprice else Double.NaN;
plot otf_buycrossprice = if otf_trend  <> 0  then  otf_buymodeprice   else Double.NaN;

otf_sellcrossprice.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
otf_buycrossprice.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

otf_buycrossprice.setdefaultColor(Color.LIGHT_GREEN);
otf_sellcrossprice.setdefaultColor(Color.PINK);

otf_sellcrossprice.SetStyle(Curve.FIRM );
otf_sellcrossprice.SetLineWeight(1);

otf_buycrossprice.SetStyle(Curve.FIRM );
otf_buycrossprice.SetLineWeight(1);


plot otf_sell =  if  otf_trend < 0 then otf_lowestup[0] else Double.NaN ;
plot otf_buy = if  otf_trend > 0  then otf_highestdn[0] else Double.NaN ;

otf_buy .setdefaultColor(Color.lime);
otf_sell.setdefaultColor(Color.magenta);


def otf_barUp = otf_trend > 0 ;
def otf_barDown = otf_trend < 0 ;
def otf_barUpCount = CompoundValue(1, if otf_barUp then (if IsNaN(otf_barUpCount[1]) then 0 else otf_barUpCount[1]) + 1 else 0, 0);

def otf_barDownCount = CompoundValue(1, if otf_barDown then ( if IsNaN( otf_barDownCount[1]) then 0 else otf_barDownCount[1] ) - 1 else 0, 0);

def otf_trendcnt = otf_barDownCount + otf_barUpCount ;

def avgtrendmove =  (close - if otf_trend > 0 then otf_buymodeprice else otf_sellmodeprice ) /otf_trendcnt ;


input ShowSuperTrendLabels = yes;
AddLabel(ShowSuperTrendLabels, "SuperTrendRangeStrategy - TF: " +otf_timeFrame/60000, color.white);
AddLabel(ShowSuperTrendLabels, "Trendind Bars " + (otf_trendcnt) ,  if otf_trend > 0  then Color.LIME else  Color.MAGENTA );
AddLabel(ShowSuperTrendLabels, "Average trend bar " + (avgtrendmove) ,  if avgtrendmove > 0  then Color.LIME else  Color.MAGENTA );
AddLabel(ShowSuperTrendLabels, "ATR " + (otf_atr) ,  if otf_trendcnt > 0  then Color.LIME else  Color.MAGENTA );

input UseMomentumFilter = no;
input TradeFrequecy= {Default "Hold", "Swing", "Scalp"};
def tf;
Switch (TradeFrequecy) {
Case "Swing":
tf = 3;
Case "Scalp":
tf = 2;
Case "Hold":
tf = 1;
}

AddLabel(UseMomentumFilter, "Momentum Filter: " + TradeFrequecy,  color.white);

def otf_trendlowestlow;
def otf_trendhighesthigh;

if otf_trend < 0
then
{
    otf_trendlowestlow = if otf_trend == otf_trend[1] then if (if UseMomentumFilter then (if tf==3 then close else if tf==2 then  low else if tf==1 then high else low) else low) < otf_trendlowestlow[1] then low else otf_trendlowestlow[1] else low[1];
    otf_trendhighesthigh =  otf_trendhighesthigh[1];
}
else
if otf_trend > 0
then
{
    otf_trendlowestlow = otf_trendlowestlow[1];
    otf_trendhighesthigh = if otf_trend == otf_trend[1] then if (if UseMomentumFilter then  (if tf==3 then close else if tf==2 then  high else if tf==1 then low else high) else high) > otf_trendhighesthigh[1] then high else otf_trendhighesthigh[1] else high[1];
}
else
{
    otf_trendlowestlow = otf_trendlowestlow[1];
    otf_trendhighesthigh = otf_trendhighesthigh[1];
}

 
Input ShowSuperTrendHighAndLow = yes;
def trendlowest = if otf_trend<>otf_trend[1] and otf_trend > 0 then otf_trendlowestlow[1] else trendlowest[1];
def trendhighest = if otf_trend<>otf_trend[1] and otf_trend < 0 then otf_trendhighesthigh[1] else trendhighest[1];

plot STrendlowestlow =  if ShowSuperTrendHighAndLow and otf_trend >  0 and otf_trendlowestlow == otf_trendlowestlow[1]then otf_trendlowestlow else double.NaN;
plot STrendhighesthigh =  if ShowSuperTrendHighAndLow and  otf_trend < 0 and otf_trendhighesthigh == otf_trendhighesthigh[1] then otf_trendhighesthigh  else double.NaN;

STrendlowestlow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
STrendhighesthigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
STrendlowestlow.SetDefaultColor(color.red);
STrendhighesthigh.SetDefaultColor(color.green);


##################################################################################################################             
######################################### Trend shifting upper and lower bands #########################################################
##################################################################################################################       
def max1h = max( otf_trendhighesthigh,otf_sellcrossprice );
def min1h = min( otf_trendhighesthigh,otf_sellcrossprice ) ;
def max1l = max(  otf_trendlowestlow,otf_buycrossprice  ) ;
def min1l = min(  otf_trendlowestlow,otf_buycrossprice  ) ;
#################################
input ShowOrderBlockCloud = yes;
#################################
addCloud(if ShowOrderBlockCloud and otf_trendcnt < 0    then min1h  else   double.NaN ,max1h, color.red );
addCloud(if ShowOrderBlockCloud and otf_trendcnt > 0   then max1l  else   double.NaN ,min1l, color.green    );
#################################


def cloudrange = absValue( if otf_trendcnt < 0 then otf_sellmodeprice - otf_trendhighesthigh else otf_buymodeprice - otf_trendlowestlow);

input showSignals = yes;
input showSignalLines = yes;
def useStops = yes;
input SuperTrendRangeStrategyOrders = "**SuperTrendRange Entry Orders**";
input useIntraDaySignalsOnDailyMode = no; #hint useIntraDaySignalsOnDailyMode: Strategy simulate intra day trades on daily time frame
input OrderEntryUseCloudRange =  no;#hint UseLessRisk: Strategy simulate when trend momentum is on and new high delta from previous high is less than the cloudrange*RiskFactor
input OrderEntryUseAtrCloudRange =  yes;#hint UseMoreRisk: Strategy simulate when trend momentum is on and new high delta from previous high is less than the ATR*RiskFactor
input RiskFactor = 1.4;#hint RiskFactor: Cloud percentage factor
input RiskBars = 3;#hint RiskBars: Number of bars to calculate for momentum delta

def enableIntraday = if !useIntraDaySignalsOnDailyMode then if getAggregationPeriod() < aggregationPeriod.DAY then 1 else 0 else 1;



def buylIGHTisk =   otf_trendhighesthigh > otf_trendhighesthigh[1]  and close >  otf_trendhighesthigh[RiskBars] ;
def SelllIGHTisk =  otf_trendlowestlow < otf_trendlowestlow[1]  and close < otf_trendlowestlow[RiskBars] ;

def buyLessRisk =   otf_trendhighesthigh > otf_trendhighesthigh[1]  and close >  otf_trendhighesthigh[RiskBars]  and (otf_trendhighesthigh- otf_trendhighesthigh[RiskBars] <= min(cloudrange,avgtrendmove)*RiskFactor);
def sellLessRisk =  otf_trendlowestlow < otf_trendlowestlow[1]  and close < otf_trendlowestlow[RiskBars]  and ( otf_trendlowestlow- otf_trendlowestlow[RiskBars] <= -min(cloudrange,avgtrendmove)*RiskFactor);

def buyMoreRisk =  otf_trendhighesthigh > otf_trendhighesthigh[1] and close >  otf_trendhighesthigh[1]  and (otf_trendhighesthigh- otf_trendhighesthigh[RiskBars] <= otf_ATR*RiskFactor);
def sellMoreRisk =  otf_trendlowestlow < otf_trendlowestlow[1] and close < otf_trendlowestlow[1] and ( otf_trendlowestlow- otf_trendlowestlow[RiskBars] <= -otf_ATR*RiskFactor);


AddOrder(OrderType.BUY_AUTO, EnableStrategy and activerange and ActiveTradeTime and enableIntraday and  OrderEntryUseCloudRange and buyLessRisk and !buyLessRisk[1], name = if OrderSimbol then "B" else  mode+"B(lr)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,  EnableStrategy and activerange and ActiveTradeTime and enableIntraday and OrderEntryUseCloudRange  and sellLessRisk and !sellLessRisk[1], name =  if OrderSimbol then "S" else   mode+"S(lr)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


AddOrder(OrderType.BUY_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and enableIntraday and OrderEntryUseAtrCloudRange and buyMoreRisk and !buyMoreRisk[1], name =   if OrderSimbol then "B" else   mode+"B(mr)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,!useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and enableIntraday and OrderEntryUseAtrCloudRange and sellMoreRisk and !sellMoreRisk[1], name =   if OrderSimbol then "S" else    mode+"S(mr)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

##################################################################
#                          Gandalf Pattern                            #
##################################################################
def averagePrice = ohlc4;
def medianPrice = hl2;
def medianBodyPrice = MidBodyVal();

def entryGandaldfPattern = (averagePrice[1] < medianPrice[1] and
    medianPrice[2] <= averagePrice[1] and
    medianBodyPrice[2] <= averagePrice[3]) or
    (averagePrice[1] < medianPrice[3] and
    medianBodyPrice < medianPrice[2] and
    medianBodyPrice[1] < medianBodyPrice[2]);

def exitGandalfPattern = (averagePrice[1] < medianBodyPrice[1] and
    medianPrice[2] == medianBodyPrice[3] and
    medianBodyPrice[1] <= medianBodyPrice[4]) or
    (averagePrice[2] < medianBodyPrice and
    medianPrice[4] <= averagePrice[3] and
    medianBodyPrice[1] <= averagePrice[1]);





input GandalfStrategyOrders = "**Gandalf Entry Orders**";
input OrderEntryUseGwiz =  NO;#hint OrderEntryUseGwiz: Strategy simulate Long orders when Gandelf Long Entry Price Pattern is found on any timeframe and no new lower lows are registered. Exit entries are simulated when the supertrend turns bearish or close price is under the reversing projections levels
AddOrder(OrderType.BUY_to_open,   EnableStrategy and activerange and ActiveTradeTime  and !useSignalOrderEntry and ( OrderEntryUseGwiz ) and entryGandaldfPattern and !SelllIGHTisk, name =  if OrderSimbol then "B" else    mode+"B(Wiz)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_to_close,  EnableStrategy and activerange and ActiveTradeTime  and !useSignalOrderEntry and OrderEntryUseGwiz and ((SelllIGHTisk )or  (sellunderlevels and !sellunderlevels[1])), name =  if OrderSimbol then "Sx" else   mode+"Sx(mr)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


#################################################
input useWizDailyBiasTrend = no;
Input conservativeOrders = no;
#################################################
#################################################
input showDailyBiasBubble = no;
# DailyBias?

# Mobius?

# Study tracks the open vs previous close and current days closing bias?

# V01.07.2015?

def RTHopen = open(period = AggregationPeriod.DAY);
def prevRTHclose = close(period = AggregationPeriod.DAY)[1];
def RTHclose = close(period = AggregationPeriod.DAY);
def countUp = if RTHopen < prevRTHclose and
                 RTHclose < RTHopen
              then countUp[1] + 1
              else countUp[1];

def countDn = if RTHopen > prevRTHclose and
                 RTHclose > RTHopen
              then countDn[1] + 1
              else countDn[1];

def barCount = CompoundValue(1, barCount[1] + 1, 0);
def Pup = (barCount - countUp) / BarNumber();
def Pdn = (barCount - countDn) / BarNumber();

AddLabel(1, "%O < PC and C < O = " + AsPercent(Pup) +
 "  %O > PC and C > O = " + AsPercent(Pdn), 
 if RTHopen < prevRTHclose and RTHclose < RTHopen
 then Color.RED
 else if RTHopen < prevRTHclose and RTHclose > RTHopen
 then Color.YELLOW
 else Color.WHITE);

def dailybias = if RTHopen < prevRTHclose and RTHclose < RTHopen then -1 else  if RTHopen < prevRTHclose and RTHclose > RTHopen  then 1 else dailybias[1];



AddChartBubble(showdailybiasBubble and  dailybias <> dailybias[1], close, "Daily Bias:" + "%O < PC and C < O = " + AsPercent(Pup) +
 "  %O > PC and C > O = " + AsPercent(Pdn),  if RTHopen < prevRTHclose and RTHclose < RTHopen
 then Color.RED
 else if RTHopen < prevRTHclose and RTHclose > RTHopen
 then Color.YELLOW
 else Color.WHITE);

# End Code Daily Bias   


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 dfIV = if IsNaN(imp_volatility(period = AggregationPeriod.DAY))
            then dfIV[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 * dfIV) / (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 otf_trend > 0  then Color.LIME  else if otf_trend < 0 
 then Color.MAGENTA else Color.CURRENT  else Color.GRAY  else Color.CURRENT ) ;

def otf_trendingBars = 0;

def wizdb_buy = if conservativeOrders then otf_trend > 0 else 1 and (entryGandaldfPattern and  dailybias > 0 ) and !( exitGandalfPattern and !entryGandaldfPattern) ;
def wdizbz_sell = if conservativeOrders then otf_trend < 0 else 1 and  (   dailybias < 0 ) and (exitGandalfPattern or !entryGandaldfPattern);

def otf_trenddb_BUY_auto =  (dailybias > 0 and  otf_trendcnt > max(otf_trendingBars,0) and CI < CI[1]);
def otf_trenddb_sell_auto = (dailybias < 0 and  otf_trendcnt < min(-otf_trendingBars,0) and CI < CI[1] );

def otf_trenddb_Sell_to_close = ( !( CI < CI[1] ) and otf_trend <> otf_trend[1] );
def otf_trenddb_BUY_to_close = (!( CI < CI[1] ) and otf_trend <> otf_trend[1]);



def WDBBuySignal = (EnableStrategy and activerange and ActiveTradeTime and useWizDailyBiasTrend and wizdb_buy) or
(EnableStrategy and activerange and ActiveTradeTime and useWizDailyBiasTrend and otf_trenddb_BUY_auto ) ;

def WDBSellSignal =  EnableStrategy and activerange and ActiveTradeTime and useWizDailyBiasTrend and otf_trenddb_sell_auto ;

def WDBSellStop  = closeallmarket or !activerange or ( EnableStrategy and activerange and ActiveTradeTime and useWizDailyBiasTrend and otf_trenddb_BUY_to_close);

def WDBBuyStop = closeallmarket or !activerange or ( EnableStrategy and activerange and ActiveTradeTime and useWizDailyBiasTrend and wdizbz_sell  ) or
(  EnableStrategy and activerange and ActiveTradeTime and useWizDailyBiasTrend and otf_trenddb_Sell_to_close  );



AddOrder(OrderType.BUY_AUTO,  EnableStrategy and activerange and ActiveTradeTime and !useSignalOrderEntry and useWizDailyBiasTrend and wdbbuysignal, name = if OrderSimbol then "B" else " B(***)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO, EnableStrategy and activerange and ActiveTradeTime and !useSignalOrderEntry  and useWizDailyBiasTrend and wdbsellsignal, name = if OrderSimbol then "S" else  " S(***)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

AddOrder(OrderType.BUY_to_close, EnableStrategy and activerange and ActiveTradeTime  and !useSignalOrderEntry  and useWizDailyBiasTrend and WDBSellStop, name = if OrderSimbol then "Bx" else  " B(***x)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_to_close, EnableStrategy and activerange and ActiveTradeTime and !useSignalOrderEntry  and useWizDailyBiasTrend and WDBBuyStop, name =  if OrderSimbol then "Sx" else  " S(***x)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));


######################################################################################################################################################################

def buy_ind =
(wdbBuySignal) or
(EnableStrategy and activerange and ActiveTradeTime  and ( OrderEntryUseGwiz ) and entryGandaldfPattern and !SelllIGHTisk) or
(EnableStrategy  and activerange and OrderEntryUsePmShiftingLevels  and  buyabovelevels and !buyabovelevels[1]) or
(EnableStrategy  and activerange and  OrderEntryUseProjectedMoveTouch and  touchvalley and touchvalleycnt == 1 and touchvalleycnt[1] == 0) or
(EnableStrategy  and activerange and  OrderEntryUseProjectedMove and  valley and   valleycnt == 1 and valleycnt[1]== 0 ) or
(EnableStrategy and activerange and OrderEntryUseDirectionMove and  Dailydirection > 0 and leveldir> 0) or
(EnableStrategy and  activerange and OrderEntryUseAutoPmOrBounceTouch and  OrderEntryUseTouchAuto and touchvalleycnt == 1 and touchvalleycnt[1] == 0) or
(EnableStrategy and activerange and OrderEntryUseAutoPmOrBounceTouch and OrderEntryUsePmAuto and   valleycnt == 1 and valleycnt[1] == 0) or
(EnableStrategy and  activerange and OrderEntryUseBuyBias  and if OrderEntryUsePmShiftingLevels then leveldir > 0 else 1 and  ( ( valleycnt == 1 and valleycnt[1] == 0 ) or (touchvalleycnt == 1 and touchvalleycnt[1] == 0))) or
(EnableStrategy  and activerange and ActiveTradeTime and  pmvalid and OrderEntryUseMarketShiftPmAutoExit and Dailydirection < 0 and Pojected_low_bar > Pojected_high_bar[1]) or
(EnableStrategy and activerange and ActiveTradeTime and enableIntraday and  OrderEntryUseCloudRange and buyLessRisk and !buyLessRisk[1]) or
(EnableStrategy and activerange and ActiveTradeTime and enableIntraday and OrderEntryUseAtrCloudRange and buyMoreRisk and !buyMoreRisk[1])

;

def sell_ind =
 (wdbSellSignal) or
(EnableStrategy and activerange and ActiveTradeTime and OrderEntryUsePmShiftingLevels  and activerange and sellunderlevels and !sellunderlevels[1]) or
(EnableStrategy  and activerange and  OrderEntryUseProjectedMoveTouch and  touchpeak  and  touchpeakcnt == 1 and touchpeakcnt[1] == 0) or
(EnableStrategy  and activerange and  OrderEntryUseProjectedMove and  peak and peakcnt == 1 and peakcnt[1] == 0) or
(EnableStrategy and activerange and OrderEntryUseDirectionMove and  Dailydirection < 0 and leveldir < 0) or
(EnableStrategy and activerange and OrderEntryUseAutoPmOrBounceTouch  and  OrderEntryUseTouchAuto and  touchpeakcnt == 1 and touchpeakcnt[1] == 0) or
(EnableStrategy and activerange and OrderEntryUseAutoPmOrBounceTouch and  OrderEntryUsePmAuto and peakcnt == 1 and peakcnt[1] == 0) or
(EnableStrategy and activerange and OrderEntryUseSellBias   and if OrderEntryUsePmShiftingLevels then leveldir < 0 else 1 and  (   touchpeakcnt == 1 and touchpeakcnt[1] == 0 or  peakcnt == 1 and peakcnt[1] == 0 )) or
( EnableStrategy  and activerange and ActiveTradeTime and  pmvalid and  OrderEntryUseMarketShiftPmAutoExit and  Dailydirection > 0 and Pojected_high_bar < Pojected_low_bar[1]) or
(EnableStrategy and activerange and ActiveTradeTime and enableIntraday and OrderEntryUseCloudRange  and sellLessRisk and !sellLessRisk[1]) or
(EnableStrategy and activerange and ActiveTradeTime and enableIntraday and OrderEntryUseAtrCloudRange and sellMoreRisk and !sellMoreRisk[1])
;



##################################################################
#     Signals                          #
##################################################################


def sellStop = closeallmarket or !activerange or WDBSellStop or
(EnableStrategy  and activerange and ActiveTradeTime and OrderEntryUseBuyBias  and buytoclosebias
) or
( EnableStrategy  and activerange and ActiveTradeTime and  pmvalid and OrderEntryUseMarketShiftPmExit and Dailydirection < 0 and Pojected_low_bar > Pojected_high_bar[1]) ;

def buyStop = closeallmarket or !activerange or WDBBuyStop or
(EnableStrategy and activerange and ActiveTradeTime and OrderEntryUseSellBias  and  selltoclosebias)or
(EnableStrategy  and activerange and ActiveTradeTime and  pmvalid and  OrderEntryUseMarketShiftPmExit and  Dailydirection > 0 and Pojected_high_bar < Pojected_low_bar[1]) or
(EnableStrategy and activerange and ActiveTradeTime  and OrderEntryUseGwiz and ((SelllIGHTisk )or  (sellunderlevels and sellunderlevels[1])));


def BuySignal = buy_ind;
def SellSignal = sell_ind;
#######################################
##  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
def orderPrice = if (isOrder and (BuySignal or SellSignal)) then open[-1] else orderPrice[1];


# If not already long and get a BuySignal
plot BuySig = if (isOrder and isLong 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 (isOrder and isShort 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);
#######################################
## Orders
#######################################


def pricelevel = orderPrice;

def prevpricelevel = if pricelevel <> pricelevel[1] then pricelevel[1] else prevpricelevel[1];

plot OrderBlock = pricelevel;
OrderBlock.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
OrderBlock.SetDefaultColor(color.cyan);


def top = if prevpricelevel < pricelevel then pricelevel else prevpricelevel ;
def bottom = if prevpricelevel > pricelevel then pricelevel else prevpricelevel ;


AddOrder(OrderType.BUY_AUTO,useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and buysignal, name = if OrderSimbol then "B" else mode+" B(*)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_AUTO,useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and sellsignal, name = if OrderSimbol then "S" else  mode +" S(*)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));

AddOrder(OrderType.BUY_to_close,useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime  and sellstop, name = if OrderSimbol then "Bx" else  mode+" B(x)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_to_close,useSignalOrderEntry and  EnableStrategy and activerange and ActiveTradeTime and buystop, name =  if OrderSimbol then "Sx" else  mode+" S(x)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));



AddOrder(OrderType.BUY_to_close, EnableStrategy and  (closeAllmarket or !activerange), name = if OrderSimbol then "Bx" else  " B(x)@ "  + open[-1], price = open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1));
AddOrder(OrderType.SELL_to_close, EnableStrategy and ( closeAllmarket or !activerange), name =  if OrderSimbol then "Sx" else  " S(x)@ "  + open[-1],  price = open[-1], tickcolor = GetColor(4), arrowcolor = GetColor(4));




##################################################################
#     Alerts                          #
##################################################################



def buyalert = isorder and islong;
def sellalert =isorder and isshort;

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 Activealert and !Activealert[1] and buyalert, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(Activealert and Activealert  and !Activealert[1] and sellalert, "Sell Signal" , Alert.BAR, Sound.Ding);



#######################################
##  START of Strategies DashBoard
####################################
addOrder(OrderType.BUY_AUTO, no); #dont change this line
input enableDashBoard = no;
input ShowStrategyCurrentPnlBubble = yes;
input ShowStrategyPnlBubble = no;
input ShowStrategyPnlEntryBubble = yes;
input ShowStrategyPnlVertical = no;
Input ShowStrategyProfitLossLabels = yes;
def fpl = FPL();
def StrategyEntryprice = if IsNaN(EntryPrice())  then 0 else EntryPrice();
def ep = entryprice();
def poschange = ( StrategyEntryprice <> StrategyEntryprice[1] and StrategyEntryprice == 0 ) or (  StrategyEntryprice <> StrategyEntryprice[1] and StrategyEntryprice[1] == 0  )   or (  StrategyEntryprice <> StrategyEntryprice[1] and StrategyEntryprice[1] > 0   and StrategyEntryprice[0] > 0 );
def pnlentry =  if  poschange  then  fpl[1] else pnlentry[1];
def currentprofit = fpl() - pnlentry[1];
def pnlprofit =  if pnlentry <> pnlentry[1] then  fpl[1] - pnlentry[1] else 0  ;
def entryprofit = (if pnlprofit> 0 then 1 else -1 )  * absValue( if  poschange  then if StrategyEntryprice == 0 then open[0] - ep[1] else ep-ep[1] else 0) ;
def dollarentryprofitloss = Round(((entryprofit ) / TickSize()) * TickValue());

AddChartBubble(enableDashBoard and ShowStrategyPnlEntryBubble and poschange and absValue(dollarentryprofitloss  )>0, open[0], AsDollars(dollarentryprofitloss[0]), if dollarentryprofitloss[0] > 0 then Color.light_GREEN else if  dollarentryprofitloss[0] < 0 then Color.pink else Color.BLUE);
AddVerticalLine(ShowStrategyPnlVertical and ShowStrategyPnlEntryBubble and poschange, AsDollars(fpl) + " (" + dollarentryprofitloss + ")" ,  if dollarentryprofitloss > 0 then Color.GREEN else if dollarentryprofitloss < 0 then Color.RED else if pnlentry == 0 then Color.WHITE else Color.CYAN);

def fplpnlprofit = pnlprofit;
AddChartBubble(enableDashBoard and ShowStrategyPnlBubble and poschange[0] and absValue(fplpnlprofit  )>0, open[0], AsDollars(fplpnlprofit[0]), if fplpnlprofit[0] > 0 then Color.GREEN else if  fplpnlprofit[0] < 0 then Color.RED else Color.BLUE);
AddVerticalLine(enableDashBoard and ShowStrategyPnlVertical and ShowStrategyPnlBubble and poschange, AsDollars(fpl) + " (" + pnlprofit + ")" ,  if pnlprofit > 0 then Color.GREEN else if pnlprofit < 0 then Color.RED else if pnlentry == 0 then Color.WHITE else Color.CYAN);
def lastentry =if isnan( entryprice()) then lastentry[1] else entryprice() ;
AddChartBubble(enableDashBoard and ShowStrategyCurrentPnlBubble  and !IsNaN(entryprice()) and !IsNaN(close) and IsNaN(close [-1] ) and HighestAll(BarNumber()) and absValue(currentprofit)> 0, lastentry, AsDollars(currentprofit[0]), if currentprofit[0] > 0 then Color.green else if  currentprofit[0] < 0 then Color.red else Color.BLUE);

def pl = if ShowStrategyPnlEntryBubble then if isnan( dollarentryprofitloss) then 0 else dollarentryprofitloss else if isnan(fplpnlprofit) then 0 else fplpnlprofit;
def StrategyLongprofitLossSum = CompoundValue(1, if BarNumber() == 1 then 0 else if pl > 0 then StrategyLongprofitLossSum[1] + pl[0] else StrategyLongprofitLossSum[1], 0);
def StrategyShortprofitLossSum = CompoundValue(1, if BarNumber() == 1 then 0 else if pl < 0 then StrategyShortprofitLossSum[1] + pl[0] else StrategyShortprofitLossSum[1], 0);

##************************
def Strategylosstradecnt = CompoundValue(1, if BarNumber() == 1 then 0 else if pl < 0 then Strategylosstradecnt[1] + 1 else Strategylosstradecnt[1], 0);
def StrategyProfittradecnt = CompoundValue(1, if BarNumber() == 1 then 0 else if pl > 0 then StrategyProfittradecnt[1] + 1 else StrategyProfittradecnt[1], 0);

#def Strategylosstradecnt = if  BarNumber() == 1 then 0 else if pl > 0 then StrategyProfittradecnt[1] + 1 else StrategyProfittradecnt[1] ;
#def Strategylosstradecnt = if  BarNumber() == 1 then 0 else if pl < 0 then Strategylosstradecnt[1] + 1 else Strategylosstradecnt[1] ;

def Strategytradecnt = StrategyProfittradecnt + Strategylosstradecnt;

# What percent were winners
def StrategyPCTWin = Round(((StrategyProfittradecnt) / (Strategytradecnt)) * 100, 2) ;
def StrategyPCTLoss = Round(((Strategylosstradecnt) / (Strategytradecnt)) * 100, 2) ;
def StrategyPCTWinamt = Round(((absValue(StrategyLongprofitLossSum/StrategyProfittradecnt)) /absValue( (StrategyLongprofitLossSum/StrategyProfittradecnt) + absValue(StrategyShortprofitLossSum/Strategytradecnt))) * 1, 2) ;
def PCTLossamt =  Round(((absValue(StrategyShortprofitLossSum/Strategylosstradecnt)) /absValue( (StrategyLongprofitLossSum/StrategyProfittradecnt) + absValue(StrategyShortprofitLossSum/Strategytradecnt))) * 1, 2) ;
plot PltEntryPrice = if enableDashBoard then  ep else double.nan;
PltEntryPrice.SetPaintingStrategy(PaintingStrategy.DASHES);
PltEntryPrice.SetdefaultColor(color.cyan);
PltEntryPrice.assignValueColor(if currentprofit then color.green else
if entryprofit < 0 then color.red else color.cyan );


def Strategylowestdrawdown =  min(if isnan(currentprofit) then 0 else currentprofit,Strategylowestdrawdown[1]);
def StrategyHigestdrawUp =  max(if isnan(currentprofit) then 0 else currentprofit,StrategyHigestdrawUp[1]);
def Strategylowestloss = min(pl,Strategylowestloss[1]);
def highestwin = max(pl,highestwin[1]);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels,"Last Entry: "+lastentry +"("+currentprofit +")" ,if currentprofit > 0 then color.light_green else if currentprofit < 0 then color.light_red else color.cyan );
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "PNL: " + (FPL()), if FPL() > 0 then Color.LIME else Color.RED);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Winners: " + StrategyPCTWin + "%", if StrategyPCTWin > 50 then Color.GREEN else if StrategyPCTWin > 40 then Color.YELLOW else Color.GRAY);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "ProfitLossSum: " + (StrategyLongprofitLossSum + StrategyShortprofitLossSum), if (StrategyLongprofitLossSum + StrategyShortprofitLossSum) > 0 then Color.LIME else Color.RED);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "ShortprofitLossSum: " + (StrategyShortprofitLossSum), Color.pink);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "LongprofitLossSum: " + (StrategyLongprofitLossSum), Color.LIME);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Trades: " + (Strategytradecnt), Color.WHITE);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Profit Trades: " + (StrategyProfittradecnt), if StrategyProfittradecnt > Strategylosstradecnt then Color.LIME else Color.RED);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Loss Trades: " + (Strategylosstradecnt), if StrategyProfittradecnt < Strategylosstradecnt then Color.LIME else Color.pink);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Profit Factor: " +round(absvalue (StrategyLongprofitLossSum/StrategyShortprofitLossSum)),color.cyan);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Lowest Loss: " + (Strategylowestloss), Color.pink);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Lowest DrawDown: " + (Strategylowestdrawdown), Color.pink);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Highest DrawUp: " + (StrategyHigestdrawUp), Color.LIME);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Highest Win: " + (highestwin), Color.LIME);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "PCTWin Trades: " + (StrategyPCTWin), Color.GREEN);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "PCTLoss Trades: " + (StrategyPCTLoss), Color.PINK);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "PCTWin Amount: " + (StrategyPCTWinamt), Color.GREEN);
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "PCTLoss Amount: " + (PCTLossamt), Color.PINK);

def firstentry = if Strategytradecnt ==1 then close[1] else firstentry[1];
def buyandhold = Round(((close - firstentry ) / TickSize()) * TickValue());
AddLabel(enableDashBoard and ShowStrategyProfitLossLabels, "Buy&Hold: " + (buyandhold), if buyandhold > 0 then Color.LIME else Color.RED);
# Mobius
def CurrentDOW = GetDayOfWeek(GetYYYYMMDD());
def RTHstart =  CurrentDOW <> CurrentDOW[1];
def daysOnChart = if RTHstart 
then compoundValue(1, daysOnChart[1] + 1, 1)
else daysOnChart[1];
addLabel(1, "Days on Chart: " + daysOnChart, color.cyan);
addLabel(1, "Bars on Chart: " + barnumber(), color.cyan);

#######################################
##  END of Strategy DashBoard
#######################################
 
That is awesome my brother. If I had been using options data to follow this asset I probably would have gotten short today as that has the first day with retracement potential from my "ViewOfVolume".
I would have gotten short around noon after my "DPLs" were clear.
View attachment 20837

I would love any thoughts or constructive criticisms you may have for me. I haven't relaunched the ViewOfVolume quite yet as it was lagging and repainting for some users and I was terrified of leading others the wrong way with mistakes.
I haven't found any outright bugs in the old code but I am concerned that it was overburdening computers.

View attachment 20838
sometimes the candles are black and cant see the candles on chart anyway to fix this?
 
I believe his is talking about the chart on the right, I think it is a repaint and the black makes it hard to see the sticks.
 

Attachments

  • Screenshot 2024-03-18 at 5.27.48 PM.png
    Screenshot 2024-03-18 at 5.27.48 PM.png
    93.5 KB · Views: 172

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
520 Online
Create Post

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top