Last Day of Month

Discussions about the testing and simulation of mechanical trading systems using historical data and other methods. Trading Blox Customers should post Trading Blox specific questions in the Customer Support forum.
Post Reply
Chris67
Roundtable Knight
Roundtable Knight
Posts: 1052
Joined: Tue Dec 16, 2003 2:12 pm
Location: London

Last Day of Month

Post by Chris67 » Wed Jun 19, 2019 11:12 am

Be extremely grateful if anyone could assist ?

Simple query - did my usual - spend hours on forum looking for answer but didnt "really " get what i needed

I want to exit on close on last day of month
obviously lastdayofmonth isnt recognised unless 1- i guess ? thats what ive sort of picked up ?
is it possible to do a market on close for last day of month and if so what is the line of cose - the response i got when using 1 - was out of data so i guess it was the right line of code but needed verification to ignore the last trade in the test or something like that ?

anyway hello and goodbye to all
cc

Roger Rines
Roundtable Knight
Roundtable Knight
Posts: 2000
Joined: Wed Oct 06, 2004 10:52 am
Location: San Marcos, CA

Re: Last Day of Month

Post by Roger Rines » Wed Jun 19, 2019 1:34 pm

Chris67 wrote:
Wed Jun 19, 2019 11:12 am
[SNIP]
I want to exit on close on last day of month
obviously lastdayofmonth isnt recognised unless 1- i guess ? thats what ive sort of picked up ?

is it possible to do a market on close for last day of month and if so what is the line of cose - the response i got when using 1 - was out of data so i guess it was the right line of code but needed verification to ignore the last trade in the test or something like that ?
[SNIP]
Knowing when to time the exit requires knowledge of when the last tradeday of the month the contract is in will appear.

Coding a custom script section to find that day someplace before the day before the last day arrives will allow you to generate an exit for the last day. In real trading, it is usually best to get out of or roll into the next contract at least by the close of the day before the last trade day.

Attached to this post is a group of functions that I've used for many years with TB when I've wanted to do what you are thinking. They are also capable of doing a lot more than what you asked, but as a learning exercise, consider roaming through the functions to see what is possible. Also, write simple test code outside of the system process so you will be able to learn how the functions work and how those that are called within some of the function respond and work. In simple terms, get comfortable with the functions before you depend upon them.

When you are reviewing the code, notice that some functions will call other function in the list attached, so those need to be included in the blox as well. In my use of these, all of them are in the same blox that is added to the system blox list so they can be called from the script in the system blox where you will need to know when you need to do something.

All of the items in the attached file are custom scripts. Only the individual functions, without the items I sprinkled in between the various date functions, need to be copied and used. If you try to paste everything, the Blox Basic Parser will flag the junk until those parser flagged items are REMd-OUT.

For information about Custom Functions, look in the Builder's Help File.
DateFunctions_v4_01.00.inc.zip
TB Custom Date Functions - TB-v4
(5.2 KiB) Downloaded 8 times
Good luck!
Roger...

Chris67
Roundtable Knight
Roundtable Knight
Posts: 1052
Joined: Tue Dec 16, 2003 2:12 pm
Location: London

Re: Last Day of Month

Post by Chris67 » Thu Jun 20, 2019 12:19 am

Extremely kind of you to reply and extremely useful information for which I am very grateful - thank you !
p.s hope you are well !!
15 years since started using TB now - doesn't seem real - i think I've spent more time with TB in 15 years than my partner ... it should come with a warning :)
best
c

Tim Arnold
Site Admin
Site Admin
Posts: 8753
Joined: Tue Apr 06, 2004 1:41 pm
Location: Boston, MA
Contact:

Re: Last Day of Month

Post by Tim Arnold » Thu Jun 20, 2019 4:57 pm

For backtesting, just check the MONTH(test.currentDate) vs. the MONTH(instrument.date). If these are different, then the instrument date is the last day of the month, and you can place orders to exit. However the exit will be on the first day of the new month.

