Buy and Sell on 1st and Last of Month every year
Author: akar
Creation Date: 10/2/2014 2:08 AM
profile picture

akar

#1
I want to buy on the first of the month and sell on the last day of every year. e.g here is Sep 1 and Sep 30.
The code works if the day is a weekday but fails on Sat and Sun.

What am I doing wrong here ?


CODE:
Please log in to see this code.
profile picture

akar

#2
My bad. I didn't realize that 9/3 is a holiday. The code works fine for 10/1 - 10/31. Now the question is how do I find out if the day is a stock market holiday in US ?
profile picture

Eugene

#3
QUOTE:
Now the question is how do I find out if the day is a stock market holiday in US ?

See QuickRef (F11 key) > MarketInfo Class > Holidays Property.

QUOTE:
I want to buy on the first of the month and sell on the last day of every year.

However, the approach is not robust: hardcoding dates this way is unreliable. Here's how to find out the first day of month...

CODE:
Please log in to see this code.


...and the last day of month (with the help of WealthLab.Rules):

CODE:
Please log in to see this code.


Combining this together, we arrive at the following code:

CODE:
Please log in to see this code.
profile picture

Cone

#4
This is sufficient for the condition, right?

CODE:
Please log in to see this code.


The trick for live trading, however, it to know if tomorrow (next session) is the first session of the month. And in that case you can do this with the help of Community.Components:

CODE:
Please log in to see this code.
profile picture

Eugene

#5
QUOTE:
This is sufficient for the condition, right?

Right. Actually, this is a leftover of my experiments with the code when I tried to figure out why it works on U.S. symbols but fails to exit at the last day of year on any other symbols. The problem turned out to be in the DateOfNextTradingDay function. Give your code a try on any international stock not included in the Market Manager to see.
profile picture

Cone

#6
DateOfNextTradingDay() is for U.S. stocks only. It eliminates Saturdays, Sundays, and any Holidays contained in Markets.xml.
This website uses cookies to improve your experience. We'll assume you're ok with that, but you can opt-out if you wish (Read more).