AddOrder thinkScript - Backtest Buy & Sell in ThinkorSwim

I don’t see any portfolio functions in the conditional orders section. EntryPrice() is there (but it’s not in the portfolio section).
Also, I checked to confirm I do have “Advanced Trading” turned on from the Ameritrade website, but no portfolio functions available at the conditional order screen. I messaged TD chat support and was told portfolio functions are not available in conditional orders. Did something change?

When you create your Conditional Order you will need to use the Thinkscript Editor instead of the Condition Wizard and manually write your desired code... What you are looking for is beyond the scope of the Condition Wizard... You can use virtually ANY logic Thinkscript in the Thinkscript Editor... You just can't use formatting, plotting, or AddOrder functionality... Stick to conditional logic and you should be fine... 💡
 
Will definitely check that out later tonight... That’s probably where I went wrong, I tried to use the condition wizard when referencing a study that had a portfolio function in the code and got rejected. Thanks for the clarifications RAD 😊
I’ll jump straight into the ThinkScript portion of the conditional orders and then try to either copy/paste a code or write a new code. It kinda boggles me that they wouldn’t just make it easily accessible. Maybe that will be added on a future update.
 
Is there a way to differentiate tradesize by symbol, stocks use 100, futures use 1? I was thinking a combination of getsymbol and some type of string function to search for the "/" in futures, but couldn't really find one.
 
Is there a way to differentiate tradesize by symbol, stocks use 100, futures use 1? I was thinking a combination of getsymbol and some type of string function to search for the "/" in futures, but couldn't really find one.

@pine Unfortunately, Thinkscript doesn't have string manipulation functions...
 
Last edited by a moderator:
I`m trying out the MovAvgTwoLinesStrat. Thing is, I realized it's taking long and short positions. Is there a way to disable the option to take short positions? It's messing up the reports, as I dont short stocks.
 
@Benjaminsabe

Code:
#
# TD Ameritrade IP Company, Inc. (c) 2013-2021
#

input price = close;
input fastLength = 20;
input slowLength = 50;
input averageType = AverageType.EXPONENTIAL;

plot FastMA = MovingAverage(averageType, price, fastLength);
plot SlowMA = MovingAverage(averageType, price, slowLength);
FastMA.SetDefaultColor(GetColor(1));
SlowMA.SetDefaultColor(GetColor(2));

AddOrder(OrderType.BUY_TO_OPEN, FastMA crosses above SlowMA, tickColor = GetColor(1), arrowColor = GetColor(1), name = "MovAvgTwoLinesStratLE");
AddOrder(OrderType.SELL_TO_CLOSE, FastMA crosses below SlowMA, tickColor = GetColor(2), arrowColor = GetColor(2), name = "MovAvgTwoLinesStratSE");
 
I`m trying out the MovAvgTwoLinesStrat. Thing is, I realized it's taking long and short positions. Is there a way to disable the option to take short positions? It's messing up the reports, as I dont short stocks.

You can actually turn them off right in the Strategy Settings Panel by Changing the MovAvgTwoLinesStratLE setting from Auto to Buy To Open and the MovAvgTwoLinesStratSE to Sell To Close...

5ybBN8y.png
 
Setting up a day trading system. Is there an AddOrder argument that would allow me to close a position at the end of day (4:00 EST)?
I imagine an if statement would be needed/

Thanks!
 
I am looking for some insight from you all. I am new to TOS and first question:
Can I do automated trading in TOS?
How reliable are profits in the report (right click /Report) of a strategy? The report is based on internal ticks or only on OHLC candle data?
 
My experience with tos strategy testing is that the p&l figures are off, as on testing the strategy executes at prices you never can.

Maybe others have different experiences
 
My experience with tos strategy testing is that the p&l figures are off, as on testing the strategy executes at prices you never can.

Maybe others have different experiences
You would assume that slippage can take how many % profits away?
 
