ソースを参照

Ticket: 5131 ReEntry and Filters

Huzaifa-MQLDev 9 ヶ月 前
コミット
a89616b6d3
2 ファイル変更433 行追加15 行削除
  1. BIN
      vol_hedge_strategy_mt5.ex5
  2. 433 15
      vol_hedge_strategy_mt5.mq5

BIN
vol_hedge_strategy_mt5.ex5


+ 433 - 15
vol_hedge_strategy_mt5.mq5

@@ -12,6 +12,48 @@ CTrade  trade;
 //+------------------------------------------------------------------+
 //+------------------------------------------------------------------+
 //| Expert initialization function                                   |
 //| Expert initialization function                                   |
 //+------------------------------------------------------------------+
 //+------------------------------------------------------------------+
+enum NewsCloseOrder
+  {
+   CloseAllRunningOrder=0,
+   LetTheOrderRun=1,
+  };
+enum selectLine
+  {
+   LineOnNewsBar =0,
+   LineOnNewsStop=1
+  };
+
+#import "volHedgeNewsFilter.ex5"
+
+//+------------------------------------------------------------------+
+//|                                                                  |
+//+------------------------------------------------------------------+
+void initiateNews();
+int returnNewsStatus(bool High_Impact_News=true
+                     ,int High_Start_Time=60//Stop Trade before high News (min)
+                     ,int High_Stop_Time=15 //Stop Trade after high News (min)
+                     ,bool show_high_line=true//Show verticle Line when high news comes
+
+                     ,bool Medium_Impact_News=true
+                     ,int Medium_Start_Time=60//Stop Trade before medium News (min)
+                     ,int Medium_Stop_Time=15 //Stop Trade after medium News (min)
+                     ,bool show_medium_line=true//Show verticle Line when medium news comes
+
+                     ,bool Low_Impact_News=true
+                     ,int Low_Start_Time=60//Stop Trade before low News (min)
+                     ,int Low_Stop_Time=15 //Stop Trade after low News (min)
+                     ,bool show_low_line=true//Show verticle Line when low news comes
+
+                     ,string symbol=""
+                     ,string expert=""
+                     ,int GMT_Broker_Time=2
+                     ,selectLine sl=0
+                     ,string extraSymbol=""
+                    );
+void initiateNews();
+bool checkDate(string &lastNewsTitle, string &symbolNews, string &impactNews, string &news1, string &news2, string &news3, datetime &timeRemaining, datetime date,string expertname = "",string symbol = "",string extraSymbol="", int gmt=2,string description_1 = "",int candle = 0);
+void PrintStructure();
+#import
 
 
 struct new_trade_store
 struct new_trade_store
   {
   {
@@ -42,6 +84,11 @@ enum lotcalculator
 
 
 sinput       string                  string_0                   = "<><><><><><> General SETTINGS <><><><><><>";   //__
 sinput       string                  string_0                   = "<><><><><><> General SETTINGS <><><><><><>";   //__
 input        int                     magic_no                   = 333;             // Magic no
 input        int                     magic_no                   = 333;             // Magic no
+input        bool                    bothHitsSl                 = false;           // Open after Both Hits StopLoss
+input        int                     maxTrades                  = 2;               // Max Concurrent Trades
+input        int                     maxSlippage                = 5;               // Max Slippage
+input        bool                    enableSpreadFilter         = false;           // Enable Spread Filter
+input        double                  maximumSpread              = 10;              // Maximum Spread
 
 
 input        string                  string_1                   = "<><><><><><> Lot Management<><><><><><>";   //__
 input        string                  string_1                   = "<><><><><><> Lot Management<><><><><><>";   //__
 input        lotcalculator           lot_calculator             = fix;             // Lot Size Option
 input        lotcalculator           lot_calculator             = fix;             // Lot Size Option
@@ -51,8 +98,25 @@ input        double                  dollars                    = 10;
 
 
 input        string                  string_2                   = "<><><><><><> Time Filter Setting <><><><><><> ";//_
 input        string                  string_2                   = "<><><><><><> Time Filter Setting <><><><><><> ";//_
 input        bool                    enableTimeSession          = false;           // Enable Time Session
 input        bool                    enableTimeSession          = false;           // Enable Time Session
-input        string                  start_time                 = "01:00";         // Start Session
-input        string                  end_time                   = "23:59";         // End Session
+input        string                  start_time_session         = "01:00";         // Start Session
+input        string                  end_time_session           = "23:59";         // End Session
+
+input        string                  news                       = "<><><><><><> News Settings <><><><><><>";         // News
+input        NewsCloseOrder          newsClose                  = CloseAllRunningOrder; // On News Action on Running Orders
+input        bool                    High_Impact_News           = true;                 //High Impact News
+input        int                     High_Start_Time            = 60;                   //Stop Trade before high News (min)
+input        int                     High_Stop_Time             = 15;                   //Stop Trade after high News (min)
+input        bool                    show_high_line             = true;                 //Show verticle Line when high news comes
+input        selectLine              Select_News_Line           = 0;                    //News Line
+input        bool                    mobileAlert                = true;                 //Mobile Alert
+input        bool                    Medium_Impact_News         = false;                // Medium Impact News
+input        int                     Medium_Start_Time          = 60;                   // Stop Trade before medium News (min)
+input        int                     Medium_Stop_Time           = 15;                   // Stop Trade after medium News (min)
+input        bool                    show_medium_line           = false;                // Show vertical Line when medium news comes
+input        bool                    Low_Impact_News            = false;                // Low Impact News
+input        int                     Low_Start_Time             = 60;                   // Stop Trade before low News (min)
+input        int                     Low_Stop_Time              = 15;                   // Stop Trade after low News (min)
+input        bool                    show_low_line              = false;                // Show vertical Line when low news comes
 
 
 // Global Variables
 // Global Variables
 static double tickCurrentBid = 0;
 static double tickCurrentBid = 0;
@@ -60,6 +124,9 @@ double tickPreviousBid = 0;
 static double tickCurrentAsk = 0;
 static double tickCurrentAsk = 0;
 double tickPreviousAsk = 0;
 double tickPreviousAsk = 0;
 datetime startSessionTime, endSessionTime;
 datetime startSessionTime, endSessionTime;
+int GMT_Broker_Time = +2; // GMT_Broker_Time Time of your Broker
+int                     gmt                        = 0;                   // GMT_Broker_Time Time of your Broker
+string Lname="newsLabel3";
 //+------------------------------------------------------------------+
 //+------------------------------------------------------------------+
 //|                                                                  |
 //|                                                                  |
 //+------------------------------------------------------------------+
 //+------------------------------------------------------------------+
@@ -67,9 +134,8 @@ int OnInit()
   {
   {
 //---
 //---
    Print(" OnInIt. ");
    Print(" OnInIt. ");
-
    trade.SetExpertMagicNumber(magic_no);
    trade.SetExpertMagicNumber(magic_no);
-   trade.SetDeviationInPoints(10);
+   trade.SetDeviationInPoints(maxSlippage);
    trade.SetTypeFilling(ORDER_FILLING_IOC);
    trade.SetTypeFilling(ORDER_FILLING_IOC);
    trade.LogLevel(LOG_LEVEL_ALL);
    trade.LogLevel(LOG_LEVEL_ALL);
    trade.SetAsyncMode(false);
    trade.SetAsyncMode(false);
@@ -124,8 +190,34 @@ int OnInit()
       Print(" InValid Handler. Error: ", GetLastError());
       Print(" InValid Handler. Error: ", GetLastError());
      }
      }
 
 
-   timeFilter(true,start_time, end_time, startSessionTime, endSessionTime);
+   timeFilter(true,start_time_session, end_time_session, startSessionTime, endSessionTime);
    Print(" Session Start  = ", startSessionTime,  " Asian  Session End = ", endSessionTime);
    Print(" Session Start  = ", startSessionTime,  " Asian  Session End = ", endSessionTime);
+
+   int timeDifference = (int)TimeCurrent() - (int)TimeGMT();
+   Print("Time Difference is: ", timeDifference);
+
+   if(timeDifference > 0)
+     {
+      GMT_Broker_Time = (int)MathRound((double)timeDifference / 3600.0);
+     }
+   else
+      if(timeDifference < 0)
+        {
+         GMT_Broker_Time = (int)MathRound((double)timeDifference / 3600.0);
+        }
+      else // timeDifference == 0
+        {
+         GMT_Broker_Time = 0;
+        }
+
+   Print("Gmt Time: ", TimeGMT(), " Broker Gmt Time: ", GMT_Broker_Time);
+   gmt = GMT_Broker_Time;
+
+   if(!MQLInfoInteger(MQL_TESTER))
+     {
+      initiateNews(); // change here
+     }
+
 //---
 //---
    return(INIT_SUCCEEDED);
    return(INIT_SUCCEEDED);
   }
   }
