Previous Day and PreMarket Breakout For ThinkOrSwim

Ramisegal

Active member
Plus
Previous Day and PreMarket High Low Breakout Strategy

Basic strategy to backtest a break of previous day sessions high and low
The script is not using a secondary aggregation.

The previous day high low breakout strategy is a day trading technique that offers multiple opportunities to trade in either direction (long or short). However, it's important to remember that this strategy, like any other, has its pros and cons. Always keep in mind that this strategy should be used primarily as part of a short-term trading concept, and be sure to:

  • Focus on intraday charts (e.g., 1-minute, 5-minute, or 15-minute charts)
  • Identify the previous day's high and low prices
  • Look for breakouts above the high or below the low
  • Set stop-losses and take-profits accordingly
  • Monitor market conditions and adjust your strategy as needed

By following these guidelines and considering the strategy's advantages and disadvantages, you can effectively incorporate the previous day high low breakout strategy into your trading plan.



#PriorDayPreMarketTimeStrategy

Toi8tgPsdahRvLrc2HrMCCHyN7bD6jZz8_IXfjyhRJee_QJz3WNbpQ_QRar5ZqiSceATO_gf8cwfBo1Ry282tlRCs3oNRYx0f2VLDSBef8mj1tNikey9lttS0SddAYi2N57LC30_9ESf6rLe0BV512k


l8-fuRAPGZUQX2PGE4Q7CaeAQLs8ZVUOxZKjKjyRGgFqfcWAG22eMU2TN0qZk6T_VFvW0r8U9i05jAhlQuS7AOaOFj9iqT9Njb4TLjF5p3iS8FLa570JzSvXN7YbcRlUPEhNElOOk6LIegiq9hwqVHs


Code:
#RamiSegal PriorDayPreMarketTimeStrategy Version 1.0 3/23/2024
input EnableStrategy = yes;
input UseMarketTime = no; #hint UseMarketTime: Use Trading hours?
input TradeTimeStart = 0800;
input TradeTimeEnd = 1555;
input UseTradeOffTradeTime = yes;
input UseMarketTradeTimeToExitPositions = no; #hint UseMarketTradeTimeToExitPositions: Exit/Close open trades based on the market hours selected
input UseDateRange = no; #hint UseDateRange: Trade Signals within the date range specified
input ActiveStartDate = 20230101;
input ActiveEndDate = 20240101;

def activedaterange = GetYYYYMMDD() >= ActiveStartDate and GetYYYYMMDD() <= ActiveEndDate;
def activerange = if UseDateRange then  activedaterange else 1;
AddLabel(UseDateRange, if activerange then "Range " + asPrice(ActiveStartDate) + " - " + asPrice(ActiveEndDate) else ""  , Color.WHITE );


def ActiveTradeTime = if UseMarketTime then if SecondsTillTime(TradeTimeStart) <= 0 and
                           SecondsTillTime(TradeTimeEnd) >= 0  then 1 else 0
                    else 1;

def Active =  if SecondsTillTime(TradeTimeStart) <= 0 and  SecondsTillTime(TradeTimeEnd) >= 0  then 1 else 0;

def closeallmarket =   ( if UseTradeOffTradeTime then ActiveTradeTime and !ActiveTradeTime[1] else  !ActiveTradeTime and ActiveTradeTime[1])  and UseMarketTradeTimeToExitPositions;

input ShowTime = yes;

input TimeZone = 10.5;
def Hours = Floor(TimeZone + SecondsFromTime(0930) / 60 / 60) - 1;
def Minutes = ((TimeZone + SecondsFromTime(930) / 60 / 60) % 1) * 60;

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



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


#PostAndRegularTradingStudy
Input ShowverticalTradingHours = NO;
input ShowRthBubbles = yes;

input useImpulse = yes;
INPUT OrderSimbol = NO;


def bar = BarNumber();

def Today = getDay() == getLastDay();
def RTH = if SecondsFromTime(0930) >= 0 and SecondsTillTime(1600) >= 0 then 1 else 0;

def RTH_Bar1 = if RTH and !RTH[1] then bar else double.nan;

Script T{
  def RTH = if SecondsFromTime(0930) >= 0 and
               SecondsTillTime(1600) >= 0
            then 1
            else 0;
  def cT = if RTH and !RTH[1]
           then 1
           else if RTH
                then cT[1] + 1
                else cT[1];
  plot Data = if RTH then cT else double.nan;
}
AddVerticalLine(ShowverticalTradingHours and T().RTH and !t().RTH[1], "Open", Color.light_Gray, Curve.Long_Dash);
AddVerticalLine(ShowverticalTradingHours and SecondsTillTime(1030) == 0 and
                SecondsFromTime(1030) == 0, "EU", Color.light_Gray, Curve.Long_Dash);
AddVerticalLine(ShowverticalTradingHours and SecondsTillTime(1200) == 0 and
                SecondsFromTime(1200) == 0, "Noon", Color.light_Gray, Curve.Long_Dash);
AddVerticalLine(ShowverticalTradingHours and SecondsTillTime(1500) == 0 and
                SecondsFromTime(1500) == 0, "Last H", Color.light_Gray, Curve.Long_Dash);
AddVerticalLine(ShowverticalTradingHours and !T().RTH and T().RTH[1], "Close", Color.light_Gray, Curve.Long_Dash);
 
