AddOrder thinkScript - Backtest Buy & Sell in ThinkorSwim

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

I would like to take the following scan criteria and convert this into a strategy, that when true it will trigger a buy signal. I am looking to use this with stocks in order to back test my strategy in OnDemand. I have not figured out what will be the sell signal yet but needed to start somewhere.

vIHleZu.png
 
@martinstocks87 The problem is that your scan looks at an entire market whereas a strategy can only be run on a single symbol... Therefore, your idea can't be coded in Thinkscript... You could, however, possibly use parts of your scan criteria to monitor a single symbol for Buy and Sell signals and paint them onto a chart...
 
This is the whole strategy I'm trying to build. It's made of MACD and Williams Alligator.
Code:
input fastLength = 12;
input slowLength = 26;
input macdLength = 9;
input averageType = AverageType.EXPONENTIAL;
def diff = reference MACD(fastLength, slowLength, macdLength, averageType).Diff;

def lips = reference WilliamsAlligator().Lips;
def teeth = reference WilliamsAlligator().Teeth;

def price = open;
def Closeprice = close;

def sucess = diff crosses above 0 and price > lips;
def exit = price < lips or closeprice < lips;

def Q = 50/(price - teeth);
input digits = 0;
def buyQ = roundup(Q, digits);

AddOrder(OrderType.BUY_TO_OPEN, condition = sucess, open[-1], tradesize = buyQ, Color.GREEN, Color.GREEN, "BUY");
AddOrder(OrderType.SELL_TO_CLOSE, condition = exit, open[-1], tradesize = buyQ, Color.RED, Color.RED, "SELL");

Now those are the lines that are relevant to my problem:

Code:
def teeth = reference WilliamsAlligator().Teeth;
def price = open;
def Q = 50/(price - teeth);
input digits = 0;
def buyQ = roundup(Q, digits);
AddOrder(OrderType.BUY_TO_OPEN, condition = sucess, open[-1], tradesize = buyQ, Color.GREEN, Color.GREEN, "BUY");

There isn't any problem with the code... except its showing nothing when I'm trying to use the tradesize like this. When I'll change buyQ to "def buyQ = 50;" it'll show it. The thing is that I want to have a changing number of size according to my constant $$$ risk.
What I'm doing wrong?

Thanks!
 
Last edited by a moderator:
Here is an example:

Code:
input tradesize = 50;

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

Not sure if that's what you're looking for.
 
Last edited by a moderator:
Thank you for the comment. This is not what I'm aiming.

I'll try to explain it better:

image.png


In this picture you can see that 'price - teeth' = 3. My risk is 50$. So in this example I want it to buy 50/3 = 16.667 ~ 17.

How do I make it happen? Hope its more clear now.
 