@@ -141,6 +233,120 @@ void OnDeinit(const int reason)
 //| Expert tick function                                             |
 //| Expert tick function                                             |
 //+------------------------------------------------------------------+
 //+------------------------------------------------------------------+
 void OnTick()
 void OnTick()
+  {
+     static int status=-1,preStatus=-1;
+   if(!MQLInfoInteger(MQL_TESTER))
+     {
+      status=returnNewsStatus(High_Impact_News
+                              ,High_Start_Time
+                              ,High_Stop_Time
+
+                              ,show_high_line
+                              ,Medium_Impact_News
+                              ,Medium_Start_Time
+                              ,Medium_Stop_Time
+
+                              ,show_medium_line
+                              ,Low_Impact_News
+                              ,Low_Start_Time
+                              ,Low_Stop_Time
+
+                              ,show_low_line
+                              ,Symbol()
+                              ,MQLInfoString(MQL_PROGRAM_NAME)
+                              ,GMT_Broker_Time
+                              ,Select_News_Line
+                              ,""
+                             );
+     }
+   else
+      status=0;
+
+   if(status==0)
+     {
+      mainActivity();
+     }
+   if(status==1 || status==2 || status==3)
+     {
+      if(newsClose==0)
+        {
+         if(orderCount_1(POSITION_TYPE_BUY,magic_no)>0)
+            closeTrades(POSITION_TYPE_BUY,magic_no);
+         if(orderCount_1(POSITION_TYPE_SELL,magic_no)>0)
+            closeTrades(POSITION_TYPE_SELL,magic_no);
+        }
+      else
+         if(newsClose==1)
+           {
+            if((orderCount_1(POSITION_TYPE_BUY,magic_no)>0) || (orderCount_1(POSITION_TYPE_SELL,magic_no)>0))
+              {
+               mainActivity();
+              }
+           }
+
+     }
+   if(status!=preStatus)
+     {
+      if(status==0 && preStatus!=-1)
+        {
+         // if(ObjectFind(0,Lname))
+           {
+
+            // ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrRed);
+            ObjectSetString(0,Lname,OBJPROP_TEXT,"");
+           }
+         Alert("Trading is start");
+         if(mobileAlert)
+            SendNotification("Trading is start");
+
+         preStatus=status;
+        }
+      else
+         if(status==1)
+           {
+            ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrRed);
+            ObjectSetString(0,Lname,OBJPROP_TEXT,"High Impact News");
+            Alert("Trading Stop due to high impact news");
+
+            if(mobileAlert)
+               SendNotification("Trading Stop due to high impact news");
+
+            preStatus=status;
+           }
+         else
+            if(status==2)
+              {
+               ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrBlue);
+               ObjectSetString(0,Lname,OBJPROP_TEXT,"Medium Impact News");
+               Alert("Trading Stop due to medium impact news");
+
+               if(mobileAlert)
+                  SendNotification("Trading Stop due to medium impact news");
+
+               preStatus=status;
+              }
+            else
+               if(status==3)
+                 {
+                  ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrGreen);
+                  ObjectSetString(0,Lname,OBJPROP_TEXT,"Low Impact News");
+                  Alert("Trading Stop due to low impact news");
+
+                  if(mobileAlert)
+                     SendNotification("Trading Stop due to low impact news");
+
+                  preStatus=status;
+                 }
+     }
+   else
+     {
+      mainActivity();
+     }
+  }
+//+------------------------------------------------------------------+
+//|                                                                  |
+//+------------------------------------------------------------------+
+void mainActivity()
   {
   {
 //---
 //---
    double Bid = SymbolInfoDouble(Symbol(), SYMBOL_BID);
    double Bid = SymbolInfoDouble(Symbol(), SYMBOL_BID);
@@ -169,14 +375,94 @@ void OnTick()
      }
      }
 
 
 // Print(" Time is: ", TimeCurrent());
 // Print(" Time is: ", TimeCurrent());
