AddOrder thinkScript - Backtest Buy & Sell in ThinkorSwim

Hello,
So I am learning here so please go easy on me lol. So I am trying to create a strategy to backtest as follows:

Buy Condition = buy when MACD value is below zero and value crosses above avg.
Edit Condition = Price when buy condition was triggered minus lowest of the price candle and add that to Price at buy condition.
- So let's say Buy condition was triggered when TSLA at 600$, and the lowest of the past three candles is 595. So the target exit would be 600+(600-595) = when the close crosses above 605.

Here is my simple script:
Code:
input tradesize = 10;

def Cross = MACD()."Value" is less than or equal to MACD()."ZeroLine" and MACD()."Value" crosses above MACD()."Avg";
def A = if cross then lowest(low,3) else cross[1];
def B = if cross then close else cross[1];
def Target = B+(b-a);

AddOrder(OrderType.BUY_TO_OPEN, cross, open[-1], tradesize, Color.CYAN, Color.CYAN);
AddOrder(OrderType.SELL_TO_CLOSE, close>=target or close <a , open[-1], tradesize, Color.MAGENTA, Color.MAGENTA);

ISSUE: So as you can see from the image, it seems like entry and exit are being triggered almost at the same time and I cant figure out why, I tried info posted here: https://usethinkscript.com/threads/...buy-sell-in-thinkorswim.741/page-8#post-42477. But I am still not able to figure it out...
GOv22H9.png



Thank you for your help, I really appreciate it
 
Last edited by a moderator:

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

@toncuz In answer to your original question, yes, I know how to combine multiple strategies... It sounds like you'll need to learn how to combine them yourself as well... You don't seem to appreciate the help provided so you'll have to learn to help yourself like the rest of us did... Be a self-starter rather than expecting others to do your research and coding for you...

As for your comment regarding testing multiple strategies, you're wrong because I have tested multiple strategies many times... Several strategies included in Thinkorswim are intended for that very purpose... Time to roll up your sleeves and start learning rather than complaining and making false statements...
that is interesting, i knew that multiple strats were included when running a report even if they are unchecked but never thought to actually use that ability, thanks!
 
@Learnbot Wouldn't it make more sense to base your exit price off EntryPrice()...???
Yes sir it would but don’t I have to define entryprice()? Am I misunderstanding that function?
So if I have to define entryprice() then “cross” on my script posted above would be Entryprice() right?
 
Yes sir it would but don’t I have to define entryprice()? Am I misunderstanding that function?
So if I have to define entryprice() then “cross” on my script posted above would be Entryprice() right?

EntryPrice() is automatically assigned when an order is entered, whether a Long or a Short... You don't have to provide an entry price for AddOrder(), unless you want to, as it can be automatically assigned by the function...

Most all Strategies rely on conditions for entry and exit, unless you define a limit or stoploss for exits... The conditions can be single or multiple... It never hurts to review the many Strategies that come standard with Thinkorswim as you can borrow ideas from them for your own use...
 
EntryPrice() is automatically assigned when an order is entered, whether a Long or a Short... You don't have to provide an entry price for AddOrder(), unless you want to, as it can be automatically assigned by the function...

Most all Strategies rely on conditions for entry and exit, unless you define a limit or stoploss for exits... The conditions can be single or multiple... It never hurts to review the many Strategies that come standard with Thinkorswim as you can borrow ideas from them for your own use...
appreciate your input, i tried the entryprice() function but didn't have much luck lol oh well it's all good, I'll just manually backtest it I guess. Thank you for your time though
 
@Learnbot Truth be told, I do most all of my backtesting manually due to the inherent inadequacies of the AddOrder() function... In fact, while showering tonight I had an idea for a different way of testing that I might experiment with later... My vision is a more accurate order processing script... Still just a thought but something I could definitely get into...
 
@Learnbot Truth be told, I do most all of my backtesting manually due to the inherent inadequacies of the AddOrder() function... In fact, while showering tonight I had an idea for a different way of testing that I might experiment with later... My vision is a more accurate order processing script... Still just a thought but something I could definitely get into...
agree I have noticed some of the fills in back resting are off so I totally agree with you on that point. If you do come around to making adjustment to your back testing idea please do inform me or post it here so I can learn. Thank you boss
 
