syed ea (26 Nov 2023)

 //+------------------------------------------------------------------+

//|                                                      Syed EA.mq5 |

//|                                  Copyright 2023, MetaQuotes Ltd. |

//|                                             https://www.mql5.com |

//+------------------------------------------------------------------+

#include <Trade\Trade.mqh>

CTrade trade;

#property copyright "Copyright 2023, MetaQuotes Ltd."

#property link      "https://www.mql5.com"

#property version   "1.00"

double ordersendlot,close0,high1,high2,low1,low2,open1,open2,close1,close2,buyprice,sellprice,stoploss,takeprofit,sl_val;

datetime entry=0,currenttime=0;

enum  list1  // enumeration of named constants

   {

    FixedLotCalculation,

    RiskBasedCalculation

   };


input list1 QuantityCalculation=0;

enum  list2 // enumeration of named constants

   {

    SingleTradeMode,

    MultiTradeMode

   };

input list2 StrategyMode=0;

input double EntryBuffer=0.0003;

input double RewardMultiplier=2;

input double FixedLotSize=0.01;

input double Risk=1;

input int MAGIC_NUMBER=12345;

input int OrderCancelTimeFrame=1;

input int SpreadFilterValue=30;

input string INFO1="Moving Average settings";

input bool Use_MA=true;

input int MA_Period=10;

input ENUM_MA_METHOD Ma_Type=0;

input bool Use_ART=true;

input int ATRPeriod=14;

input double AtrLevelToTrde=0.00020;


input string INFO2="TRAILLING STOPLOSS MODULE";

input bool USE_TSL=true;

input double Breakevenpercentage=20;

input bool exitbreakevenlots=true;

input double BreakevenExitLotpercentage=50;

input double MaxLoss;


int ma,buyopenpos,sellopenpos;

double MA_BUFF[],Spread,balance,buy_breakevenvalue,sell_breakevenvalue,buy_breakevenlot,sell_breakevenlot;

string lotcal,stgmode;

bool mabuy=false,masell=false;

bool BUY=false,SHORT=false;datetime orderdeleattime_buy,orderdeleattime_sell;

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

//---

   

//---

   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

//---

   

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+





void ma_condition()

{

open1=iOpen(Symbol(),PERIOD_CURRENT,1);

close1=iClose(Symbol(),PERIOD_CURRENT,1);

high1=iHigh(Symbol(),PERIOD_CURRENT,1); 

low1=iLow(Symbol(),PERIOD_CURRENT,1);

ma= iMA(Symbol(),PERIOD_CURRENT,MA_Period,0,Ma_Type,PRICE_CLOSE);

ArraySetAsSeries(MA_BUFF,true);

CopyBuffer(ma,0,0,3,MA_BUFF);


if (close1>open1&&high1>MA_BUFF[1]&&Use_MA==true)

{

mabuy=true;masell=false;



}


if (close1<open1&&low1<MA_BUFF[1]&&Use_MA==true)

{


mabuy=false;masell=true;


}



if (Use_MA==false)

{

mabuy=true;masell=true;


}



}




double lotsizecalculation(double risk, double sl_val)

{

double riskval,risklotsize,fixedlot;


if (QuantityCalculation==0){lotcal="FixedLotCalculation";}

  if (QuantityCalculation==1){lotcal="RiskBasedCalculation";}


   if (lotcal=="RiskBasedCalculation")

   {

   double ticksize=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE);

   double tickval=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE);

   double lotstep = SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);

   if (ticksize==0||tickval==0||lotstep==0){ return 0;}

      

   double riskmoney=AccountInfoDouble(ACCOUNT_BALANCE)*risk/100;

   double moneyperlot= (sl_val/ticksize)*tickval*  lotstep    ;

   

   double lots = MathFloor(riskmoney/moneyperlot ) * lotstep;

   

   

   return lots;

      

      

   }


   if (lotcal=="FixedLotCalculation")

   {


   fixedlot=FixedLotSize;

   return fixedlot;

   }

   return 0.00;

}  






