Finding the First and Last Bar of the day in ThinkorSwim

How would I display high, low and 50% of the High and Low as lines of the previous day only to the next day( or today)?
 
How would I display high, low and 50% of the High and Low as lines of the previous day only to the next day( or today)?

This uses the TOS DailyHighLow indicator, with a mid line (50%) added.

The image is shown with showOnlyLastPeriod set to YES

Screenshot 2023-11-20 062558.png
Code:
#
# TD Ameritrade IP Company, Inc. (c) 2011-2023
#

input aggregationPeriod = AggregationPeriod.DAY;
input length = 1;
input displace = -1;
input showOnlyLastPeriod = no;

plot DailyHigh;
plot DailyLow;
if showOnlyLastPeriod and getday() != getlastday() {
#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(4));
DailyHigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
DailyLow.SetDefaultColor(GetColor(4));
DailyLow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

plot Mid = (dailyhigh + dailylow) / 2;
mid.setpaintingStrategy(paintingStrategy.HORIZONTAL);
 
This uses the TOS DailyHighLow indicator, with a mid line (50%) added.

The image is shown with showOnlyLastPeriod set to YES
Thank you;) but for some reason is not showing me the correct High and Love Globex ?
 

Attachments

  • High and Low.jpg
    High and Low.jpg
    574.8 KB · Views: 60
Last edited:
Thank you;) but for some reason is not showing me the correct High and Love Globex ?
I does not show correct high and low for me either

The above code used what TOS defines as a "DAY", which is just Regular Trading Hours.

So I have modified an auto fib study I did to include post/pre/rth times for each time range.

It has an option to display the last x times and more fib levels than you requested.

The image shows the current developing ranges levels only selected

Screenshot 2023-11-24 065034.jpg
Code:
#Auto_Fib_Input_Time_Range_Developing
input start             = 1800;
input end               = 1600;

input ShowLast_x_ranges = No;
input X_ranges     = 1;

def ymd = GetYYYYMMDD();
def na  = Double.NaN;
def bn  = BarNumber();

def sec1 = SecondsFromTime(start);
def sec2 = SecondsFromTime(end);
def isTime1 = (sec1 >= 0 and sec1[1] < 0) or (sec1 < sec1[1] and sec1 >= 0);
def isTime2 = (sec2 >= 0 and sec2[1] < 0) or (sec2 < sec2[1] and sec2 >= 0) or (if TickValue() <= .01 and (sec2 <= 0) then GetYYYYMMDD() != GetYYYYMMDD()[-1] else 0);
def inRange = CompoundValue(1, if isTime1 then 1 else if isTime2 then 0 else inRange[1], 0);
def lastbn = HighestAll(if IsNaN(close[-1]) then bn else na);

def rhi =  if ymd != ymd[1] then high else if inRange == 1 then Max(high, rhi[1]) else rhi[1];
def rlo =  if ymd != ymd[1] then low else if inRange == 1 then Min(low, rlo[1]) else rlo[1];

def rangecount     = if ymd != ymd[1] then rangecount[1] + 1 else rangecount[1];
def x_breakcount = HighestAll(rangecount) - rangecount + 1;

input showtimerange_label = yes;
AddLabel(showtimerange_label, "HL Time Range: " + AsPrice(start) + " to " + AsPrice(end), Color.YELLOW);

input Fpos236 = .236;
input Fpos382 = .382;
input Fpos50  = .5;
input Fpos618 = .618;
input Fpos764 = .764;

def range  = rhi - rlo;
def F236   = rhi - (range * Fpos236);
def F382   = rhi - (range * Fpos382);
def F50    = rhi - (range * Fpos50);
def F618   = rhi - (range * Fpos618);
def F764   = rhi - (range * Fpos764);

