made a 2 EMA cross EA, need advice - page 3

 
deVries:


not if you test with current spread this is very crazy moving so spread can become very huge

so how did you do the test ??

fixed spread or current spread ??


ok, so this is the time I go google "spread"

I appreciate that you are answering my stupid questions))

I will be back in a while

 
prupru:


ok, so this is the time I go google "spread"

I appreciate that you are answering my stupid questions))

I will be back in a while

Spread = Ask - Bid
 

and each tick this value can change

reason why i asked method how you did do the test

 
deVries:

and each tick this value can change

reason why i asked method how you did do the test

exactly!

I the difference was due to the current spread testing, when I performed the tests with fixed spread they were exactly the same!

Thank you guys so much!

I have really improved my knowledge.

And please let me know if there is something left to be improved in the code.

 
prupru:

exactly!

I the difference was due to the current spread testing, when I performed the tests with fixed spread they were exactly the same!

Thank you guys so much!

I have really improved my knowledge.

And please let me know if there is something left to be improved in the code.


if you show what your code has become now

like to see also a new errorhandling, see comment RaptorUK https://www.mql5.com/en/forum/148529

 
deVries:


if you show what your code has become now

like to see also a new errorhandling, see comment RaptorUK https://www.mql5.com/en/forum/148529

Ok, here we go:

#property copyright "me"
#property link      "killnosock.net"
extern int SlowEma = 21;
extern int FastEma = 10;
extern int MaxRisk = 100;// % of Depo to be traded per order
extern int  TakeProfit=0;
extern int  StopLoss=0;
extern int TrailingStop=0;
extern int Slippage = 10;

extern double MinDiff = 0.002;

int LastBars = 0;
//0 - undefined, 1 - bullish cross (fast MA above slow MA), -1 - bearish cross (fast MA below slow MA)
int PrevCross = 0;

int init(){return(0);}
int deinit() {return(0);}

price normalization:

double NormPrice(double g_price)
{
   return (NormalizeDouble(g_price,MarketInfo(Symbol(),MODE_DIGITS)));
}

GetLot function, I guess it hasn't changed

//function GetLot, get size of the lot according to MaxRisk
double GetLot(int Risk)
{double Free    =AccountFreeMargin();
 double One_Lot =MarketInfo(Symbol(),MODE_MARGINREQUIRED);
 double Min_Lot =MarketInfo(Symbol(),MODE_MINLOT);
 double Max_Lot =MarketInfo(Symbol(),MODE_MAXLOT);
 double Step    =MarketInfo(Symbol(),MODE_LOTSTEP);
 double Lot     =MathFloor(Free*Risk/100/One_Lot/Step)*Step;
 if(Lot<Min_Lot) Lot=Min_Lot;
 if(Lot>Max_Lot) Lot=Max_Lot;
 if(Lot*One_Lot>Free) {
 Alert(" free= ", AccountFreeMargin()," for one lot= ", MarketInfo(Symbol(),MODE_MARGINREQUIRED)," lot= ", Lot);
 return(0.0);}
return(Lot);}

New Order function, now uses normalised prices:

//function NewOrder, place new order
int NewOrder(int Cmd,double Lot)
{double TP=0; //тейкпрофит
 double SL=0; //стоплосс
 double PR=0; //Цена
 color clr = CLR_NONE;
 while(!IsTradeAllowed()) Sleep(10);
 RefreshRates();
 if(Cmd==OP_BUY)
   {PR=Ask;
    if(TakeProfit>0) TP=NormPrice(Ask + Ask*TakeProfit/100);
    if(StopLoss>0) SL=NormPrice(Ask - Ask*StopLoss/100);
    if(SL<0) SL = 0;
    if(TP<0) TP = 0;
    clr = Green;}
 if(Cmd==OP_SELL)
   {PR=Bid;
    if(TakeProfit>0) TP=NormPrice(Bid - Bid*TakeProfit/100);
    if(StopLoss>0) SL=NormPrice(Bid + Bid*StopLoss/100);
    if(SL<0) SL = 0;
    if(TP<0) TP = 0;
    clr=Red;}
 int tic=OrderSend(Symbol(),Cmd,Lot,PR,Slippage,SL,TP,"",0,0,clr);
 if(tic<0)
  {
   Print("open order error:",GetLastError());
   Print("cmd ", Cmd, " Lot ", Lot, " PR ", PR, " Slip ", Slippage, " SL ", SL, " TP ", TP, " Ask ", Ask, " Bid ", Bid);
  }
return(tic);}