void OnTick()

  {

  balance=AccountInfoDouble(ACCOUNT_BALANCE);

  

  if (QuantityCalculation==0){lotcal="FixedLotCalculation";}

  if (QuantityCalculation==1){lotcal="RiskBasedCalculation";}

  

  if (StrategyMode==0){stgmode="SingleTradeMode";}

  if (StrategyMode==1){stgmode="MultiTradeMode";}

  

  

     Spread = SymbolInfoInteger(Symbol(), SYMBOL_SPREAD);

     

     high1=iHigh(Symbol(),PERIOD_CURRENT,1);

     high2=iHigh(Symbol(),PERIOD_CURRENT,2);

     

     low1=iLow(Symbol(),PERIOD_CURRENT,1);

     low2=iLow(Symbol(),PERIOD_CURRENT,2);

     

     open1=iOpen(Symbol(),PERIOD_CURRENT,1);

     open2=iOpen(Symbol(),PERIOD_CURRENT,2);

     

     close1=iClose(Symbol(),PERIOD_CURRENT,1);

     close2=iClose(Symbol(),PERIOD_CURRENT,2);

     

     close0=iClose(Symbol(),PERIOD_CURRENT,0);

     currenttime=iTime(Symbol(),PERIOD_CURRENT,0);

     

     

      ma_condition();

     //Comment("MA_BUFF1: "+MA_BUFF[1]+"\n\nMA_BUFF2: "+MA_BUFF[2]+"\n\n Spread: "+Spread);

     

     

    // Comment("currenttime: "+currenttime+"\n\norderdeleattime_buy: "+orderdeleattime_buy+"\n\norderdeleattime_sell: "+orderdeleattime_sell);

     

     //Comment("high1: "+high1+"\n\nhigh2: "+high2+"\n\nlow1: "+low1+"\n\nlow2: "+low2+"\n\nopen1: "+open1+"\n\nopen2: "+open2+"\n\nclose1: "+close1+"\n\nclose2: "+close2);

     buyopenpos=  check_buy_open_position();  

     sellopenpos=check_SELL_open_position();

     

     //Comment("buyopenpos= "+buyopenpos+"\n\nsellopenpos= "+sellopenpos);

     

     

     if(SHORT==false&&sellopenpos<1&&buyopenpos<1&&stgmode=="SingleTradeMode"&&mabuy==true&&Spread<SpreadFilterValue&&close1>open1 && close2<open2 && high1<high2 && low1<low2 && close1>low2 && close1<high1 && entry!=iTime(Symbol(),PERIOD_CURRENT,0))

         {

           entry=iTime(Symbol(),PERIOD_CURRENT,0);

           int spread= (int)SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);

           

           buyprice=iHigh(Symbol(),PERIOD_CURRENT,1)+EntryBuffer;

           buyprice=NormalizeDouble(buyprice,_Digits); 

                     

           stoploss=NormalizeDouble(iLow(Symbol(),PERIOD_CURRENT,1),_Digits);      

           sl_val=buyprice-stoploss;

           ordersendlot=lotsizecalculation(Risk,  sl_val);

           

           if (USE_TSL==true)

           {

           

           buy_breakevenvalue=sl_val*Breakevenpercentage /100;

           buy_breakevenvalue=buy_breakevenvalue+buyprice;

           buy_breakevenlot=ordersendlot*BreakevenExitLotpercentage /100;

           buy_breakevenlot=ordersendlot-buy_breakevenlot;

           buy_breakevenlot=NormalizeDouble(buy_breakevenlot,2);

           }

           //Comment("buybreakevenvalue: "+breakevenvalue+"\n\n buybreakevenlot: "+breakevenlot);

           

           

           takeprofit=sl_val*RewardMultiplier;

           takeprofit=buyprice+takeprofit;

           takeprofit=NormalizeDouble(takeprofit,_Digits);     

           trade.BuyStop(ordersendlot,buyprice,Symbol(),stoploss,takeprofit,ORDER_TIME_GTC,0,0);

           buydraw();


           BUY=true;

           

           Alert("BUY @ "+Symbol()+ " buyprice: "+buyprice+" takeprofit: "+takeprofit+" stoploss: "+stoploss);

           SendNotification("BUY @ "+Symbol()+" buyprice: "+buyprice+" takeprofit: "+takeprofit+" stoploss: "+stoploss);

           

  

           orderdeleattime_buy =  AddMinutesToTime(iTime(Symbol(),PERIOD_CURRENT,0),OrderCancelTimeFrame);          

     }

     

     

      if (BUY==false&&buyopenpos<1&&sellopenpos<1&&stgmode=="SingleTradeMode"&&masell==true&&Spread<SpreadFilterValue&&close1<open1 && close2>open2 && high1>high2 && low1>low2 && close1>low2 && close1<high1 && entry!=iTime(Symbol(),PERIOD_CURRENT,0))

     {

     

           entry=iTime(Symbol(),PERIOD_CURRENT,0);

           int spread= (int)SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);

           sellprice=iLow(Symbol(),PERIOD_CURRENT,1)-EntryBuffer;

           sellprice=NormalizeDouble(sellprice,_Digits);     

           stoploss=NormalizeDouble(iHigh(Symbol(),PERIOD_CURRENT,1),_Digits);     

           sl_val=stoploss-sellprice;

           ordersendlot=lotsizecalculation(Risk,  sl_val);

           

           

           if (USE_TSL==true)

           {

           

           sell_breakevenvalue=sl_val*Breakevenpercentage /100;

           sell_breakevenvalue=sellprice-sell_breakevenvalue;

           sell_breakevenlot=ordersendlot*BreakevenExitLotpercentage /100;

           sell_breakevenlot=ordersendlot-sell_breakevenlot;

           sell_breakevenlot=NormalizeDouble(sell_breakevenlot,2);

           }

           // Comment("sellbreakevenvalue: "+breakevenvalue+"\n\n sellbreakevenlot: "+breakevenlot);

           takeprofit=sl_val*RewardMultiplier;

           takeprofit=sellprice-takeprofit;

           takeprofit=NormalizeDouble(takeprofit,_Digits);     

           trade.SellStop(ordersendlot,sellprice,Symbol(),stoploss,takeprofit,ORDER_TIME_GTC,0,0);

   

           selldraw();

           //orderpselldraw()lacement

       

           //orderplacement

           

           SHORT=true;

           Alert("SELL @ "+Symbol()+" sellprice: "+sellprice+" takeprofit: "+takeprofit+" stoploss: "+stoploss);

           SendNotification("SELL @ "+Symbol()+" sellprice: "+sellprice+" takeprofit: "+takeprofit+" stoploss: "+stoploss);    


      orderdeleattime_sell  =  AddMinutesToTime(iTime(Symbol(),PERIOD_CURRENT,0),OrderCancelTimeFrame);

     

     }

     

     

     

     

     

     //Multi trade mode

     

     

     

     

     

     if(stgmode=="MultiTradeMode"&&mabuy==true&&Spread<SpreadFilterValue&&close1>open1 && close2<open2 && high1<high2 && low1<low2 && close1>low2 && close1<high1 && entry!=iTime(Symbol(),PERIOD_CURRENT,0))

         {

           entry=iTime(Symbol(),PERIOD_CURRENT,0);

           int spread= (int)SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);

           

           buyprice=iHigh(Symbol(),PERIOD_CURRENT,1)+EntryBuffer;

           buyprice=NormalizeDouble(buyprice,_Digits); 

                     

           stoploss=NormalizeDouble(iLow(Symbol(),PERIOD_CURRENT,1),_Digits);      

           sl_val=buyprice-stoploss;

           ordersendlot=lotsizecalculation(Risk,  sl_val);

           Comment("ordersendlotbuy: "+ordersendlot);

           

           takeprofit=sl_val*RewardMultiplier;

           takeprofit=buyprice+takeprofit;

           takeprofit=NormalizeDouble(takeprofit,_Digits);     

           trade.BuyStop(ordersendlot,buyprice,Symbol(),stoploss,takeprofit,ORDER_TIME_GTC,0,0);

           buydraw();


           BUY=true;

           

           Alert("BUY @ "+Symbol()+ " buyprice: "+buyprice+" takeprofit: "+takeprofit+" stoploss: "+stoploss);

           SendNotification("BUY @ "+Symbol()+" buyprice: "+buyprice+" takeprofit: "+takeprofit+" stoploss: "+stoploss);

           

  

           orderdeleattime_buy =  AddMinutesToTime(iTime(Symbol(),PERIOD_CURRENT,0),OrderCancelTimeFrame);

            

          

           

     }

     

     if (stgmode=="MultiTradeMode"&&masell==true&&Spread<SpreadFilterValue&&close1<open1 && close2>open2 && high1>high2 && low1>low2 && close1>low2 && close1<high1 && entry!=iTime(Symbol(),PERIOD_CURRENT,0))

     {

     

           entry=iTime(Symbol(),PERIOD_CURRENT,0);

           int spread= (int)SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);

           sellprice=iLow(Symbol(),PERIOD_CURRENT,1)-EntryBuffer;

           sellprice=NormalizeDouble(sellprice,_Digits);     

           stoploss=NormalizeDouble(iHigh(Symbol(),PERIOD_CURRENT,1),_Digits);     

           sl_val=stoploss-sellprice;

           ordersendlot=lotsizecalculation(Risk,  sl_val);

           

           Comment("ordersendlotsell: "+ordersendlot);

           

           

           takeprofit=sl_val*RewardMultiplier;

           takeprofit=sellprice-takeprofit;

           takeprofit=NormalizeDouble(takeprofit,_Digits);     

           trade.SellStop(ordersendlot,sellprice,Symbol(),stoploss,takeprofit,ORDER_TIME_GTC,0,0);

   

           selldraw();

           //orderpselldraw()lacement

       

           //orderplacement

           

           SHORT=true;

           Alert("SELL @ "+Symbol()+" sellprice: "+sellprice+" takeprofit: "+takeprofit+" stoploss: "+stoploss);

           SendNotification("SELL @ "+Symbol()+" sellprice: "+sellprice+" takeprofit: "+takeprofit+" stoploss: "+stoploss);    


      orderdeleattime_sell  =  AddMinutesToTime(iTime(Symbol(),PERIOD_CURRENT,0),OrderCancelTimeFrame);

     

     }

     

     //////////tsl module

     if (USE_TSL==true&&stgmode=="SingleTradeMode")

           {

           

           if(BUY==true && buy_breakevenvalue>0 && close0>buy_breakevenvalue)

           {

           

           Alert("Breakeven executed buy trade @ "+Symbol());

           buy_breakevenvalue=0;buytsl(NormalizeDouble(buyprice,_Digits));

           BUY=false;

           if (exitbreakevenlots==true)

           {

           

            exit_buy_partial( buy_breakevenlot );

           

           }

           

           

           }

           

          if(SHORT==true && sell_breakevenvalue>0 && close0<sell_breakevenvalue)

           {

          

           Alert("Breakeven executed sell trade @ "+Symbol());

           sell_breakevenvalue=0;selltsl(NormalizeDouble(sellprice,_Digits));

           SHORT=false;

            if (exitbreakevenlots==true)

           {

           exit_sell_partial( sell_breakevenlot );

           

           

           }

           

           }

          

           }

     

     

     

     

     

     

     

     

     

    ////ORDER CANCELATION

    if (BUY==true)

    {

    

    if(close0<=low1&&currenttime<=orderdeleattime_buy&& orderdeleattime_buy>0)

    {

    BUYEXIT();CheckAndCancelBuyStopOrders();

    Alert("Buy stop cancelled previous candle low break @ "+Symbol());

    orderdeleattime_buy=0;

    }

    

    if (currenttime>orderdeleattime_buy&& orderdeleattime_buy>0)

    {

    orderdeleattime_buy=0;CheckAndCancelBuyStopOrders();

    BUYEXIT();

    Alert("Buy stop cancelled Trade not triggered candle closed  @ "+Symbol());

    }

 

    } 

    

     

     

      if (SHORT==true)

    {

    

    if(close0>=high1&&currenttime<=orderdeleattime_sell&&orderdeleattime_sell>0)

    {

    orderdeleattime_sell=0;

   SELLEXIT();CheckAndCancelSELLStopOrders() ;

    Alert("Sell stop cancelled previous candle High break @ "+Symbol());

    }

    

    if (currenttime>orderdeleattime_sell&&orderdeleattime_sell>0)

    {

  orderdeleattime_sell=0;

  CheckAndCancelSELLStopOrders();

    Alert("Sell stop cancelled Trade not triggered candle closed  @ "+Symbol());SELLEXIT();

    }

 

    } 

     

   

  }

