AddOrder thinkScript - Backtest Buy & Sell in ThinkorSwim

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

Hi there, I really like the Bollinger SE and LE on the SPY 20 day chart, but can't work out how to turn it into an alert. Can anyone help? Thank you so much.
 
You're asking for the opposite of what people normally ask for.

The Bollinger Bands® Short Entry strategy generates a Short Entry signal when the price crosses below the upper band.
The Bollinger Bands® Long Entry strategy generates a Long Entry signal when the price crosses above the lower band.

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);
 
You are a ROCK STAR! Thank you so much!

So I pasted this into an alert on the SPY 20 day/1 hour script window, and it didn't give me the option to click OK... is something wrong? I would paste a screenshot but the Imgur thing isn't working. It is saying "Exactly one plot expected" - is that right? Also has a note saying Trigger if: At or above 341.608 ,.... Do I need to somehow "tell:" the Alert that this refers to the particular Bollinger strategy?
 
Last edited by a moderator:
Hello guys,
Is there some sort of Strategy template for dummies where I can plug in the indicators and test them? I usually do them by hand but I'm looking for a quicker method so it doesnt take me sooooo long to backtest. I'm not savvy with coding at all. Looking for some help if anyone has the time. Many thanks!
 
Hello guys,
Is there some sort of Strategy template for dummies where I can plug in the indicators and test them? I usually do them by hand but I'm looking for a quicker method so it doesnt take me sooooo long to backtest. I'm not savvy with coding at all. Looking for some help if anyone has the time. Many thanks!
The AddOrder() function is used for backtesting Strategies... If you have a Study that you are interested in, just copy it over into a Strategy and insert AddOrder() commands at the bottom using the same criteria that is providing you with signals... You can then Right-Click on the results of the Strategy and Click on Report to see the results...
 
Would like to buy a script to back test calendar spread on Options. Is it possible and where is the best place to post such request?
 
Backtesting scripts in ThinkorSwim are for regular indicators and will only purchase shares.
 
Hello, I have been programming for a few years but I am brand new to thinkscript and have run into some issues I cant fix. Any help is appreciated.

As you can see from the screen shot below the buy and sell is not working correctly. In this example this should not buy here because the close of the last bar was 2.24 and sma1 was 2.15 which means it was less. I am not sure why it is buying here.... The condition to buy is (close1 < sma1)

nCPcxBO.jpg


In the second example I am not sure why it is selling here. The bar before had close1 > sma1 and not close < sma1 like the condition is to sell.

KZJe3Wf.jpg


The other problem I have is when I use entryPrice() it doesnt actually find that and just grabs the last price so I may buy 10 shares at $1 a piece and then it goes to 1.02 and now it is going to just close 9 of the shares instead of 10. Does anyone know how to just find however many shares are left and close it? Instead of making this super hard like I am. I cant seem to find anything like PositionSize() or something that I could use for tradeSize to close? Thanks!

This is my code
Code:
plot sma1 = (close[2]+close[1])/2;
def close1 = close[1];
def close2 = close[2];
def sma2 = (close[3]+close[2])/2;

AddOrder(OrderType.BUY_TO_OPEN, tradeSize = (10000/LastPrice) ,condition = ((close1 > (sma1*.9997)) and (close2<sma2)),  name = "BUY");

AddOrder(OrderType.SELL_AUTO, tradeSize = (3333/entryPrice()), condition = (LastPrice crosses above (entryprice()*1.039998)),  name = "TAKE PROFIT 1");
plot tp1 = if (LastPrice crosses above (entryprice()*1.039998),yes,no);
AddOrder(OrderType.SELL_AUTO, tradeSize = (3333/entryPrice()), condition = (LastPrice crosses above (entryprice()*1.069998)),  name = "TAKE PROFIT 2");
plot tp2 = if (LastPrice crosses above (entryprice()*1.069998),yes,no);
AddOrder(OrderType.SELL_AUTO, tradeSize = (1667/entryPrice()), condition = (LastPrice crosses above (entryprice()*1.149998)),  name = "TAKE PROFIT 3");
plot tp3 = if (LastPrice crosses above (entryprice()*1.149998),yes,no);

