Finding the First and Last Bar of the day in ThinkorSwim

isnt allowing me to add image
but heres a link
i guess the code would be something like this but for last bar of day

#CODE BELOW
AddLabel(1, "52Week HIGH = " + Highest(high(period = AggregationPeriod.Week),52), Color.plum);
AddLabel(1, "52Week LOW = " + Lowest(low(period = AggregationPeriod.Week),52), Color.plum);
#END CODE

This is data off the last bar shown as a label and with lines

Capture.jpg
Ruby:
def lasthigh  = if IsNaN(close[-1]) and !IsNaN(close) then high else lasthigh[1];
def lastclose = if IsNaN(close[-1]) and !IsNaN(close) then close else lastclose[1];
def lastlow   = if IsNaN(close[-1]) and !IsNaN(close) then low  else lastlow[1];

input showlines = yes;
plot lhigh   = if !showlines then double.nan else lasthigh;
plot lclose  = if !showlines then double.nan else  lastclose;
plot llow    = if !showlines then double.nan else  lastlow;
lhigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
lclose.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
llow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

lhigh.SetDefaultColor(Color.GREEN);
lclose.SetDefaultColor(Color.YELLOW);
llow.SetDefaultColor(Color.RED);

input showlabels = yes;
AddLabel(showlabels, "High Bar: " + AsText(lasthigh), Color.green);
addlabel(showlabels, "Close Bar: " + astext(lastclose), color.yellow);
AddLabel(showlabels, "Low Bar: " + AsText(lastlow), Color.RED);
 
This is data off the last bar shown as a label and with lines
awesome thank you,,,,,,

are you able to modify this code to where it only shows text on the chart bubbles but not the price didgits??


# https://usethinkscript.com/threads/need-help-with-top-ultimate-breakout-indicator.1243/
input ShowTodayOnly = yes;
input BuyorSell = {default Buy, Sell};
input BuyEntry = 3;
input SellEntry = 3;
input BuyExit = 20;
input SellExit = 20;
input ATRLength = 50;
input TargetATRMult = 1;
input DisplayLines = yes;
#input PriceDigits=NumberFormat.TWO_DECIMAL_PLACES;

input PriceDigit=2;

def H = high;
def L = low;

def h1 = Highest(H, SellExit);
def ih2=if H != h1 then H else 0.0;
#def h2 = Highest(ih2, SellExit);
def h2=fold i =1 to SellExit with ip=0.0 do if GetValue(H,i)==h1 or GetValue(H,i)<ip then ip else GetValue(H,i);
#def h3 = Highest(if (H == h1 or H == h2) then 0 else H, SellExit);
def h3=fold i1 =1 to SellExit with ip1=0.0 do if GetValue(H,i1)==h1 or GetValue(H,i1)==h2 or GetValue(H,i1)<ip1 then ip1 else GetValue(H,i1);
def HH = (h2 + h3) / 2.0;

#plot pHH=HH;

def l1 = Lowest(L, BuyExit);
#def l2 = Lowest(if L == l1 then 1000000 else L, BuyExit);
def l2=fold i2 =1 to BuyExit with ip2=10000000.0 do if GetValue(L,i2)==l1 or GetValue(L,i2)>ip2 then ip2 else GetValue(L,i2);
def l3 = Lowest(if L == l1 or L == l2 then 1000000 else L, BuyExit);
def LL = (l2 + l2) / 2.0;

def QB = Highest(H, BuyEntry);
def QS = Lowest(L, SellEntry);

def ATRVal = ATR(length = ATRLength,averageType= AverageType.SIMPLE);
def mATR = Highest(ATRVal, ATRLength);

def dl = DisplayLines == yes;
def trade;
plot entry;

switch (BuyorSell){
case Buy:
trade = 1;
#entry.SetDefaultColor(color.GREEN);
case Sell:
trade = -1;
}
#AddLabel(1,trade);
#def c1 = (BuyorSell == "Buy") and barnumber() > Max(SellExit, BuyExit);
#def c2 = (BuyorSell == "Sell") and Barnumber() > Max(SellExit, BuyExit);

entry.AssignValueColor(if trade == 1 then Color.GREEN else if trade == -1 then Color.RED else Color.GREEN);
#entry.setPaintingStrategy(paintingStrategy.LINE);
plot stop;
stop.SetDefaultColor(Color.CYAN);

def EntryPr;
def co = BarNumber() > Max(SellExit, BuyExit);
def pos;

switch (BuyorSell){
case Buy:
entry = QB[1];
stop = LL[1];
pos = if co and high > QB[1] then 1 else if low < LL[1] then 0 else pos[1];
EntryPr = if high > QB[1] and pos == 1 and pos[1] < 1 then QB[1] else if pos == 0 then Double.NaN else EntryPr[1];

case Sell:
entry = QS[1];
stop = HH[1];
pos = if co and low < QS[1] then -1 else if high[1] > HH[2] then 0 else pos[1];
EntryPr = if low < QS[1] and pos == -1 and pos[1] > -1 then QS[1] else if pos == 0 then Double.NaN else EntryPr[1];
}