//+------------------------------------------------------------------+


void exit_sell_partial(double lots )

{



for (int i=PositionsTotal()-1;i>=0;i--)

{

  

  string currencypair=PositionGetSymbol(i);

  int position_direction=PositionGetInteger(POSITION_TYPE);


  if(currencypair==Symbol() && position_direction == POSITION_TYPE_SELL)

  {

  ulong ticket=PositionGetTicket(i);

  

  trade.PositionClosePartial(ticket,lots);

  

  }




}}




void exit_buy_partial(double lots )

{



for (int i=PositionsTotal()-1;i>=0;i--)

{

  

  string currencypair=PositionGetSymbol(i);

  int position_direction=PositionGetInteger(POSITION_TYPE);


  if(currencypair==Symbol() && position_direction == POSITION_TYPE_BUY)

  {

  ulong ticket=PositionGetTicket(i);

  

  trade.PositionClosePartial(ticket,lots);

  

  }




}}




void selltsl(double NEWSL)

{



for (int i=PositionsTotal()-1;i>=0;i--)

{

  

  string currencypair=PositionGetSymbol(i);

  int position_direction=PositionGetInteger(POSITION_TYPE);

  

  if(currencypair==Symbol() && position_direction == POSITION_TYPE_SELL)

  {

  ulong ticket=PositionGetTicket(i);

  double tp=PositionGetDouble(POSITION_TP);

  trade.PositionModify(ticket,NEWSL,tp);

  

  }



}


}