To exit ON the last day of the month, you need to place that order 2 days before the end of the month. This can also be done in backtesting, using the negative index (future looking) property on the date.

Code: Select all

IF Month(instrument.date[-2]) <> Month(instrument.date[-1]) THEN
 Broker.ExitAllUnitsOnClose
ENDIF
For live orders, you would need to have a parameter to let the system know that it is the last day of the month and exit.

Roger Rines
Roundtable Knight
Roundtable Knight
Posts: 2000
Joined: Wed Oct 06, 2004 10:52 am
Location: San Marcos, CA

Re: Last Day of Month

Post by Roger Rines » Thu Jun 20, 2019 5:18 pm

Thanks for the kind words.

There are many functions in the attached ".inc" file. ".inc" is a file suffix that identifies an included file. In this case, that suffix designator is used as a matter of habit from many decades of programming.

While the ".inc" is not common, it is only a text file. Renaming the file to use a ".txt" suffix will enable it to be opened by any text editor.

Functions in the file are the logic process required to deliver the feature each function name mentions.

For example, the function: DayOfWeekJulian
Implies it will return the "Day of Week" number (0 to 6) from a TB-Julian-Date number.

Code: Select all

  
   '  ==============================================================
   '   SCRIPT NAME:     DayOfWeekJulian
   '   BLOX TYPE:       Script FUNCTION 
   '   CODE VERSION:    1.0    
   '   CREATION DATE:   20080727
   '   LAST UPDATE:     20080820
   '   TRADING BLOX:    2.3.b7 or later
   '   PROGRAMMER:      Roger Rines
   '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   '   DESCRIPTION:  This function returns the Day of Week Number 
   '                 from Julian Date Number it gets.
   '                 Sunday = 0 to Saturday = 6   
   '   USE: When the Date is a Julian Number and the Day of the Week
   '	      value is needed.
   '
   '   CODE FUNCTION CALL:
   '     Function_Result = Script.Execute( "DayOfWeekJulian", JulianNumber )
   '        OR
   '     PRINT Script.Execute( "DayOfWeekJulian", JulianNumber )
   '  --------------------------------------------------------------
   '  DayOfWeekJulian - FUNCTION START
   '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   '  Function Parameter Variables
   VARIABLES: JulianNumber_DoWJ        Type: Integer
   '  Function Working Variables
   VARIABLES: DayNum_DoWJ              Type: Integer
   '  --------------------------------------------------------------
   '  Assign ParameterList Items to Parameter Variables
   JulianNumber_DoWJ = script.parameterList[1]  '  INTEGER
   '  --------------------------------------------------------------
   '  Ensure There is Correct Calling Information
   If JulianNumber_DoWJ < 1 THEN 
      '  EXIT FUNCTION
      DayNum_DoWJ = -1   '  Report Error
   ELSE
      '  Calculate Day Of Week Value    
      DayNum_DoWJ = JulianNumber_DoWJ  MOD 7 
   ENDIF '  JulianNumber_DoWJ = 0
   '  --------------------------------------------------------------
   '  Return Function Value
   script.SetReturnValue( DayNum_DoWJ )
   '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   '  DayOfWeekJulian - FUNCTION END
   '  ============================================================== /[CODE]
   To use this ability, the code shown here is all that is required to be pasted into a system block, or a Date-Function Blox you create.
   
   To use this function, this execute statement is all that needs to be entered:
   PRINT Script.Execute( "DayOfWeekJulian", JulianNumber )  ' JulianNumber would be an integer that contains a date value as a Julian Number.
   
For this function:  GetMonthLastTradeDate
This function will return the "LastTradeDate" in the month value contained in the "iYMDDate" integer value.

