AddOrder thinkScript - Backtest Buy & Sell in ThinkorSwim

@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), close[0], tradeSize, Color.MAGENTA, Color.MAGENTA);
You are correct, if I had an exact number than ur suggestion would work like a charm however the issue is entryprice plus xyz number changes because that number is based on the entry price.
sorry to make it super complicated, but i know I am not explaining the exact thing I’m trying to do. Let me try and explain it a little better

so I have a buy condition based on ben’s script, let’s say if condition A meets then I place an order Aka
Code:
input tradeSize = 100;
AddOrder(OrderType.BUY_TO_OPEN, IN, open[-1], tradeSize, Color.CYAN, Color.CYAN);

so the code above buys 100 shares at specific price correct? So my biggest issue is I need a script that tells TOS what that price is because my exit strategy is based on risk reward.

so let’s say the above code bought 100 shares at 100$ per share, I want the exit order to trigger IF the current bar’s close is either $102 (target) or price falls down to $98 (stop loss).

(my stop loss is basically risk reward scenario, I’m risking 2% to make 2%)

hope this clarifies what I’m trying to do And the reason I’m doing this is because not all strategies provide 1 to 1 or 1 to 2 or so on risk rewards, some strategies produce better winning percentage if the RR is correct for that specific strategy.
 
Last edited by a moderator:

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

@Learnbot I tested it with your 2% and it works. There some problems with it because of multiple uparrow signals before sell, ext hour, and lower time frames. This is what the bottom of my code looks like, the 3 line of addlabel code can be removed since I was just using them for checking the code. I tested it with SPY, TSLA, and AMD.

Code:
input tradeSize = 100;

def entryprice = if uparrow then close else entryprice[1];


AddOrder(OrderType.BUY_TO_OPEN, uparrow, close[0], tradeSize, Color.CYAN, Color.CYAN);


def Target = entryprice + (entryprice*0.02);
Def Stoploss = entryprice - (entryprice*0.02);

addlabel(yes, entryprice);
addlabel(yes, target);
addlabel(yes, stoploss);
AddOrder(OrderType.SELL_TO_CLOSE, close >= target or close <= stoploss, open[-1], tradeSize, Color.MAGENTA, Color.MAGENTA);
 
Last edited by a moderator:
function entryprice() must be defined by itself.
As an example: myEntry = entryPrice();
now you can manipulate myEntry anyway you like.
you cannot reference entryPrice until you define it.
 
If I have a plot ArrowDown and/or a plot ArrowUp, then follow it with a AddOrder statement, the arrows are removed from the chart. If I comment out the AddOrder statement, the arrows remain on the chart. How can I get the arrows to remain on the chart and also add an order?
 
Generally, arrows don't disappear with the addition of the AddOrder. It would be easier to pinpoint the problem if you provide the script.
 
Code:
plot ArrowDown = 35.6;
ArrowDown.setpaintingStrategy(paintingStrategy.ARROW_DOWN);
ArrowDown.setDefaultColor(color.white);
ArrowDown.setLineWeight(1);

plot ArrowUp = 35;
ArrowUp.setpaintingStrategy(paintingStrategy.ARROW_UP);
ArrowUp.setDefaultColor(color.white);
ArrowUp.setLineWeight(1);

AddOrder(OrderType.BUY_AUTO, GetQuantity() <> 0, open[-1], GetQuantity(), Color.ORANGE, Color.ORANGE, "FlattedPosition @ " + close);

If I comment out the AddOrder, the arrows show, otherwise the arrows don't show.
 
Last edited by a moderator:
@epete Sorry, still have no idea what you are trying to do. Your arrow syntax still makes no sense to me.

Can you explain what you are trying to do and post an image of the arrows showing up on a chart.
 
It really doesn't matter what type of arrow I plot, adding in the AddOrder seems to blank them out.

Code:
# Moving Average Crossover With Arrows
# Mobius
# Chat Room Request 01.25.2017
# Modified a bit by BenTen

input price = close;
input fastLength = 9;
input slowLength = 20;
input averageType = AverageType.EXPONENTIAL;
input averageType2 = AverageType.SIMPLE;

plot FastMA = MovingAverage(averageType, price, fastLength);
plot SlowMA = MovingAverage(averageType2, price, slowLength);

plot ArrowUp = if FastMA crosses above SlowMA
               then low
               else double.nan;
     ArrowUP.SetPaintingStrategy(PaintingStrategy.Arrow_UP);
     ArrowUP.SetLineWeight(1);
     ArrowUP.SetDefaultColor(Color.Green);

#AddOrder(OrderType.BUY_AUTO, GetQuantity() <> 0, open[-1], GetQuantity(), Color.ORANGE, Color.ORANGE, "FlattedPosition @ " + close);# Moving Average Crossover With Arrows
# Mobius
# Chat Room Request 01.25.2017
# Modified a bit by BenTen

input price = close;
input fastLength = 9;
input slowLength = 20;
input averageType = AverageType.EXPONENTIAL;
input averageType2 = AverageType.SIMPLE;

plot FastMA = MovingAverage(averageType, price, fastLength);
plot SlowMA = MovingAverage(averageType2, price, slowLength);

