# Support Needed - Moving Average EA

41

Moving Average EA

Logic:

- Always in market and holding trade based on prevailing trend.

- Check for signal once per new bar. ** I think this is not working. (See attached picture of backtest)

- Signal triggered if Closing Price of Previous Bar crosses the 5 EMA in the opposite direction.

- Action taken upon signal:

2. Open new trade in opposite direction.

The EA:

```extern int       MA_Period=5;
extern int       MA_Method=1;
extern double    Lots=0.1;
int init() {return(0);}
int deinit(){return(0);}
int start()
{
int BarOpen = 0;           //Run Once Per Bar
if (Open[0] != BarOpen)
{
BarOpen=Open[0];

if (Close[2]<iMA(NULL,0,MA_Period,0,MA_Method,0,2)&&Close[1]>iMA(NULL,0,MA_Period,0,MA_Method,0,1)) // Uptrend
{
int total = OrdersTotal(); //Close Short Positions
for(int i=total-1;i>=0;i--)
{
OrderSelect(i, SELECT_BY_POS);
if(OrderSymbol()==Symbol()&& OrderType()==1)
{bool result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );}
}
OrderSend (Symbol(),0,Lots,Ask,3,NULL,NULL,NULL,0,0,Green); // Open Long Position
}

if (Close[2]>iMA(NULL,0,MA_Period,0,MA_Method,0,2)&&Close[1]<iMA(NULL,0,MA_Period,0,MA_Method,0,1)) //Downtrend
{
total = OrdersTotal(); //Close Long Positions
for(i=total-1;i>=0;i--)
{
OrderSelect(i, SELECT_BY_POS);
if(OrderSymbol()==Symbol()&& OrderType()==0)
{result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );}
}
OrderSend (Symbol(),0,Lots,Bid,3,NULL,NULL,NULL,0,0,Green); //Open Short
}

return(0);
}
}```

My Problem:

1. EA opening multiple positions (too many) in the same bar.

Can someone please point out my mistake ?

I'm using the fact that each bar opening price is different to differentiate one bar from another.

Thanks.

1757

...I'm using the fact that each bar opening price is different to differentiate one bar from another

Use the opening time of the bar to be the <last order time>

Something like this OTTOMH

```extern int TP = 30;
extern int SL = 20;

static LastOrderTime datetime;

init ()
{

LastOrderTime = Time[1]; // initialise variable

return(0);
}

start()
{
if (LastOrderTime < Time[0]) // A new bar has started since last order
{
// Do order stuff

LastOrderTime = Time[0]; // reset variable

}

return(0);
}```

FWIW

-BB-

41

BarrowBoy:

Use the opening time of the bar to be the <last order time>

Something like this OTTOMH

FWIW

-BB-

BarrowBoy,

Thanks !