-   timeFilter(false,start_time, end_time, startSessionTime, endSessionTime);
-   Comment(" Session Start  = ", startSessionTime,  " Asian  Session End = ", endSessionTime);
+   timeFilter(false,start_time_session, end_time_session, startSessionTime, endSessionTime);
+// Comment(" Session Start  = ", startSessionTime,  " Asian  Session End = ", endSessionTime);
    if((!enableTimeSession) || (enableTimeSession && TimeCurrent() >= startSessionTime && TimeCurrent() <= endSessionTime))
    if((!enableTimeSession) || (enableTimeSession && TimeCurrent() >= startSessionTime && TimeCurrent() <= endSessionTime))
      {
      {
       tradePlacingCheck();
       tradePlacingCheck();
+      if(bothHitsSl)
+        {
+         removeBuySellOnSlHit();
+        }
+     }
+  }
+//+------------------------------------------------------------------+
+//+------------------------------------------------------------------+
+//|                                                                  |
+//+------------------------------------------------------------------+
+void closeTrades(int type,int magicno)
+  {
+   Print("Total order: ",OrdersTotal());
+   for(int i= PositionsTotal()-1; i>=0; i--)
+     {
+      //  Print(" Selection: ",OrderSelect(i,SELECT_BY_POS)," i: ",i,"  OrdersTotal(): ", OrdersTotal());
+      ulong ticket = PositionGetTicket(i);
+      if(PositionSelectByTicket(ticket))
+        {
+         if(PositionGetInteger(POSITION_TYPE) == type)
+           {
+            if(PositionGetInteger(POSITION_MAGIC) == magicno && PositionGetString(POSITION_SYMBOL) == Symbol())
+              {
+               //trade.PositionClose(PositionGetInteger(POSITION_TICKET))
+               if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
+                 {Print("Problem in closing order order ",PositionGetInteger(POSITION_TICKET)); }
+               else
+                 {
+                  Print("Order Closed by closeTrades() new filter",PositionGetInteger(POSITION_TICKET));
+                 }
+              }
+           }
+        }
+     }
+  }
+//+------------------------------------------------------------------+
+//|                                                                  |
+//+------------------------------------------------------------------+
+int orderCount_1(int type,int magic)
+  {
+   int count1=0;
+   for(int i= PositionsTotal()-1; i>=0; i--)
+     {
+      //  Print(" Selection: ",OrderSelect(i,SELECT_BY_POS)," i: ",i,"  OrdersTotal(): ", OrdersTotal());
+      ulong ticket = PositionGetTicket(i);
+      if(PositionSelectByTicket(ticket))
+        {
+         //   if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY || PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
+         if(PositionGetInteger(POSITION_MAGIC) == magic && PositionGetString(POSITION_SYMBOL) == Symbol())
+           {
+            //trade.PositionClose(PositionGetInteger(POSITION_TICKET))
+            if(PositionGetInteger(POSITION_TYPE) == type)
+              {
+               count1++;
+              }
+           }
+        }
      }
      }
