Buy and sell prices

I am a novice coder (obviously) and do not know how to code the formula below to get the proper buy and sell prices. I want the buyprice = .01 above EMA10 and the sellprice = .01 below EMA50. That is to say when the price goes above EMA10 buy immediately and when the price goes below EMA50 sell immediately. I have been at this for two days including checking out this forum as well as the AB help menu and simply cannot figure it out. I know it is fairly simply but again I am a novice. Any help would be greatly appreciated. Thank you!!! Neil

SetOption ("initialequity", 100000 ) ; 
setPositionSize( 2, spsPercentOfEquity);
SetOption ("ActivateStopsImmediately", True ) ; 
SetOption ("AllowSamebarExit", True ) ; 
SetTradeDelays (0,0,0,0);

numTicks = Optimize ( "Stop", 1, 1, 10 , 1 ); 


VolumeAverage = MA ( Volume , 20 ) ; 
volumefilter = VolumeAverage > 50000 AND volumeaverage < 4000000;

EMA10 = EMA(C, 10);
EMA25 = EMA (C, 25);
EMA100 = EMA(C,100); 
EMA50 = EMA (C, 50);
EMA200 = EMA(C, 200);



Buy  = Cross (High, EMA 10) AND High >10 AND volumefilter; 
Sell = Cross (EMA50, Low); 
SellPrice = ?
BuyPrice = ?

applyStop (stopTypeloss, stopModePoint,  numticks* TickSize, True );


There is one conceptual problem with this idea. Your system is using close price for calculations (and you can only know the close price after trading session end), yet you want it to trade before the close (in the middle of the day). That is a future leak in the idea itself.

A naive answer would be:

BuyPrice = EMA10;
SellPrice = EMA50;

but both EMAs are only known at the session close. Backtesting such a system would give you over-optimistic results, non-reproducible in practice.

A 100% safe system (from future leaks point of view) uses previous bar data to calculate signals for current bar. A "bleeding edge" system would be trading on current bar close using current bar data (in practice it means calculating the system few seconds before close and placing order on close accepting some slippage). A "breakout" system can trade intraday, if it only uses current bar open price for calculations and eventually high/low for the trigger only.

All other cases are better handled and precisely backtested if you backtest using intraday data instead. That way you know what happens during the day.

1 Like

That is a good point . I would have to figure out how to reference the previous days EMA's. Either way using buyprice = EMA10 and Sellprice = EMA50 my stops do not work which is the same problem I was having before. My trades only exit on EMA crosses never on stops?

In debugging the system it is useful to do things one step at a time and use "divide and conquer" strategy as described here: How do I debug my formula?

If you want to check stops, disable temporarily regular exits using:

Sell = 0; 

and only leave ApplyStop, so you can see when stops are generated.
Chances are that your regular exits simply come earlier.

2 Likes

No sir. Instead of my stops being executed at my stop price they are executed at the next days low.

As I wrote - it is your task to understand your own code. Previously you wrote "my stops do not work " now you say they actually work but the execution price is incorrect.
You see your data, your screen and your formula. We don't.
It is your task to check things. Stop can be executed at low if for example the low is actually equal to open and stop is triggered by the gap (at open). Because stop could not be executed earlier, it is executed at first time when it can be executed (the open). Again - you see your data and it is up to you to check.

@neilrosenbloom ,
To reference an earlier value:

buyprice = Ref(EMA10,-1);  // Use prior bar EMA value
2 Likes

I am sorry I used the wrong terminology; as I said I am a novice. I included my formula in my original post and spent days trying to debug it, but I simply have not been able to. There are occasions where there are gaps but more often it just trades through my stop and gets me out on the next days low. I though adding SetTradeDelays (0,0,0,0); would do the trick but it has not. I am willing to work at this and not just ask for help without putting in the effort but after several days of attempting to figure out what I am doing wrong I decided to ask for help!!! Here is my formula with your suggested sellprice and buyprice:

SetOption ("initialequity", 100000 ) ; 
setPositionSize( 2, spsPercentOfEquity);
SetOption ("ActivateStopsImmediately", True ) ; 
SetOption ("AllowSamebarExit", True ) ; 
SetTradeDelays (0,0,0,0);

numTicks = Optimize ( "Stop", 1, 1, 10 , 1 ); 


VolumeAverage = MA ( Volume , 20 ) ; 
volumefilter = VolumeAverage > 50000 AND volumeaverage < 4000000;

EMA10 = EMA(C, 10);
EMA25 = EMA (C, 25);
EMA100 = EMA(C,100); 
EMA50 = EMA (C, 50);
EMA200 = EMA(C, 200);

Buy =  Cross (High, ema10) AND high > 10 AND volumefilter;
BuyPrice = ema10; 
Sell =  Cross (EMA50, low);
SellPrice = ema50;
 
applyStop (stopTypeloss, stopModePoint,  numticks* TickSize, True );
type or paste code here

I put the tick value at $.10 (10 cents)

I use Yahoo data

