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.
 
Code:
def highVol = volume > (2 * volume[1]) and volume == highest(volume, 5);
plot isHighVol = if highVol then volume else double.NaN;
isHighVol.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_up);
isHighVol.SetDefaultColor(Color.white);
isHighVol.SetLineWeight(3);

this study I wrote also works for after hours. Is there a way to only show it for regular trading hours (9:30 - 4:00)?
 
I tried to insert a time limit code into me study, no result.
I want to limit signals to day only (from 9-30 till 15-25).
What is wrong or shall I add something?

Code:
def price = close;
def X=2;
def N=5;
def iAvg = Average(volume[1],5);

def MarketOpenTime = 0930;
input TimeToStopSignal = 1525;
def TradeTimeFilter = SecondsFromTime(TimeToStopSignal);

plot signaldown = close[1]>close[2] and Volume<Volume[1] and volume[1]>iAvg;
plot signalup = close[1]<close[2] and Volume[1]>Volume[2] and volume[1]>iAvg;

signaldown.SetPaintingStrategy(paintingStrategy = PaintingStrategy.BOOLEAN_ARROW_DOWN);
signalup.SetPaintingStrategy(paintingStrategy = PaintingStrategy.BOOLEAN_ARROW_UP);
signaldown.SetDefaultColor(color = Color.YELLOW);
signalup.SetDefaultColor(color = Color.CYAN);
signalup.SetLineWeight(5);
signaldown.SetLineWeight(5);
 
I am wanting to show how much a strategy would have made if it was used on a stock during a trading day. It would find where the first time the buy order condition is true, then find the next time the sell order condition is true, and it would divide the sell close by the buy close to find the percent gained. Then I guess take the sum of each order's percents to find the total percent made. I want to put this on a scanner column so I can see which stocks a strategy would have done best on.

And using code like this to only get the trades which are during the trading day.
Code:
input start_time = 0930;
input endtime = 1600;
def Active = if GetLastDay() == GetDay() and SecondsFromTime(start_time) >= 0 and SecondsFromTime(endtime) <
0 then 1 else 0;
I use day:2min
I don't know what kind of code would be able to do this, like if you have to use fold loops or something.
 
I don't even know if there's much point posting this code since it's very personalized to the strategy I'm using, but I did for the most part solve how to get the trading day's total percent profit from a strategy.
I had to put a loop in a loop to get the buy and sell orders together. The order values were a tiny bit off, but I got them as close as possible.
This is the segment of code I worked into my strategy
Code:
input start_time = 0930;
input endtime = 1540;
def Active = if GetLastDay() == GetDay() and SecondsFromTime(start_time) >= 0 and SecondsFromTime(endtime) <
0 then 1 else 0;

def cond1 = MainAM > SignalAM and MainAM - SignalAM > 0 and MainAM[1] - SignalAM[1] < 0;
def cond2 =  MainAM < SignalAM and MainAM - SignalAM < 0 and MainAM[1] - SignalAM[1] > 0;
def var1 = if cond1 then (open*.8+close*.2) else 0;
def var2 = if cond2 then (open*.8+close*.2) else 0;
def openings = if Active and !Active[1] then (if cond1 then var1 else 1) else if Active then (if cond1 then var1 else openings[1]) else 0;
def closings = if Active and !Active[1] then 0 else if Active then closings[1] + (if openings==1 then 0 else var2/openings) else if !Active and Active[1] then closings[1] + (if MainAM[1] > SignalAM[1] then (open[1]*.8+close[1]*.2)/openings[1] else 0) else closings[1];

def orders = if Active and !Active[1] then cond1 else if Active then orders[1] + cond1 else (if isNaN(orders[1]) then 0 else orders[1]);

plot result = closings-orders;
 
Last edited:
I was hoping to find a study that plots RTH pivots (woodies, standard, fibonacci) without having to manually disable extended hours in TOS. Thanks in advance
 