void buytsl(double NEWSL)

{



for (int i=PositionsTotal()-1;i>=0;i--)

{

  

  string currencypair=PositionGetSymbol(i);

  int position_direction=PositionGetInteger(POSITION_TYPE);

  

  if(currencypair==Symbol() && position_direction == POSITION_TYPE_BUY)

  {

  ulong ticket=PositionGetTicket(i);

  double tp=PositionGetDouble(POSITION_TP);

  trade.PositionModify(ticket,NEWSL,tp);

  

  }



}


}





int  check_buy_open_position()

{

   int numberofbuyposition=0;

   for (int i = PositionsTotal()-1;i>=0;i--)

   {

      string currencypair=PositionGetSymbol(i);

      int position_direction=PositionGetInteger(POSITION_TYPE);

      if (Symbol()==currencypair && position_direction == POSITION_TYPE_BUY)

      {

         numberofbuyposition=numberofbuyposition+1;

      }

   }

return numberofbuyposition;

}


int  check_SELL_open_position()

{

   int numberofSELLposition=0;

   for (int i = PositionsTotal()-1;i>=0;i--)

   {

      string currencypair=PositionGetSymbol(i);

      int position_direction=PositionGetInteger(POSITION_TYPE);

      if (Symbol()==currencypair && position_direction == POSITION_TYPE_SELL)

      {

         numberofSELLposition=numberofSELLposition+1;

      }

   }

return numberofSELLposition;

}