I remember it was significant but not the exact percent - try an experiment to see when you get your trade signal and where you could execute and then check where tos executed. I kind of remember tos executed at the prices I never saw.

But, maybe its changed, maybe others had different experiences, please dont take my comments as some sort of last word on the topic.
 
Hello all! Forgive my ignorance, but I am trying to build a custom script for backtesting moving average strategies. I have found a script I would like to start with but it does not show up on my charts. I am sure I will need lots of help trying to get the script to do all that I want but I have to figure this out first. Any help would be greatly appreciated! Here is the script.

Code:
input longEntries = yes;
input shortEntries = no;

input fastMALength = 8;
input slowMALength = 21;
input averageTypeFast = AverageType.EXPONENTIAL;
input averageTypeSlow = AverageType.SIMPLE;
input quantity = 100;

plot fastMA = MovingAverage(averageTypeFast, close, fastMALength);
plot slowMA = MovingAverage(averageTypeSlow, close, slowMALength);

AddOrder(OrderType.BUY_TO_OPEN, (longEntries) and fastMA crosses above slowMA, open[-1], quantity);
AddOrder(OrderType.SELL_TO_CLOSE, fastMA crosses below slowMA, open[-1], quantity);

AddOrder(OrderType.SELL_TO_OPEN, (shortEntries) and fastMA crosses below slowMA, open[-1], quantity);
AddOrder(OrderType.BUY_TO_CLOSE, fastMA crosses above slowMA, open[-1], quantity);

AddLabel(yes, fastMALength + (if averageTypeFast == 0 then " Simple" else if averageTypeFast == 1 then " EMA" else if averageTypeFast == 2 then " Weighted" else if averageTypeFast == 3 then " Wilders" else " Hull") + " x " + slowMALength + (if averageTypeSlow == 0 then " Simple" else if averageTypeSlow == 1 then " EMA" else if averageTypeSlow == 2 then " Weighted" else if averageTypeSlow == 3 then " Wilders" else " Hull"), Color.YELLOW);
 
Last edited by a moderator:
How I put the prior day low as a stop loss after my buy signal triggers? And then likewise I’d want to use the same magnitude for my profit target. So if low of prior day was -$1.20 below my entry, I also want profit target of +$1.20
 
@KMcFarland7 Once you have calculated the profit/stop loss target you want you can add it to and subtract it from the EntryPrice() and create AddOrder()'s accordingly... EntryPrice() - target and EntryPrice + target would be your conditions for exits...
 
NEED HELP TO CLEAN THIS BACKTEST STATERGY UP.

Guys this is a tough one for a rookie like me. I decided to back-test an indicator that I found on this site. link in brackets below. I will call it the "TTM ALT:

(https://usethinkscript.com/threads/mobius-momentum-squeeze-experiment-for-thinkorswim.1215/)

I then decided to to see if I could make it into a strategy and alter the could to run as a strategy.
1. I changed the exit to 3 under the 21 EMA.
2. I tried to get the code to match the entry that the TTM ALT shows.
3. I used # to comment out the code I though I did not need
4. it works but it is ugly. The study is still showing up in the back-test area.

HERE IS THE CODE. and thanks.

Code:
# TTM SQUEEZE ALT BACKTEST W CHART v2
input price = CLOSE;
input ShortLength1 = 5;
input ShortLength2 = 14;
input ShortLength3 = 5;
input LongLength1 = 12;
input LongLength2 = 55;
input LongLength3 = 7;

# Momentum Oscillators

plot MS = Average(Average(price, ShortLength1) - Average(price, ShortLength2), ShortLength3);
plot MS2 = Average(Average(price, LongLength1) - Average(price, LongLength2), LongLength3);
# Wave A
def MSGreens = If (MS >= 0, MS, 0);
def MSReds = If (MS < 0, MS, 0);
# Wave C
def MS2Blues = If (MS2 >= 0, MS2, 0);
def MS2Yellows = If (MS2 < 0, MS2, 0);

plot MS_Pos = MSGreens;
MS_Pos.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
MS_Pos.AssignValueColor(if MSGreens < MSGreens[1] then Color.GREEN else Color.DARK_GREEN);

plot MS_Neg = MSReds;
MS_Neg.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
MS_Neg.AssignValueColor(if MSReds < MSReds[1] then CreateColor(255, 60, 60) else Color.DARK_RED);

plot MS2_Pos = MS2Blues;
MS2_Pos.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
MS2_Pos.AssignValueColor(if MS2Blues < MS2Blues[1] then Color.BLUE else Color.CYAN);

plot MS2_Neg = MS2Yellows;
MS2_Neg.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
MS2_Neg.AssignValueColor(if MS2Yellows < MS2Yellows[1] then Color.YELLOW else Color.LIGHT_RED);

# Squeeze Indicator

input length = 20;
input nK = 1.5;
input nBB = 2.0;

def BBHalfWidth = StDev(price, length);
def KCHalfWidth = nK * Average(TrueRange(high,  close,  low),  length);
plot isSqueezed = nBB * BBHalfWidth / KCHalfWidth < 1;
isSqueezed.Hide();
plot BBS_Ind = If(isSqueezed, 0, Double.NaN);
BBS_Ind.SetPaintingStrategy(PaintingStrategy.SQUARES);
BBS_Ind.SetLineWeight(3);
BBS_Ind.AssignValueColor(Color.RED);

# Bollinger Resolution

def BBSMA = Average(price, length);
def BBSMAL = BBSMA + (-nBB * BBHalfWidth);
def BBSMAU = BBSMA + (nBB * BBHalfWidth);
def PerB = RoundUp((price - BBSMAL) / (BBSMAU - BBSMAL) * 100, 0);

#BELOW NOT NEEDED FOR BACKTEST.
#AddLabel(yes, Concat("%B: ", PerB), if PerB < 0 then Color.YELLOW else if PerB > 0 and PerB[1] < 0 then Color.GREEN else Color.WHITE);

# Parabolic SAR Signal

input accelerationFactor = 0.0275;
input accelerationLimit = 0.2;

def SAR = ParabolicSAR(accelerationFactor = accelerationFactor, accelerationLimit = accelerationLimit);
plot bearishCross = Crosses(SAR, price, CrossingDirection.ABOVE);
bearishCross.Hide();
# plot signalDown = If(bearishCross, 0, Double.NaN);
# signalDown.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
# signalDown.SetLineWeight(3);
# signalDown.AssignValueColor(Color.DOWNTICK);

def ema3 = ExpAverage(close, 3);
def ema21 = ExpAverage(close, 21);

# ADDED FOR EXITS
def BearishTrade = if ema21 > EMA3 and ema21[1] <= ema21[1] then 1 else 0;


plot bullishCross = Crosses(SAR, price, CrossingDirection.BELOW);
bullishCross.Hide();
plot signalUp =  If(bullishCross, 0, Double.NaN);
signalUp.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
signalUp.SetLineWeight(3);
signalUp.AssignValueColor(Color.UPTICK);

AddOrder(OrderType.BUY_TO_OPEN, bullishCross, open[-1], 100);
# AddOrder(OrderType.Sell_To_Close, high>= entryPrice() + entryPrice()*0.03, entryPrice() + entryPrice()*0.03, 100);
# ORIFINAL BELOW
# AddOrder(OrderType.Sell_To_Close, bearishCross, open[-1], 100);
# ADDED FOR BETTER TRADE
AddOrder(OrderType.SELL_TO_CLOSE, BearishTrade, open[-1], 100);


#AddOrder(OrderType.Sell_To_Open, bearishCross, open[-1], 100);
#AddOrder(OrderType.Buy_To_Close, low <= entryPrice() - #(entryPrice()*0.03),  entryPrice() - (entryPrice()*0.03), 100);
#AddOrder(OrderType.Buy_To_Close, bullishCross, open[-1], 100);
 
Last edited by a moderator:

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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