Last edited:
Hi,
I'm looking for a code that only trigger alert from 10am-16pm.
My setup is simple, for day trading using 1-minute chart, get the average per min volume for 1st 30 mins, a baseline to compare to the rest of the day.
If the vol is higher than the baseline, then trigger the alert for a potential breakout to enter, works well for consolidation in the afternoon.
For example, FSR 3/1/2021, 2:30pm

My problem is from 9:30-10am, the vol still accumulating thus the per min vol still low, the alert get trigger too often.
How to only trigger after 10am? Any help is greatly appreciated.

Right now the code is the following
Code:
input startTime = 0930;
input endTime = 1000;

def curVolume = volume;
def Active = SecondsFromTime(startTime) >= 0 and SecondsTillTime(endTime) >= 0;
def Vol30Mins = if Active and !Active[1] then volume
                else if Active then Vol30Mins[1] + volume
                else Vol30Mins[1];

Alert(curVolume >= Round(Vol30Mins/30,0), Sound.Ring);
 
How to only trigger after 10am? Any help is greatly appreciated.

Code:
input startTime = 0930;
input endTime = 1000;

def curVolume = volume;
def Active = SecondsFromTime(startTime) >= 0 and SecondsTillTime(endTime) >= 0;
def Vol30Mins = if Active and !Active[1] then volume
                else if Active then Vol30Mins[1] + volume
                else Vol30Mins[1];

Alert(curVolume >= Round(Vol30Mins/30,0), Sound.Ring);

I usually just give the answer instead of pushing the requestor to figure it out but this one is so easy I'm pretty sure you didn't try. You already have all the pieces in your script. Let's see if you can do it. I'll even give you some hints that should make it ridiculously obvious.

1. This code has an example of using SecondsFromTime() to do something only after the specified time.
2. This code already has a variable that represents 10am.
3. The line at the bottom uses Alert(). I bet we need to change something there.
4. We can see the word and used in multiple places in this code to require multiple conditions are true before doing something.
 
I usually just give the answer instead of pushing the requestor to figure it out but this one is so easy I'm pretty sure you didn't try. You already have all the pieces in your script. Let's see if you can do it. I'll even give you some hints that should make it ridiculously obvious.

1. This code has an example of using SecondsFromTime() to do something only after the specified time.
2. This code already has a variable that represents 10am.
3. The line at the bottom uses Alert(). I bet we need to change something there.
4. We can see the word and used in multiple places in this code to require multiple conditions are true before doing something.
Thanks for the hint, I tried to put time limt as 2nd condition like this but Vol30Mins become incompatible and marked red. In other words, volume condition becomes invalid.
Alert(SecondsFromTime(1000) >= 0 and SecondsTillTime(1800) >= 0, curVolume >= Round(Vol30Mins / 30, 0), Sound.Ring);

------------------------------------------------------------
OK, I changed comma to and, the error goes away. I didn't know the "and" is condition separator, I thought it's the comma.
The code is like this now. Let me see if works properly.
Alert(SecondsFromTime(1000) >= 0 and SecondsTillTime(1800) >= 0 and curVolume >= Round(Vol30Mins / 30, 0), Sound.Ring);
 
Last edited:
Thanks for the hint, I tried to put time limt as 2nd condition like this but Vol30Mins become incompatible and marked red. In other words, volume condition becomes invalid.
Alert(SecondsFromTime(1000) >= 0 and SecondsTillTime(1800) >= 0, curVolume >= Round(Vol30Mins / 30, 0), Sound.Ring);

------------------------------------------------------------
OK, I changed comma to and, the error goes away. I didn't know the "and" is condition separator, I thought it's the comma.
The code is like this now. Let me see if works properly.
Alert(SecondsFromTime(1000) >= 0 and SecondsTillTime(1800) >= 0 and curVolume >= Round(Vol30Mins / 30, 0), Sound.Ring);

Looks good to me.
 
Looks good to me.
Yes, it works as intended.

One more question, how to get the average first 30 minutes vol for the last 30 days?
I've been trying to modify the following code but to no avail. It seems I can't define the period.
Code:
def volLast30DayAvg = (volume(period = "DAY")[1] + volume(period = "DAY")[2] +....volume(period = "DAY")[30]) / 30;

Can you help me out? Thank you.
 

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