def BTarget;
def BTarget2;
def EntryLine;
def TradeRisk;

switch (BuyorSell){
case Buy:
BTarget = if pos == 1 and pos[1] < 1 then (EntryPr + (TargetATRMult * 2 * mATR)) else if pos == 1 then BTarget[1] else Double.NaN;
BTarget2 = if pos == 1 and pos[1] < 1 then (EntryPr + 2 * (TargetATRMult * 2 * mATR)) else if pos == 1 then BTarget2[1] else Double.NaN;
EntryLine = if LL < EntryPr then EntryPr else Double.NaN;
TradeRisk = (EntryPr - LL) / mATR;

case Sell:
BTarget = if pos == -1 and pos[1] > -1 then (EntryPr - (TargetATRMult * 2 * mATR)) else if pos == -1 then BTarget[1] else Double.NaN;
BTarget2 = if pos == -1 and pos[1] > -1 then (EntryPr - 2 * (TargetATRMult * 2 * mATR)) else if pos == -1 then BTarget2[1] else Double.NaN;
EntryLine = if HH > EntryPr then EntryPr else Double.NaN;
TradeRisk = (HH - EntryPr ) / mATR;
}

plot pBTarget = if dl and co then BTarget else Double.NaN;
pBTarget.SetDefaultColor(Color.YELLOW);

plot pBTarget2 = if dl and co then BTarget2 else Double.NaN;
pBTarget2.SetDefaultColor(Color.MAGENTA);

plot pEntryLine = if dl and co then EntryLine else Double.NaN;
pEntryLine.SetDefaultColor(Color.WHITE);

#plot pbt=if dl and co and (pos == 1 or pos == -1) and pos[1] == 0 then BTarget else double.NaN;
#pbt.setPaintingStrategy(paintingStrategy.VALUES_BELOW);

def valco=dl and co and (pos == 1 or pos == -1) and pos[1] == 0;
def rBTarget=round(BTarget,PriceDigit);
def rBTarget2=round(BTarget2,PriceDigit);
def rEntryPr=round(EntryPr,PriceDigit);





def exv=if trade == 1 then LL else HH;
def rexv = round(exv,PriceDigit);
def rTradeRisk = round(TradeRisk,PriceDigit);

AddChartBubble(valco,exv,rexv + "(" +rTradeRisk + "STOP LOSS)", Color.RED);
AddChartBubble(valco, BTarget,rBTarget + "(" + "T1)", Color.YELLOW);
AddChartBubble(valco, BTarget2,rBTarget2 + "(" + "T2)", Color.PLUM);
AddChartBubble(valco, ENtryPr,rENtryPr + "(" + "ENTER)", Color.WHITE);
#AddChartBubble(1,H,pos);

#END
 
Here is the study for the first bar of the month, run this on a daily aggregation

Code:
def mth = GetMonth();
plot newMonth = mth != mth[1];
newMonth.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
newMonth.SetDefaultColor(Color.YELLOW);
newMonth.SetLineWeight(3);
how about first bar of day? some stocks like to pull back to the open and bonce, is there a way to plot a line for the close of the first bar of day instead of chart bubble
 
how about first bar of day? some stocks like to pull back to the open and bonce, is there a way to plot a line for the close of the first bar of day instead of chart bubble

This will plot the open at premarket and regular trading hours as horizontal lines.

Ruby:
def open_pre = if gettime() crosses below regularTradingEnd(getyyyYMMDD()) then open else open_pre[1];
plot pre_open = open_pre;
pre_open.setpaintingStrategy(paintingStrategy.HORIZONTAL);
pre_open.setdefaultColor(color.cyan);

def open_rth = if gettime() crosses above regularTradingstart(getyyyYMMDD()) then open else open_rth[1];
plot rth_open = open_rth;
rth_open.setpaintingStrategy(paintingStrategy.HORIZONTAL);
rth_open.setdefaultColor(color.magenta);
 
I came across this script which it has helped TREMENDOUSLY so thank you for that! However, how do I script for the strategy to NOT take a trade at the last bar? For clarification, I am telling the strategy to close out any trades on the last bar (that part is working just fine) but on rare occasions, the conditions of the strategy are being met RIGHT AT THE LAST BAR OF THE DAY and therefore the strategy is entering into a new trade while simultaneously closing any existing trades. Any help on how to tell the strategy to NOT TAKE A NEW POSITION ON THE LAST BAR OF THE DAY? Thank you in advance.
 
Last edited:
I came across this script which it has helped TREMENDOUSLY so thank you for that! However, how do I script for the strategy to NOT take a trade at the last bar? For clarification, I am telling the strategy to close out any trades on the last bar (that part is working just fine) but on rare occasions, the conditions of the strategy are being met RIGHT AT THE LAST BAR OF THE DAY and therefore the strategy is entering into a new trade while simultaneously closing any existing trades. Any help on how to tell the strategy to NOT TAKE A NEW POSITION ON THE LAST BAR OF THE DAY? Thank you in advance.
Figured out my own question. If anyone wondering, just add

