AddOrder Statement & Strategy Trading Time

In this simple Strategy, I need help adding 3 things. An Addorder code that sells any open positions before market close, a way to tell my strategy to only take positions when the market is open and don't take any positions after market close. I will leave the code down below. Any help given is truly appreciated.



Code:
#200SMA
input price = close;
input length = 200;
input displace = 0;

plot SMA = Average(price[-displace], length);

#ORDERCODE
def quantity = 100;

def Buy = price >= SMA;
def Sell = price <= SMA;


AddOrder(OrderType.BUY_TO_OPEN, Buy, price, quantity, name = "Buytoopen");
AddOrder(OrderType.SELL_TO_CLOSE, Sell, price, quantity, name = "Selltoclose");
 
Solution
In this simple Strategy, I need help adding 3 things. An Addorder code that sells any open positions before market close, a way to tell my strategy to only take positions when the market is open and don't take any positions after market close. I will leave the code down below. Any help given is truly appreciated.



Code:
#200SMA
input price = close;
input length = 200;
input displace = 0;

plot SMA = Average(price[-displace], length);

#ORDERCODE
def quantity = 100;

def Buy = price >= SMA;
def Sell = price <= SMA;


AddOrder(OrderType.BUY_TO_OPEN, Buy, price, quantity, name = "Buytoopen");
AddOrder(OrderType.SELL_TO_CLOSE, Sell, price, quantity, name = "Selltoclose");
you can do some things with time in Tos:
to take trades...
In this simple Strategy, I need help adding 3 things. An Addorder code that sells any open positions before market close, a way to tell my strategy to only take positions when the market is open and don't take any positions after market close. I will leave the code down below. Any help given is truly appreciated.



Code:
#200SMA
input price = close;
input length = 200;
input displace = 0;

plot SMA = Average(price[-displace], length);

#ORDERCODE
def quantity = 100;

def Buy = price >= SMA;
def Sell = price <= SMA;


AddOrder(OrderType.BUY_TO_OPEN, Buy, price, quantity, name = "Buytoopen");
AddOrder(OrderType.SELL_TO_CLOSE, Sell, price, quantity, name = "Selltoclose");
you can do some things with time in Tos:
to take trades only during regular trading hours:
Code:
def rth = if SecondFromTime(0930) > 0 and SecondsTillTime(1600) > 0 then 1 else 0;
you can then add the rth condition to your AddOrder():
Code:
AddOrder(OrderType.BUY_TO_OPEN, Buy AND rth == 1, price, quantity, name = "Buytoopen");

to handle your other condition, selling open positions before the close, you can do something similar:
Code:
def FiveToGo = if secondsTillTime(1600) < 300 and secondsTillTime(1600)[1] > 300 then 1 else 0;
and add the FiveToGo similarly but with an OR
Code:
AddOrder(OrderType.SELL_TO_CLOSE, Sell OR FiveToGo == 1, price, quantity, name = "Selltoclose");

Of course, I haven't actually tested this, but the idea is solid. Tweak to your needs and if it still doesn't work, come on back and let me know what failed.

Happy Trading,
-mashume

EDIT: Changed the AddOrder() above to reflect the need for explicit comparisons as discussed below.
 
Last edited:
Solution

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

This worked great @mashume but there is one slight issue that I can't figure out. Sometimes the orders don't close out before the market closes which is confusing me a bit. I'll leave the new code along with an image down below to show you an example.

Code:
#200SMA
input price = close;
input length = 200;
input displace = 0;

plot SMA = Average(price[-displace], length);

#ORDERCODE

def MarketOpen = if SecondsFromTime(0930) > 0 and SecondsTillTime(1600) > 0 then 1 else 0;
def MarketClose = if secondsTillTime(1600) < 300 and secondsTillTime(1600)[1] > 300 then 1 else 0;

def quantity = 100;

def Buy = price >= SMA;
def Sell = price <= SMA;
def sell2 = price;


AddOrder(OrderType.BUY_TO_OPEN, Buy and MarketOpen, price, quantity, name = "Buytoopen");
AddOrder(OrderType.SELL_TO_CLOSE, Sell or MarketClose , price, quantity, name = "Selltoclose");


The Circle is where the order closed out but the order should have closed where the square is. Any thought on why this could be ?

R1AD2z3.png
 