@MerryDay Still not working :(

This is what I wrote:

Code:
input risk = 50;
def buyQ = round(risk/price - teeth, 0);

AddOrder(OrderType.BUY_TO_OPEN, condition = sucesstest, open[-1], tradesize = buyQ, Color.GREEN, Color.GREEN, "BUY");
 
Last edited by a moderator:
@Camus1612
Not working is not a very detailed explanation. I just wrote the syntax using your logic. Are you saying you are getting a syntax error?
Otherwise, is your logic not correct?
When troubleshooting logic, you can put in labels and chart bubbles to see the values of your calculations to determine if what you think you are calculating is what is actually being done.
 
Last edited:
@Camus1612
Not working is not a very detailed explanation. I just wrote the syntax using your logic. Are you saying you are getting a syntax error?
Otherwise, is your logic not correct?
When troubleshooting logic, you can put in labels and chart bubbles to see the values of your calculations to determine if what you think you are calculating is what is actually being done.
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, open[-1] tradesize = buyQ, Color.GREEN, Color.GREEN, "BUY");
AddOrder(OrderType.SELL_TO_CLOSE, condition = exit, open[-1], 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?
 
Last edited by a moderator:
I am thinking that a 'bar' script is needed to carry the calculated tradesize used in the BUY_TO_OPEN forward
so it is available in the SELL_TO_CLOSE order.
@rad14733 and @barbaros taught me everything I know about Addorders maybe they will weigh in.
 
@Camus1612 Unfortunately, TOS allows for multiple Buys using AddOrder() but I'm fairly certain that Sell orders close the entire trade regardless of how many shares have been bought... Therefore, you can scale into a simulated trade but you cannot scale out...

@MerryDay Thanks for the kind words...
 
@Camus1612 Unfortunately, TOS allows for multiple Buys using AddOrder() but I'm fairly certain that Sell orders close the entire trade regardless of how many shares have been bought... Therefore, you can scale into a simulated trade but you cannot scale out...

@MerryDay Thanks for the kind words...
Thank you for the comment.
So according for what you're saying it should've worked. Because its working perfectly when I'm putting 50 as tradesize but when I put the formula which stated above - I get 0 signals.
What I'm missing here?
 
Good evening,

I have a question that is above my scripting skills, so I have a treading strategy based on one of the VIP indicators, the issue is with the exit part. I want to enter with VIP indicator signal (which i have figured out) but the exit I want to set based on the entry price. Here is my entry code:

Code:
input tradeSize = 100;
AddOrder(OrderType.BUY_TO_OPEN, IN, open[-1], tradeSize, Color.CYAN, Color.CYAN);

Now what I want to happen is exit if the entry price drops down by 2% or goes up by 2%, basically 1 to 1 risk-reward. I have the exit code mapped out too but I just down know how to get the entry price to calculate out 2% win or loss for exit, here is my broken exit strategy code:

Code:
AddOrder(OrderType.SELL_TO_CLOSE, **Idk**, open[-1], tradeSize, Color.MAGENTA, Color.MAGENTA);

any help would be very helpful,

Thank you for your time and happy holidays
 
Last edited by a moderator:
Take a look at this example:

Code:
input length = 20;
input trendSetup = 3;

def BodyMax = Max(open, close);
def BodyMin = Min(open, close);
def IsEngulfing = BodyMax > BodyMax[1] and
    BodyMin < BodyMin[1];
def IsWhite = open < close;
def IsBlack = open > close;
def IsPrevDoji = IsDoji(length)[1];

def Bullish = IsDescending(close, trendSetup)[1] and
    (IsBlack[1] or IsPrevDoji) and
    IsWhite and
    IsEngulfing;

def sell_condition = if Bullish then close else sell_condition[1];
def sell_location = (2/100) * sell_condition;

input tradeSize = 100;

def IN = Bullish;
def OUT = sell_condition - sell_location;
AddOrder(OrderType.BUY_TO_OPEN, IN, open[-1], tradeSize, Color.CYAN, Color.CYAN);
AddOrder(OrderType.Sell_TO_CLOSE, OUT, open[-1], tradeSize, Color.CYAN, Color.CYAN);

plot data = OUT;
data.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
data.SetDefaultColor(Color.YELLOW);
 
Last edited by a moderator:
Hi Ben, thank you for the prompt reply, however, the issue is I don't have an exit strategy. My exit strategy is based on the entry price. So lets say my strategy generates a buy signal and at that time the stock price is 100$ I buy 100 shares at 100$, stop loss is set to $98 and profit-taking is at 102$.

so what I want to do is figure out what my entry price is (AddOrder(OrderType.BUY_TO_OPEN, IN, close[0], tradeSize, Color.CYAN, Color.CYAN)) and then build my exit strategy based on the entry price.

I looked into TOS's Entryprice() function but I cant seem to understand how to make it work.

so basically my exit condition would be either one of these conditions:

def Target = Entryprice() + (entryprice()*0.02)
Def Stoploss = Entryprice() - (entryprice()*0.02)
 
@Learnbot This is what I use. Replace buycondition with your actual entry condition.

Code:
def entryprice = if buycondition then close else entryprice[1];

AddOrder(OrderType.SELL_TO_CLOSE, close >= (entryprice + target) or close <= (entryprice - SL), open[-1], tradeSize, Color.MAGENTA, Color.MAGENTA);
 
Last edited by a moderator:
@Learnbot I just tried it with your code and it works. The "target" in my code is different from your code so change "target" to some number.

Code:
AddOrder(OrderType.SELL_TO_CLOSE, close >= (entryprice + .25) or close <= (entryprice - .10), open[-1], tradeSize, Color.MAGENTA, Color.MAGENTA);

EDIT: Nevermind I see what you mean.
EDIT2: Okay, so it works but depends on your chart timeframe, 1.02*entryprice might be high enough that it won't hit therefore it will never sell but the code I posted does work.
 
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
398 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