LastBarofDay[-1] is False

and it won't take an entry on the last bar.
 
Here is the study for the first bar of the month, run this on a daily aggregation

Code:
def mth = GetMonth();
plot newMonth = mth != mth[1];
newMonth.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
newMonth.SetDefaultColor(Color.YELLOW);
newMonth.SetLineWeight(3);
How would I count the number of bars since the first bar?

Example: I want to count the number of bars since a higher time frame opened.(day, week, month, etc.).

(Why I want this: I run into back-testing issues where if I reference higher time frame, that higher time frame can report data based on what happened later, versus the status of that higher time frame on that exact bar. This thread kinda explains my issue:

https://usethinkscript.com/threads/...-data-back-testing-versus-live-testing.10366/

My hope was that if I could count the number of bars since the higher time frame opened, I could derive the high/low at a bar based on getting the highest/lowest values up until that bar occurred. This would then make it a lot easier to test mutliple time frame, versus only being able to test multiple time frame by advancing in on-demand, or advancing with live data.
 
How would I count the number of bars since the first bar?

Example: I want to count the number of bars since a higher time frame opened.(day, week, month, etc.).

(Why I want this: I run into back-testing issues where if I reference higher time frame, that higher time frame can report data based on what happened later, versus the status of that higher time frame on that exact bar. This thread kinda explains my issue:

https://usethinkscript.com/threads/...-data-back-testing-versus-live-testing.10366/

My hope was that if I could count the number of bars since the higher time frame opened, I could derive the high/low at a bar based on getting the highest/lowest values up until that bar occurred. This would then make it a lot easier to test mutliple time frame, versus only being able to test multiple time frame by advancing in on-demand, or advancing with live data.
You can't backtest MTF indicators due to the repainting. In real-time, a 1hr indicator on a 5-min timeframe will repaint for 12 bars. In backtesting it will already be repainted yielding results not possible to obtain in real trading.
 
You can't backtest MTF indicators due to the repainting. In real-time, a 1hr indicator on a 5-min timeframe will repaint for 12 bars. In backtesting it will already be repainted yielding results not possible to obtain in real trading.
I'm aware of that limitation.

I'm looking for a solution that steps outside of multiple time frames to provide what I'm looking for. I don't know if "virtual" time frame better communicates what I'm driving at, or not.

I'm looking for a virtual time frame that is an accumulation of the lower time frame, and thus get away from the multiple time frame/multiple aggregation issues. What I'm envisioning would be possible if I could figure out how to count bars since period began.

That is, to approximate this:
Code:
def WeeklyHigh = High(period = AggregationPeriod.WEEK);
def WeeklyLow = Low(period = AggregationPeriod.WEEK);
def DailyHigh = High(period = AggregationPeriod.DAY);
def DailyLow = Low(period = AggregationPeriod.DAY);

I want to do this instead:
Code:
def count_of_days = <<number of days since the week started>>;
def VirtualWeeklyHigh = highest(high(period=AggregationPeriod.DAY), count_of_days);
def VirtualWeeklyLow = lowest(low(period=AggregationPeriod.DAY), count_of_days);
def DailyHigh = High(period = AggregationPeriod.DAY);
def DailyLow = Low(period = AggregationPeriod.DAY);

Because the "virtual" week is simply an accumulation of days, I don't have to reference the AggregationPeriod.WEEK time frame in the second code. My challenge is figuring out "count_of_days" (or any alternative to get what I'm looking for).

Also, if I back-tested the virtual week, Monday and Tuesday would have different "count_of_days", so it would be back-test friendly.

Hope this explains the idea a bit better.
 
I'm aware of that limitation.

I'm looking for a solution that steps outside of multiple time frames to provide what I'm looking for. I don't know if "virtual" time frame better communicates what I'm driving at, or not.

I'm looking for a virtual time frame that is an accumulation of the lower time frame, and thus get away from the multiple time frame/multiple aggregation issues. What I'm envisioning would be possible if I could figure out how to count bars since period began.

That is, to approximate this:
Code:
def WeeklyHigh = High(period = AggregationPeriod.WEEK);
def WeeklyLow = Low(period = AggregationPeriod.WEEK);
def DailyHigh = High(period = AggregationPeriod.DAY);
def DailyLow = Low(period = AggregationPeriod.DAY);

I want to do this instead:
Code:
def count_of_days = <<number of days since the week started>>;
def VirtualWeeklyHigh = highest(high(period=AggregationPeriod.DAY), count_of_days);
def VirtualWeeklyLow = lowest(low(period=AggregationPeriod.DAY), count_of_days);
def DailyHigh = High(period = AggregationPeriod.DAY);
def DailyLow = Low(period = AggregationPeriod.DAY);

Because the "virtual" week is simply an accumulation of days, I don't have to reference the AggregationPeriod.WEEK time frame in the second code. My challenge is figuring out "count_of_days" (or any alternative to get what I'm looking for).

