Martingale program

 

Hi, this martingale to my program isn't executing in the program. any ideas why?


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double bid=MarketInfo(Symbol(),MODE_BID);
double lot=MarketInfo(Symbol(),MODE_LOTSIZE);
double point=MarketInfo(Symbol(),MODE_POINT);
double tickSize=MarketInfo(Symbol(),MODE_TICKSIZE);
//double LotSize=0.01;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
#include <stdlib.mqh> 
enum Position
{ 
 q=0,// Buy Only
 w=1,// Sell Only
 r=2 // Both
};
enum trade
{ 
 a=0,//Strategy 1
 b=1,//Strategy 2
 d=2,//Strategy 3
 s=3 //Strategy 4
};
enum yn
{ 
 n=0,//ON
 y=1 //OFF
};


input string MM_Settings        = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>";// Money Management Settings .............................................
input double Lot                = 0.01;   // Lot 
input bool   Martingale         = 1;      // Use Martinga
input double Multiplier         = 2;      // Lot Multiplier
input int    MartinSteps        = 13;     // Martingale attempts 
input string Grid_Parameters    = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>";//Grid Parameters .......................................................
input yn     Use_grid           = 1;      // Use Grid
input int    Distance           = 10;     // Grid Distance
input int    MaxOpenOrders      = 1;      // Grid Add Open Orders
input double Multiplier1        = 2;      // Grid Multiplier
input int    CloseAtPipsProfit  = 5;      // Profit in pips
input double PercentProfit      = 5;      // Percent Profit
input string Trade_Parameters   = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>";//Trade Parameters .......................................................
input Position Trade            = 2;      // Trade Open Type
input double TakeProfit         = 1000;     // Take Profit   
input double StopLoss           = 1000;     // Stop Loss   
input bool   ExitOpposite       = 0;      // Opposite Signal
input int    MN                 = 1;      // Magic
input string TrailingStopLoss   = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>";// Trailing Stop Settings ...............................................
input bool   UseTrailingStop    = 0;      // Use Trailing 
input double TrailingStart          = 15;     // Trailing Start
input double TrailingStop       = 10;     // Trailing Distance 
input string Time_Filter        = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>";// Time Filter ................................................................. 
input bool   Use_Time_Filter    = 0;      // Use Time Filter
input string Time_Start         = "00:00";// Time Start
input string Time_End           = "23:59";// Time End 



double ClosingArray[100];
int Pip=10, lotdigit=0,sh=0,sg=0,sf=0,ss=0;
string text[26], prefix="";
bool Buy=0, Sell=0; 


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
  static int LastBar;
   if(OrdersTotal()<=100 && Bars > LastBar)
      //SELL
      int   res;
    if((High[3]-Low[3])/point >= 70 && Low[2] > Low[3] && High[3] <= High[2] &&
                        (Open[3]+Close[3])/2 <= Close[2] && Close[2] > Open[3] && Open[2] > Close[2] && Open[3] < Close[3]
                        && Open[1] > Close[1] && Close[1] <= Open[3]+30*_Point)
                       {
                        res=OrderSend(Symbol(),OP_SELL,Lots(),Bid,1,Bid+StopLoss*_Point,Bid-TakeProfit*Point,NULL,0,0,Green);
                       }
      LastBar=Bars+1;
   return;
  }
//+------------------------------------------------------------------+
double Lots()
  {double lots = Lot,LastLot=0, 
   LotStep = MarketInfo(Symbol(),MODE_LOTSTEP), MR = MarketInfo(Symbol(),MODE_MARGINREQUIRED),
   MaxLot = MarketInfo(Symbol(),MODE_MAXLOT), MinLot = MarketInfo(Symbol(),MODE_MINLOT);
  
   if(Martingale && LastLoss() <= MartinSteps){ lots = NormalizeDouble(lots * MathPow(Multiplier, LastLoss()), lotdigit);}
  
   if(Use_grid == 0){
   if(Orders(-1)==0){ LastLot = Lot;}else{ LastLot = FindLast("lot")*Multiplier1;}     
   if(Orders(-1) <= 1000){ lots = NormalizeDouble(LastLot,lotdigit);}   
    }  
  
   return( MathRound(MathMin(MathMax(lots,MinLot),MaxLot)/LotStep)*LotStep );}