+   return count1;
   }
   }
 //+------------------------------------------------------------------+
 //+------------------------------------------------------------------+
+//|                                                                  |
+//+------------------------------------------------------------------+
+int orderCount(int type)
+  {
+   int count = 0;
+   for(int i= PositionsTotal()-1; i>=0; i--)
+     {
+      ulong ticket = PositionGetTicket(i);
+
+      if(PositionSelectByTicket(ticket))
+        {
+         if(PositionGetInteger(POSITION_MAGIC) == magic_no && PositionGetString(POSITION_SYMBOL) == Symbol())
+           {
+            if(PositionGetInteger(POSITION_TYPE) == type)
+              {
+               count++;
+              }
+           }
+        }
+     }
+   return count;
+  }
 //+------------------------------------------------------------------+
 //+------------------------------------------------------------------+
 //|                                                                  |
 //|                                                                  |
 //+------------------------------------------------------------------+
 //+------------------------------------------------------------------+
@@ -221,15 +507,24 @@ void tradePlacingCheck()
         {
         {
          if(newTradeStore[i].price > 0)
          if(newTradeStore[i].price > 0)
            {
            {
-            double levelPriceIs = newTradeStore[i].price;
-            if((tickPreviousBid > levelPriceIs && tickCurrentBid < levelPriceIs) ||
-               (tickPreviousBid < levelPriceIs && tickCurrentBid > levelPriceIs))
+            if(TimeCurrent() > newTradeStore[i].start_time && TimeCurrent() < newTradeStore[i].end_time)
               {
               {
-               ulong buyTicket = placeBuyTrade(newTradeStore[i].stop_loss, newTradeStore[i].take_profit);
-               ulong sellTicket = 0; // placeSellTrade(newTradeStore[i].stop_loss, newTradeStore[i].take_profit);
-
-               newTradeStore[i].buy_ticket = buyTicket;
-               newTradeStore[i].sell_ticket = sellTicket;
+               double levelPriceIs = newTradeStore[i].price;
+               if((tickPreviousBid > levelPriceIs && tickCurrentBid < levelPriceIs) ||
+                  (tickPreviousBid < levelPriceIs && tickCurrentBid > levelPriceIs))
+                 {
+                  if(countLiveTrades() < maxTrades)
+                    {
+                     if((enableSpreadFilter && spreadFilter()) || !enableSpreadFilter)
+                       {
+                        ulong buyTicket = placeBuyTrade(newTradeStore[i].stop_loss, newTradeStore[i].take_profit);
+                        ulong sellTicket = placeSellTrade(newTradeStore[i].stop_loss, newTradeStore[i].take_profit);
+
+                        newTradeStore[i].buy_ticket = buyTicket;
+                        newTradeStore[i].sell_ticket = sellTicket;
+                       }
+                    }
+                 }
               }
               }
            }
            }
         }
         }