AddOrder(OrderType.SELL_TO_CLOSE, tradeSize = if (tp1 == no,10000/entryPrice(),if(tp1 == yes and tp2 == no,(10000*.666666667)/entryPrice(),if(tp1 == yes and tp2 == yes and tp3 == no,(10000*.3333333334)/entryPrice(),if(tp1 == yes and tp2 == yes and tp3 == yes,(10000*.1666667)/entryPrice(),10000/entryPrice())))) ,condition = (close1 < sma1),  name = "CLOSE LONG POS");
 
ThinkorSwim has its own limitation when it comes to backtesting, especially the entry and exit price isn't always spot on. Take a look at the sample backtesting script below.

Code:
def pUP = buy_condition;
def pDown = sell_condition;

AddOrder(OrderType.BUY_TO_OPEN, condition = pUP, price = open[-1],100, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "Long");
AddOrder(OrderType.SELL_TO_CLOSE, condition = pDown, price = open[-1],100, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "Cover");

Hopefully, that helps.
 
Last edited by a moderator:
Hi Everyone. Just getting started with ThinkScript and I feel like there should be an easy solution. Sorry if this has already been answered somewhere. I searched but was not able to find an existing thread.

I am writing my first ThinkScript strategy, and basically, all I want to do is to have my AddOrder do a BUY_TO_OPEN if I do not have any positions currently open, and then a SELL_TO_CLOSE only if I already have a position open. I just want to have one position open at any one time. I have some code that runs, but what is happening currently is that if my buy conditions are met, it does the BUY_TO_OPEN for whatever ticks that the buy condition is true for, regardless of whether or not I already have a position opened. So what happens is that I will have multiple open positions and then multiple closes sporadically on my charts, that don't necessarily all match up and cancel each other out.

Here are my two AddOrder calls:

Code:
AddOrder(OrderType.BUY_TO_OPEN, (if BuyCondition then (yes) else no), open[-1], numshares, Color.GREEN, Color.GREEN, "Buy Shares: " );
AddOrder(OrderType.SELL_TO_CLOSE, (if (SellConditionATRs) then yes else no), open[-1], numshares, Color.RED, Color.RED, "Sell Shares: " + numshares);

I tried to nest these AddOrders into some if then else types statements to try and do the logic, but ThinkScript doesn't seem to like putting them into if then else structures. How can I achieve what I'm trying to? Any help would be greatly appreciated! Thanks in advance!
 
@SheeshkaBob You can use EntryPrice() to check whether an order is already open for a security... It will either return the Entry Price or it will return Double.NaN... Something like !EntryPrice() should work for your needs... You would add the "and !EntryPrice()" onto your existing conditional clause portion of AddOrder(OrderType.BUY_TO_OPEN)...
 
Hey everyone, I am wondering if it possible to code a strategy so I can have multiple buy orders and all of them sell on the next selling criteria? My strategy presents multiple "buy in" points and can be used to increase my position size before I need to sell. Is it even possible to do this or is the computer only able to handle one buy order at a time?
 
As I recall, as long as you have your TOS set to allow multiple trades you can have multiple Buys but only one Sell...

Actually, for backtesting it only does single Buys and Sells... Unfortunately...
 
Last edited:
As I recall, as long as you have your TOS set to allow multiple trades you can have multiple Buys but only one Sell...

Actually, for backtesting it only does single Buys and Sells... Unfortunately...
Actually found that you can change this in the "global settings" in the "edit studies" portion. Super useful. Someone in the ThinkScript Lounge told me about it!
 
Actually found that you can change this in the "global settings" in the "edit studies" portion. Super useful. Someone in the ThinkScript Lounge told me about it!
Yes, that was the setting I was referring to... Pretty sure it works for Strategies but not 100%... Have you tried it yet...???
 
Hi everyone

I am new here. I joined because I am getting into thinkscript and this seemed like a great forum for learning.

I am currently stumped by what must be a stupid question, regardless of the reason...

If my strategy gets a buy signal on a stock, how do I place an order using GetATMOption data for a specified contract date (collected in the input field)?

I think I know how to find the GetATMOption data, I just don't know what to do with it once I receive the buy signal from the strategy running on my stock chart. Is there a way to point addorder to a specific option contract outside of the instrument where the strategy is running that generates the addorder condition?

Thank you!

-Smoky
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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