AddOrder thinkScript - Backtest Buy & Sell in ThinkorSwim

Appreciate the quick reply DBSully. I am trying to adapt this idea to another forum members strategy that they posted here. Actually it is J007RMC's Pivot Confirmation with Trading Levels - https://usethinkscript.com/threads/pivot-confirmation-with-trading-levels.1843/#post-16985 . I am liking what they have done with that.

Their coding level and yours are above my skill level. I am trying to get the AddOrders to follow his coding and make the full and partial trades at the pivot levels he is using. Thought it would be a great way to learn by trying to deconstruct how things work :). I am plodding along and am sure I will need further help in the future.

Cheers,
Rick
 
Last edited by a moderator:
@RickAns The best way to learn is to keep doing what you are doing. Break apart the different lines of code in other people's studies and strategies, and figure out how each part works. Thinkscript is an odd language, but you'll be surprised at how far you can get if yo stick with it. This site is amazing - lots of help here.
 
Hello All,
Thank you for your time. I've got code that will enter an order using AddOrder, I want the order to exit once I've hit a stop or take profit once I've hit a limit. But all I've found is getting out on some other indicator like the candles position against a MA or something. Also I cannot create my open order with a 'trailing stop' type which would be similar.

This is what I tried as an exit, but it only exits on the MA (last line). Also I cant add an AddOrder inside an if statement so that does not help.

Basically how can I get pl of an order I just entered ?

Code:
# sell if you can make 100
AddOrder(OrderType.BUY_TO_CLOSE,GetOpenPL()> 100, open[-1], 100, Color.ORANGE, Color.BLUE);
# sell if you will loose 50
AddOrder(OrderType.BUY_TO_CLOSE,GetOpenPL() < -50, open[-1], 100, Color.ORANGE, Color.BLUE);
# get out of short position when first candle above moving average

AddOrder(OrderType.BUY_TO_CLOSE, low > AVG1 , open[-1], 100, Color.RED, Color.RED);

Can anyone tell me what the -1 means in open[-1] ? Does it mean the open of the next candle ?

Thanks !
 
Does this help?

https://tlc.thinkpipes.com/center/charting/thinkscript/reference/Functions/Others/EntryPrice.html
EntryPrice();

Description
Returns the price of the entry order. For several entry orders in the same direction as the currently held position the function returns the average price for all of them.

Example
AddOrder(OrderType.SELL_TO_CLOSE, close > EntryPrice() + 3 or close < EntryPrice() - 9);

Adds a Sell order for closing a long position when the Close price is either greater than the entry price by 3 (for taking profits) or less by 9 (for safety).
 
Glad to help, hope it works. :)

I thought the EntryPrice() + 'Whatever your limit number' would be handy for the stop exit.

Believe I read somewhere (but not verified) that numbers or percentages could be used for something like that. Such as up 100 points or up 50% from said price. Of course it was from another page with different examples which I cannot find at the moment. Also may be confusing two separate things completely. Been reading through a lot of stuff trying to learn.
 
Last edited by a moderator:
Hi RickAns,
Thanks yes it worked exactly as expected. So you can compare the current price with the price at which you entered. So lets say you bought when the symbol was at 500 then you could sell when the symbol gets to $5 more than your entry or $5 less and so on. In backtesting it proved to be a very poor strategy for me to implement.
Code:
# if goes up $5 or goes down $3,
AddOrder(OrderType.SELL_TO_CLOSE, close < (EntryPrice()-3) or close > (EntryPrice()+5) , open[-1], 100, Color.RED, Color.RED);
 
Last edited by a moderator:
Does a strategy always buy/sell 100 units? Or can this be adjusted somehow? For reference I have a sample code located below
Code:
input price = close;
input length = 34;
input displace = 0;

def AvgExp = HullMovingAvg(price[-displace], length);

plot Value = 1;