Also, if I back-tested the virtual week, Monday and Tuesday would have different "count_of_days", so it would be back-test friendly.

Hope this explains the idea a bit better.
Well, I've been able to determine that this method I'm proposing won't work as simply as I propose, because the highest() & lowest() functions require constants, and won't accept dynamic values. ... It was worth a shot at least ... :D
 
well can't you just count how many bars there are in the lower timeframe to make up the length of the longer timeframe to simulate and then use those long lengths instead of your original ones? I hope that made sense :)
Hahahaa, so funny (were you snooping on me the other day as I was having this conversation with MsTradeCombine):

How about I use 5 days for virtual week, 21 days for virtual month, etc. Thus, my virtual weekly high = highest(high, 5), and virtual quarter high = highest(high, 63), etc.?

If you didn't mean it that way, let me know. I like new ideas. :D

I should probably test the 5/21/63/252 study (this technique is already used by some for moving averages and what-not), and it's not quite the same as MTF, but maybe I'm too rigid to want a virtual MTF in the first place.
 
i don't think i've seen any other threads by u :) but what i do to avoid the MTF strategy pitfalls is simulate the length on the smaller timeframe for example if i want to see the (thirty minute time frame) 4 length RSI on the 5 min chart ill calculate 4 x 6 = 24 length. I do this with all my studies.

Here's what I would do to simulate what you're looking for. Is there a way to incorporate the day count? If so, could you share that maybe? I've been meaning to learn how to code that kind of thing but haven't got around to it yet. This is basically just Daily High Low (td study) with a rolling length plot.

Ruby:
#Highest Lowest Edit


#
# TD Ameritrade IP Company, Inc. (c) 2011-2022
#

#no counting involved here

# ROLLING DAILY HIGH LOW CHANNEL #
input aggregationPeriod = AggregationPeriod.DAY;
input length = 5;
input displace = -1;
input showOnlyLastPeriod = no;

plot DailyHigh;
plot DailyLow;
if showOnlyLastPeriod and !IsNaN(close(period = aggregationPeriod)[-1]) {
    DailyHigh = Double.NaN;
    DailyLow = Double.NaN;
} else {
    DailyHigh = Highest(high(period = aggregationPeriod)[-displace], length);
    DailyLow = Lowest(low(period = aggregationPeriod)[-displace], length);
}


DailyHigh.SetDefaultColor(GetColor(1));
DailyHigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
DailyLow.SetDefaultColor(GetColor(1));
DailyLow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
DailyHigh.Hide();
DailyLow.Hide();

plot highest = highest(DailyHigh[1], length);
highest.setDefaultColor(color.light_green);
plot lowest = lowest(DailyLow[1], length);
lowest.setDefaultColor(color.light_red);

# ROLLING WEEKLY HIGH LOW CHANNEL #


input aggregationPeriodW = AggregationPeriod.DAY; #hint: displacing by 1 means MTF will be fine if you want to change to Week

input lengthW = 21; #hint if change to Week Agg then change length back to 5 or whatever u want

input displaceW = -1;
input showOnlyLastPeriodW = no;

plot WHigh;
plot WLow;
if showOnlyLastPeriod and !IsNaN(close(period = aggregationPeriod)[-1]) {
    WHigh = Double.NaN;
    WLow = Double.NaN;
} else {
    WHigh = Highest(high(period = aggregationPeriod)[-displace], length);
    WLow = Lowest(low(period = aggregationPeriod)[-displace], length);
}

plot Whighest = highest(WHigh[1], lengthW);
Whighest.setDefaultColor(color.dark_green);
plot Wlowest = lowest(WLow[1], lengthW);
Wlowest.setDefaultColor(color.dark_red);


WHigh.SetDefaultColor(GetColor(2));
WHigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
WLow.SetDefaultColor(GetColor(2));
WLow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
WHigh.Hide();
WLow.Hide();

#day channel
AddCloud(highest, lowest, color.yellow, color.white);

#week channel
AddCloud(Whighest, Wlowest, color.light_gray, color.white);
 
here's a slightly different way to do it using FIRST

here is an example

Code:
#First Bar Close and Volume of REGULAR TRADING HOURS

def mktOpen = SecondsFromTime(0930) == 0 or GetDay() <> GetDay();

#First Bar Info
def high1 = First(close);

#Define  Todays First Bar Close
def today_firstbarclose = if mktOpen and high1 then close else today_firstbarclose[1];
#Define  Todays First Bar Volume
def today_firstbarvol = if mktOpen and high1 then volume else today_firstbarvol[1];

#Label
AddLabel(yes, " Todays First RTH Bar Close =" + today_firstbarclose, Color.LIGHT_GRAY);
AddLabel(yes, " Todays First RTH Bar Volume =" + today_firstbarvol, Color.LIGHT_GRAY);
 