plot ORH;
plot ORL;
plot Fib50;
plot Fib236;
plot Fib382;
plot Fib618;
plot Fib764;
if ShowLast_x_ranges and x_breakcount > X_ranges
then {
    ORH      = Double.NaN;
    ORL      = Double.NaN;
    Fib50    = Double.NaN;
    Fib236   = Double.NaN;
    Fib382   = Double.NaN;
    Fib618   = Double.NaN;
    Fib764   = Double.NaN;

} else {
    ORH      = rhi;
    ORL      = rlo;
    Fib50    = F50;
    Fib236   = F236;
    Fib382   = F382;
    Fib618   = F618;
    Fib764   = F764;

}


ORH.SetDefaultColor(Color.WHITE);
ORH.SetStyle(Curve.LONG_DASH);
ORH.SetLineWeight(2);

ORL.SetDefaultColor(Color.WHITE);
ORL.SetStyle(Curve.LONG_DASH);
ORL.SetLineWeight(2);

Fib50.SetDefaultColor(Color.WHITE);
Fib50.SetStyle(Curve.LONG_DASH);
Fib50.SetLineWeight(1);

Fib236.SetDefaultColor(Color.CYAN);
Fib236.SetStyle(Curve.LONG_DASH);
Fib236.SetLineWeight(1);

Fib382.SetDefaultColor(Color.YELLOW);
Fib382.SetStyle(Curve.LONG_DASH);
Fib382.SetLineWeight(1);

Fib618.SetDefaultColor(Color.YELLOW);
Fib618.SetStyle(Curve.LONG_DASH);
Fib618.SetLineWeight(1);

Fib764.SetDefaultColor(Color.CYAN);
Fib764.SetStyle(Curve.LONG_DASH);
Fib764.SetLineWeight(2);

input showbubbles = yes;

input bubblemover = 1;
def mo  = bubblemover;
def mo1 = mo + 1;


AddChartBubble(showbubbles and ORH[mo1] and IsNaN(ORH[mo]), ORH[mo1], "H", ORH.TakeValueColor());
AddChartBubble(showbubbles and Fib236[mo1] and IsNaN(Fib236[mo]), Fib236[mo1], "23.6", Fib236.TakeValueColor());
AddChartBubble(showbubbles and Fib382[mo1] and IsNaN(Fib382[mo]), Fib382[mo1], "38.2", Fib382.TakeValueColor());
AddChartBubble(showbubbles and Fib50[mo1] and IsNaN(Fib50[mo]), Fib50[mo1], "50", Fib50.TakeValueColor());
AddChartBubble(showbubbles and Fib618[mo1] and IsNaN(Fib618[mo]), Fib618[mo1], "61.8", Fib618.TakeValueColor());
AddChartBubble(showbubbles and Fib764[mo1] and IsNaN(Fib764[mo]), Fib764[mo1], "76.4", Fib764.TakeValueColor());
AddChartBubble(showbubbles and ORL[mo1] and IsNaN(ORL[mo]), ORL[mo1], "L", ORL.TakeValueColor(), no);
 
Last edited by a moderator:
Hi, everybody!
Need some help from the respected community.
I want to make a scanner that selects stocks by comparing the close of the first hourly bar (10:00) with the high or low of the last hourly bar of the previous day. It is not difficult to implement for a chart, but is it possible to implement it in a scanner?
The scanner should work as a dynamic list, i.e. display stocks that meet the criteria after 10:00 NY.
 
Hi, everybody!
Need some help from the respected community.
I want to make a scanner that selects stocks by comparing the close of the first hourly bar (10:00) with the high or low of the last hourly bar of the previous day. It is not difficult to implement for a chart, but is it possible to implement it in a scanner?
The scanner should work as a dynamic list, i.e. display stocks that meet the criteria after 10:00 NY.

This seems to work

Screenshot 2024-01-01 133431.png

Screenshot 2024-01-01 133547.png

Code:
def previousday_last1hrhigh    = if GetYYYYMMDD() != GetYYYYMMDD()[1] then high[1] else previousday_last1hrhigh[1];
def today1000close = if SecondsFromTime(1000) == 0 then close else today1000close[1];
plot scan = today1000close > previousday_last1hrhigh;
 
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

View attachment 5237

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.
Thanks, Is it possible to create one for the first bar and last bar of the week ?
 

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