Value.AssignValueColor(if price > avgExp then color.GREEN else Color.RED);
Value.SetPaintingStrategy(PaintingStrategy.LINE_VS_POINTS);

AddOrder(OrderType.BUY_AUTO, price crosses above AvgExp);
AddOrder(OrderType.Sell_AUTO, price crosses below AvgExp);
 
I have something for you, it does require some tweaking though. It also has been the best workaround since TOS does not give WR, only P/L.

The idea is to isolate winning trades as a gain of 1 and losing trades as a loss of 1, regardless of whether it was a big or small loss.

https://tos.mx/SWDW3kQ
Code:
##Template for counting strategies
#Updated: 4.25.2020 by DeftMove - gkc
#Negative and positive winrate represented by DOLLAR AMOUNT P/L in report above/below zero

#PLACE STUDIES HERE


input tradeLot = 1; #hint tradeLot: Number of shares per order.
input analyzeWR = yes; #hint analyzeWR = if YES, dollar amounts P/L in report above/below zero are considered win/loss discrepancy. if NO, dollar amounts P/L in report are considered P/L
input runBuyAnalysis = yes; #hint runBuyAnalysis: if YES, run upward plays, if NO, prevent upward plays
def entryConditionBuy = ; #edit for each strategy, UP ENTRY CONDITIONS
def exitConditionBuy  = ; #edit for each strategy, UP EXIT  CONDITIONS
def exitGoodBuy = open[-1] > EntryPrice();
def exitBadBuy  = open[-1] < EntryPrice();

AddOrder(OrderType.BUY_TO_OPEN, condition = entryConditionBuy and runBuyAnalysis, price = open[-1], tradeLot, name = "BuyOpen " + open[-1]);
AddOrder(OrderType.SELL_TO_CLOSE, runBuyAnalysis and exitConditionBuy and exitGoodBuy, price = if analyzeWR then EntryPrice() + 1 else open[-1], tradeLot, name = "SellClose " + open[-1] + "P/L: " +  (open[-1] - EntryPrice()));
AddOrder(OrderType.SELL_TO_CLOSE, runBuyAnalysis and exitConditionBuy and exitBadBuy, price = if analyzeWR then EntryPrice() - 1 else open[-1], tradeLot, name = "SellClose " + open[-1] + "P/L: " +  (open[-1] - EntryPrice()));

input runSellAnalysis = yes; #hint runSellAnalysis: if YES, run downward plays, if NO, prevent downward plays
def entryConditionSell = ; #edit for each strategy, DOWN ENTRY CONDITIONS
def exitConditionSell = ; #edit for each strategy, DOWN EXIT  CONDITIONS
def exitGoodSell = open[-1] < EntryPrice();
def exitBadSell  = open[-1] > EntryPrice();

AddOrder(OrderType.SELL_TO_OPEN, condition = entryConditionSell and runSellAnalysis, price = open[-1], tradeLot, name = "SellOpen " + open[-1]);
AddOrder(OrderType.BUY_TO_CLOSE, runSellAnalysis and exitConditionSell and exitGoodSell, price = if analyzeWR then EntryPrice() - 1 else open[-1], tradeLot, name = "BuyClose " + open[-1] + "P/L: " + (EntryPrice() - open[-1]));
AddOrder(OrderType.BUY_TO_CLOSE, runSellAnalysis and exitConditionSell and exitBadSell, price = if analyzeWR then EntryPrice() + 1 else open[-1], tradeLot, name = "BuyClose " + open[-1] + "P/L: " + (EntryPrice() - open[-1]));

Your strategy/studies need to generate entry and exit conditions for upward and downward trades for this to work. Place them in the conditions indicated.

Once you click the reports, the default settings will give you a P/L in dollar amounts. Positive amounts mean your strategy has a >50% win rate, negative means it is <50% WR.