double FindLast(string ParamName) 
{
  double mOrderPrice=0, mOrderLot=0;int PrevTicket=0, CurrTicket=0;
  
  for(int i = OrdersTotal() - 1; i >= 0; i--) 
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) 
      if(OrderSymbol() == Symbol() && OrderMagicNumber() == MN) 
       {
        CurrTicket = OrderTicket();
        if(CurrTicket > PrevTicket) 
         {
          PrevTicket = CurrTicket;
          mOrderPrice = OrderOpenPrice();
          mOrderLot = OrderLots();         
         }
      }   
  if(ParamName == "price") return(mOrderPrice);
  else if(ParamName == "lot") return(mOrderLot);
  return(0);
}      

int LastLoss()
  {int count=0, PrevTicket=0, CurrTicket=0;
    for(int x=0;x<=OrdersHistoryTotal()-1;x++)
      {bool os = OrderSelect(x,SELECT_BY_POS,MODE_HISTORY); 
       if(OrderSymbol()==Symbol() && (MN==0 || OrderMagicNumber()==MN)){
        
            if(OrderType() <= OP_SELL) CurrTicket = OrderTicket();
            if(CurrTicket > PrevTicket) 
              {PrevTicket = CurrTicket;  
               if(OrderProfit() < 0) count++;
               if(OrderProfit() > 0 || count >= MartinSteps) count=0;}}//}
              } 
   return(count);
}    
//////////////////
int Orders(int type=-1)
{int count=0;
   //-1= All,0=Buy,1=Sell,2=BuyLimit,3=SellLimit,4=BuyStop,5=SellStop,6=AllBuy,7=AllSell,8=AllMarket,9=AllPending;   
   for(int x=OrdersTotal()-1;x>=0;x--)
    {if(OrderSelect(x,SELECT_BY_POS,MODE_TRADES)){ 
      if(OrderSymbol()==Symbol() && (MN==0 || OrderMagicNumber()==MN)) 
        {if(type < 0){ count++;}
         if(OrderType() == type && type >= 0){ count++;}  
         if(OrderType() <= 1 && type == 8){ count++;}  
         if(OrderType() > 1 && type == 9){ count++;}  
         if((OrderType() == 0 || OrderType() == 2 || OrderType() == 4) && type == 6){ count++;}
         if((OrderType() == 1 || OrderType() == 3 || OrderType() == 5) && type == 7){ count++;}}}}   
         return(count);}
