Include time limit in backtesting strategy?

blindsquirrel

New member
The documentation on time and date functions in thinkscript is pretty thin.

What I need is to limit my strategies trades to Mon-Fri, 8:30 - 3:00 pm (future's market day session).
  • No trades should open before 8:30.
  • All positions should flatten at 5 min before 3:00.

Looking at example scripts that use time, I attempted implementing some code:

Python:
# Flatten is true if we're 5 min or less from end of futures trading
def startTime = 0830;;
def lastFiveMinuteBar = 1455;
def endOfTradingTime = 1500;

def flatten = (GetTime() >= lastFiveMinuteBar AND GetTime() < endOfTradingTime);

But, it doesn't seem to be working.

Is there a way to get human readable time formatting from the GetTime() function?

Any help is appreciated.
 
I use this script for time.

Code:
###### TIME ######

input zoneStartAM = 930;
input zoneEndAM = 1200;
input zoneStartPM = 1330;
input zoneEndPM = 1600;

###### TIME END #####


AddOrder(OrderType.SELL_TO_OPEN, secondsTillTime(zoneStartAM) <= 0 && secondsTillTime(zoneEndAM) >= 0 and

AddOrder(OrderType.BUY_TO_CLOSE,  secondsTillTime(zoneEndPM) <= 0 , CLOSE[0], 1, Color.ORANGE, 
Color.RED, name = "MARKET CLOSE SHORT");

It stops trading during lunch period and closes after16:00

40d6AY7.jpg
 
Last edited:
Very helpful, thanks.

Here's my working code:

Python:
# Flatten is true if we're 20 min or less from end of futures trading
def twentyMinutesTillClose = 1640;

def flatten = SecondsFromTime(twentyMinutesTillClose) > 0 AND SecondsFromTime(twentyMinutesTillClose) < 1200;

AddOrder(OrderType.BUY_TO_CLOSE, flatten, tradeSize = contracts, tickcolor = GetColor(6), arrowcolor = GetColor(6), name="flatten");

And to prevent opening trades in last 20 min.:
Python:
AddOrder(OrderType.SELL_TO_OPEN, signal AND !flatten, tradeSize = contracts, tickcolor = GetColor(6), arrowcolor = GetColor(6));
 
AddOrder(OrderType.SELL_TO_OPEN, secondsTillTime(zoneStartAM) <= 0 && secondsTillTime(zoneEndAM) >= 0 and AddOrder(OrderType.BUY_TO_CLOSE, secondsTillTime(zoneEndPM) <= 0 , CLOSE[0], 1, Color.ORANGE, Color.RED, name = "MARKET CLOSE SHORT");

BTW, I assume this isn't your actual code? If I paste it into TS editor I get errors.

Curious, because it looked like you were chaining 2 AddOrders together.
 
Good evening, I wanted to know if there is any code to apply to a strategy that does the following:
The strategy starts when the market opens and if the closing conditions of the strategy do not exist, it closes one minute before the market closes.
Is what I request viable?
 
Try this

Code:
# Positioning --------------------------------------------------------

input usetimefilter = Yes;
input rthopen = 0931;
input rthclose = 1555;
def RTH = if usetimefilter == yes then if SecondsFromTime(rthopen) >= 0 and
               SecondsTillTime(rthclose) >= 0
            then 1
            else 0 else 1;

Then just enter RTH as one of the conditions change the time to whatever you like

Thus If RTH and other condition ect.
 
I want to backtest a strategy but I am confused on how you can set the code up to trade only during specific hours. I seen a few strategies presented here that do that but cannot replicate it and thought I could ask for some advice here.

Thanks!
 
I want to backtest a strategy but I am confused on how you can set the code up to trade only during specific hours. I seen a few strategies presented here that do that but cannot replicate it and thought I could ask for some advice here.

Thanks!
Time simply becomes part of your conditional triggers for Buys and Sells in your AddOrder() function calls... 💡
 
I am trying to get backtest trades to execute only from 8:00 am EST to 8:00 pm EST (regular day + regular extended hours). Lots of executions with this code but it does not eliminate the executions outside the normal extended hours - I am trading SPY (which trades 24/5 so thinkorswim thinks extended hours for SPY is 24/5)

Where is my code wrong? (or perhaps there is an easier way to restrict trades to only reg hours plus extended hours (8 am - 8 pm EST).

Code:
def x = ExpAverage(close, 30);
def y = ExpAverage(close,10);

input DayTimeStart=0800; # 8AM EST
input NightTimeEnd=1959; # 8PM EST

def CountfromStart=SecondsfromTime(DayTimeStart);
def CounttillEnd= Secondstilltime(NightTimeEnd);

def dayperiod=If(CountfromStart >0 && CounttillEnd >0,1,-1);

def long = y crosses above x and dayperiod==1;
def short = y crosses below x and dayperiod == 1;

plot a = long;
plot b = short;

AddOrder( OrderType.BUY_TO_OPEN, long, open[-1], 100);
AddOrder(OrderType.SELL_TO_OPEN, short, open[-1], 100);
 
Last edited:
@hectorgasm This is what I use. Checks that we're in last 5 min of RTH and then closes before market closes, you can change the times to fit your exit. Doesn't give perfect exits and it's probably not the best code but I haven't had any problems yet.
def lastentry_time = 1555;
def endofday = 1600;

def allexit = SecondsFromTime(lastentry_time) > 0 and
SecondsTillTime(endofday) >=0;

AddOrder(OrderType.BUY_TO_CLOSE, allexit, open, tickcolor=color.orange, arrowColor=color.orange, name="all exit");
 
Hi all,
I am writing a strategy but I am unsure of how to place time into it. ie, when the stoch crosses above 80 on the ONE HOUR. Something like that. Is that "Get Time"?

Edit: I found it!
 
Hey guys,

I've been messing around with an Intraday Trading Strategy and I don't want to hold any positions overnight, so I would like my strategy to automatically sell when the market closes. Any chance anybody knows how to make this happen?
 

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