How to execute code on one side of moving average only?

Created at 10 Apr 2020, 08:13
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
MR

Mr4x

Joined 12.04.2019

How to execute code on one side of moving average only?
10 Apr 2020, 08:13


Hi,

I have what I think is a fairly simple request but cannot for the life of me figure it out.

I am basically looking to have an expression built in to my bot that allows me to execute only buy trades when market is above moving average, and only sell trades when market is below a defined moving average. There is no requirement to close any open trades when crossing the MA or anything like that.

I have tried building one using the code in the Sample Trend cBot included with cTrader but the problem is it will still only let me place one trade in either direction when moving average is crossed. It also uses a fast and slow moving average, which is irrelevant to me as I only need 1 moving average

So for example:

 

if CurrentMovingAverage <= DefinedMovingAverage

ProcessSell();

if CurrentMovingAverage >= DefinedMovingAverage

ProcessBuy();

 

I can provide more code if required for context / troubleshooting.

Many thanks,

Mr4x


@Mr4x
Replies

firemyst
04 Sep 2020, 09:03

RE:

Mr4x said:

Hi,

I have what I think is a fairly simple request but cannot for the life of me figure it out.

I am basically looking to have an expression built in to my bot that allows me to execute only buy trades when market is above moving average, and only sell trades when market is below a defined moving average. There is no requirement to close any open trades when crossing the MA or anything like that.

I have tried building one using the code in the Sample Trend cBot included with cTrader but the problem is it will still only let me place one trade in either direction when moving average is crossed. It also uses a fast and slow moving average, which is irrelevant to me as I only need 1 moving average

So for example:

 

if CurrentMovingAverage <= DefinedMovingAverage

ProcessSell();

if CurrentMovingAverage >= DefinedMovingAverage

ProcessBuy();

 

I can provide more code if required for context / troubleshooting.

Many thanks,

Mr4x

You need to say:

//In your OnTick or OnBar event for bots depending on whether you want to check every tick or every bar

if (Bars.ClosePrices.Last(0) > MovingAverage.Result.Last(0))
{
   //the code to execute when price is above the moving average
}
else if (Bars.ClosePrices.Last(0) < MovingAverage.Result.Last(0))
{
    //the code to execute when price is below the moving average
}
else
{
   //what you want to do, if anything, when the MA == the currency closing/tick price.
   //rare event, but could happen so have to account for it!
}

 


@firemyst