def activerth = RegularTradingStart(GetYYYYMMDD()) - GetTime() < 0 and RegularTradingEnd(GetYYYYMMDD()) - GetTime() > 0;

DefineGlobalColor("RTHOPEN", Color.white);
DefineGlobalColor("RTHCLOSE", Color.GRAY);
DefineGlobalColor("RTHLOW", Color.orange);
DefineGlobalColor("RTHHIGH", Color.light_green);
DefineGlobalColor("AFTERRTHHIGH", Color.GREEN);
DefineGlobalColor("AFTERRTHLOW", Color.RED);
DefineGlobalColor("HIGH", Color.dark_GREEN);
DefineGlobalColor("LOW", Color.dark_red);


def charth = high; 
def chartl = low; 
def charto = open;
def chartc = close ;

def RTHOpen = if activerth and !activerth[1]  then charto else  RTHOpen[1];
def RTHClose = if !activerth and activerth[1]  then chartc else  RTHClose[1];

plot rtho = RTHOpen ; 
 rtho.SetPaintingStrategy(PaintingStrategy.POINTS ); 
 rtho.SetDefaultColor(GlobalColor("RTHOPEN")); 
addchartbubble(ShowRthBubbles and rtho==rtho[1] and isNaN(close[2]) and !isNaN(close[3]), rtho,"Open",GlobalColor("RTHOPEN"));

plot rthc =   RTHClose; 
 rthc.SetPaintingStrategy(PaintingStrategy.POINTS ); 
 rthc.SetDefaultColor(GlobalColor("RTHCLOSE")); 
addchartbubble(ShowRthBubbles and rthc==rthc[1] and isNaN(close[3]) and !isNaN(close[4]), rthc,"Close",GlobalColor("RTHCLOSE"));



def RTHLow = if activerth and !activerth[1] then chartl 
 else if activerth and chartl < RTHLow[1] then chartl else RTHLow[1]; 

def pRTHLow = if activerth <> activerth[1] then RTHLow[1] else pRTHLow[1];

def RTHhigh = if activerth and !activerth[1] then charth 
 else if activerth and charth > RTHhigh[1] then charth else RTHhigh[1]; 

def pRTHhigh = if activerth <> activerth[1] then RTHhigh[1] else pRTHhigh[1];


plot ll = if !activerth then RTHLow 
else if activerth then pRTHLow else double.nan; 
 ll.SetPaintingStrategy(PaintingStrategy.Squares); 
 ll.SetDefaultColor(GlobalColor("RTHLOW"));

def PLValue = if !IsNaN(ll) then ll else PLValue[1];
def PLBarOrigin = if !IsNaN(ll) then bar else PLBarOrigin[1];

addchartbubble(ShowRthBubbles and if Bar == HighestAll(PLBarOrigin) then PLBarOrigin else Double.NaN, PLValue,"PrevRTH,Low",GlobalColor("RTHLOW"));

plot hh = if  !activerth then RTHhigh  else if activerth  then pRTHhigh else double.nan; 
 hh.SetPaintingStrategy(PaintingStrategy.Squares); 
 hh.SetDefaultColor(GlobalColor("RTHHIGH")); 

def PHBarOrigin = if !IsNaN(hh) then bar else PHBarOrigin[1];
def PHValue = if !IsNaN(hh) then hh else PHValue[1];

addchartbubble(ShowRthBubbles and if Bar == HighestAll(PHBarOrigin) then PHBarOrigin else Double.NaN, PHValue,"PrevRTH,High",GlobalColor("RTHHIGH"));


def aRTHhigh = if !activerth and activerth[1] then charth 
 else if !activerth and charth > aRTHhigh[1] then charth 
 else aRTHhigh[1];

def aRTHLow = if !activerth and activerth[1] then chartl   
else if !activerth and chartl < aRTHLow[1] then chartl
else aRTHLow[1];

def paRTHhigh = if activerth <> activerth[1] then aRTHhigh[1] else paRTHhigh[1];
def paRTHLow = if activerth <> activerth[1] then aRTHLow[1] else paRTHLow[1];

plot ahh = if  activerth  then aRTHhigh else if !activerth then paRTHhigh else double.nan; 
 ahh.SetPaintingStrategy(PaintingStrategy.POINTS ); 
 ahh.SetDefaultColor(GlobalColor("AFTERRTHHIGH"));   
def APHBarOrigin = if !IsNaN(ahh) then bar else APHBarOrigin[1];
def APHValue = if !IsNaN(Ahh) then Ahh else APHValue[1];
addchartbubble(ShowRthBubbles and if Bar == HighestAll(APHBarOrigin) then APHBarOrigin else Double.NaN, APHValue,"PreRTH,High",GlobalColor("AFTERRTHHIGH"));


plot all = if activerth then aRTHLow else if !activerth then paRTHLow else double.nan; 
 all.SetPaintingStrategy(PaintingStrategy.POINTS); 
 all.SetDefaultColor(GlobalColor("AFTERRTHLOW")); 

def APLBarOrigin = if !IsNaN(aLL) then bar else APLBarOrigin[1];
def APLValue = if !IsNaN(aLL) then aLL else APLValue[1];
addchartbubble(ShowRthBubbles and if Bar == HighestAll(APLBarOrigin) then APLBarOrigin else Double.NaN, APLValue,"PreRTH,Low",GlobalColor("AFTERRTHLOW"));