Close 1 or all orders

I have not changed the order close function to check for symbol and magic numbers, because I am going to trade at one symbol only and with only one EA per account. But I will do it after I deal with other more important issues and tuning.

//CloseOrder
void CloseOrder()
{double PR=0;
 while(!IsTradeAllowed()) Sleep(10);
 RefreshRates();
 if(OrderType()==OP_BUY)  PR=Bid;
 if(OrderType()==OP_SELL) PR=Ask;
 if(!OrderClose(OrderTicket(),OrderLots(),PR,Slippage,CLR_NONE))
  {
   Print("Close order error: ",GetLastError());
   Print("Type ", OrderType()," PR ",PR, " Ask ", Ask, " Bid ", Bid, " OrderTicket ", OrderTicket(), " OrderLots ", OrderLots());
  }
return;}
//--------------------------- end of close order

//Close all Orders
void CloseAllOrders()
{
  for(int i=OrdersTotal()-1;i>=0;i--)
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
     {
      CloseOrder();
     }
return;}

I have changed the EMA cross detection from comparising EmaDiff[2] to EmaDiff[1] to comparising EmaDiff[0] to zero and using an additional flag (all this coming from some example I found)

On a minute scale Demo account it makes false triggers when the spread is so high that a buy deal make EMAs intersect and then a sell deal coming after that within the same minute bar make them seperate again.

[url=http://postimg.org/image/udq4ufmqf/][img]http://s15.postimg.org/udq4ufmqf/mess.jpg[/img][/url]

I am thinking of how to deal with this right now

// check cross
void CheckCross()
{
   double FMA_Current = iMA(Symbol(),0,FastEma,0,MODE_EMA,PRICE_CLOSE,0);
   double SMA_Current = iMA(Symbol(),0,SlowEma,0,MODE_EMA,PRICE_CLOSE,0);
   double Poin = (FMA_Current + SMA_Current)/2;
   double Lot;
   if (PrevCross == 0) //Was undefined
   {
      if ((FMA_Current - SMA_Current) >= MinDiff * Poin) PrevCross = 1; //Bullish state
      else if ((SMA_Current - FMA_Current) >= MinDiff * Poin) PrevCross = -1; //Bearish state
      return;
   }
   else if (PrevCross == 1) //Was bullish
   {
      if ((SMA_Current - FMA_Current) >= MinDiff * Poin) //Became bearish
      {
         CloseAllOrders();
         Lot = GetLot(MaxRisk);
         NewOrder(OP_SELL,Lot);
         PrevCross = -1;
      }
   }
   else if (PrevCross == -1) //Was bearish
   {
      if ((FMA_Current - SMA_Current) >= MinDiff * Poin) //Became bullish
      {
         CloseAllOrders();
         Lot = GetLot(MaxRisk);
         NewOrder(OP_BUY,Lot);
         PrevCross = 1;
      }
   }
}

the trailing stop function:

// trailing stop
void DoTrailing()
{
   int total = OrdersTotal();
   for (int pos = 0; pos < total; pos++)
   {
      if (OrderSelect(pos, SELECT_BY_POS) == false) continue;
      if (OrderSymbol() == Symbol())
      {
         if (OrderType() == OP_BUY)
         {
            RefreshRates();
            if (Bid - OrderOpenPrice() >= TrailingStop * Bid/100) //If profit is greater or equal to the desired Trailing Stop value
            {
               if (OrderStopLoss() < (Bid - TrailingStop * Bid/100)) //If the current stop-loss is below the desired trailing stop level
                  OrderModify(OrderTicket(), OrderOpenPrice(), NormPrice(Bid - TrailingStop * Bid/100), OrderTakeProfit(), 0);
            }
         }
         else if (OrderType() == OP_SELL)
         {
            RefreshRates();
            if (OrderOpenPrice() - Ask >= TrailingStop * Ask/100) //If profit is greater or equal to the desired Trailing Stop value
            {
                      if ((OrderStopLoss() > (Ask + TrailingStop * Ask/100)) || (OrderStopLoss() == 0)) //If the current stop-loss is below the desired trailing stop level
                  OrderModify(OrderTicket(), OrderOpenPrice(), NormPrice(Ask + TrailingStop * Ask/100), OrderTakeProfit(), 0);
            }
         }
      }
   }   
}

and the body itself:

//main program
int start()
  {

   if (TrailingStop > 0) DoTrailing();
          
        static datetime Time0;
        if (Time0 == Time[0]) return;
        Time0 = Time[0];
      {
       CheckCross();     
              
      }

   return(0);
  }

Thanks for your interest!



 
prupru:


I have not changed the order close function to check for symbol and magic numbers, because I am going to trade at one symbol only and with only one EA per account. But I will do it after I deal with other more important issues and tuning.


don't be lazy, do it directly !!!!

it's an important thing you always have to include

if you want to fix your program and we give advise what is needed to do

then if you don't wanna work to fix it then what are we doing helping you ??

 
deVries:


don't be lazy, do it directly !!!!

it's an important thing you always have to include

if you want to fix your program and we give advise what is needed to do

then if you don't wanna work to fix it then what are we doing helping you ??


ok, ok, just take it easy)