void CheckAndCancelBuyStopOrders() {

    string chartSymbol = _Symbol; // Get the current chart symbol


    

    for(int i = OrdersTotal() - 1; i >= 0; i--) {

        ulong orderTicket = OrderGetTicket(i); // Get the ticket number of the order

        if(orderTicket > 0) {

            string orderSymbol = OrderGetString(ORDER_SYMBOL);

             

            ENUM_ORDER_TYPE orderType = ENUM_ORDER_TYPE(OrderGetInteger(ORDER_TYPE));

               

            

            if(orderSymbol == chartSymbol && orderType == ORDER_TYPE_BUY_STOP) {

                bool result = trade.OrderDelete(orderTicket); // Attempt to cancel the order

                if(result) {

                    Print("Buy Stop order ", orderTicket, " on ", orderSymbol, " has been successfully canceled.");

                } else {

                    Print("Failed to cancel Buy Stop order ", orderTicket, ", error code: ", GetLastError());

                }

            }

        } else {

            Print("Failed to get order ticket for index ", i, ", error code: ", GetLastError());

        }

    }

}


void CheckAndCancelSELLStopOrders() {

    string chartSymbol = _Symbol;

    

    for(int i = OrdersTotal() - 1; i >= 0; i--) {

        ulong orderTicket = OrderGetTicket(i); 

        if(orderTicket > 0) {

            string orderSymbol = OrderGetString(ORDER_SYMBOL);

          

            ENUM_ORDER_TYPE orderType = ENUM_ORDER_TYPE(OrderGetInteger(ORDER_TYPE));

         

            

            if(orderSymbol == chartSymbol && orderType == ORDER_TYPE_SELL_STOP) {

                bool result = trade.OrderDelete(orderTicket); 

                if(result) {

                    Print("Buy Stop order ", orderTicket, " on ", orderSymbol, " has been successfully canceled.");

                } else {

                    Print("Failed to cancel Buy Stop order ", orderTicket, ", error code: ", GetLastError());

                }

            }

        } else {

            Print("Failed to get order ticket for index ", i, ", error code: ", GetLastError());

        }

    }

}












