Strategy based on ema crossover


Category:
0
0

I am trying to backtest a strategy of 9/20 ema crossing (buying or shorting on the crossover) and am having a little issue. My code will initiate the initial buy when I want it to but it won’t sell out and rebuy when the criteria is met. Any thoughts? I am newish to coding but here is my code:  (*Note: on the sell command, I have two duplicate lines of the order to create a reversal trade, otherwise it would just sell my position to 0.)

input shortMAlength = 9;
input longMAlength = 20;

def shortMA = ExpAverage(length = shortMAlength, data = CLOSE);
def longMA = ExpAverage(length = longMAlength, data = CLOSE);

def buy = shortMA > longMA;

addOrder(OrderType.BUY_TO_OPEN, buy, name = “BUY”);

def sell = shortMA < longMA;

addOrder(OrderType.SELL_TO_OPEN, sell, name = “SHORT”);

addOrder(OrderType.SELL_TO_OPEN, sell, name = “SHORT”);

Marked as spam
Posted by (Questions: 1, Answers: 1)
Asked on July 28, 2019 9:54 am
279 views
0
Private answer

I updated the title of your question so that it describes the context of your request. The title you had: "TOS Strategy Coding" was far too vague and would not assist viewers seeking a similar solution.

As to your code. I see a few mistakes. One is that you have duplicated the sell order. That will not help at all. But it will not create the problem you have described. The real problem is being caused by your application of order types. You can get full details here:

http://tlc.thinkorswim.com/center/reference/thinkScript/Constants/OrderType.html

So there are six order types. And they are meant to be used in pairs. For instance if you want to open a long position and close that same long position you would use these two order types. One for each of the AddOrder() statements:

OrderType.BUY_TO_OPEN
OrderType.SELL_TO_CLOSE

You see that? One is the entry (TO_OPEN), and the other is the exit (TO_CLOSE). In your code you are using the wrong order type for your sell order. You are using:

OrderType.SELL_TO_OPEN

And you should be using:

OrderType.SELL_TO_CLOSE

If you wanted a pair of order types to produce a "stop and reverse" type of strategy then you would use these two order types:

OrderType.BUY_AUTO
OrderType.SELL_AUTO

When these two order types are used it will cause the strategy to always be in a position. The BUY_AUTO will close out any short position and go long. The SEL_AUTO will close out any long position and go short.

Marked as spam
Posted by (Questions: 37, Answers: 4079)
Answered on July 28, 2019 11:21 am
0
Thank you! I thought that was for at the "open" of the market. I will read up on your tutorials. Thanks again for the clear advice!
( at July 28, 2019 11:31 am)