/////////////////////
bool CloseOrders(int type=-1)
{ //-1= All,0=Buy,1=Sell,2=BuyLimit,3=SellLimit,4=BuyStop,5=SellStop,6=All Buys,7=All Sells,8=All Market,9=All Pending;
  bool oc=0; double ask=MarketInfo(Symbol(), MODE_ASK), bid=MarketInfo(Symbol(), MODE_BID); 
  for(int i=OrdersTotal()-1;i>=0;i--){
  bool os = OrderSelect(i,SELECT_BY_POS, MODE_TRADES);
  if(OrderSymbol()==Symbol() && (MN==0 || OrderMagicNumber()==MN))
    {   
     if(type==-1){
     if(OrderType()==0){ oc = OrderClose(OrderTicket(),OrderLots(),bid,1000,clrGold);}
     if(OrderType()==1){ oc = OrderClose(OrderTicket(),OrderLots(),ask,1000,clrGold);}      
     if(OrderType()>1){ oc = OrderDelete(OrderTicket());}}  
     if(OrderType()>1 && type==9){ oc = OrderDelete(OrderTicket());} 
     if(OrderType()<=1 && type==8){ oc = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),1000,clrGold);}
     if(OrderType()==type && type==0){ oc = OrderClose(OrderTicket(),OrderLots(),bid,1000,clrGold);}
     if(OrderType()==type && type==1){ oc = OrderClose(OrderTicket(),OrderLots(),ask,1000,clrGold);} 
     if(OrderType()==type && OrderType()> 1){ oc = OrderDelete(OrderTicket());} 
     if(OrderType()==0 && type==6){ oc = OrderClose(OrderTicket(),OrderLots(),bid,1000,clrGold);}  
     if((OrderType()==2 || OrderType()== 4) && type==6){ oc = OrderDelete(OrderTicket());}   
     if(OrderType()==1 && type==7){ oc = OrderClose(OrderTicket(),OrderLots(),ask,1000,clrGold);}  
     if((OrderType()==3 || OrderType()== 5) && type==7){ oc = OrderDelete(OrderTicket());}       
     for(int x=0;x<100;x++)
     {
      if(ClosingArray[x]==0)
      {
       ClosingArray[x]=OrderTicket();
       break; } } } }
  return(oc);
}      
///////////////////////////
bool MarginCheck(int type)// 0 - buy, 1 - sell;
{if((AccountFreeMarginCheck(Symbol(), type, Lots()) <= 0.0 || 
      GetLastError() == ERR_NOT_ENOUGH_MONEY)){
      Print("NOT ENOUGH MONEY TO TRADE OPEN");return(false);}             
      return(true);}     
///////////////////////////////
//+------------------------------------------------------------------+
//| Check Symbol Points                                              |
//+------------------------------------------------------------------+     
double point(string symbol=NULL)  
  {string sym=symbol;
   if(symbol==NULL) sym=Symbol();
   double bid=MarketInfo(sym,MODE_BID);
   int digits=(int)MarketInfo(sym,MODE_DIGITS);
   if(digits<=1) return(1); //CFD & Indexes  
   if(digits==4 || digits==5) return(0.0001); 
   if((digits==2 || digits==3) && bid>1000) return(1);
   if((digits==2 || digits==3) && bid<1000) return(0.01);
   if(StringFind(sym,"XAU")>-1 || StringFind(sym,"xau")>-1 || StringFind(sym,"GOLD")>-1) return(0.1);//Gold  
   return(0);}
/////////////////////////////////
bool CurrBar()
{bool yes = 1;
   for(int i = OrdersTotal()-1; i >= 0; i--)
      {if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
                {if(OrderSymbol()==Symbol() && (MN==0 || OrderMagicNumber()==MN)) 
                 {if(OrderOpenTime() >= iTime(Symbol(),0,0)) yes = 0;}}}   
                    return(yes);}     
                    bool ClosedBar()
                  {bool yes = 1;
                for(int i = OrdersHistoryTotal()-1; i>=0; i--)
             {if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) 
          {Print("Error in history!"); break;}
        if(OrderSymbol() != Symbol() || OrderType()>OP_SELL) continue;
      if(OrderSymbol()==Symbol() && (MN==0 || OrderMagicNumber()==MN)) 
   {if(OrderOpenTime() >= iTime(NULL,0,0)) yes = 0;}}   
return(yes);}  
      
