AddOrder thinkScript - Backtest Auto Buy & Sell in ThinkorSwim

diazlaz

Well-known member
2019 Donor
VIP
This thread demonstrates how you can use the AddOrder logic to create your own ThinkorSwim backtesting script. It also contains requests and code examples made by other members—worth looking over.

Hi Everyone,

Inspired by @RobertPayne and this post, for a while, I been trying to replicate the auto functionality in the AddOrder. Seems the behavior is different when from Auto and Manual on how AddOrder is executed.

I'm trying to simulate the buy and sell and simulate the reversal from going long to short or vice-versa in the same bar. Auto it seems the entry is taken at the same bar while manual is on the next bar.

Let's use this as an example:



Ruby:
def EMA = ExpAverage(close, 8);
def STATE = if close > ema then 100 else -100;
plot EMA8 = EMA;

AssignPriceColor (
if STATE == 100 then COLOR.GREEN else COLOR.RED);

AddOrder(OrderType.BUY_AUTO,no);

In this example, if close > ema then go long else go short, if you're in a long trade and trend changes, reverse and go short, vice-versa.

1) Using Auto:

Ruby:
def EMA = ExpAverage(close, 8);
def STATE = if close > ema then 100 else -100;
plot EMA8 = EMA;

AssignPriceColor (
if STATE == 100 then COLOR.GREEN else COLOR.RED);

AddOrder(OrderType.BUY_AUTO,no);

##Automatic
AddOrder(OrderType.BUY_AUTO, condition = (STATE == 100),  name = "BAUTO: " + BarNumber());
AddOrder(OrderType.SELL_AUTO, condition = (STATE == -100),  name = "SAUTO: " + BarNumber());



This works as expected, notice that is opening and closing the position at the same bar with a buy to open and a sell to close, vice-versa.

2) Using Manual

Ruby:
def EMA = ExpAverage(close, 8);
def STATE = if close > ema then 100 else -100;
plot EMA8 = EMA;

AssignPriceColor (
if STATE == 100 then COLOR.GREEN else COLOR.RED);

##Long
AddOrder(OrderType.BUY_TO_OPEN, condition = (STATE == 100),  name = "BTO: " + BarNumber());
AddOrder(OrderType.SELL_TO_CLOSE, condition = (STATE == -100),  name = "STC: " + BarNumber());

##Short
AddOrder(OrderType.SELL_TO_OPEN, condition = (STATE == -100),  name = "STO: " + BarNumber());
AddOrder(OrderType.BUY_TO_CLOSE, condition = (STATE == 100),  name = "BTC: " + BarNumber());

The behavior is different, it executes in the next bar as such:



The reason, is i'm trying to build a strategy that will reverse on trend, but at times, I will pause getting into new positions, but want to close the position when trend change occurs BUT entire in the direction of the trend when that condition is cleared.

Any suggestions or ideas would be greatly appreciated.
 
Last edited by a moderator:

YungTraderFromMontana

Well-known member
I have the credentials for what I want to trigger the orders in the strategy but am a novice at coding and can't figure out how to create the automatic orders. All I need is code where I can quickly plug in my credentials for when a order takes place. (ex buy put when , sell put when).

I finally have the signals and orders on my strategy finished but now want to backtest it. Ideally it would allow me to fine tune my strategy by showing me an updating P/L. When I would make a change in the strategy, there would also be a change in the results. This could allow me to perfect my strategy and squeeze every possible dollar or cut every preventable loss. Any feedback will be helpful in passing this final step so thanks everyone.
 

Miket

Member
How do you guys backtest a strategy on ThinkorSwim? I'd like to take a look at the results for the Sequence Counter found in TOS.
 

tomsk

Well-known member
VIP
How do you guys backtest a strategy on ThinkorSwim? I'd like to take a look at the results for the Sequence Counter found in TOS.

@Miket You can backtest any studies by using the Strategy functionality on TOS.
Here is a very simple example of a strategy
Bullish when price closes above the 34 EMA and bearish when prices closes below the 34 EMA

Code:
input length = 34;
input price = close;