plot _ll  =  highestAll(if isNaN(close[-1]) 
                               then if activerth then  RTHLow else aRTHLow
else double.nan); 
 _ll.SetStyle(Curve.SHORT_DASH); 
 _ll.SetDefaultColor(GlobalColor("LOW"));
addchartbubble(ShowRthBubbles and _ll==_ll[1] and isNaN(close[4]) and !isNaN(close[5]), _ll,"Lowest",GlobalColor("LOW"));

plot _hh = highestAll(if isNaN(close[-1]) 
                               then if activerth then  RTHhigh else aRTHhigh
                               else Double.NaN);
 _hh.SetStyle(Curve.SHORT_DASH);
 _hh.SetDefaultColor(GlobalColor("HIGH")); 

addchartbubble(ShowRthBubbles and _hh==_hh[1] and isNaN(close[4]) and !isNaN(close[5]), _hh,"Highest",GlobalColor("HIGH"));


input ShowLabels = yes;
#################################################

# DailyBias?
# Mobius?
# Study tracks the open vs previous close and current days closing bias?
# V01.07.2015?


def countUp = if RTHopen < RTHclose and
                 RTHclose < RTHopen
              then countUp[1] + 1
              else countUp[1];

def countDn = if RTHopen > RTHclose 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(ShowLabels , "Daily Bias:" + "%O < PC and C < O = " + AsPercent(Pup) +
 "  %O > PC and C > O = " + AsPercent(Pdn), 
 if RTHopen < RTHclose and RTHclose < RTHopen
 then Color.RED
 else if RTHopen < RTHclose and RTHclose > RTHopen
 then Color.YELLOW
 else Color.WHITE);

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

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

input showDailyBiasBubble = no;
#################################################

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 < RTHclose and RTHclose < RTHopen
 then Color.RED
 else if RTHopen < RTHclose 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 dailyiv =  if  !activerth and activerth[1]  then if IsNaN(imp_volatility()) then dailyiv[1] else imp_volatility() else dailyiv[1];
def HTH = Highest(Max(high, close[1]), FractalCalculationsLength);
def LTL = Lowest(Min(low, close[1]), FractalCalculationsLength);
def CIb = (((close * dailyiv) / (HTH - LTL)) / Log(10));
def CI = WildersAverage(CIb, Periods_for_the_Smoothed_Signal_Line);


AddLabel(ShowLabels , if CI < CI[1] then "Trending" else "Choppy", if CI < CI[1] then Color.GREEN else Color.RED);



input sourcehigh = high;
input sourcelow = low;
input sourceclose = close;
input nATR = 5;
input ATRMult = .7;
input tmV = 3;
input AvgType = AverageType.SIMPLE;
Input TrendingBars = 1;
AddLabel(ShowLabels, "TF: " + GetAggregationPeriod() / 60000, Color.WHITE);

def h = Highest(sourcehigh, tmV);
def l = Lowest(sourcelow, tmV);
def c = (Highest(sourceclose, tmV) + Lowest(sourceclose, tmV)) / 2;

def ATR = MovingAverage(AvgType, TrueRange(h, c, l), nATR);
def UP = c + (ATRMult * ATR);
def DN = c + (-ATRMult * ATR);

def priceclose = c;
def lowestup = if UP <= lowestup[1] then UP[0] else if priceclose < lowestup[1] and priceclose < UP[0] then lowestup[1] else UP[0];
def highestdn = if DN >= highestdn[1] then DN[0] else if priceclose > highestdn[1] and priceclose > DN[0]  then highestdn[1] else DN[0];

def trend = if  priceclose[0] crosses below highestdn[1] then -1 else if  priceclose[0] crosses above lowestup[1]  then 1 else trend[1];

plot sell =  if  trend < 0 then lowestup[0] else Double.NaN ;
plot buy = if  trend > 0  then highestdn[0] else Double.NaN ;


sell.SetDefaultColor(  Color.MAGENTA );
buy.SetDefaultColor( Color.LIME );

def barUp = trend > 0 ;
def barDown = trend < 0 ;
def barUpCount = CompoundValue(1, if barUp then (if IsNaN(barUpCount[1]) then 0 else barUpCount[1]) + 1 else 0, 0);
def barDownCount = CompoundValue(1, if barDown then ( if IsNaN( barDownCount[1]) then 0 else barDownCount[1] ) - 1 else 0, 0);
def trendcnt = barDownCount + barUpCount ;

AddLabel(ShowLabels, "Trending Bars " + (trendcnt) ,  if trend > 0  then Color.LIME else  Color.MAGENTA );

input AssignPriceColorByCurrentTrend = no;
AssignPriceColor( if trend > 0  and AssignPriceColorByCurrentTrend then Color.LIME else  if trend < 0 and AssignPriceColorByCurrentTrend then Color.MAGENTA else Color.CURRENT);

input UseMomentumFilter = yes;
input TradeFrequecy = {default "Hold", "Swing", "Scalp"};
def tf;
switch (TradeFrequecy) {
case "Swing":
    tf = 3;
case "Scalp":
    tf = 2;
case "Hold":
    tf = 1;
}

AddLabel(ShowLabels and UseMomentumFilter, "Momentum Filter: " + TradeFrequecy,  Color.WHITE);

def otf_trendlowestlow;
def otf_trendhighesthigh;