[CODE]
   '  ==============================================================
   '   SCRIPT NAME:     GetMonthLastTradeDate
   '   BLOX TYPE:       Script FUNCTION
   '   CODE VERSION:    1.0    
   '   CREATION DATE:   20140122
   '   LAST UPDATE:     20140122
   '   TRADING BLOX:    4.3
   '   PROGRAMMER:      Roger Rines
   '  --------------------------------------------------------------
   '   DESCRIPTION:  Function Get Month's Last Trade-Date
   '   USE: Date validity test.
   '   CODE FUNCTION CALL:
   '     Function_Result = script.Execute("GetMonthLastTradeDate", _
   '                                         iYMDDate)
   '        OR
   '     PRINT script.Execute("GetMonthLastTradeDate", iYMDDate)
   '  --------------------------------------------------------------
   '  GetMonthLastTradeDate FUNCTION - START
   '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   '  Function Parameter Variables
   VARIABLES: iDate_GNT, iYr_GNT, iMth_GNT, iDay_GNT  Type: Integer
   VARIABLES: iDateOK_GNT, iNextDate_GNT              Type: Integer
   '  --------------------------------------------------------------
   '  Send Parameter to Working variable
   iDate_GNT = script.parameterList[1]  '  INTEGER

   '  Test Date Validity
   iDateOK_GNT = script.Execute("IsValidDate", iDate_GNT)   

   '  Ensure Date is within range
   If iDateOK_GNT THEN
      '  Parse into date components
      iYr_GNT = Year(iDate_GNT)
      iMth_GNT = Month(iDate_GNT)
      iDay_GNT = DayOfMonth(iDate_GNT)

      '  Get parse date items to find last trade date
      iNextDate_GNT = script.Execute( "LastTradeDateOfMonth", _
                                          iYr_GNT, iMth_GNT )
      '  If Month's Last Trade Date 
      If iNextDate_GNT < iDate_GNT THEN
         '  Increment Month Value
         iMth_GNT = iMth_GNT + 1
         
         '  Keep dates real
         If iMth_GNT > 12 THEN
            '  Increment Year
            iYr_GNT = iYr_GNT + 1
            '  Use first month of next year
            iMth_GNT = 1   
            
            '  Get Next Trade Possible End-of-Month Date
            iNextDate_GNT = script.Execute( "LastTradeDateOfMonth", _
                                                iYr_GNT, iMth_GNT )
         ENDIF '  iMth_GNT > 12
      ENDIF '  iNextDate_GNT > iDate_GNT      
   ELSE
      '  Generate Error Date
      iNextDate_GNT = -1
   ENDIF '  iDate_GNT > 19900101 AND iDateOK_GNT
   '  --------------------------------------------------------------
   '  Return Function Value
   script.SetReturnValue( iNextDate_GNT )
   '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   '  GetMonthLastTradeDate FUNCTION - END
   '  ==============================================================
 

To get the LastTradeDate of the month submitted, this statemend shown in the code area above is all that is needed:
PRINT script.Execute("GetMonthLastTradeDate", iYMDDate)

However, this function calls a custom Function named: "IsValidDate"
This function contains the code that uses simple date logic to determine if the submitted date value sent the "GetMonthLastTradeDate " is valid before it attempts to figure out the date of the last trade-date.

When a custom function is called, that means another custom function must be included to make the "GetMonthLastTradeDate " work without creating an error.

===============================================================
To take most of the mystery out of how to use what was sent earlier, a new Zip file is attached and it contains a Suite and a System setup that has two Blox that can be added to a system like what is shown in the example in this available download.

The blox contained in the Suite are:
Date Function Tester.tbx
Date Functions_v4.tbx
Date Test Log Window Results.txt


The first blox exercises the function in the second blox. When the suite is executed using a single data file for the test, the output that is sent to the Log Window is also in the Zip file so you will get a glimpse of what to expect when you run the suite.

This version of the custom date function was updated during the period when Trading Blox v4 was released and active. Today's created Suite was assembled using TBv5 5.3.3.7

I should have sent it this way too begin with, but with time pressure high right now and my assumption everyone is a professional programmer, I only succeeded in proving the fallacy of how assumptions are one our biggest failures.

Good Luck,
Roger...
DateFunction Blox_v4.zip
Date Function Tester Suite w/Blox and Output
(22.21 KiB) Downloaded 2 times

Post Reply