New coder here. How can I make the script begin trading at a certain time and stop trading at a certain time. I do not want to trade the first 15 minutes and the last 15 minutes
 
New coder here. How can I make the script begin trading at a certain time and stop trading at a certain time. I do not want to trade the first 15 minutes and the last 15 minutes
This should help:

Code:
input usetimefilter = Yes;
input rthopen = 0930;
input rthclose = 1600;
def RTH = if usetimefilter == yes then if SecondsFromTime(rthopen) >= 0 and SecondsTillTime(rthclose) >= 0 then 1 else 0 else 1;


plz adjust rthopen and rthclose time to whatever time u need to start and stop, also make sure u add rth to ur signals. For example Plot buysignal = buycondition(whatever ur signal is) and rth is true;
 
You're asking for the opposite of what people normally ask for.



The Bollinger Bands indicator is already available in ThinkorSwim. However, it doesn't come with the arrows or alerts when the price crosses above or below the bands. I assume that is what you're looking for.

Here is the code:

Code:
#
# TD Ameritrade IP Company, Inc. (c) 2007-2020
#

input price = close;
input displace = 0;
input length = 20;
input Num_Dev_Dn = -2.0;
input Num_Dev_up = 2.0;
input averageType = AverageType.Simple;

def sDev = stdev(data = price[-displace], length = length);

plot MidLine = MovingAverage(averageType, data = price[-displace], length = length);
plot LowerBand = MidLine + num_Dev_Dn * sDev;
plot UpperBand = MidLine + num_Dev_Up * sDev;

LowerBand.SetDefaultColor(GetColor(0));
MidLine.SetDefaultColor(GetColor(1));
UpperBand.SetDefaultColor(GetColor(5));

def buy = close crosses above LowerBand;
def sell = close crosses below UpperBand;

plot bullish = buy;
bullish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
bullish.SetDefaultColor(Color.GREEN);
bullish.SetLineWeight(1);
plot bearish = sell;
bearish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
bearish.SetDefaultColor(Color.RED);
bearish.SetLineWeight(1);

# Alerts
Alert(bullish, " ", Alert.Bar, Sound.Chimes);
Alert(bearish, " ", Alert.Bar, Sound.Bell);
Hey Ben what triggers the bullish and Bearish arrows ? Instantly when it goes out of the bands ? Or outside heading back into bands ? Thanks .
 
Hey Ben what triggers the bullish and Bearish arrows ? Instantly when it goes out of the bands ? Or outside heading back into bands ? Thanks .
Code:
def buy = close crosses above LowerBand;
def sell = close crosses below UpperBand;

so per @BenTen’s code, buy arrow plots when close of the candle crosses above lower band and sell arrow when close crosses below upper band.
hope this helps
 
Hi everyone!, I'd like to set strategies on my chart for backtest but I don't want it auto trade (everything manual as I used indicator)
So, can anyone show me how set up strategies as it is, thank you.
 
Thank you for your time, I already read that but still confuse in AddOrder() it had 2 different command Auto_Buy or Auto_Sell and Buy_To_ Open Sell_to_Close
so, as your answers TOS not do auto trading mean evenly I set strategies on my chart I still safe right? (not auto trading)
the purpose that i want to use strategies on my chart for backtest .... my indicator
 
Here is a AddOrder Script Snippet:
For example, I want to test for a certain condition, then when that condition is hit, calculate 95% of the current price and set an order to buy at that price.

Code:
def buytrig = <insert buy trigger>;
def tradeprice1 = if buytrig then high * .95 else tradeprice1[1];
def selltrig = <insert sell trigger>;
def tradeprice2 = if selltrig then low + low * .05 else tradeprice2[1];

addOrder(orderType.BUY_TO_OPEN, buytrig and !buytrig[1], open[-1], 100, color.YELLOW, color.GREEN, "BUY");
addOrder(orderType.BUY_TO_close, selltrig, open[-1], 100, color.YELLOW, color.RED, "SELL");
 