if trend < 0
then
{
    otf_trendlowestlow = if trend == 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 trend > 0
then
{
    otf_trendlowestlow = otf_trendlowestlow[1];
    otf_trendhighesthigh = if trend == 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 ShowHighAndLow = yes;
plot t1rendlowestlow =  if ShowHighAndLow and trend >  0 and otf_trendlowestlow == otf_trendlowestlow[1]then otf_trendlowestlow else double.NaN;
plot t1rendhighesthigh =  if ShowHighAndLow and  trend < 0 and otf_trendhighesthigh == otf_trendhighesthigh[1] then otf_trendhighesthigh  else double.NaN;

t1rendlowestlow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
t1rendhighesthigh .SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
t1rendlowestlow.SetDefaultColor(color.red);
t1rendhighesthigh.SetDefaultColor(color.green);


input PaintFractalCalculationsBars = yes;
AssignPriceColor( if PaintFractalCalculationsBars then if  CI < CI[1] 
 then if trend > 0 then Color.LIME  else 
   Color.MAGENTA    else Color.GRAY  else Color.CURRENT ) ;

def cistatus =  CI < CI[1];

def cilowest = if (cistatus <> cistatus[1] and !cistatus) or bar == 1 then low else min(cilowest[1],low);
def cihighest = if (cistatus <> cistatus[1]and !cistatus) or bar == 1 then high else max(cihighest[1],high);

plot cil = if cistatus and trend > 0 then cilowest else double.nan;
plot cih = if cistatus and trend < 0 then  cihighest else double.nan;
cil.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
cih.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
cil.SetDefaultColor(color.gray);
cih.SetDefaultColor(color.gray);




DEF _BUYSIGNAL = ( (  open crosses above MIN(AHH,HH)   ) OR ( open [1] < ALL AND open > ALL ));
DEF _SELLSIGNAL = ( (  open crosses below  MAX(ALL,LL) )OR  (open[1] > AHH AND open < AHH))  ;

DEF BUYSIGNAL_ = ( (  open crosses above  MIN(AHH,HH)  )OR ( open[1] < LL AND open > LL ));
DEF SELLSIGNAL_ = ( (  open crosses below MAX(ALL,LL) )OR  (open[1] > HH AND open < HH))  ;


def buyImpulse = if useImpulse then  close > highest(open,tmv)[1] else 1;
def sellImpulse =  if useImpulse then close < lowest( open,tmv)[1] else 1;

DEF _buysignal_ = (buyImpulse  ) and ( (!activerth AND  _BUYSIGNAL ) OR (activerth AND  BUYSIGNAL_ ));
DEF _SELLSIGNAL_ = (sellImpulse ) and ((!activerth AND  _SELLSIGNAL  ) OR (Activerth AND  SELLSIGNAL_ ));

DEF buysignal = (_buysignal_) and buyImpulse;
DEF SELLSIGNAL = (_SELLSIGNAL_ ) and sellImpulse;

def SellStop =   closeallmarket or !activerange;
def BuyStop =   closeallmarket or !activerange;


input Show_trade_odds_Labels = yes;
input useAlerts = no;
input showSignals = yes;
def showstops = yes;
input showSignalLines = yes;
input showSignalBubbles = yes;
input showSignalStudyPnlBubbles = yes;



#######################################
##  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] == 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     
if CurrentPosition[1] == 0 {            # FLAT

        if (BuySignal) {
            CurrentPosition = 1;
        } else if (SellSignal) {
            CurrentPosition = -1;
        } 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;

# If not already long and get a BuySignal
plot BuySig = if (!isLong[1] and BuySignal and showSignals) then 1 else 0;
BuySig.AssignValueColor(Color.CYAN);
BuySig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySig.SetLineWeight(5);

Alert(BuySig and useAlerts, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(BuySig and useAlerts, "Buy Signal", Alert.BAR, Sound.Ding);

# If not already short and get a SellSignal
plot SellSig = if (!isShort[1] and SellSignal and showSignals) then 1 else 0;
SellSig.AssignValueColor(Color.CYAN);
SellSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSig.SetLineWeight(5);

Alert(SellSig and useAlerts, "Sell Signal", Alert.BAR, Sound.Ding);
Alert(SellSig and useAlerts, "Sell Signal", Alert.BAR, Sound.Ding);

# If long and get a BuyStop
plot BuyStpSig = if (isflat and isLong[1] and showSignals and ShowStops) then 1 else 0;
BuyStpSig.AssignValueColor(Color.LIGHT_GRAY);
BuyStpSig.SetPaintingStrategy(  PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig.SetLineWeight(3);

Alert(BuyStpSig and useAlerts, "Buy Stop Signal", Alert.BAR, Sound.Ding);
Alert(BuyStpSig and useAlerts, "Buy Stop Signal", Alert.BAR, Sound.Ding);

# If short and get a SellStop
plot SellStpSig = if (isflat and isShort[1] and showSignals and ShowStops) then 1 else 0;
SellStpSig.AssignValueColor(Color.LIGHT_GRAY);
SellStpSig.SetPaintingStrategy(  PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig.SetLineWeight(3);

Alert(SellStpSig and useAlerts, "Sell Stop Signal", Alert.BAR, Sound.Ding);
Alert(SellStpSig and useAlerts, "Sell Stop Signal", Alert.BAR, Sound.Ding);

#######################################
## Orders
#######################################

def isOrder = if CurrentPosition == CurrentPosition[1] then 0 else 1; # Position changed so it's a new order

# If there is an order, then the price is the next days close
def orderPrice = if (isOrder and (BuySignal or SellSignal)) then open[-1] else orderPrice[1];

plot OrderEntry = orderPrice;
OrderEntry.SetPaintingStrategy(PaintingStrategy.dASHES);
OrderEntry.SetDefaultColor(color.cyan);
input showVerticalSignals = yes;

addverticalLine(showverticalsignals and CurrentPosition<>CurrentPosition[1], if isFlat then "Flat" else if isShort then "Short" else if islong then "Long" else "",
if isFlat then color.gray else if isShort then color.magenta else if islong then color.lime else color.white);
AddChartBubble(showSignalBubbles and BuySig and !isnan(orderprice), low, "B@ " + orderprice,color.lime, 0);
AddChartBubble(showSignalBubbles and SellSig and !isnan(orderprice), high, "S@ " + orderprice,color.magenta, 0);
AddChartBubble(showSignalBubbles and SellStpSig  , low, "Buy to Close@ " + open[-1],color.gray, 0);
AddChartBubble(showSignalBubbles and BuyStpSig   , high, "Sell to Close@ " + open[-1],color.gray, 0);



#######################################
## Study vased Price and Profit
#######################################


def profitLoss;

if (!isOrder or orderPrice[1] == 0)   {
    profitLoss = 0;
} else if  (isOrder ) and (isflat[1] ) {
    profitLoss = 0;
} else if  (!isLong   and isOrder ) and (isLong[1] ) {
    profitLoss = open[-1] - orderPrice[1];
} else if (!isShort  and isOrder ) and (isShort[1] ) {
    profitLoss = orderPrice[1] - open[-1];
} else {
    profitLoss = 0;
}


def  ShortsProfitsSum = CompoundValue(1, if IsNaN(isOrder) or BarNumber() == 1 then 0 else if isOrder and isShort[1] then ShortsProfitsSum[1] + if isnan(profitLoss) then 0 else if profitLoss > 0 then profitLoss else 0 else ShortsProfitsSum[1], 0);
def  ShortsLossSum = CompoundValue(1, if IsNaN(isOrder) or BarNumber() == 1 then 0 else if isOrder and isShort[1] then ShortsLossSum[1] + if isnan(profitLoss) then 0 else if profitLoss < 0 then profitLoss else 0 else ShortsLossSum[1], 0);

def dollarShortsLossSum = Round((ShortsLossSum / TickSize()) * TickValue())  ;
def dollarShortsProfitsSum = Round((ShortsProfitsSum / TickSize()) * TickValue())  ;

def  LongsProfitsSum = CompoundValue(1, if IsNaN(isOrder) or BarNumber() == 1 then 0 else if isOrder and islong[1] then LongsProfitsSum[1] + if isnan(profitLoss) then 0 else if profitLoss > 0 then profitLoss else 0 else LongsProfitsSum[1], 0);
def  LongsLossSum = CompoundValue(1, if IsNaN(isOrder) or BarNumber() == 1 then 0 else if isOrder and islong[1] then LongsLossSum[1] + if isnan(profitLoss) then 0 else if profitLoss < 0 then profitLoss else 0 else LongsLossSum[1], 0);
def dollarLongsProfitsSum = Round((LongsProfitsSum / TickSize()) * TickValue())  ;
def dollarLongsLossSum = Round((LongsLossSum / TickSize()) * TickValue())  ;


# Total Profit or Loss
def profitLossSum = CompoundValue(1, if IsNaN(isOrder) or BarNumber() == 1 then 0 else if isOrder then profitLossSum[1] + if isnan(profitLoss) then 0 else profitLoss else profitLossSum[1], 0);

def  LossSum = CompoundValue(1, if IsNaN(isOrder) or BarNumber() == 1 then 0 else if isOrder then LossSum[1] + if isnan(profitLoss) then 0 else if profitLoss < 0 then profitLoss else 0 else LossSum[1], 0);

def  ProfitSum = CompoundValue(1, if IsNaN(isOrder) or BarNumber() == 1 then 0 else if isOrder then ProfitSum[1] + if isnan(profitLoss) then 0 else if profitLoss > 0 then profitLoss else 0 else ProfitSum[1], 0);
def dollarLossSum = Round((LossSum / TickSize()) * TickValue())  ;
def dollarProfitSum = Round((ProfitSum / TickSize()) * TickValue())  ;

# Current Open Trade Profit or Loss
def TradePL = if isLong then Round(((close - orderPrice) / TickSize()) * TickValue()) else if isShort then Round(((orderPrice - close) / TickSize()) * TickValue()) else 0;

# How many trades won or lost
def profitWinners = CompoundValue(1, if IsNaN(profitWinners[1]) or BarNumber() == 1 then 0 else if isOrder and !isflat[1] and profitLoss > 0 then profitWinners[1] + 1 else profitWinners[1], 0);
def profitLosers = CompoundValue(1, if IsNaN(profitLosers[1]) or BarNumber() == 1 then 0 else if isOrder and !isflat[1] and profitLoss < 0 then profitLosers[1] + 1 else profitLosers[1], 0);
def profitPush = CompoundValue(1, if IsNaN(profitPush[1]) or BarNumber() == 1 then 0 else if isOrder and !isflat[1] and profitLoss == 0 then profitPush[1] + 1 else profitPush[1], 0);




#########################
#########################
# Math
#########################
#########################
# Convert to actual dollars based on Tick Value for bubbles
def dollarProfitLoss = if orderPrice[1] == 0 or IsNaN(orderPrice[1]) then 0 else Round((profitLoss / TickSize()) * TickValue());

# Closed Orders dollar P/L
def dollarPLSum = Round((profitLossSum / TickSize()) * TickValue())  ;

# Split profits or losses by long and short trades
def profitLong = CompoundValue(1, if IsNaN(profitLong[1]) or BarNumber() == 1 then 0 else if isOrder and isLong[1] then profitLong[1] + dollarProfitLoss else profitLong[1], 0);
def profitShort = CompoundValue(1, if IsNaN(profitShort[1]) or BarNumber() == 1 then 0 else if isOrder and isShort[1] then profitShort[1] + dollarProfitLoss else profitShort[1], 0);
def countLong = CompoundValue(1, if IsNaN(countLong[1]) or BarNumber() == 1 then 0 else if isOrder and isLong[1] then countLong[1] + 1 else countLong[1], 0);
def countShort = CompoundValue(1, if IsNaN(countShort[1]) or BarNumber() == 1 then 0 else if isOrder and isShort[1] then countShort[1] + 1 else countShort[1], 0);

# What was the biggest winning and losing trade
def biggestWin = CompoundValue(1, if IsNaN(biggestWin[1]) or BarNumber() == 1 then 0 else if isOrder and (dollarProfitLoss > 0) and (dollarProfitLoss > biggestWin[1]) then dollarProfitLoss else biggestWin[1], 0);
def biggestLoss = CompoundValue(1, if IsNaN(biggestLoss[1]) or BarNumber() == 1 then 0 else if isOrder and (dollarProfitLoss < 0) and (dollarProfitLoss < biggestLoss[1]) then dollarProfitLoss else biggestLoss[1], 0);

def orderCount = CompoundValue(1, if IsNaN(orderCount[1]) or BarNumber() == 1 then 0 else if ((isorder or isflat) and !isflat[1])  then orderCount[1] + 1 else orderCount[1], 0);

# What percent were winners
def PCTWin = Round((profitWinners / (profitWinners+profitLosers)) * 100, 2);

# Average trade
def avgTrade = Round((dollarPLSum / (orderCount )), 2);

#######################################
## Win / Loss labels
#######################################
AddLabel(ShowLabels and Show_trade_odds_Labels, "Closed Orders: " + orderCount ,  Color.white );
AddLabel(ShowLabels and Show_trade_odds_Labels,  " P/L: " + AsDollars(dollarPLSum), if dollarPLSum > 0 then Color.GREEN else if dollarPLSum < 0 then Color.YELLOW else Color.GRAY);
AddLabel(ShowLabels and Show_trade_odds_Labels,  " Profit Sum: " + AsDollars(dollarProfitSum), if dollarProfitSum > 0 then Color.GREEN else if dollarProfitSum < 0 then Color.YELLOW else Color.GRAY);
AddLabel(ShowLabels and Show_trade_odds_Labels,  " Loss Sum: " + AsDollars(dollarLossSum), if dollarLossSum > 0 then Color.GREEN else if dollarLossSum < 0 then Color.YELLOW else Color.GRAY);


AddLabel(ShowLabels and if !IsNaN(orderPrice) and Show_trade_odds_Labels then 1 else 0, "Closed+Open P/L: " + AsDollars(TradePL + dollarPLSum), if ((TradePL + dollarPLSum) > 0) then Color.GREEN else if ((TradePL + dollarPLSum) < 0) then Color.YELLOW else Color.GRAY);




AddLabel(ShowLabels and Show_trade_odds_Labels, "Longs Profit Sum: " + AsDollars(dollarLongsProfitsSum), if dollarLongsProfitsSum > 0 then Color.GREEN else if dollarLongsProfitsSum < 0 then Color.YELLOW else Color.GRAY);

AddLabel(ShowLabels and Show_trade_odds_Labels, "Longs Loss Sum: " + AsDollars(dollarLongsLossSum), if dollarLongsLossSum > 0 then Color.GREEN else if dollarLongsLossSum < 0 then Color.YELLOW else Color.GRAY);
#
#

AddLabel(ShowLabels and Show_trade_odds_Labels, "Shorts Profit Sum: " + AsDollars(dollarShortsProfitsSum), if dollarShortsProfitsSum > 0 then Color.GREEN else if dollarShortsProfitsSum < 0 then Color.YELLOW else Color.GRAY);
AddLabel(ShowLabels and Show_trade_odds_Labels, "Shorts Loss Sum: " + AsDollars(dollarShortsLossSum), if dollarShortsLossSum > 0 then Color.GREEN else if dollarShortsLossSum < 0 then Color.YELLOW else Color.GRAY);


AddLabel(ShowLabels and Show_trade_odds_Labels, "Avg per Trade: " + AsDollars(avgTrade), if avgTrade > 0 then Color.GREEN else if avgTrade < 0 then Color.YELLOW else Color.GRAY);
AddLabel(ShowLabels and Show_trade_odds_Labels, "Winners: " + PCTWin + "%", if PCTWin > 50 then Color.GREEN else if PCTWin > 40 then Color.YELLOW else Color.GRAY);

AddLabel(ShowLabels and Show_trade_odds_Labels, "MaxUp: " + AsDollars(biggestWin) + " MaxDown: " + AsDollars(biggestLoss), Color.WHITE);

AddLabel(ShowLabels and  if !IsNaN(CurrentPosition) and Show_trade_odds_Labels then 1 else 0, if !isflat then  "Open: " + (if isLong then "Bought" else  "Sold") + " @ " + orderPrice else "Flat", Color.WHITE);
AddLabel(ShowLabels and if !IsNaN(orderPrice) and Show_trade_odds_Labels then 1 else 0, "Open Trade P/L: " + AsDollars(TradePL), if (TradePL > 0) then Color.GREEN else if (TradePL < 0) then Color.YELLOW else Color.GRAY);

def RTHstart = if getaggregationPeriod() < aggregationPeriod.day then  SecondsFromTime(1600) == 0 else  getday() <> getday()[1];
def daysOnChart = if RTHstart 
then compoundValue(1, daysOnChart[1] + 1, 1)
else daysOnChart[1];
addLabel(Show_trade_odds_Labels, "Days on Chart: " + daysOnChart, color.cyan);


def from_dayofmonth = if BarNumber() == 1 then GetDayOfMonth(GetYYYYMMDD()) else from_dayofmonth[1];
def from_month = if BarNumber() == 1 then GetMonth() else from_month[1];
def from_year  = if BarNumber() == 1 then GetYear() else from_year[1];

AddLabel(ShowLabels, "1st Bar: " + from_month  + "/" + from_dayofmonth + "/"  + (AsPrice(from_year)),
             if !IsNaN(GetTime())
             then Color.LIME
             else if IsNaN(GetTime())
                  then Color.PINK
                  else Color.WHITE);

#######################################
##  Bubbles for Profit/Loss
#######################################

AddChartBubble(showSignals and showSignalStudyPnlBubbles and isOrder and isLong[1], low, "$" + dollarProfitLoss, if dollarProfitLoss == 0 then Color.LIGHT_GRAY else if dollarProfitLoss > 0 then Color.GREEN else Color.WHITE, 0);
AddChartBubble(showSignals and showSignalStudyPnlBubbles and isOrder and isShort[1], high, "$" + dollarProfitLoss, if dollarProfitLoss == 0 then Color.LIGHT_GRAY else if dollarProfitLoss > 0 then Color.GREEN else Color.white, 1);


AddChartBubble(showSignals and showSignalStudyPnlBubbles and !isOrder and (islong or isshort) and !IsNaN(orderprice)  and IsNaN(close [-1] ) and  !IsNaN(close) and HighestAll(BarNumber()) and TradePL> 0, orderprice, "$" +TradePL, if  TradePL == 0 then Color.LIGHT_GRAY else if TradePL > 0 then Color.light_GREEN else Color.pink, 1);

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

AddOrder(OrderType.BUY_TO_CLOSE, EnableStrategy and activerange and ActiveTradeTime  and SellStop , name = if OrderSimbol then "Bx" else  " B(x)@ "  + open[-1], price = open[-1], tickcolor = GetColor(9), arrowcolor = GetColor(9));
AddOrder(OrderType.SELL_TO_CLOSE, EnableStrategy and activerange and ActiveTradeTime and BuyStop, name = if OrderSimbol then "Sx" else  " S(x)@ "  + open[-1], price = open[-1], tickcolor = GetColor(7), arrowcolor = GetColor(7));




Scan Previous Day High and Low Breakout not using secondary aggregation
jf4TwNilEHqF7BYsfY_7B5aMMPxAR__dOjMgRNM226AOZNVnNPz6ek8hPaJt8KwfCqSmvQA-tcW8v1gw4WC2EBe3qctLM_UhJSQVjdePyw273YIYGRtpnEvH12-CkMm-tVPHe2neGiq1qH9waktYwp4

lpC0dDAE7M9B1p-kCU9M2PLD_kqOvZnMD6yzVkaH8ov8moujYEOSymX0t7OxiGNS9S3Wy5mSQQSR86jb1Oq7snQp41V0ZBYsr8HN7Mx4ZjNqCrMeaeFyBpEuhOuP4Ju8VYCudDCXyNw5HpmCG2Dx4y0


#RTH_PRE_highlow use in the scan


Code:
#RTH_PRE_highlow use in the scan
 
def activerth = RegularTradingStart(GetYYYYMMDD()) - GetTime() < 0 and RegularTradingEnd(GetYYYYMMDD()) - GetTime() > 0;
input bubble = yes;
DefineGlobalColor("RTHOPEN", Color.white);
DefineGlobalColor("RTHCLOSE", Color.GRAY);
DefineGlobalColor("RTHLOW", Color.orange);
DefineGlobalColor("RTHHIGH", Color.light_green);
DefineGlobalColor("AFTERRTHHIGH", Color.GREEN);
DefineGlobalColor("AFTERRTHLOW", Color.RED);
DefineGlobalColor("HIGH", Color.dark_GREEN);
DefineGlobalColor("LOW", Color.dark_red);


def h = high; 
def l = low; 
def o = open;
def c = close ;
def bar = BarNumber();
def RTHOpen = if activerth and !activerth[1]  then o else  RTHOpen[1];
def RTHClose = if !activerth and activerth[1]  then c else  RTHClose[1];

plot rtho = RTHOpen ; 
 rtho.SetPaintingStrategy(PaintingStrategy.POINTS ); 
 rtho.SetDefaultColor(GlobalColor("RTHOPEN")); 
addchartbubble(bubble and rtho==rtho[1] and isNaN(close[2]) and !isNaN(close[3]), rtho,"Open",GlobalColor("RTHOPEN"));

plot rthc =   RTHClose; 
 rthc.SetPaintingStrategy(PaintingStrategy.POINTS ); 
 rthc.SetDefaultColor(GlobalColor("RTHCLOSE")); 
addchartbubble(bubble and rthc==rthc[1] and isNaN(close[3]) and !isNaN(close[4]), rthc,"Close",GlobalColor("RTHCLOSE"));



def RTHLow = if activerth and !activerth[1] then l 
 else if activerth and l < RTHLow[1] then l else RTHLow[1]; 

def pRTHLow = if activerth <> activerth[1] then RTHLow[1] else pRTHLow[1];

def RTHhigh = if activerth and !activerth[1] then h 
 else if activerth and h > RTHhigh[1] then h else RTHhigh[1]; 

def pRTHhigh = if activerth <> activerth[1] then RTHhigh[1] else pRTHhigh[1];


plot ll = if !activerth then RTHLow 
else if activerth then pRTHLow else double.nan; 
 ll.SetPaintingStrategy(PaintingStrategy.Squares); 
 ll.SetDefaultColor(GlobalColor("RTHLOW"));

def PLValue = if !IsNaN(ll) then ll else PLValue[1];
def PLBarOrigin = if !IsNaN(ll) then bar else PLBarOrigin[1];

addchartbubble(bubble and if Bar == HighestAll(PLBarOrigin) then PLBarOrigin else Double.NaN, PLValue,"PrevRTH,Low",GlobalColor("RTHLOW"));

plot hh = if  !activerth then RTHhigh  else if activerth  then pRTHhigh else double.nan; 
 hh.SetPaintingStrategy(PaintingStrategy.Squares); 
 hh.SetDefaultColor(GlobalColor("RTHHIGH")); 

def PHBarOrigin = if !IsNaN(hh) then bar else PHBarOrigin[1];
def PHValue = if !IsNaN(hh) then hh else PHValue[1];

addchartbubble(bubble and if Bar == HighestAll(PHBarOrigin) then PHBarOrigin else Double.NaN, PHValue,"PrevRTH,High",GlobalColor("RTHHIGH"));


def aRTHhigh = if !activerth and activerth[1] then h 
 else if !activerth and h > aRTHhigh[1] then h 
 else aRTHhigh[1];

def aRTHLow = if !activerth and activerth[1] then l   
else if !activerth and l < aRTHLow[1] then l
else aRTHLow[1];

def paRTHhigh = if activerth <> activerth[1] then aRTHhigh[1] else paRTHhigh[1];
def paRTHLow = if activerth <> activerth[1] then aRTHLow[1] else paRTHLow[1];

plot ahh = if  activerth  then aRTHhigh else if !activerth then paRTHhigh else double.nan; 
 ahh.SetPaintingStrategy(PaintingStrategy.POINTS ); 
 ahh.SetDefaultColor(GlobalColor("AFTERRTHHIGH"));   
def APHBarOrigin = if !IsNaN(ahh) then bar else APHBarOrigin[1];
def APHValue = if !IsNaN(Ahh) then Ahh else APHValue[1];
addchartbubble(bubble and if Bar == HighestAll(APHBarOrigin) then APHBarOrigin else Double.NaN, APHValue,"PreRTH,High",GlobalColor("AFTERRTHHIGH"));


plot all = if activerth then aRTHLow else if !activerth then paRTHLow else double.nan; 
 all.SetPaintingStrategy(PaintingStrategy.POINTS); 
 all.SetDefaultColor(GlobalColor("AFTERRTHLOW")); 

def APLBarOrigin = if !IsNaN(aLL) then bar else APLBarOrigin[1];
def APLValue = if !IsNaN(aLL) then aLL else APLValue[1];
addchartbubble(bubble and if Bar == HighestAll(APLBarOrigin) then APLBarOrigin else Double.NaN, APLValue,"PreRTH,Low",GlobalColor("AFTERRTHLOW"));


plot _ll  =  highestAll(if isNaN(close[-1]) 
                               then if activerth then  RTHLow else aRTHLow
else double.nan); 
 _ll.SetStyle(Curve.SHORT_DASH); 
 _ll.SetDefaultColor(GlobalColor("LOW"));
addchartbubble(bubble and _ll==_ll[1] and isNaN(close[4]) and !isNaN(close[5]), _ll,"Lowest",GlobalColor("LOW"));

plot _hh = highestAll(if isNaN(close[-1]) 
                               then if activerth then  RTHhigh else aRTHhigh
                               else Double.NaN);
 _hh.SetStyle(Curve.SHORT_DASH);
 _hh.SetDefaultColor(GlobalColor("HIGH")); 

addchartbubble(bubble and _hh==_hh[1] and isNaN(close[4]) and !isNaN(close[5]), _hh,"Highest",GlobalColor("HIGH"));
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
376 Online
Create Post

Similar threads

Similar threads

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