Here is a list of trades, sorted with the worst on top so you can see the issue clearly:

image

You can see the stops are not activated.

Thanks for your help!!! Neil

But what is the TickSize for all those symbols? You use that in your formula, but did you set it at all? If you did not change it for every symbol, the default TickSize value is 0. We don't know the values that you use.

In settings I set the ticksize as .1 From what I can tell the formula works as planned EXCEPT on down days that open when the EMA25 is less than the EMA50. Then instead of the .1 stop kicking in it gets me out at the next days close. I have been banging my head on this for days and simply can't figure it out!!!

Sorry, ignore that last comment. I had a different formula working when I back tested.

The following sample gives a clearer picture of the issues I am having:

SetOption ("initialequity", 100000 ) ; 
setPositionSize( 2, spsPercentOfEquity);
SetOption ("ActivateStopsImmediately", True ) ; 
SetOption ("AllowSamebarExit", True ) ; 
SetTradeDelays (0,0,0,0);
numTicks = Optimize ( "Stop", 1, 1, 10 , 1 ); 

EMA10 = EMA(C, 10);
EMA25 = EMA (C, 25);
EMA50 = EMA (C, 50);

rsifilter = RSI(range = 20);

Buy =  rsifilter < 40 AND Open > 10;
BuyPrice = open; 
Sell =  Cross (Ref(ema50, -1), Ref(ema25, -1)); 
SellPrice = Ref(ema50, -1); 
applyStop (stopTypeloss, stopModePoint,  numticks* TickSize, True );

Tick size in settings $.10
This is a screen shot of results:

image

Lines 10 and 11 illustrate the issues I am having.

Line 10 Long BHE 2/7/20 - 30.01 and closes out position next day (after weekend) at 26.48 instead of stopping me out $.10 (what I set tick size in settings) below open 30.01 which was also buy price
Same thing happens in line 11 Long DBD 21.85 on 10/31/17 and closes out next day at 19.3 instead of stopping me out $.10 below buy/opening 21.85.
And again APTS 1/11/18, FCX 3/2/17, DAC 5/19/10, APV 5/22/19, ALTR 3/4/20 – all down days with EMA 25 below EMA 50.
On these days it gets me out at the high of the next day. I understand the high of the next day is as close to the sellprice = Ref (EMA50, -1) as it can get but why not stop me out?
DCO 9/21/11 DAR 7/31/15 AA 6/11/12 are examples of down days where EMA25 is below EMA50 and stop executed

You need to read the documentation on ApplyStop
http://www.amibroker.com/guide/afl/applystop.html

The manual describes supported scenarios. Scenarios not described in the manual are not supported.

Also you need to check the bars you are getting raw signals on (using for example "SCAN")

If regular exit is triggered on the very same bar as stop, it depends on "ActivateStopsImmediately" setting whenever stop will be executed before regular symbol or not. If you want to change the behavior you have to change "ActivateStopsImmediately" setting. If it is set to True, stops are checked after regular signals. If it is set to False, stops are checked before.

First of all you have some problematic code parts:

That one is future leak because RSI is calculated at close but you enter at same bar Open (Trade delay being zero). So instead you should do:

SetTradeDelays (0,0,0,0);
//....

Buy =  Ref(rsifilter,-1) < 40 AND Open > 10;
BuyPrice = open; 

Not being a mistake but there isn't two times Ref() function required. You may just write like this:

Sell =  Ref(Cross(ema50, ema25), -1); 

That sellprice is not guarenteed all the time at all.
EMA50 may be outside of H-L bound of a bar.
So if you do not want AB to exit at H-L bound at such cases then e.g. you may do like this:

SellPrice = Min(Open,Ref(ema50,-1)); 

In addition to previous post,

If you do single symbol backtest on symbol BHE you will see that you have multiple same bar conflicts for your reported date (range).

See conflicts with your settings below:
25

26

Regular exit (EMA cross) comes at same bar as stop trigger. So with your code and settings and with backtestRegular mode (default backtest mode) it exits that next trade at next bar regular SellPrice but not at stop trigger price.

  • backtestRegular - regular, signal-based backtest, redundant signals are removed as shown in this picture

If you set at different backest mode (e.g. backtestRegularRaw) then you will see that stop loss is getting triggered at same bar as regular exit and at stop price (with your code).

SetBacktestMode(backtestRegularRaw);
  • backtestRegularRaw - signal-based backtest, redundant (raw) entry signals are NOT removed, only one position per symbol allowed

27

Upper example was rather for the case that ema is used as stop price.

You just want to exit after cross.
So since EMA may be above or below of bar you may do like this if you do not want it to exit at H-L price in such cases:

prevEMA50 = Ref(ema50,-1);
SellPrice = IIf(H > prevEMA50 AND L < prevEMA50, prevEMA50, Close);

So if previous bar's EMA price is not reached at bar development after cross then exit at close of bar.

1 Like

Thank you Tomasz and fxshrat. Great information. I will be sifting through it tomorrow. Again THANK YOU!! Neil

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.