this is for a request from here,
https://usethinkscript.com/threads/...hourly-candle-high-and-low-with-labels.15416/
to modify the code in post#1 to show prices in labels for several days

----------------------

show labels with, the high and low from the last x days,
from the first and/or last bars of the day.

pick first bar, last bar, or both
pick a quantity for recent days to look at, 1 to 8

a couple of test bubbles can be turned on see some prices and counts.

day 1 is the current day. day 2 is the previous one, 3 is before that,...

Code:
# labels_firstlastbar_xdays_00d

# https://usethinkscript.com/threads/previous-day-5-days-last-hourly-candle-high-and-low-with-labels.15416/
#previous day / 5 days last hourly candle high and low with labels?

#This indicator of @korygill's is pretty cool.
#https://usethinkscript.com/threads/finding-the-first-and-last-bar-of-the-day-in-thinkorswim.526/

#-------------------------------


def na = double.nan;
def bn = barnumber();

input days_back = 5;
input bars = { First , default Last , both };
input show_labels = yes;


def lookbackdays = if days_back < 1 then 1
 else if days_back > 8 then 8
 else days_back;

addlabel( (days_back < 1 or days_back > 8), " wrong value for 'days_back'. needs to be between  1 and 8", color.cyan);

DefineGlobalColor("first", color.green);
DefineGlobalColor("last", color.cyan);
# GlobalColor("first");
# GlobalColor("last");

#DefineGlobalColor("Gray", CreateColor(28, 28, 28));  #Gray



#-------------------------------
# https://usethinkscript.com/threads/finding-the-first-and-last-bar-of-the-day-in-thinkorswim.526/
# GetDayValues
# Author: Kory Gill, @korygill
# VERSION HISTORY (sortable date and time (your local time is fine), and your initials
# 20190823-1400-KG    - Created.

declare hide_on_daily;
#declare once_per_bar;