Last edited by a moderator:
EDIT: Silly me, this was already answered here: https://usethinkscript.com/threads/...t-auto-buy-sell-in-thinkorswim.741/post-41368

About the bubbles - currently can't understand how I use it I'll go over this again later and will try to write one for the 'teeth'.
By not working I mean that I don't get any signals. There's not a syntax error (which I assume is a problem with the code itself), it just don't give me signals to buy and sell.
If I change it to a number like 50 instead of the syntax you wrote. It does give me signals.

I think I know what the problem is.
Code:
input risk = 50;
def buyQ = round(risk/price - teeth, 0);

AddOrder(OrderType.BUY_TO_OPEN, condition = success, close, tradesize = buyQ, Color.GREEN, Color.GREEN, "BUY");
AddOrder(OrderType.SELL_TO_CLOSE, condition = exit, close, tradesize = buyQ, Color.RED, Color.RED, "SELL");
With the buy order there's not a problem.
I think that in order to make a trade it needs to sell the same amount of shares I've bought, while on the sell order the tradesize is getting other numbers because the 'price' and 'teeth' are different than the ones on the buy order. So if it bought 120 shares it won't sell the same number of shares. So maybe I need it to sell the same amount it bought in order to receive signals.
Does it makes any sense?

Based on a quick test, if you don't specify the quantity, the SELL_TO_CLOSE should sell everything you bought.

Instead of this:
Code:
AddOrder(OrderType.SELL_TO_CLOSE, condition = exit, open[-1], tradesize = buyQ, Color.RED, Color.RED, "SELL");

Try this:
Code:
AddOrder(OrderType.SELL_TO_CLOSE, condition = exit, open[-1], Color.RED, Color.RED, "SELL");
 
Last edited by a moderator:
Hey!
I have been backtesting and I want to test taking incremental profits. In this case, selling 1 contract at 1 atr, 1 at 2, and 1 at three.
This code is for the last part of the strategy and does not have all the variables. It is not optimal, but I am learning.

Code:
#keltner channels
input kdisplace = 0;

def shift1 = 1 * MovingAverage( AverageType.SIMPLE, TrueRange(high, close, low), 21);
def shift2 = 2 * MovingAverage( AverageType.SIMPLE, TrueRange(high, close, low), 21);
def shift3 = 3 * MovingAverage( AverageType.SIMPLE, TrueRange(high, close, low), 21);

def kaverage = MovingAverage( AverageType.SIMPLE, price, length);

def Upper_Band1 = kaverage[-displace] + shift1[-displace];
def Upper_Band2 = kaverage[-displace] + shift2[-displace];
def Upper_Band3 = kaverage[-displace] + shift3[-displace];

#profit targets
def profit1 = close crosses above Upper_Band1;
def profit2 = close crosses above Upper_Band2 or close crosses below Upper_Band1;
def profit3 = close crosses above Upper_Band3 or close crosses below Upper_Band1 or close crosses below Upper_Band2;

#stop
def stop = close < ema34 and close[1] < ema34;

AddOrder(OrderType.BUY_TO_OPEN, buy, open[-1], 3, tickcolor = Color.GREEN, arrowcolor = Color.GREEN);
AddOrder(OrderType.SELL_to_close, profit1, open[-1], 1, tickcolor = Color.RED, name = "Profit1");
AddOrder(OrderType.SELL_to_close, profit2, open[-1], 1, tickcolor = Color.RED, name = "Profit2");
AddOrder(OrderType.SELL_to_close, profit3, open[-1], 1, tickcolor = Color.RED, name = "Profit3");
AddOrder(OrderType.SELL_to_close, sell, open[-1], 1, tickcolor = Color.RED, name = "Turned");
AddOrder(OrderType.SELL_to_close, stop, open[-1], 3, tickcolor = Color.RED, name = "Stop");

The code keeps opening a position at 3 contracts and then at profit1 it will sell all the contracts. I have tried sell_auto but it then opens a short position.

Is it possible to take incremental profits and not open new short positions?
 
Last edited by a moderator:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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