@@ -450,3 +745,126 @@ void timeFilter(bool onInit,string startTime,string endTime,datetime & sessionSt
 //+------------------------------------------------------------------+
 //+------------------------------------------------------------------+
 //|                                                                  |
 //|                                                                  |
 //+------------------------------------------------------------------+
 //+------------------------------------------------------------------+
+void removeBuySellOnSlHit()
+  {
+   for(int i = 0 ; i < MaxOrders ; i++)
+     {
+      bool isBuyPresent=false, isSellPresent=false;
+      if(newTradeStore[i].buy_ticket != -1 && newTradeStore[i].sell_ticket != -1)
+        {
+         for(int j = PositionsTotal()-1; j>=0; j--)
+           {
+            ulong ticket = PositionGetTicket(j);
+            if(PositionSelectByTicket(ticket))
+              {
+               if(ticket == newTradeStore[i].buy_ticket)
+                 {
+                  isBuyPresent=true;
+                 }
+              }
+           }
+
+         for(int j = PositionsTotal()-1; j>=0; j--)
+           {
+            ulong ticket = PositionGetTicket(j);
+            if(PositionSelectByTicket(ticket))
+              {
+               if(ticket == newTradeStore[i].sell_ticket)
+                 {
+                  isSellPresent = true;
+                 }
+              }
+           }
+
+         if(!isBuyPresent && !isSellPresent)
+           {
+            if(tradeHitSL(newTradeStore[i].buy_ticket) && tradeHitSL(newTradeStore[i].sell_ticket))
+              {
+               Print("Buy/Sell Ticket is closed on StopLoss so removed from struct. Buy Ticket: ", newTradeStore[i].buy_ticket, " Sell Ticket: ", newTradeStore[i].sell_ticket);
+               newTradeStore[i].buy_ticket  = (ulong)-1;
+               newTradeStore[i].sell_ticket = (ulong)-1;
+               //newTradeStore[i].symbol      = "";
+               //newTradeStore[i].price       = 0.0;
+               //newTradeStore[i].stop_loss   = 0.0;
+               //newTradeStore[i].take_profit = 0.0;
+               //newTradeStore[i].start_time  = 0;
+               //newTradeStore[i].end_time    = 0;
+              }
+           }
+        }
+     }
+  }
+//+------------------------------------------------------------------+
+//|                                                                  |
+//+------------------------------------------------------------------+
+bool tradeHitSL(ulong positionID)
+  {
+
+   if(HistorySelectByPosition(positionID))
+     {
+      for(int i = 0; i < HistoryDealsTotal(); i++)
+        {
+         ulong dealTicket = HistoryDealGetTicket(i);
+         ulong dealPositionID = HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
+
+         if(HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT && dealPositionID == positionID)
+           {
+            int dealType = (int)HistoryDealGetInteger(dealTicket, DEAL_TYPE);
+            string comment = HistoryDealGetString(dealTicket, DEAL_COMMENT);
+
+            if(StringFind(comment, "sl", 0) >= 0)
+              {
+               //               if(dealType == DEAL_TYPE_BUY)
+               //                 {
+               //
+               //                 }
+               return true;
+              }
+           }
+        }
+     }
+   return false;
+  }
+//+------------------------------------------------------------------+
+//|                                                                  |
+//+------------------------------------------------------------------+
+int countLiveTrades()
+  {
+   int count = 0;
+
+   for(int i = 0; i < PositionsTotal(); i++)
+     {
+      ulong ticket = PositionGetTicket(i);
+      if(PositionSelectByTicket(ticket))
+        {
+         if(PositionGetInteger(POSITION_MAGIC) == magic_no)
+           {
+            if(PositionGetString(POSITION_SYMBOL) == Symbol())
+              {
+               if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY || PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
+                 {
+                  count++;
+                 }
+              }
+           }
+        }
+     }
+   return count;
+  }
+//+------------------------------------------------------------------+
+//|                                                                  |
+//+------------------------------------------------------------------+
+bool spreadFilter()
+  {
+   long spreadIs = SymbolInfoInteger(Symbol(), SYMBOL_SPREAD);
+   if(spreadIs > maximumSpread)
+     {
+      return false;
+     }
+   return true;
+  }
+//+------------------------------------------------------------------+
+//|                                                                  |
+//+------------------------------------------------------------------+
+
+//+------------------------------------------------------------------+