Help with study based on Time and Moving Average

TraderBro

New member
Hi,

I spent a long time trying to figure this out with no success. I'll start off by saying what I'm trying to achieve:

I enter positions manually, and I am trying to set up a conditional order as a stop.
This conditional order should be based on:
  1. If last price is under the 10 day simple moving average (on the daily chart)
  2. Since I would like to execute the order within standard trading hours (not aftermarket), I'd like the stop to trigger is the price drops below the 10 day moving average within the last 15 minutes of the trading day.

To set this up I created a conditional order template and used the wizard to easily add the rules that I mentioned above
ORfNs7m.png


This is the code I used to calculate and plot the minutes left for each trading day:

Code:
def EndTime = RegularTradingEnd(GetYYYYMMDD());
def GetTime = GetTime();

def SecondsRemained = RoundUp((EndTime - GetTime) / 1000);
def MinutesRemained = SecondsRemained / 60;

plot MinutesLeft = MinutesRemained;

After reading about the different functions in the ThinkScript Learning Center I realized that most of these time functions will not give me the correct time when I am using a daily aggregation period.

Does anyone know a way around this issue so I can get the correct time left before the end of the trading day?
If that's not possible then do you know of any other way I can get achieve my goal using a conditional order?

Thanks!
 
@TraderBro I can't see anyway around your conundrum given that secondary aggregations are not allowed in conditional orders.
You can't try to count minutes if you are trading on a daily chart. Minutes are an intraday function.
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Hi,

I spent a long time trying to figure this out with no success. I'll start off by saying what I'm trying to achieve:

I enter positions manually, and I am trying to set up a conditional order as a stop.
This conditional order should be based on:
  1. If last price is under the 10 day simple moving average (on the daily chart)
  2. Since I would like to execute the order within standard trading hours (not aftermarket), I'd like the stop to trigger is the price drops below the 10 day moving average within the last 15 minutes of the trading day.

To set this up I created a conditional order template and used the wizard to easily add the rules that I mentioned above
ORfNs7m.png


This is the code I used to calculate and plot the minutes left for each trading day:

Code:
def EndTime = RegularTradingEnd(GetYYYYMMDD());
def GetTime = GetTime();

def SecondsRemained = RoundUp((EndTime - GetTime) / 1000);
def MinutesRemained = SecondsRemained / 60;

plot MinutesLeft = MinutesRemained;

After reading about the different functions in the ThinkScript Learning Center I realized that most of these time functions will not give me the correct time when I am using a daily aggregation period.

Does anyone know a way around this issue so I can get the correct time left before the end of the trading day?
If that's not possible then do you know of any other way I can get achieve my goal using a conditional order?

Thanks!
i'm not sure what will work in order code, to pick the last bar of the day. there is a study here that works on a chart.
https://usethinkscript.com/threads/finding-the-first-and-last-bar-of-the-day-in-thinkorswim.526/

maybe you could base your formulas on the shortest time frame, 15 min. then use multipliers to estimate the longer times.
at 15 min, there are 26 bars in a day ( 390 min). to get a 10 day period, use 26*10. ( assuming there is enough historical data)
 
@TraderBro Perhaps SecondsTillTime(1545) <= 0 as a trigger might be easier... SecondsTillTime() and SecondsFromTime() are quite easy to work with...

Thanks for the reply, I initially tried to write a script that uses these functions as it seemed the easiest, but it will not work in my scenario because these functions only work on intra-day timeframes.

This is from the TD Learning Center page:

Returns the number of seconds till the specified time (24-hour clock notation) in the EST timezone. Note that this function always returns zero when chart's aggregation period is greater than or equal to 1 day.

Because I'm using this on the daily chart it always returns 0. I'll continue trying some of the other methods members posted...
 
Given the limitations with time-based functions on the daily timeframe, maybe it makes sense to switch to intraday and approximate the SMA by extending the length to match a day. For instance, use a 4 hour chart without extended hours and 20 SMA.