plot EMA = ExpAverage(price, length);
EMA.AssignValueColor(if EMA > EMA[1]
                     then Color.Green
                     else Color.Red);
AssignPriceColor(if EMA > EMA[1]
                 then Color.Green
                 else Color.Red);
AddOrder(OrderType.BUY_AUTO, EMA crosses above EMA[1]);
AddOrder(OrderType.Sell_AUTO, EMA crosses below EMA[1]);

To see the results of your strategy, position your mouse on any of the strategy points on your chart
Right click the mouse and select "Show report"
You will then see a table of your buy/sell strategy with date of trade, price as well as P/L from that strategy
 

msammons

Member
In OnDemand TOS back testing is it possible to use an if statement for an AddOrder?

Something that would, for example, sell short every cross-below but buy long every cross-above (and closes trade when it crosses the other way): all in one TOS strategy

Something like:

def cross-above= cross above EMA;
def cross-below = cross below EMA;

if cross-above then AddOrder(OrderType.BUY_TO_OPEN, cross-above, open[-1], 100) else if cross-below then AddOrder(OrderType.SELL_TO_OPEN, cross-below, open[-1], 100) else no;
if close > EMA then AddOrder(OrderType.SELL_TO_CLOSE, cross-below, open[-1], 100) else if close < EMA then AddOrder(OrderType.BUY_TO_CLOSE, cross-above, open[-1], 100) else no;
 

tomsk

Well-known member
VIP
Don't think that is a valid syntax and from all the different AddOrder statements I have seen, it is generally used without any if-then-else construct. Probably best to vary the condition upon which a buy/sell order is triggered, so if the condition is not triggered, no buy/sell order is effected.
 
Last edited:

msammons

Member
Thank you - is there any way to back test 2 (separate) strategies at the same time using TOS OnDemand back testing?
 

kaflesu

New member
I am trying to backtest the strategy using the thinkorswim. Whenever I add the strategy and add the FloatingPL, after pressing apply it disappear from the Lower. Does anyone know the reason?

Nevermind, It seems like I have created study, not the strategy.
 

Rainmaker

New member
Hi everyone, I have been trying this out for hours and would appreciate some help. I am trying to set up a simple conditional order such that when a stock on a 5-minute chart closes past a certain level, it triggers a market buy order.

I am using other timeframes for the chart, so I didn't use the default "<current period>" and used the AggregationPeriod.FIVE_MIN

This is the entire code on thinkScript editor:
close("period" = AggregationPeriod.FIVE_MIN) more than 100 within 60 bars

I got the error "secondary period cannot be less than primary." Can someone tell me what went wrong?
 

Bobbydigital83

Member
VIP
I'm looking all over the internet to for an idea but cannot find one. I have created these lines of code but results are not producing the results that I was expecting. I have basic TOS coding skills but this one is really frustrating me on figuring out.

Code:
AddOrder(OrderType.SELL_TO_CLOSE, EntryPrice() + 2.5 or EntryPrice() - 1); #TP at  EP +2.5 points or SL at EP -1 points
AddOrder(OrderType.buy_TO_CLOSE, EntryPrice() - 2.5 or EntryPrice() + 1); #TP at EP -2.5 points or SL at EP +1 points

Any help would be greatly appreciated!
 

dvorakm

New member
2019 Donor
VIP
I am trying to test out a strategy, but the sell orders are not behaving (selling at wrong time) and therefore jacking with the open orders. Could someone please help me with a command to test out the buying only part of a strategy? That is, implement only the buying portion of the strategy so I can test and refine that portion.

When I comment out the "sell" potion, I only get one "buy" order, because it is expecting a sell to close. What I am trying to do is bypass that and have multiple buy orders triggered by the strategy, ignoring the "sell" part. Then, I would be able to refine the selling part of the script so that it sells at the correct time.
 

gwbabcock

New member
One way to do it is to keep your logic out of AddOrder statement. Here is an example:

Code:
input EMALenShort = 9;
input EMALenLong = 20;