double CheckPipsProfit(int type=-1) //-1= All,0=Buy,1=Sell; 
{
   double BuyPt=0, SellPt=0; 
      
   for(int i=OrdersTotal()-1;i>=0;i--)
      {
       bool os = OrderSelect(i,SELECT_BY_POS, MODE_TRADES);            
       if(OrderSymbol()==Symbol() && (MN==0 || OrderMagicNumber()==MN))
         {        
         if(OrderType()==OP_BUY){
         BuyPt=BuyPt+((MarketInfo(OrderSymbol(),MODE_BID)-OrderOpenPrice())/point());} 
         if(OrderType()==OP_SELL){
         SellPt=SellPt+((OrderOpenPrice()-MarketInfo(OrderSymbol(),MODE_ASK))/point());} 
         }} 
       if(0==type){ return(BuyPt);}
       if(1==type){ return(SellPt);}
       if(-1==type){ return(BuyPt+SellPt);}
   return(0);
} 
double CheckProfit(int type=-1) //-1= All,0=Buy,1=Sell;
{
   double BuyPt=0, SellPt=0; 
       
   for(int i=OrdersTotal()-1;i>=0;i--)
      {
       bool os = OrderSelect(i,SELECT_BY_POS, MODE_TRADES);            
       if(OrderSymbol()==Symbol() && (MN==0 || OrderMagicNumber()==MN))
         {        
          if(OrderType()==OP_BUY){ BuyPt+=OrderProfit()+OrderSwap()+OrderCommission();} 
          if(OrderType()==OP_SELL){ SellPt+=OrderProfit()+OrderSwap()+OrderCommission();} 
         }} 
       if(0==type){ return(BuyPt);}
       if(1==type){ return(SellPt);}
       if(-1==type){ return(BuyPt+SellPt);}
   return(0);
} 
 
  1. double bid=MarketInfo(Symbol(),MODE_BID);
    double lot=MarketInfo(Symbol(),MODE_LOTSIZE);
    double point=MarketInfo(Symbol(),MODE_POINT);
    double tickSize=MarketInfo(Symbol(),MODE_TICKSIZE);
    //double LotSize=0.01;

    Those are not assignments; they are initialization of a common (globally declared), or static variable with a constant. They work exactly the same way in MT4/MT5/C/C++.

    1. They are initialized once on program load.

    2. They don't update unless you assign to them.

    3. In C/C++ you can only initialize them with constants, and they default to zero. In MTx you should only initialize them with constants. There is no default in MT5, or MT4 with strict (which you should always use).

      MT4/MT5 actually compiles with non-constants, but the order that they are initialized is unspecified and

      Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:

      1. Terminal starts.
      2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
      3. OnInit is called.
      4. For indicators OnCalculate is called with any existing history.
      5. Human may have to enter password, connection to server begins.
      6. New history is received, OnCalculate called again.
      7. New tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.

    4. Unlike indicators, EAs are not reloaded on chart change, so you must reinitialize them, if necessary.
                external static variable - MQL4 programming forum #2 (2013)

  2. res=OrderSend(Symbol(),OP_SELL,Lots(),Bid,1,Bid+StopLoss*_Point,Bid-TakeProfit*Point,NULL,0,0,Green);

    You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit and open at the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close to a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)
      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes. My GBPJPY shows average spread = 26 points, but average maximum spread = 134 (your broker will be similar).

 
William Roeder #:
  1. Those are not assignments; they are initialization of a common (globally declared), or static variable with a constant. They work exactly the same way in MT4/MT5/C/C++.

    1. They are initialized once on program load.

    2. They don't update unless you assign to them.

    3. In C/C++ you can only initialize them with constants, and they default to zero. In MTx you should only initialize them with constants. There is no default in MT5, or MT4 with strict (which you should always use).

      MT4/MT5 actually compiles with non-constants, but the order that they are initialized is unspecified and

      Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:

      1. Terminal starts.
      2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
      3. OnInit is called.
      4. For indicators OnCalculate is called with any existing history.
      5. Human may have to enter password, connection to server begins.
      6. New history is received, OnCalculate called again.
      7. New tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.

    4. Unlike indicators, EAs are not reloaded on chart change, so you must reinitialize them, if necessary.
                external static variable - MQL4 programming forum #2 (2013)

  2. You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit and open at the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close to a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)
      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes. My GBPJPY shows average spread = 26 points, but average maximum spread = 134 (your broker will be similar).

thanks William

Reason: