How to get last trading day of month?

never_noob

New member
I am trying to code up a strategy that breaks the days of the month into trading days (e.g. first trading day is TD1, second is TD2, etc) but I also need to know which day is the last day of the month for strategies that require closing at end of month. For whatever reason, I am finding this impossible to do in ThinkScript; it seems like there is some weird way that TS handles the date math that is not letting me find the last trading day. I can find the current trading day very easy, and my plan for finding the last trading day was to calculate the first day of the following month (e.g. next month is Nov 1, 2022, which is 20221101) and then set a variable "lastday" as true whenever CountTradingDays between the current day and the first day of the next month is 0 (or 1, depending on whether it counts inclusive or not). Before that, I need to get the count of trading days until the first day of the next month. It seems easy enough, but it's not working no matter what I try.

What is bizarre is I can write code to calculate the first day of the next month in YYYYMMDD format. So, for instance, it's easy to get TS to calculate the first day of next month as 20221101. That works fine. If I use CountTradingDays to count the days between today and the calculation to get that number, it doesn't work. But if I hardcode in that number, it works just fine. This makes no sense, as I've printed both the output of the calculation and the number itself to a label and both are identical. I've been banging my head against the wall for hours. Anyone have any ideas?

def currentday = GetYYYYMMDD();
def thismonth = GetMonth();
def nextmonth = if thismonth ==12 then 1 else thismonth+1;
def thisyear = GetYear();

def startofmonth = ((10000 * thisyear) + (100 * thismonth) + 1);
def startnextmonth = ((10000 * thisyear) + (100 * nextmonth) + 1);

def daysleft = CountTradingDays(GetYYYYMMDD(), startnextmonth);

AddLabel (yes, daysleft, color.GREEN);
#Trying to display this ^^^^ as a label just to even test the output of 'daysleft' throws an error!

However, if I use the same line of code, but hardcode in "Startnextmonth", it works perfectly fine and correctly identifies the number of remaining trade days
def daysleft = CountTradingDays(GetYYYYMMDD(), 20221101);
#this works fine!

Then I make a label to test the output of "startnextmonth" using the code from the first block of code, I show that it displays 20221101 just fine - so its the exact same value as the one I'm hardcoding.

I am at a complete loss here.
 
Solution
I am trying to code up a strategy that breaks the days of the month into trading days (e.g. first trading day is TD1, second is TD2, etc) but I also need to know which day is the last day of the month for strategies that require closing at end of month. For whatever reason, I am finding this impossible to do in ThinkScript; it seems like there is some weird way that TS handles the date math that is not letting me find the last trading day. I can find the current trading day very easy, and my plan for finding the last trading day was to calculate the first day of the following month (e.g. next month is Nov 1, 2022, which is 20221101) and then set a variable "lastday" as true whenever CountTradingDays between the current day and...
I am trying to code up a strategy that breaks the days of the month into trading days (e.g. first trading day is TD1, second is TD2, etc) but I also need to know which day is the last day of the month for strategies that require closing at end of month.


this code line is causing errors,
def daysleft2 = CountTradingDays(GetYYYYMMDD(), 20221101);

the first parameter is the start date and should not be greater than the 2nd parameter.
on dates after 20221101, the start date parameter will be greater than the end date.

https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/CountTradingDays


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

here is a different way,

on a daily chart,
..this finds the bar that is the last day of the month.

on an intraday chart, times less than a day,
..this finds the last bar, of the last day of the month.

it uses a month function to read a number for a month.
then compares that number to the value in the next bar, to see when it changes.

GetDayofMonth() isn't needed, i just included it in case you wanted to read the date of last trading day.

Code:
#def mo_day = GetDayofMonth(GetYyyyMmDd());

def mo = GetMonth();

# will be true when the current month value is different than the next value
def mo_last_day = (mo != mo[-1]);

input test1_bubbles = yes;
addchartbubble(test1_bubbles, low,
mo + "\n" +
#mo_day + "\n" +
mo_last_day
, (if mo_last_day then color.yellow else color.gray), (if mo_last_day then 1 else 0));
#
 