datetime AddMinutesToTime(datetime currentTime, int minutesToAdd) {

    // Convert the current time to a structure

    MqlDateTime dt;

    TimeToStruct(currentTime, dt);


    // Add the specified minutes

    dt.min += minutesToAdd;

    if (dt.min >= 60) {

        dt.hour += dt.min / 60;

        dt.min %= 60;

    }


    // Convert the modified structure back to time

    return StructToTime(dt);

}



void BUYEXIT(){


ObjectCreate(Symbol(),"BUYEXIT"+iTime(Symbol(),PERIOD_CURRENT,0),OBJ_ARROW_STOP,0,TimeCurrent(),low1);

}

void SELLEXIT(){


ObjectCreate(Symbol(),"SELLEXIT"+iTime(Symbol(),PERIOD_CURRENT,0),OBJ_ARROW_STOP,0,TimeCurrent(),high1);

}





void buydraw()

           { 

           

               ObjectCreate(Symbol(),"BUYSIGNAL"+iTime(Symbol(),PERIOD_CURRENT,0),OBJ_ARROW_BUY,0,TimeCurrent(),low1);

              

             

               

           }

           

           

                     

void selldraw()

           { 

           

           

            ObjectCreate(Symbol(),"SELLSIGNAL"+iTime(Symbol(),PERIOD_CURRENT,0),OBJ_ARROW_SELL,0,TimeCurrent(),high1);

            

           

            }


Comments

Popular posts from this blog

MQL5 : Add time to current time in mins

MQL5 : Get current trading session