here it is, I think that should do the trick.

open order function:

OrderSend(Symbol(),Cmd,Lot,PR,Slippage,SL,TP,"",Expert_ID,0,clr);

close all order function:

//Close all Orders
void CloseAllOrders()
{
  for(int i=OrdersTotal()-1;i>=0;i--)
   {
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
     {
      if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == Expert_ID))  CloseOrder();
     }
    else
     {
      Print("Error selecting order: ",GetLastError());
      Print(" i= ", i, " Symbol= ", OrderSymbol());
     }
   }
return;}
 

I have a bigger problem now, my broker tends to partially execute orders.

Dear Customer,

Please be hereby advised that your trade has been opened partially (2.32 lots out of 15.84) at the price 587.318.

Should you have any additional questions on this issue, don’t hesitate to contact us.

Kind Regards,

Broker.

here is what support say:

Please be advised, during periods of high volatility or low liquidity, Limit Orders may be partially executed. This means that the position will get filled immediately fully or partially if the price is met. In you case your order was executed partially, that is why you have received notification letter.

I understand how to close all orders despite them being closed partially, I just have to do Close all Orders while OrdersTotal() > 0, but I don't know what to yet when orders open partially.

edit:

Just realized that I have to check proper Symbol and magicnumber orders, it is a bit more difficult

edit: here is the close all orders function that should close orders even with partial closure

//Close all my Orders
void CloseAllOrders()
{
int notMyOrders = 0;

for(int j=OrdersTotal()-1;j>=0;j--)
{
    if(OrderSelect(j,SELECT_BY_POS,MODE_TRADES))
      {
       if ((OrderSymbol() != Symbol()) || (OrderMagicNumber() != Expert_ID)) notMyOrders++;
      }
    else
      {
       Print("Error selecting order: ",GetLastError());
       Print(" j= ", j, " Symbol= ", OrderSymbol());
      }    
}

 while (OrdersTotal()>notMyOrders)
 {
  for(int i=OrdersTotal()-1;i>=0;i--)
   {
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
     {
      if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == Expert_ID))  CloseOrder();
     }
    else
     {
      Print("Error selecting order: ",GetLastError());
      Print(" i= ", i, " Symbol= ", OrderSymbol());
     }
   }
 }


return;}
 

Here is how I am going to struggle with partial execution of open orders,

Opening order will no longer be performed with a NewOrder function, but it will be done with this one:

//OpenOrders in case of partial execution
int OpenPartOrders(int Cmd, double Lot)
{
 int NumOrders = 0;
 int LastTic = -1;
 double Step = MarketInfo(Symbol(),MODE_LOTSTEP);
 double LotRemains = Lot;
 
 //MathFloor( /Step)*Step;;
while (LotRemains>0)
 {
  LastTic = NewOrder(Cmd, LotRemains);
  NumOrders++;
  if(OrderSelect(LastTic, SELECT_BY_TICKET)==true)
     {
      LotRemains = LotRemains - OrderLots();
      Print("NumberOfOrders ", NumOrders, " Ticket ", LastTic, " LotRemains ", LotRemains, " initial Lot ", Lot);          
     }
  else
   {
    Print("OrderSelect returned the error of ",GetLastError());
    LotRemains = 0;//not to create an endless loop opening new orders again and again
   }
 } 
return(NumOrders);}