I am trying to code up a strategy that breaks the days of the month into trading days (e.g. first trading day is TD1, second is TD2, etc) but I also need to know which day is the last day of the month for strategies that require closing at end of month. For whatever reason, I am finding this impossible to do in ThinkScript; it seems like there is some weird way that TS handles the date math that is not letting me find the last trading day. I can find the current trading day very easy, and my plan for finding the last trading day was to calculate the first day of the following month (e.g. next month is Nov 1, 2022, which is 20221101) and then set a variable "lastday" as true whenever CountTradingDays between the current day and the first day of the next month is 0 (or 1, depending on whether it counts inclusive or not). Before that, I need to get the count of trading days until the first day of the next month. It seems easy enough, but it's not working no matter what I try.

What is bizarre is I can write code to calculate the first day of the next month in YYYYMMDD format. So, for instance, it's easy to get TS to calculate the first day of next month as 20221101. That works fine. If I use CountTradingDays to count the days between today and the calculation to get that number, it doesn't work. But if I hardcode in that number, it works just fine. This makes no sense, as I've printed both the output of the calculation and the number itself to a label and both are identical. I've been banging my head against the wall for hours. Anyone have any ideas?



However, if I use the same line of code, but hardcode in "Startnextmonth", it works perfectly fine and correctly identifies the number of remaining trade days



Then I make a label to test the output of "startnextmonth" using the code from the first block of code, I show that it displays 20221101 just fine - so its the exact same value as the one I'm hardcoding.

I am at a complete loss here.

This seems to work somehow to automatically do what I think you want). Just experimented to find this. You can even find the first trading day of future months input.

Screenshot-2022-10-17-030357.png
Ruby:
input months_in_advance = 1;
plot mo = if !IsNaN(close(period = AggregationPeriod.MONTH)[months_in_advance]) then GetYYYYMMDD() else 0;

AddLabel(1, "First Trading Day of Next (" + months_in_advance + ") Month " + AsPrice(HighestAll(mo)), color.yellow);

def daysleftauto = CountTradingDays(GetYYYYMMDD(), HighestAll(mo));
def daysleftmanual = CountTradingDays(GetYYYYMMDD(), 20221101);
AddLabel(1, "Auto " + daysleftauto + " Manual " + daysleftmanual, Color.WHITE);
 
Solution
this code line is causing errors,
def daysleft2 = CountTradingDays(GetYYYYMMDD(), 20221101);

the first parameter is the start date and should not be greater than the 2nd parameter.
on dates after 20221101, the start date parameter will be greater than the end date.

I actually don't get an error for the manual/hardcode example at all. Keep in mind this was just an example to see what problem I was having.

What is happening is that if I hardcode in that date, it works fine, but if I create code that generates that date (even printing it to a label to double check that it's precisely the correct format) it doesn't work when it's encoded.

I tried to use the code you shared (which I appreciate) but it didn't seem to indicate the trading days remaining in the month.
 
This seems to work somehow to automatically do what I think you want). Just experimented to find this. You can even find the first trading day of future months input.
This code didn't work for me - I just got the gray warning icon at the top left, same as when my own scripts weren't working.
 
This code didn't work for me - I just got the gray warning icon at the top left, same as when my own scripts weren't working.
The code still worked for me even though the warning was there. The warning did not render the result unusable. Are the results in the labels in the image post #3 not what you wanted or you found them usable in your code?
 
Code:
declare lower;
def thismonth = GetMonth();
def nextmonth = if thismonth == 12 then 1 else thismonth+1;
def thisyear = GetYear();
def NextYear = if thismonth == 12 then GetYear() + 1 else GetYear();;
def startofmonth = ((10000 * thisyear) + (100 * thismonth) + 1);
def startnextmonth = ((10000 * nextyear) + (100 * nextmonth) + 1);
def daysleft = CountTradingDays(Min(Startnextmonth,startofmonth), Max(Startnextmonth,startofmonth));
plot TradingDaysInMonth = daysleft;
plot t = 30;
plot b = 1;

edit: didn't read the question, I was just removing the errors.
change/add these lines
def today = getyYYYMMDD();
def daysleft = CountTradingDays(Min(Startnextmonth,today), Max(Startnextmonth,today));
 
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
444 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