AddOrder thinkScript - Backtest Buy & Sell in ThinkorSwim

Hey!
I have been backtesting and I want to test taking incremental profits. In this case, selling 1 contract at 1 atr, 1 at 2, and 1 at three.
This code is for the last part of the strategy and does not have all the variables. It is not optimal, but I am learning.

Code:
#keltner channels
input kdisplace = 0;

def shift1 = 1 * MovingAverage( AverageType.SIMPLE, TrueRange(high, close, low), 21);
def shift2 = 2 * MovingAverage( AverageType.SIMPLE, TrueRange(high, close, low), 21);
def shift3 = 3 * MovingAverage( AverageType.SIMPLE, TrueRange(high, close, low), 21);

def kaverage = MovingAverage( AverageType.SIMPLE, price, length);

def Upper_Band1 = kaverage[-displace] + shift1[-displace];
def Upper_Band2 = kaverage[-displace] + shift2[-displace];
def Upper_Band3 = kaverage[-displace] + shift3[-displace];

#profit targets
def profit1 = close crosses above Upper_Band1;
def profit2 = close crosses above Upper_Band2 or close crosses below Upper_Band1;
def profit3 = close crosses above Upper_Band3 or close crosses below Upper_Band1 or close crosses below Upper_Band2;

#stop
def stop = close < ema34 and close[1] < ema34;

AddOrder(OrderType.BUY_TO_OPEN, buy, close, 3, tickcolor = Color.GREEN, arrowcolor = Color.GREEN);
AddOrder(OrderType.SELL_to_close, profit1, close, 1, tickcolor = Color.RED, name = "Profit1");
AddOrder(OrderType.SELL_to_close, profit2, close, 1, tickcolor = Color.RED, name = "Profit2");
AddOrder(OrderType.SELL_to_close, profit3, close, 1, tickcolor = Color.RED, name = "Profit3");
AddOrder(OrderType.SELL_to_close, sell, close, 1, tickcolor = Color.RED, name = "Turned");
AddOrder(OrderType.SELL_to_close, stop, close, 3, tickcolor = Color.RED, name = "Stop");

The code keeps opening a position at 3 contracts and then at profit1 it will sell all the contracts. I have tried sell_auto but it then opens a short position.

Is it possible to take incremental profits and not open new short positions?
I'm not aware of a way to take incremental profits, sorry.
@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...

Reference link: https://usethinkscript.com/threads/...t-auto-buy-sell-in-thinkorswim.741/post-41368
 
Last edited by a moderator:

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

Hello,
So I am learning here so please go easy on me lol. So I am trying to create a strategy to backtest as follows:

Buy Condition = buy when MACD value is below zero and value crosses above avg.
Edit Condition = Price when buy condition was triggered minus lowest of the price candle and add that to Price at buy condition.
- So let's say Buy condition was triggered when TSLA at 600$, and the lowest of the past three candles is 595. So the target exit would be 600+(600-595) = when the close crosses above 605.

Here is my simple script:
Code:
input tradesize = 10;

def Cross = MACD()."Value" is less than or equal to MACD()."ZeroLine" and MACD()."Value" crosses above MACD()."Avg";
def A = if cross then lowest(low,3) else cross[1];
def B = if cross then close else cross[1];
def Target = B+(b-a);

AddOrder(OrderType.BUY_TO_OPEN, cross, close[0], tradesize, Color.CYAN, Color.CYAN);
AddOrder(OrderType.SELL_TO_CLOSE, close>=target or close <a , close[0], tradesize, Color.MAGENTA, Color.MAGENTA);

ISSUE: So as you can see from the image, it seems like entry and exit are being triggered almost at the same time and I cant figure out why, I tried info posted here: https://usethinkscript.com/threads/...buy-sell-in-thinkorswim.741/page-8#post-42477. But I am still not able to figure it out...
GOv22H9.png



Thank you for your help, I really appreciate it
@Learnbot, [I realize this is a belated response, but it might help someone else with a similar question.

Instead of this:
Code:
def A = if cross then lowest(low,3) else cross[1];
def B = if cross then close else cross[1];

Try this:
Code:
def A = if cross then lowest(low,3) else A[1];
def B = if cross then close else B[1];

Rationale:
1. The way you've defined cross, it's value is 1 or 0.
2. The way you've defined B and A, It's possible for B and A to be assigned the Cross value (1 or 0) (look at your "ELSE" statement).
3. I'm assuming you actually want A and B to have their prior values as an ELSE condition, not prior values for "Cross".
Note: The "try this" code snippet above should replace your "def A" and "def B".

Example Code below uses plots to demonstrate the problem in your original code. Load up the Databox to more easily visualize the plot values. (The technique of using plots or labels to determine values is oft-mentioned across this site. Hope this example helps!)

Example Code to demonstrate the issue.
Code:
declare lower;
def Cross = MACD()."Value" is less than or equal to MACD()."ZeroLine" and MACD()."Value" crosses above MACD()."Avg";
def A = if cross then lowest(low,3) else cross[1];
def B = if cross then close else cross[1];
def Target = B+(b-a);

plot valueCross = Cross;
plot valueA = A;
plot ValueB = B;
plot ValueTarget = Target;
valueCross.SetDefaultColor(Color.WHITE);
valueA.SetDefaultColor(Color.RED);
ValueB.SetDefaultColor(Color.YELLOW);
ValueTarget.SetdefaultColor(Color.CYAN);

To replicate, you can use an AAPL Daily chart, from 3/14/2022

Databox from your original code:

UT7F2Zs.png


Databox from fixed code:

yuSWnij.png


References:
https://tlc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/def
https://tlc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/plot
https://tlc.thinkorswim.com/center/howToTos/thinkManual/charts/Useful-Tools/Data-Box
 
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.

View attachment 8449
I know this post is quite old, but does anyone what the complete stochastic crossing stochastic line is in the above post. I am unfamiliar with using a stochastic crossing over another stochastic. Just trying to learn something. :)
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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