plot ArrowUp = if FastMA crosses above SlowMA
               then low
               else double.nan;
     ArrowUP.SetPaintingStrategy(PaintingStrategy.Arrow_UP);
     ArrowUP.SetLineWeight(1);
     ArrowUP.SetDefaultColor(Color.Green);

#AddOrder(OrderType.BUY_AUTO, GetQuantity() <> 0, open[-1], GetQuantity(), Color.ORANGE, Color.ORANGE, "FlattedPosition @ " + close);

Here is the chart showing the arrows and without the arrows after uncommenting the AddOrder line.
Chart w-arrows
Chart wo-arrows
 
Last edited by a moderator:
@epete
I haven't looked at what you posted yet.
But based on your description, I am hypothesizing that you have this script saved under the Study tab.
To the right of the Study tab is the Strategy tab.
All scripts containing the AddOrder statement must be saved under the Strategy tab.

PS: the script you posted contains duplicated code.
 
Thanks MerryDay - I had it as a study and not a strategy! Two steps back and one step forward, typical programming. Just starting my journey into ThinkScript. Although, back in the day I did a lot of COBOL and RPG programming... LOL Thank goodness for this forum.
 
Last edited:
It must have been that you did not define an exit condition for the strategy. Also, when you have a backtesting script, you need to add it as a strategy instead of an indicator.

I modified your script a bit and it works.

O8qmUcJ.png


Code:
# Mobius
# Chat Room Request 01.25.2017
# Modified a bit by BenTen

input price = close;
input fastLength = 9;
input slowLength = 20;
input averageType = AverageType.EXPONENTIAL;
input averageType2 = AverageType.SIMPLE;

plot FastMA = MovingAverage(averageType, price, fastLength);
plot SlowMA = MovingAverage(averageType2, price, slowLength);

def ArrowUp = FastMA crosses above SlowMA;
def ArrowDown = FastMA crosses below SlowMA;

AddOrder(OrderType.BUY_TO_OPEN, condition = ArrowUp, price = open[-1],1, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "Long");
AddOrder(OrderType.Sell_TO_CLOSE, condition = ArrowDown, price = open[-1],1, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "Long");

You can continue to build on top of it.
 
Last edited by a moderator:
I want to test a strategy when the Daily and Weekly candles are green. My entry would be placed in a 5 minute timeframe when the previous condition is met and RSI > 30.
 
That can be done using the built in scanner and using the built in WIZARD, give it a try, look on YouTube on how to use the wizard.. these are the setting you requested below

cYihDtf.png
 
After lots of trial and error I've created my first strategy I usually trade in thinkscript however it's not executing trades or sending alerts. Is there any flaw in the code or is thinkscipt not capable of these things? Any help is greatly appreciated!

Code:
#Inputs

input tradesize = 1;
input price = close;
input deviations = 2.0;
input fullRange = Yes;
input length = 21;

#Define

def regression;
def stdDeviation;
if (fullRange) {
    regression = InertiaAll(price);
    stdDeviation = StDevAll(price);
} else {
    regression = InertiaAll(price, length);
    stdDeviation = StDevAll(price, length);
}

def UpperLine = regression + (deviations*.5) * stdDeviation;
def MiddleLine = regression;
def LowerLine = regression - deviations * stdDeviation;

#Signal

#Long Open
def Condition1 = if
price[1] <= LowerLine
then 1 else Double.NaN;

#Long Close
def Condition2 = if
price[1] >= MiddleLine
then 1 else Double.NaN;

#Short Open
def Condition3 = if
price[1] >= Upperline
then 1 else Double.NaN;

#Short Close
def Condition4 = if
price[1] <= MiddleLine
then 1 else Double.NaN;

#Orders

AddOrder(OrderType.BUY_TO_OPEN, Condition1, open[-1], tradesize, Color.CYAN, Color.CYAN);
AddOrder(OrderType.SELL_TO_CLOSE, Condition2, open[-1], tradesize, Color.CYAN, Color.CYAN);
AddOrder(OrderType.SELL_TO_OPEN, Condition3, open[-1], tradesize, Color.CYAN, Color.CYAN);
AddOrder(OrderType.BUY_TO_CLOSE, Condition4, open[-1], tradesize, Color.CYAN, Color.CYAN);


#Alert
Alert(Condition1, "STdaytrader: Long Trade Opened", Alert.ONCE, Sound.NoSound);
Alert(Condition2, "STdaytrader: Long Trade Closed", Alert.ONCE, Sound.NoSound);
Alert(Condition3, "STdaytrader: Short Trade Opened", Alert.ONCE, Sound.NoSound);
Alert(Condition4, "STdaytrader: Short Trade Closed", Alert.ONCE, Sound.NoSound);
 
Last edited by a moderator:
@danwilks12 Did you save it as a study or strategy? I think you might've saved it as a study so change it to strategy and it should work. Also, you usually need to separate the long and short code. Since this looks like regression channel code, it'll look really good on backtest but live trading will be vastly different and profit will also vary based on timeframe so be mindful if you're trading this.
 
You need to add the code above as a strategy, not an indicator.

qOl2ghp.png
 
Last edited by a moderator:
Do you have the study or studies, or are you expecting someone to write all of the code...??? What I mean is have you made any attempt at all...
The only study is MACD and EMA. I don't know were to start I back test with pen and paper. LOL sorry.
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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