Finding the First and Last Bar of the day in ThinkorSwim

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

Hi All,
Can you please share the code to fetch value of the 2nd candle after open it may be 10 min or 30min.
Looking for the current day 2nd candle values.

Thanks in advance.
SV
 
Hi All,
Can you please share the code to fetch value of the 2nd candle after open it may be 10 min or 30min.
Looking for the current day 2nd candle values.

Thanks in advance.
SV

Code:
### Grabs Value of 2nd Volume Bar of the current INTRADAY as a Label
### Only works on Intraday timeframe
def Bar2 = GetDay() <> GetDay()[2] ;
def Bar2Volume = if (Bar2) then volume else Bar2Volume[1];

AddLabel(yes,  " Intraday Volume Bar Two: " + bar2volume , Color.yellow);
 
I am trying to get a better understanding of how the GetYYYYMMDD() function works (or possibly how it is calculated), if I put in the code (example #1) then I get an error stating “the from date needs to be before the to date“. However if I put in the code (example 2) I get an accurate count of trading days. Examples one and two are identical only the input “Start” number is from one year prior. I feel like the code is possibly doing exactly what it should, but that I am not wrapping my head around this properly.
Thank you in advance for any help.

Code:
#example #1
input Start = 20210301;
def day = GetYYYYMMDD();
AddLabel(1, “Trading Days counter = “ + CountTradingDays(Start, day), color.LIGHT_GREEN);

#example #2
input Start = 2020201;
def day = GetYYYYMMDD();
AddLabel(1, “Trading Days counter = “ + CountTradingDays(Start, day), color.LIGHT_GREEN);

Or this could possibly be a CountTradingDays issue I suppose? I’m not 100% sure where my issue is or how to diagnose it. Very glad I found this forum, everyone here has been super helpful.
 
Last edited:
I am trying to get a better understanding of how the GetYYYYMMDD() function works (or possibly how it is calculated), if I put in the code (example #1) then I get an error stating “the from date needs to be before the to date“. However if I put in the code (example 2) I get an accurate count of trading days. Examples one and two are identical only the input “Start” number is from one year prior. I feel like the code is possibly doing exactly what it should, but that I am not wrapping my head around this properly.
Thank you in advance for any help.

Code:
#example #1
input Start = 20210301;
def day = GetYYYYMMDD();
AddLabel(1, “Trading Days counter = “ + CountTradingDays(Start, day), color.LIGHT_GREEN);

#example #2
input Start = 2020201;
def day = GetYYYYMMDD();
AddLabel(1, “Trading Days counter = “ + CountTradingDays(Start, day), color.LIGHT_GREEN);

Or this could possibly be a CountTradingDays issue I suppose? I’m not 100% sure where my issue is or how to diagnose it. Very glad I found this forum, everyone here has been super helpful.

Frank, see if this helps.
Code:
#Example_CountTradingDaysWorkaround
#Sleepyz
#CountTradingDays() has always had unexplained problems with the 'TO' date. This workaround by identifying the last bar on the chart and then defining the date, seems to workaround this problem.

input StartBarDate = 20210301;

def lastGetYYYYMMDD = HighestAll(if !IsNaN(close) and IsNaN(close[-1]) then GetYYYYMMDD() else Double.NaN);

AddLabel(yes, CountTradingDays(StartBarDate, lastGetYYYYMMDD) + " Trading days from " + " " + AsPrice(StartBarDate), Color.LIGHT_GRAY);
 
Sweet it works!!! Thanks so much for taking the time to help me out. I’ve been racking my brain for like a week now 😊
Spent a few nights trying to figure out how to rework all the equations backwards... of course in my mind I’m assuming that GetYYYYMMDD() is calculated like (GetYear()*10000)+(GetMonth()*100)+(GetDayOfMonth())== GetYYYYMMDD() and so I tried calculating it upside down & backwards with no luck. Lol, thanks again!!!
 
I'm trying to get the close of the very first candle of the entire chart I have loaded in TOS. I've seen studies to find the first candle of the day:

Code:
def FirstBar = if SecondsFromTime(0930) == 0 and
                
SecondsTillTime(0930) == 0
               then get barNumber()
               else FirstBar[1];


but can't figure out how to get data on the first candle of the chart. Any ideas?
 
I'm trying to get the close of the very first candle of the entire chart I have loaded in TOS. I've seen studies to find the first candle of the day:

Code:
def FirstBar = if SecondsFromTime(0930) == 0 and
               
SecondsTillTime(0930) == 0
               then get barNumber()
               else FirstBar[1];


but can't figure out how to get data on the first candle of the chart. Any ideas?

@temtam Try the following code and see if it is what you are looking for...

Ruby:
# FirstChartBarClose
#  Created by rad14733 for usethinkscript.com
#
def firstClose = Round(First(close(GetSymbol())), 2);
AddLabel(1, "First Candle Close For " + GetSymbol() + " = " + firstClose, Color.WHITE);
 
@temtam Try the following code and see if it is what you are looking for...

Ruby:
# FirstChartBarClose
#  Created by rad14733 for usethinkscript.com
#
def firstClose = Round(First(close(GetSymbol())), 2);
AddLabel(1, "First Candle Close For " + GetSymbol() + " = " + firstClose, Color.WHITE);
@tomsk @XeoNoX @rad14733
For a GetValues study I thought it would actually get the values. lol
Is there a simple way to get the values of the First bar of the day? ie the price of the Open Close High and Low?
I'm trying to make a label (addlabel) calculating the average High-Low of the last 10 First bars of the Day.
 
@tomsk @XeoNoX @rad14733
Okay i have this so far.. in addition to @korygill first post.

def FBHigh = if FBHigh[1] == 0 or firstbarofday[1] == 0 AND firstbarofday == 1 then high else FBHigh[1];
Rec FBLow = if FBLow[1] == 0 or firstbarofday[1] == 0 AND firstbarofday == 1 then low else FBLow[1];
Def MOWidth = FBHigh - FBLow;
AddLabel (yes, "AvgOR: " + round(mowidth,2), color.yellow);

This only gets me the High - Low of the latest FirstBarofday.
How would I get the average of the previous 10 firstbarofday bars?
note: i will only be using this script on the 2D 5minute chart to compare the average high-low for the first 5 minutes of today
and use this number to compare to previous 10 Days opening 5 minutes.
so if there is a more efficient approach to rewrite the whole script i'm all ears

edit: whole code for those curious
Code:
declare hide_on_daily;
declare once_per_bar;
def isRollover = GetYYYYMMDD() != GetYYYYMMDD()[1];
def beforeStart = GetTime() < RegularTradingStart(GetYYYYMMDD());

def firstBarOfDay = if (beforeStart[1] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;

Rec MOHigh = if MOHigh[1] == 0 or firstbarofday[1] == 0 AND firstbarofday == 1 then high else MOHigh[1];
Rec MOLow = if MOLow[1] == 0 or firstbarofday[1] == 0 AND firstbarofday == 1 then low else MOLow[1];

Def MOWidth = MOHigh - MOLow;
AddLabel (yes, "AvgOR: " + round(mowidth,2), color.yellow);


AddChartBubble(
    firstBarOfDay ,
    close,
    "Fb",
    Color.white,
    yes);
 
Last edited:
@TraderKevin as requested here is your scan with label rounded to the nearest whole number from the tenths of a decimal.
Plots as a label the value of the average of the first 6 volume bars of each new daily REGULAR HOUR trading session. Can use on any time frame under a day. Set your timeframe to 5 min chart and it will adjust for 5 mins.

Code:
##Thinkscript by XeoNoX via https://usethinkscript.com/
#Plots as a label the value of the average of the first 6 volume bars of each new daily REGULAR HOUR trading session.

def isRollover = GetYYYYMMDD() != GetYYYYMMDD()[1];

def beforeStart = GetTime() < RegularTradingStart(GetYYYYMMDD());

def afterEnd = GetTime() > RegularTradingEnd(GetYYYYMMDD());

####DEFINES FIRST 6 BARS OF REGULAR SESSION
def firstBar1 = if (beforeStart[1] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;
def firstBar2 = if (beforeStart[2] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;
def firstBar3 = if (beforeStart[3] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;
def firstBar4 = if (beforeStart[4] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;
def firstBar5 = if (beforeStart[5] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;
def firstBar6 = if (beforeStart[6] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;

##RECORDS AND GRABS VALUE OF THE REFERENCED VOLUME BAR
rec firstBarVolume = if firstBar1 then volume else firstBarVolume[1];
rec firstBarVolume2 = if firstBar2 then volume else firstBarVolume2[1];
rec firstBarVolume3 = if firstBar3 then volume else firstBarVolume3[1];
rec firstBarVolume4 = if firstBar4 then volume else firstBarVolume4[1];
rec firstBarVolume5 = if firstBar5 then volume else firstBarVolume5[1];
rec firstBarVolume6 = if firstBar6 then volume else firstBarVolume6[1];

### SUMS UP ALL 6 BARS and then AVERAGES THEM BY DIVIDING BY 6
def scan = (firstbarvolume + firstbarvolume2 +firstbarvolume3 + firstbarvolume4 + firstbarvolume5 + firstbarvolume6) / 6;

##PLOTS THE BARS THAT ARE BEING COUNTED
plot barcount = firstbarvolume6;

#LABEL OF Scan Rounded to the nearest Decimal.
AddLabel(yes, " Avg of First 6 vol bars: " + Round(scan,0), Color.yellow);


KKi0xVq.png

I know I'm really late for this conversation. lol... However is there a way to get this exact script to work for the previous trading day? In other words, get the previous days first 6 hourly trading bars?
 
One would think finding the first and last bar of the day in thinkscript would be easy.

I struggled to identify the first and last bars WITH extended session on and extended session off in the same study. I wrote this study, GetDayValues, to help me debug how to identify these so I could track PreviousClose and DayOpen bars in Magic Fibonacci 1.272 Indicator for ThinkorSwim v2.

I ran into issues around GetTime(), RegularTradingStart(), and RegularTradingEnd() and sometimes thinkscript would go a little bonkers and break my study if I wrote code in a certain way, which seemed valid at the time.

Sidebar: I will submit a feature request to the thinkscript to add a few built-in boolean values like IsFirstRegularBar, IsLastRegularBar, IsFirstExtendedBar, IsLastExtendedBar, IsRegularSession, IsExtendedSession, etc.

So what did I finally use to determine this?

Image of the GetDayValues study in action

cjpjDFv.png


Discussion of the chart and numbed highlights

(1) Notice the cursor is on the first bar of the day
(2) Notice the colors of the labels and how they match the indicators in the lower studies
(3) Notice the values of the labels that are applicable on the highlighted first bar of the day
(4) Notice how the indicators differ on extended and non-extended charts

Once I plotted these values (some by trial and error), I was able to finally define FirstBarOfDay and LastBarOfDay and subsequently use those to track other values like previous close, opening bar, and for other studies like Opening Range, and others, these calculations could be very useful.

The secret sauce is in the following logic in the code:
Code:
#

# logic

#

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;

Once you see it, maybe it makes perfect sense. As previously discussed, it may not be that obvious to others, and was not obvious to me. I used things like GetDate() != GetDate()[1] and other things that hard-coded start of trading to 9:30 or 6:30 which varies based on your timezone.

So I am now hopeful that this pattern for finding first/last bars can be used as the de-facto standard for how to do this. If there is a better way that you know of, please feel free to share. I could not find one with a quick search of the internet, thinkscript docs, etc.

Link to GetDayValues Flex Grid

https://tos.mx/EXWUIK

Source Code for GetDayValues

Code:
# 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;

#
# logic
#
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
#
AddChartBubble(
    firstBarOfDay and onUpper,
    close,
    "First Bar of Day",
    Color.GREEN,
    yes);

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

#
# plots
#
plot p1 = if !onUpper then isRollover else nan;
plot p2 = if !onUpper then beforeStart else nan;
plot p3 = if !onUpper then afterEnd else nan;
plot p4 = if !onUpper then firstBarOfDay else nan;
plot p5 = if !onUpper 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(!onUpper, "isRollOver", GetColor(1));
AddLabel(!onUpper, "beforeStart", GetColor(2));
AddLabel(!onUpper, "afterEnd", GetColor(3));
AddLabel(!onUpper, "firstBarOfDay", GetColor(4));
AddLabel(!onUpper, "lastBarOfDay", GetColor(5));

Disclaimer and Notices

You are free to use this code for personal use, and make derivative works from it. You are also GRANTED permission to use this code (or derivative works) for commercial purposes which includes and is not limited to selling, reselling, or packaging with other commercial indicators. Headers and attribution in this code should remain as provided, and any derivative works should extend the existing headers.
anyway can plot a line at the Last bar of day??
 
anyway this can be plotted as a chart label rather than a chart bubble? that way its out of the way? any assistance would be greatly appreciated
 
anyway this can be plotted as a chart label rather than a chart bubble? that way its out of the way? any assistance would be greatly appreciated

If you are wanting to move the bubbles more out of range, similar to label placement, then this workaround may help.

The following script will appear in as a lower pane indicator. Move it to the upper pane. At the input screen, uncheck left axis. You can choose to have the bubbles display near the top or bottom at the input showbubble.

Also, the lines that the bubbles can display on are defaulted to the color black. You can change that to something closer to your chart's background color if you like.

Capture.jpg
Ruby:
declare lower;

input showbubble = {default top, bottom};

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;

plot x = 100;
plot y = 0;
x.SetDefaultColor(Color.BLACK);
y.SetDefaultColor(Color.BLACK);

AddChartBubble(
    firstBarOfDay ,
    if showbubble == showbubble.top then x else y,
    "F",
    Color.WHITE,
    yes);
AddChartBubble(
    lastBarOfDay ,
    if showbubble == showbubble.top then x else y,
    "L",
    Color.WHITE,
    yes);
 
If you are wanting to move the bubbles more out of range, similar to label placement, then this workaround may help.

The following script will appear in as a lower pane indicator. Move it to the upper pane. At the input screen, uncheck left axis. You can choose to have the bubbles display near the top or bottom at the input showbubble.

Also, the lines that the bubbles can display on are defaulted to the color black. You can change that to something closer to your chart's background color if you like.
i guess i meant more as a ADDLABEL option,,,no chart bubbles on the chart just a dynamic label on upper left corner,,,
 
i guess i meant more as a ADDLABEL option,,,no chart bubbles on the chart just a dynamic label on upper left corner,,,

I was unsure what you would havew the ADDLABEL to display in it. All I saw was some form of First and Last text labels. Please explain and someone may be able to help.
 
I was unsure what you would havew the ADDLABEL to display in it. All I saw was some form of First and Last text labels. Please explain and someone may be able to help.
was just looking for something like how this chart has this Purple Labels On this chart,,, or would this just be the "Close" that tos already shows by default,,, am fairly new
 
I was unsure what you would havew the ADDLABEL to display in it. All I saw was some form of First and Last text labels. Please explain and someone may be able to help.
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
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
343 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