def EMAPlus = (MovAvgExponential(close, EMALenShort) - MovAvgExponential(close, EMALenLong)) >= 0;

AddOrder(OrderType.BUY_AUTO, EMAPlus,   open[1],  tickcolor = GetColor(0), arrowcolor = GetColor(0),name = "BAuto: " + BarNumber());
AddOrder(OrderType.SELL_AUTO, !EMAPlus,   open[1],  tickcolor = GetColor(1), arrowcolor = GetColor(1),name = "SAuto: " + BarNumber());

Also note BUY_AUTO and SELL_AUTO will automatically switch when EMAPlus goes from positive to negative and vv.
 

ianfaler

New member
I am looking for a program that can trade futures automatically.

As an example: Say I want to buy 1 /ES contract when the 10SMA crosses above the 20SMA on the 30 extended chart to go long.

When that happens I need a conditional order to trigger that says we want to close and go short (sell 2 contracts) of /ES when the 10SMA crosses back below the 20SMA on the 30 extended chart. When that happens we need the long order to go back in (2 contracts again so that we sell the short and buy the long). This can be done in market orders but I don't know if there is a way to create a rolling conditional order in ToS. Any idea about this? Can this be created in ToS?
 

Ken_Adams

New member
So have been messing around with ToS scanner to try to predict if tomorrow will have a gap up based off the strength of the last 15 mins of a stock. My thought is I would buy in the last 15min, maybe a 30 delta call, and sell the next morning.

Scanning the 1m chart for things like Stochslow crossingover Fast within a certain range
RSI within a range
momentum over OBV
AvgVol increasing
Thinking about adding some kind of component like "percent below yesterdays high" to the scan

Now I want to be able to backtest it but having problems writing the strategy based off my limited knowledge. Could someone point me in the right direction to get started? Maybe other strategies I could pull from, or input on other indicators to use?
 
Last edited:

tplowe56

New member
I have strategy that uses ADX, MACD, and Double Smoothed Stochastics to pick entries long and short. The audible and printed "alert" are executed at the exact time of the occurrence (when all 3 parameters are met). TheAddOrder function on the other hand appears to default to executing at the next bar, and can be adjusted to High,Low,Close,Open, of the previous bar, if coded like this:

def orderprice = low[1]; Executes a buy at the low of the previous bar (the bar in which the signal was generated) This can lead to back testing which is not accurate.

Is it possible to code the AddOrder function to execute the order at exactly the same time & price as when the alert is issued? Sorry if this has been discussed but I could not find any reference to this.
 

ryan5439

New member
What is the code for having 3 separate indicators making a buy/sell signal? This is the code for simple moving avg strat.

Code:
def crossAbove = price crosses above Avg;
def crossBelow = price crosses below Avg;
def buy;
def sell;
switch (mode) {
case  "Trend Following":
    buy = crossAbove;
    sell = crossBelow;

I want to have "crossAbove" AND another indicator tripped AND another indicator tripped creating the buy signal.
 

toopoor88

Member
Wondering if one of you high IQ people can help this dummy out. I watched some videos but for the life of me I can't figure out how to make a strategy/bastesting using the "RibbonStudy" on the thinkorswim platform. I would like to have buy or sell when it crosses below R1 and close at R3 and buy or sell when it crosses back R1 and repeat. Just wanted to test it out. Please note this is just the simple Ribbon study indicator found in the platform and not the slim ribbon. Hopefully I didn't post this in the wrong area.
 

john3

Active member
2019 Donor
Regardless of a strategy, how would I limit the backtest only to the regular trading hours (RTH)? I trade futures and always have an overnight session displayed, but for a backtest I only would like to test the RTH.

In addition, also regardless of a strategy, but let's say it is a simple MAs cross, I would like to know an average price move after a signal has been triggered. For example, 10 SMA crossing 20 SMA both ways (up/down), the strategy enters on the next bar open after the cross, what is an average price move after the cross? It would be great if after the cross it would automatically plot a line with a user-selectable target. For example, after the cross, plot a line 2 point away from the cross.

Appreciate your help!
 

Similar threads

Top