To test and tune this you can plot both in a study and then run through some symbols to see how well you can get them to line up. 19 looks a little better to me than 20.

Ruby:
plot daily = Average(close(period=AggregationPeriod.DAY), 10);
daily.SetDefaultColor(Color.LIGHT_GRAY);
plot intra = Average(close, 19);
intra.SetDefaultColor(Color.CYAN);
 
Given the limitations with time-based functions on the daily timeframe, maybe it makes sense to switch to intraday and approximate the SMA by extending the length to match a day. For instance, use a 4 hour chart without extended hours and 20 SMA.

To test and tune this you can plot both in a study and then run through some symbols to see how well you can get them to line up. 19 looks a little better to me than 20.

Ruby:
plot daily = Average(close(period=AggregationPeriod.DAY), 10);
daily.SetDefaultColor(Color.LIGHT_GRAY);
plot intra = Average(close, 19);
intra.SetDefaultColor(Color.CYAN);
Thanks for the tip. I was kind of thinking about a similar strategy using intraday timeframes as an alternative but wanted to check if anyone else can offer a solution before I go and test it out.
I'll code something using this strategy sometime this week. If anyone is interested I can share my results.
 
Hey guys, so a quick update. I wrote the script and tested it a little bit in the order condition window, it appears to trigger at the right places but I don't have real world results yet. I'll buy a QTY of 1 of a few cheap stocks that should close tomorrow under the 10 SMA and fingers crossed I'll get stopped out.

Does anyone know if I can test this reliably using the onDemand feature so I don't have to wait for market close tomorrow?

For anyone who's interested, this is the code:
Code:
# Define Times
def EndTime = RegularTradingEnd(GetYYYYMMDD());
def GetTime = GetTime();

def SecondsRemained = RoundUp((EndTime - GetTime) / 1000);
def MinutesRemained = SecondsRemained / 60;

AddLabel(yes, "MinutesRemained: " + MinutesRemained, color = Color.YELLOW);

# Check if this is the last 30 minutes of the day
input checkMinutesLeft = 30;
plot isLastPeriodOfTheDay = if MinutesRemained <= checkMinutesLeft and MinutesRemained > 0 then 1 else 0;
AddLabel(yes, "isLastPeriodOfTheDay: " +  isLastPeriodOfTheDay, color = Color.YELLOW);

# Since I cannot use time functions on daily timeframe (returns 0) I am using a 5-min timeframe with a period of 780. This basically gives the same results as the 10-day moving average on the daily timefame
input intraDayAggregation = 780;

plot daily = Average(close(period=AggregationPeriod.DAY), 10);
daily.SetDefaultColor(Color.DARK_RED);

plot intra = Average(close, intraDayAggregation);
intra.SetDefaultColor(Color.WHITE);

AddLabel(yes, "isMovingAverageBelow: " +  if intra < close then 1 else 0, color = Color.YELLOW);

I kept the plot and the labels on the chart just for testing, we don't actually use this study on the chart itself, it's only used for conditional orders. I chose a random stock (symbol AMTX) that crossed the 10 SMA a few times in the last few days

The blue spiked shows where the order would trigger. Notice the narrow spike on the end of day on Wednesday.
I use the last 30 minutes as my default condition for "isLastPeriodOfTheDay" and since the price crossed and closed below the SMA on Wednesday at the spike is narrow and would only trigger on the bar that closed at 14:45 instead of the default 14:30:

pTCQO8S.png




The 5-minute chart of this stock looks is posted below. The white line is the SMA of the current timeframe on a 780 lookback period, and the red line is the daily SMA on a 10 day lookback period.

U9ZIDDr.png



Hopefully this works when I test this live tomorrow. If anyone has a better idea on how to test this please let me me know. Thanks!

## UPDATE ##

The conditional order did not work, I did some digging at in the Learn Center at the bottom they said that studies must have exactly one plot:
https://tlc.thinkorswim.com/center/...Order-Types/thinkScript-in-Conditional-Orders

I'll revise my code later on today and test again.
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
194 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