Would anyone happen to know the specific code that would need to be written to trigger an order when a price moves above or below a simple moving average in a 30min intraday chart?
 
I broke my own rule in the answer I gave you...

have long preferred, and advocate for code to be as explicit in execution as possible, so I assign 1 and 0 to True and False conditions. Many folks take advantage of the logic ToS has which allows you to simply check that any value exists in a variable (rather than a NaN) and don't actually write out their conditions. In the long run, this makes code less legible and harder to debug.

<climbs down off soap box>

When I wrote out your buy and sell conditions, I ignored the fact that I had written out 1/0 rather than True/NaN def operations and so the buy/sell DO find a value (0 or 1) and both are True. So...

Code:
AddOrder(OrderType.BUY_TO_OPEN, Buy and MarketOpen == 1, price, quantity, name = "Buytoopen");
AddOrder(OrderType.SELL_TO_CLOSE, Sell or MarketClose == 1, price, quantity, name = "Selltoclose");

See what I changed there? I added the explicit condition that MarketOpen must be 1 (to match the def earlier)

Of course, that may not actually fix anything. But it sure makes it easier to figure out what's going on.

BTW, I note that you have your buy and sell prices set to price... this can lead to impossible to achieve results from backtesting. The signal to buy or sell is generated at the close of any given bar, and that price is the same you attempt to trade at. In reality, trading with ToS, if you wait for a bar to close (as you must to get your signal) then you've already missed the CLOSE price for your trade. You can choose to have ToS buy and sell at the OPEN of the next bar by using OPEN[-1] as your trade price -- it may be more accurate for backtesting.

Happy Trading,
Mashume
 
Thats a great explanation. Never thought of it like that. The BTW tip at the bottom sounds like it's going to help a lot. I will actually try that right after I type this just wanna put this out. I was playing with the code and noticed that the statement you typed was correct except for 1 small mistake. I believe this is what the problem was because it ended up fixing it. I basically reversed the greater than symbol into a less than symbol in the MarketClose statement and also clarified my buy and sell conditions. The problem was the strategy thought that because I had stated that
Code:
def Buy = price >= SMA;
def Sell = price <= SMA;
it opened a position up whenever the price was greater than the SMA when in reality I wanted to buy when the price crosses above the SMA. those are 2 completely different statements. When I changed those 2 things everything started working. I'll leave the edited code down below. Tell me what you think @mashume


Code:
#------------EDITED-----------
#200SMA
input SMAprice = close;
input SMAlength = 200;
input SMAdisplace = 0;

plot SMA = Average(SMAprice[-SMAdisplace], SMAlength);

#ORDERCODE

def MarketOpen = if SecondsFromTime(0930) > 0 and SecondsTillTime(1600) > 0 then 1 else 0;
def MarketClose = if secondsTillTime(1600) < 300 and secondsTillTime(1600)[1] < 300 then 1 else 0;

def Price = Open[-1];
def quantity = 100;

def Buy = price crosses above SMA;
def Sell = price crosses below SMA;


AddOrder(OrderType.BUY_TO_OPEN, Buy and MarketOpen, price, quantity, name = "Buytoopen");
AddOrder(OrderType.SELL_TO_CLOSE, Sell or MarketClose, price, quantity, name = "Selltoclose");
 
Last edited:
Thats a great explanation. Never thought of it like that. The BTW tip at the bottom sounds like it's going to help a lot. I will actually try that right after I type this just wanna put this out. I was playing with the code and noticed that the statement you typed was correct except for 1 small mistake. I believe this is what the problem was because it ended up fixing it. I basically reversed the greater than symbol into a less than symbol and also clarified my buy and sell conditions. The problem was the strategy thought that because I had stated that
Code:
def Buy = price >= SMA;
def Sell = price <= SMA;
it opened a position up whenever the price was greater than the SMA when in reality I wanted to buy when the price crosses above the SMA. those are 2 completely different statements. When I changed those 2 things everything started working. I'll leave the edited code down below. Tell me what you think @mashume


Code:
#------------EDITED-----------
#200SMA
input SMAprice = close;
input SMAlength = 200;
input SMAdisplace = 0;

plot SMA = Average(SMAprice[-SMAdisplace], SMAlength);

#ORDERCODE

def MarketOpen = if SecondsFromTime(0930) > 0 and SecondsTillTime(1600) > 0 then 1 else 0;
def MarketClose = if secondsTillTime(1600) < 300 and secondsTillTime(1600)[1] < 300 then 1 else 0;

def Price = Open[-1];
def quantity = 100;

def Buy = price crosses above SMA;
def Sell = price crosses below SMA;


AddOrder(OrderType.BUY_TO_OPEN, Buy and MarketOpen, price, quantity, name = "Buytoopen");
AddOrder(OrderType.SELL_TO_CLOSE, Sell or MarketClose, price, quantity, name = "Selltoclose");
Same issue with prices...

you need to calculate your moving average with CLOSE and place your orders at CLOSE[-1] (probably -- see notes above :) )

In the newest version of your code, you're calculating the moving average on a future bar... that gets dangerous and your into serious repaint territory. Proceed with great caution on this road.

-mashume
 
Same issue with prices...

you need to calculate your moving average with CLOSE and place your orders at CLOSE[-1] (probably -- see notes above :) )

In the newest version of your code, you're calculating the moving average on a future bar... that gets dangerous and your into serious repaint territory. Proceed with great caution on this road.

-mashume
So you are stating that the Input SMAprice= close should also be changed to the Open[-1] value? because what I did was separate the 2 prices @mashume the Moving average price is set to Close but down at the #orderCode I defined Price as def price= open[-1]
 
So you are stating that the Input SMAprice= close should also be changed to the Open[-1] value? because what I did was separate the 2 prices @mashume the Moving average price is set to Close but down at the #orderCode I defined Price as def price= open[-1]
Not what I meant. I'm still on my first cup of coffee for the day.

You should calculate your moving averages with the current bar, so CLOSE. You should have the trade price in the AddOrder() be OPEN[-1]. That way, your moving average is calculated at the close of a bar and the order price reflects the next moment in time -- the open of the following bar.

sorry for any confusion.

-mashume
 
Code:
def rth = if SecondFromTime(0930) > 0 and SecondsTillTime(1600) > 0 then 1 else 0;
you can then add the rth condition to your AddOrder():
Code:
AddOrder(OrderType.BUY_TO_OPEN, Buy AND rth == 1, price, quantity, name = "Buytoopen");

hello @mashume . i trade the /ES. therefore, i modified the above code slightly to achieve what i am trying to do, which is to test different market sessions (asian, european, american) to see which session my backtest results are mostly attributed to:

Ruby:
def tradinghours = if SecondsFromTime(0700) > 0 and SecondsTillTime(2359) > 0 then 1 else 0;

and hence:

Ruby:
AddOrder(OrderType.BUY_AUTO, RSI crosses above oversold and tradinghours == 1, Close, quantity, Color.GREEN, Color.GREEN);
AddOrder(OrderType.SELL_AUTO, RSI crosses below overbought and tradinghours == 1, Close, quantity, Color.RED, Color.RED);

the above works fine, until i need to go past 2359 hours (for secondstilltime)

the times i have set look odd because i am in asian timezone. so therefore, for me, the asian session is 0700 to 1400, european is 1400 to 2230, and american session is 2230 to 0600 (NYT 0930 to 1700).

as such, how would i need to state my secondstilltime for this to work right?

similarly, how would i need to state my inputs , since input=0700 ends up with just '700' appearing in the def line item?

thanks so much
 
Last edited:
@Ronin13 ,

I too trade almost exclusively futures and so deal with CME hours more than NYSE / NASDAQ hours.

First, please see these threads:
https://usethinkscript.com/threads/...gh-and-low-range-of-a-market.8283/#post-78022
https://usethinkscript.com/threads/...ight-session-on-futures-intraday-charts.2087/
as there is some good stuff in there.

Second, please do check the docs here: https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/SecondsFromTime and note that the seconds from time ALWAYS takes eastern time (US). I'm on the US West coast and Seconds...() take east coast times. No need to adjust for daylight savings either.

Also, I think inputs of 700 and 0700 will both work just fine, though I haven't tested it.

Surprisingly, I find that plotting the seconds from or till time as a lower indicator and adding a lot of addVerticalLine commands at various times of day can be quite informative when trying to figure out what ToS is doing at various times of day.

Time in ToS is perhaps second only to Fold() for creating confusion and frustration and confusion among coders. Best of luck, and ask more if you need to . We're here to help.

-mashume
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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