How to code sell condition with MA crossover & 5% profit in Amibroker?

I want to create a sell condition where I sell when the Close price crosses below the 20-day moving average, but only if the Close price is at least 5% higher than my buy price.

I've done my research and here’s snippet of my attempt:

Buy = Cross(Close, MA(Close, 20));
BuyPrice = Close;

ReqReturn = BuyPrice * 1.05; //required return 5%
Sell = Cross(Close,MA(Close,20)) AND Close>ReqReturn;

However, ReqReturn doesn’t return any value, and the condition doesn’t work as expected. Any help would be appreciated

You should post full code when seeking help from other forum members.

As the output states, you are using wrong format in your exploration code.

Also, do you really want to use impulse condition in your sell rule?

See,

Exploration Guide.

2 Likes

A few observations:

  • Your Buy condition requires the Close to cross up through MA(20). Your Sell condition also requires the Close to cross up through the MA(20). So that means that while you're in the trade, the close must first cross down through the MA(20) and then cross back up. It could take a significant number of bars for that condition to occur, even without your profit requirement.

  • You don't show any other exit rules besides the one Sell rule. That means you will never exit the trade for tickers that don't rise by at least 5%.

  • Your logic for finding a 5% gain is incorrect, because you are basing it on BuyPrice, which in your example is simply the Closing price. Both of these variables are arrays that change on a bar by bar basis. That means that this part of your Sell rule:

Close>ReqReturn

Is equivalent to:

Close > Close * 1.05

Of course, that will never be true. If you don't want to use ApplyStop for your profit target and instead want to do something similar to the snippet you've shown, then you will need to get the BuyPrice from the bar at which the entry occurred. You can't reliably use the ValueWhen() function, because there may have been multiple Buy signals since the trade was entered. The correct implementation is left as an exercise to the reader.

2 Likes

As a first-time poster, here are some solid guides.

Just look at trailing stop as taking profit. The core concept is the same.

AmiBroker Knowledge Base » How to plot a trailing stop in the Price chart

Easiest way to lock Buyprice - AFL Programming - AmiBroker Community Forum

2 Likes