Calculate WR by this equation:
[ (#TotalTrades - P/L) / 2 + P/L ] /#TotalTrades

There are toggles for upward or downward trades as well as to switch off WR and show P/L instead. Lastly, if you want more lots traded per order, there is an input for that as well.

Also, please let me know if there could be any improvements. I just started working on this a two days ago after I learned that strategies exist and I doubt my code is streamlined (not a code writer IRL)
 
I am new to thinkscript and would appreciate any help in writing the thinkscript code for a buy/sell strategy based on ADX and DMI+; DMI- trends on a 30m chart:

Long Entry (LE)
  • Using a 30 min stock chart along with the DMI(14, Wilders) study
  • Starting with the condition that ADX <20 and below both DI- and DI+
  • When the ADX crosses above DI-, then show the LE symbol on the chart
  • When the current ADX moves lower than the previous ADX one bar ago, then show LE - Exit symbol on the chart

Short Entry (SE)
  • Using a 30 min stock chart along with the DMI(14, Wilders) study
  • Starting with the condition that ADX <20 and below both DI- and DI+
  • When the ADX crosses above DI+, then show the LE symbol on the chart
  • When the current ADX is lower than the previous ADX one bar ago, then show LE - Exit symbol on the chart
Any assistance on writing my strategy would be much appreciated.
 
You mean like this or on the candlestick chart? Change arrows, I just changed colors so screwed up the colors a bit.

Code:
#aADX_DMI2 With slow moving average of ADX and Arrows

declare lower;
input MACDfastLen = 10;
input MACDslowLen = 30;
input MACDLen = 10;
input showADX_DMI = { "No", default "Yes"};
input showMACD = { "No", default "Yes"};
input invertNegMACD = { "Yes", default "No"};
input MACDHeight = 50;
input MACDWidth = 3;
input ADX_Avg = 3;
input DMI_Len = 9;
input No_Trend = 20;
input Low_Trend = 45;
input Strong_Trend = 60;


def fastAvg = EMA2(data = close, "smoothing factor" = 2 / (1 + MACDfastLen));
def slowAvg = EMA2(data = close, "smoothing factor" = 2 / (1 + MACDslowLen));
def Value = fastAvg - slowAvg;
def nextAvg = ExpAverage(data = Value, MACDLen);
def HistoBar = Value - nextAvg[1];
def HiScale = HighestAll(HistoBar);
def LoScale = AbsValue(LowestAll(HistoBar));
def BarScale = if HiScale > LoScale then HiScale else LoScale;

plot macd_plot = If (showMACD, If( invertNegMACD, If ( HistoBar < 0, ( -1 * HistoBar * MACDHeight / BarScale ), ( HistoBar * MACDHeight / BarScale )), HistoBar * MACDHeight / BarScale), Double.NaN);

macd_plot.AssignValueColor(if invertNegMACD then if HistoBar >= 0 then Color.CYAN else Color.MAGENTA else Color.CYAN);
macd_plot.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
macd_plot.SetLineWeight(MACDWidth);

def hiDiff = high - high[1];
def loDiff = low[1] - low;
def plusDM = if hiDiff > loDiff and hiDiff > 0 then hiDiff else 0;
def minusDM = if loDiff > hiDiff and loDiff > 0 then loDiff else 0;
def ATR = WildersAverage(TrueRange(high, close, low), DMI_Len);
plot "DI+" =
if showADX_DMI then 100 * WildersAverage(plusDM, DMI_Len) / ATR
else Double.NaN;
plot "DI-" =
if showADX_DMI then 100 * WildersAverage(minusDM, DMI_Len) / ATR
else Double.NaN;
def DX =
if ("DI+" + "DI-" > 0) then 100 * AbsValue("DI+" - "DI-") / ("DI+" + "DI-")
else 0;
plot ADX = if showADX_DMI then WildersAverage(DX, DMI_Len) else Double.NaN;
plot ADXAvg = if showADX_DMI then ExpAverage(ADX, ADX_Avg) else Double.NaN;
plot NoTrend = No_Trend;
plot LowTrend = Low_Trend;
plot StrngTrend = Strong_Trend;

plot ArrowUp = if "DI-" crosses above ADXAvg
               then  "DI-"
               else double.nan;
     ArrowUP.SetPaintingStrategy(PaintingStrategy.Arrow_UP);
     ArrowUP.SetLineWeight(3);
     ArrowUP.SetDefaultColor(Color.White);
plot ArrowDN = if "di+" crosses above ADXAvg
               then "di+"
               else double.nan;
     ArrowDN.SetPaintingStrategy(PaintingStrategy.Arrow_DOWN);
     ArrowDN.SetLineWeight(3);
     ArrowDN.SetDefaultColor(Color.Yellow);
Alert(ArrowUp, " ", Alert.Bar, Sound.Chimes);
Alert(ArrowDN, " ", Alert.Bar, Sound.Bell);

plot ArrowUpTrend = if "DI+" crosses above "DI-"
               then "DI-"
               else Double.NaN;
ArrowUpTrend.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
ArrowUpTrend.SetLineWeight(3);
ArrowUpTrend.SetDefaultColor(Color.green);
plot ArrowDNTrend = if  "DI+" crosses below "DI-"
               then "DI-"
               else Double.NaN;
ArrowDNTrend.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
ArrowDNTrend.SetLineWeight(3);
ArrowDNTrend.SetDefaultColor(Color.red);

"DI+".SetDefaultColor(Color.GREEN);
"DI-".SetDefaultColor(Color.RED);
ADX.SetDefaultColor(Color.WHITE);
ADXAvg.SetDefaultColor(Color.YELLOW);
 
Hey!

First of all not a coding wizard (you probably guessed by the title) but I have an interesting strategy to share and request help for converting this into a strategy for backtesting. Idk the source for this but I made some tweaks and here are the rules:

Longs:
Entry:
1. The 21 Period Linear regression curve > 100 Period Linear regression curve > 100 Period Simple Moving Average
2. The Aroon Up plot > Aroon Down plot
3. The slope of the 100 SMA > 0

Exit:
1. When any of those conditions are invalidated
-- or at an area (this one is on you)

Shorts are the exact opposite.

I have been using it mainly on the 1 Minute chart on futures (mainly /ES) and have got great results so far

Here is my chart w a custom slope indicator for the SMA: https://tos.mx/AmJUiJ1

Here are some example trades (these are on /ES):

Longs:
Trade 1: Entry: 3118, Exit: 3121 = 3 Points up
Trade 2: 3124.75 - 3124.25 = -0.5 Points down
Trade 3: 3127.5 - 3127.5 = Break even

kM6vmoz.png


Shorts:
Trade 1: Entry: 3052.5, Exit: 3011.25 = 41.25 Points up (*granted, not every trade will be like this)

yeA2zVR.png


I'll try my best to answer questions and open to discussion regarding the strat.

Thanks guys!

:)
 
Last edited:
Perhaps something like this:

Code:
# 1. The 21 Period Linear regression curve > 100 Period Linear regression curve > 100 Period Simple Moving Average
# 2. The Aroon Up plot > Aroon Down plot
# 3. The slope of the 100 SMA > 0

def cond_1 = linearRegCurve(length=21) > linearRegCurve(100);
def cond_2 = AroonIndicator().up > aroonIndicator().down;
def cond_3 = SimpleMovingAvg(length=100) > SimpleMovingAvg(length=100)[1];

addOrder(OrderType.BUY_TO_OPEN, cond_1 and cond_2 and cond_3);
addOrder(OrderType.SELL_TO_CLOSE, !cond_1 or !cond_2 or !cond_3);

Not sure what the results will look like, and this uses BUY_TO_OPEN rather than BUY_AUTO. Change as you see fit.

-mashume
 
Last edited:
There is a strat like this already on TOS called GoldenCrossBreakouts but I had to modify it a bit.
Here it is:
Code:
# TD Ameritrade IP Company, Inc. (c) 2017-2020
#
# edited by adii800

input fastLength = 8;
input slowLength = 34;
input averageType = AverageType.EXPONENTIAL;

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

AddOrder(OrderType.BUY_AUTO, FastMA crosses above SlowMA, tickColor = GetColor(1), arrowColor = GetColor(1), name = "EMACossover", tradeSize = 1);
AddOrder(OrderType.SELL_AUTO, FastMA crosses below SlowMA, tickColor = GetColor(2), arrowColor = GetColor(2), name = "EMACrossover", tradeSize = 1);

I highly recommend using some type of trend filter such as MACD or Aroon Indicator or something along those lines to avoid some losses.
 
Last edited:
Is it possible to get intraday backtest of more than 1 year in tos or in any other third party service thank you
 
Last edited:
I would like to adjust my backtesting strategy to enter an opening order in the opposite direction of my closing simultaneously. The AddOrders trigger when a boolean up / down arrow is triggered. The order fills on the candle after the arrow.

Example of order flow:

Arrow up, next candle BTO (time elapses) Down arrow, next candle STC (time elapses) Down arrow, next candle STO (time elapses) Up arrow, next candle BTC

Goal:
Arrow up, next candle BTO (time elapses) Down arrow, next candle STC + STO (time elapses) Down arrow, no action (time elapses) Up arrow, next candle BTC + BTO.

Code:
def TimeOpen = SecondsFromTime(0950); #function is eastern time zone
def TimeClose = SecondsFromTime(1530); #function is eastern time zone
def AfterClose = SecondsTillTime(1530); #function is eastern time zone

#closing orders
AddOrder(OrderType.SELL_TO_CLOSE, (TimeOpen >= 0 and TimeClose <= 0) and bearishTrigger, open[-1], 1, Color.PINK, Color.PINK, "STC" + " " + hl2);
AddOrder(OrderType.BUY_TO_CLOSE, (TimeOpen >= 0 and TimeClose <= 0)and bullishTrigger, open[-1], 1, Color.ORANGE, Color.ORANGE, "BTC" + " " + hl2);

#opening orders
AddOrder(OrderType.BUY_TO_OPEN, (TimeOpen >= 0 and TimeClose <= 0) and bullishTrigger, open[-1], 1, Color.YELLOW, Color.PINK, "BTO" + " " + hl2);
AddOrder(OrderType.SELL_TO_OPEN, (TimeOpen >= 0 and TimeClose <= 0) and bearishTrigger, open[-1], 1, Color.BLUE, Color.YELLOW, "STO" + " " +hl2);

#ending day order
AddOrder(OrderType.Buy_To_Close, (AfterClose <= 0) and bullishTrigger, open[-1], 1, Color.YELLOW, Color.YELLOW, "BTC" + " " +hl2);
AddOrder(OrderType.Sell_To_Close, (AfterClose <= 0) and bearishTrigger, open[-1], 1, Color.PINK, Color.PINK, "STC" + " " + hl2);
 
Last edited by a moderator:
@LetsGetItDone Welcome to the forum! I believe your question is stated clearly, it may have been overlooked. :) Perhaps try "Buy_Auto" instead of "Buy To Open", and "Sell_Auto" in place of "Sell To Open"? Buy/Sell_Auto strategy orders automatically reverse the trade when placed.
 
@LetsGetItDone In the picture you linked, doesnt the BUY_AUTO and SELL_AUTO snip show that it is reversing the trade on the same candle? It does look as if the bearishTrigger and bullishTrigger conditions are placed in the wrong order types.

Here is a picture of a simple SMA crossover strategy that buys and sells on the same candle in the same way as your snip shows.

ffFTZqF.png
 
Last edited:

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
383 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