# input onUpper = yes;
def nan = Double.NaN;
def isRollover = GetYYYYMMDD() != GetYYYYMMDD()[1];
def beforeStart = GetTime() < RegularTradingStart(GetYYYYMMDD());
def afterEnd = GetTime() > RegularTradingEnd(GetYYYYMMDD());
def firstBarOfDay = if (beforeStart[1] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;
def lastBarOfDay = if (afterEnd[-1] == 1 and afterEnd == 0) or (isRollover[-1] and firstBarOfDay[-1]) then 1 else 0;

# Identify first bar of day and last bar of day on chart
input bubbles_first_and_last = no;

AddChartBubble(
   bubbles_first_and_last and firstBarOfDay,
   close,
   "First Bar of Day",
   Color.GREEN,
   yes);

AddChartBubble(
   bubbles_first_and_last and lastBarOfDay,
   close,
   "Last Bar of Day",
   Color.GREEN,
   no);

#-------------------------------
# count days

#def bn = barnumber();
def istoday = if GetLastDay() == GetDay() then 1 else 0;
def newday = if GetDay() != GetDay()[1] then 1 else 0;
def daycnt = if bn == 1 then 1 else if (!IsNaN(close) and newday) then daycnt[1] + 1 else daycnt[1];
def maxdays = HighestAll(daycnt);
def revdaycnt = maxdays - daycnt + 1;

def daysok = if revdaycnt <= days_back then 1 else 0;
def daystoomany = if days_back < 1 or days_back > maxdays then 1 else 0;

#-------------------------------


#----------------------------
# rev day 8 , farthest from last bar
def d8firsthi = if bn == 1 then na else if daysok and revdaycnt == 8 and (bars == bars.First or bars == bars.both) and firstBarOfDay then high else d8firsthi[1];
def d8firstlo = if bn == 1 then na else if daysok and revdaycnt == 8 and (bars == bars.First or bars == bars.both) and firstBarOfDay then low else d8firstlo[1];
def d8lasthi = if bn == 1 then na else if daysok and revdaycnt == 8 and (bars == bars.last or bars == bars.both) and lastBarOfDay then high else d8lasthi[1];
def d8lastlo = if bn == 1 then na else if daysok and revdaycnt == 8 and (bars == bars.last or bars == bars.both) and lastBarOfDay then low else d8lastlo[1];

addlabel(show_labels, " " , color.black);
addlabel(show_labels and (!isnan(d8firsthi) or !isnan(d8lasthi)), "D8", color.white);
addlabel(show_labels and !isnan(d8firsthi), "F hi " + d8firsthi , GlobalColor("first"));
addlabel(show_labels and !isnan(d8firstlo), "F lo " + d8firstlo , GlobalColor("first"));
addlabel(show_labels and !isnan(d8lasthi), "L hi " + d8lasthi , GlobalColor("last"));
addlabel(show_labels and !isnan(d8lastlo), "L lo " + d8lastlo , GlobalColor("last"));

# GlobalColor("first")
# GlobalColor("last")

#----------------------------
# rev day 7
def d7firsthi = if bn == 1 then na else if daysok and revdaycnt == 7 and (bars == bars.First or bars == bars.both) and firstBarOfDay then high else d7firsthi[1];
def d7firstlo = if bn == 1 then na else if daysok and revdaycnt == 7 and (bars == bars.First or bars == bars.both) and firstBarOfDay then low else d7firstlo[1];
def d7lasthi = if bn == 1 then na else if daysok and revdaycnt == 7 and (bars == bars.last or bars == bars.both) and lastBarOfDay then high else d7lasthi[1];
def d7lastlo = if bn == 1 then na else if daysok and revdaycnt == 7 and (bars == bars.last or bars == bars.both) and lastBarOfDay then low else d7lastlo[1];

addlabel(show_labels, " " , color.black);
addlabel(show_labels and (!isnan(d7firsthi) or !isnan(d7lasthi)), "D7", color.white);
addlabel(show_labels and !isnan(d7firsthi), "F hi " + d7firsthi , GlobalColor("first"));
addlabel(show_labels and !isnan(d7firstlo), "F lo " + d7firstlo , GlobalColor("first"));
addlabel(show_labels and !isnan(d7lasthi), "L hi " + d7lasthi , GlobalColor("last"));
addlabel(show_labels and !isnan(d7lastlo), "L lo " + d7lastlo , GlobalColor("last"));

#----------------------------
# rev day 6
def d6firsthi = if bn == 1 then na else if daysok and revdaycnt == 6 and (bars == bars.First or bars == bars.both) and firstBarOfDay then high else d6firsthi[1];
def d6firstlo = if bn == 1 then na else if daysok and revdaycnt == 6 and (bars == bars.First or bars == bars.both) and firstBarOfDay then low else d6firstlo[1];
def d6lasthi = if bn == 1 then na else if daysok and revdaycnt == 6 and (bars == bars.last or bars == bars.both) and lastBarOfDay then high else d6lasthi[1];
def d6lastlo = if bn == 1 then na else if daysok and revdaycnt == 6 and (bars == bars.last or bars == bars.both) and lastBarOfDay then low else d6lastlo[1];

addlabel(show_labels, " " , color.black);
addlabel(show_labels and (!isnan(d6firsthi) or !isnan(d6lasthi)), "D6", color.white);
addlabel(show_labels and !isnan(d6firsthi), "F hi " + d6firsthi , GlobalColor("first"));
addlabel(show_labels and !isnan(d6firstlo), "F lo " + d6firstlo , GlobalColor("first"));
addlabel(show_labels and !isnan(d6lasthi), "L hi " + d6lasthi , GlobalColor("last"));
addlabel(show_labels and !isnan(d6lastlo), "L lo " + d6lastlo , GlobalColor("last"));

#----------------------------
# rev day 5
def d5firsthi = if bn == 1 then na else if daysok and revdaycnt == 5 and (bars == bars.First or bars == bars.both) and firstBarOfDay then high else d5firsthi[1];
def d5firstlo = if bn == 1 then na else if daysok and revdaycnt == 5 and (bars == bars.First or bars == bars.both) and firstBarOfDay then low else d5firstlo[1];
def d5lasthi = if bn == 1 then na else if daysok and revdaycnt == 5 and (bars == bars.last or bars == bars.both) and lastBarOfDay then high else d5lasthi[1];
def d5lastlo = if bn == 1 then na else if daysok and revdaycnt == 5 and (bars == bars.last or bars == bars.both) and lastBarOfDay then low else d5lastlo[1];

addlabel(show_labels, " " , color.black);
addlabel(show_labels and (!isnan(d5firsthi) or !isnan(d5lasthi)), "D5", color.white);
addlabel(show_labels and !isnan(d5firsthi), "F hi " + d5firsthi , GlobalColor("first"));
addlabel(show_labels and !isnan(d5firstlo), "F lo " + d5firstlo , GlobalColor("first"));
addlabel(show_labels and !isnan(d5lasthi), "L hi " + d5lasthi , GlobalColor("last"));
addlabel(show_labels and !isnan(d5lastlo), "L lo " + d5lastlo , GlobalColor("last"));

#----------------------------
# rev day 4
def d4firsthi = if bn == 1 then na else if daysok and revdaycnt == 4 and (bars == bars.First or bars == bars.both) and firstBarOfDay then high else d4firsthi[1];
def d4firstlo = if bn == 1 then na else if daysok and revdaycnt == 4 and (bars == bars.First or bars == bars.both) and firstBarOfDay then low else d4firstlo[1];
def d4lasthi = if bn == 1 then na else if daysok and revdaycnt == 4 and (bars == bars.last or bars == bars.both) and lastBarOfDay then high else d4lasthi[1];
def d4lastlo = if bn == 1 then na else if daysok and revdaycnt == 4 and (bars == bars.last or bars == bars.both) and lastBarOfDay then low else d4lastlo[1];

addlabel(show_labels, " " , color.black);
addlabel(show_labels and (!isnan(d4firsthi) or !isnan(d4lasthi)), "D4", color.white);
addlabel(show_labels and !isnan(d4firsthi), "F hi " + d4firsthi , GlobalColor("first"));
addlabel(show_labels and !isnan(d4firstlo), "F lo " + d4firstlo , GlobalColor("first"));
addlabel(show_labels and !isnan(d4lasthi), "L hi " + d4lasthi , GlobalColor("last"));
addlabel(show_labels and !isnan(d4lastlo), "L lo " + d4lastlo , GlobalColor("last"));

#----------------------------
# rev day 3
def d3firsthi = if bn == 1 then na else if daysok and revdaycnt == 3 and (bars == bars.First or bars == bars.both) and firstBarOfDay then high else d3firsthi[1];
def d3firstlo = if bn == 1 then na else if daysok and revdaycnt == 3 and (bars == bars.First or bars == bars.both) and firstBarOfDay then low else d3firstlo[1];
def d3lasthi = if bn == 1 then na else if daysok and revdaycnt == 3 and (bars == bars.last or bars == bars.both) and lastBarOfDay then high else d3lasthi[1];
def d3lastlo = if bn == 1 then na else if daysok and revdaycnt == 3 and (bars == bars.last or bars == bars.both) and lastBarOfDay then low else d3lastlo[1];

addlabel(show_labels, " " , color.black);
addlabel(show_labels and (!isnan(d3firsthi) or !isnan(d3lasthi)), "D3", color.white);
addlabel(show_labels and !isnan(d3firsthi), "F hi " + d3firsthi , GlobalColor("first"));
addlabel(show_labels and !isnan(d3firstlo), "F lo " + d3firstlo , GlobalColor("first"));
addlabel(show_labels and !isnan(d3lasthi), "L hi " + d3lasthi , GlobalColor("last"));
addlabel(show_labels and !isnan(d3lastlo), "L lo " + d3lastlo , GlobalColor("last"));

#----------------------------
# rev day 2
def d2firsthi = if bn == 1 then na else if daysok and revdaycnt == 2 and (bars == bars.First or bars == bars.both) and firstBarOfDay then high else d2firsthi[1];
def d2firstlo = if bn == 1 then na else if daysok and revdaycnt == 2 and (bars == bars.First or bars == bars.both) and firstBarOfDay then low else d2firstlo[1];
def d2lasthi = if bn == 1 then na else if daysok and revdaycnt == 2 and (bars == bars.last or bars == bars.both) and lastBarOfDay then high else d2lasthi[1];
def d2lastlo = if bn == 1 then na else if daysok and revdaycnt == 2 and (bars == bars.last or bars == bars.both) and lastBarOfDay then low else d2lastlo[1];

addlabel(show_labels, " " , color.black);
addlabel(show_labels and (!isnan(d2firsthi) or !isnan(d2lasthi)), "D2", color.white);
addlabel(show_labels and !isnan(d2firsthi), "F hi " + d2firsthi , GlobalColor("first"));
addlabel(show_labels and !isnan(d2firstlo), "F lo " + d2firstlo , GlobalColor("first"));
addlabel(show_labels and !isnan(d2lasthi), "L hi " + d2lasthi , GlobalColor("last"));
addlabel(show_labels and !isnan(d2lastlo), "L lo " + d2lastlo , GlobalColor("last"));

#----------------------------
# current day , rev=1
def d1firsthi = if bn == 1 then na else if daysok and revdaycnt == 1 and (bars == bars.First or bars == bars.both) and firstBarOfDay then high else d1firsthi[1];
def d1firstlo = if bn == 1 then na else if daysok and revdaycnt == 1 and (bars == bars.First or bars == bars.both) and firstBarOfDay then low else d1firstlo[1];
def d1lasthi = if bn == 1 then na else if daysok and revdaycnt == 1 and (bars == bars.last or bars == bars.both) and lastBarOfDay then high else d1lasthi[1];
def d1lastlo = if bn == 1 then na else if daysok and revdaycnt == 1 and (bars == bars.last or bars == bars.both) and lastBarOfDay then low else d1lastlo[1];

addlabel(show_labels, " " , color.black);
addlabel(show_labels and (!isnan(d1firsthi) or !isnan(d1lasthi)), "D1", color.white);
addlabel(show_labels and !isnan(d1firsthi), "F hi " + d1firsthi , GlobalColor("first"));
addlabel(show_labels and !isnan(d1firstlo), "F lo " + d1firstlo , GlobalColor("first"));
addlabel(show_labels and !isnan(d1lasthi), "L hi " + d1lasthi , GlobalColor("last"));
addlabel(show_labels and !isnan(d1lastlo), "L lo " + d1lastlo , GlobalColor("last"));


#----------------------------------

AddLabel(daystoomany, "you picked " + days_back + " days back, but ONLY " + maxdays + " DAYS ON CHART. pick less days for 'days_back' or change the chart", Color.CYAN);


input test_day_cnt = no;
AddChartBubble(test_day_cnt, low,
newday + " new\n" +
daycnt + " cnt\n" +
revdaycnt + " rev\n" +
maxdays + " max\n"
, (if daysok then Color.YELLOW else color.gray), no);


input test_bars_hilo = no;
addchartbubble(test_bars_hilo and (firstBarOfDay or lastBarOfDay),
(if firstBarOfDay then high else low),
"D" + revdaycnt + "\n" +
high + "\n" +
low
,(if !daysok then color.gray else if firstBarOfDay then color.green else color.cyan)
,(if firstBarOfDay then yes else no));



input test_signals = no;
plot p1 = if test_signals then isRollover else nan;
plot p2 = if test_signals then beforeStart else nan;
plot p3 = if test_signals then afterEnd else nan;
plot p4 = if test_signals then firstBarOfDay else nan;
plot p5 = if test_signals then lastBarOfDay else nan;

p1.SetDefaultColor(GetColor(1));
p2.SetDefaultColor(GetColor(2));
p3.SetDefaultColor(GetColor(3));
p4.SetDefaultColor(GetColor(4));
p5.SetDefaultColor(GetColor(5));

AddLabel(test_signals, "isRollOver", GetColor(1));
AddLabel(test_signals, "beforeStart", GetColor(2));
AddLabel(test_signals, "afterEnd", GetColor(3));
AddLabel(test_signals, "firstBarOfDay", GetColor(4));
AddLabel(test_signals, "lastBarOfDay", GetColor(5));

#


show labels with high low, from first and last bar of day, for the last 3 days
has test bubbles on
test_bars_hilo = yes
OF75z4e.jpg



error messages if wrong quantity of days is entered
q2kMw7J.jpg
 
Last edited:
How to find the first "First Bar of Day"? I can get it by using barNumber() if there are no extended hours. But I want to keep the Extended Hours enabled.
 
How to find the first "First Bar of Day"? I can get it by using barNumber() if there are no extended hours. But I want to keep the Extended Hours enabled.

The barnumbers for first and last are added in the below snippet from the above script

The image shows the same code in both with the upper including extended hours and the lower does not

Screenshot 2023-11-10 083456.png
Code:
 labels_firstlastbar_xdays_00d

# https://usethinkscript.com/threads/previous-day-5-days-last-hourly-candle-high-and-low-with-labels.15416/
#previous day / 5 days last hourly candle high and low with labels?

#This indicator of @korygill's is pretty cool.
#https://usethinkscript.com/threads/finding-the-first-and-last-bar-of-the-day-in-thinkorswim.526/

#-------------------------------


def na = double.nan;
def bn = barnumber();

input days_back = 5;
input bars = { First , default Last , both };
input show_labels = yes;


def lookbackdays = if days_back < 1 then 1
 else if days_back > 8 then 8
 else days_back;

addlabel( (days_back < 1 or days_back > 8), " wrong value for 'days_back'. needs to be between  1 and 8", color.cyan);

DefineGlobalColor("first", color.green);
DefineGlobalColor("last", color.cyan);
# GlobalColor("first");
# GlobalColor("last");

#DefineGlobalColor("Gray", CreateColor(28, 28, 28));  #Gray



#-------------------------------
# https://usethinkscript.com/threads/finding-the-first-and-last-bar-of-the-day-in-thinkorswim.526/
# GetDayValues
# Author: Kory Gill, @korygill
# VERSION HISTORY (sortable date and time (your local time is fine), and your initials
# 20190823-1400-KG    - Created.

declare hide_on_daily;
#declare once_per_bar;

# input onUpper = yes;
def nan = Double.NaN;
def isRollover = GetYYYYMMDD() != GetYYYYMMDD()[1];
def beforeStart = GetTime() < RegularTradingStart(GetYYYYMMDD());
def afterEnd = GetTime() > RegularTradingEnd(GetYYYYMMDD());
def firstBarOfDay = if (beforeStart[1] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;
def lastBarOfDay = if (afterEnd[-1] == 1 and afterEnd == 0) or (isRollover[-1] and firstBarOfDay[-1]) then 1 else 0;
def firstBarOfDayBN = if (beforeStart[1] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then bn else double.nan;
def lastBarOfDayBN = if (afterEnd[-1] == 1 and afterEnd == 0) or (isRollover[-1] and firstBarOfDay[-1]) then bn else double.nan;

# Identify first bar of day and last bar of day on chart
input bubbles_first_and_last = yes;

AddChartBubble(
   bubbles_first_and_last and firstBarOfDay,
   close,
   "First Bar of Day " + firstbarOfDayBN ,
   Color.GREEN,
   yes);

AddChartBubble(
   bubbles_first_and_last and lastBarOfDay,
   close,
   "Last Bar of Day " + lastBarOfDayBN,
   Color.GREEN,
   no);
 
Last edited:

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
561 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