Download MetaTrader 5

Problem with checking margin

To add comments, please log in or register
1mathboy1
118
1mathboy1  

I'm coding an EA and I have a margin check within my EA to make sure I have enough margin to enter a trade. But for some reason I always get an insufficient margin, and I have no idea what's wrong. Here is my code: 

 

//checks if we can send the order based on margin levels.
bool enoughmargin(double marginlevel, //Example: if you want at least 200% margin level enter 200. 
                  double lots,        //Lot size of the impending trade.
                  string symbol){     //symbol on which we are trading.
   if(lots==0){ return False;}               
   if(AccountEquity() *100  >= marginlevel * (MarketInfo(symbol,MODE_MARGINREQUIRED) * lots + AccountMargin())){
      return True;
   }
   return False;
}

double calculateLots(string symbol, double SL, int timeframe) {
   if (AutoLots == False) {
      return Lot;
   }
   double pipsAtRisk = MathAbs(iClose(symbol,timeframe,1)-SL) / (Point*multiplier);
   double currencyAtRiskForOneLot = pipsAtRisk * getValueOfTick(1.0) * multiplier;
   double maxAccountRisk = NormalizeDouble( (AccountEquity() * (risk / 100)), 2);
   double calculatedLots = NormalizeDouble(maxAccountRisk / currencyAtRiskForOneLot, 2);
   
   if(!enoughmargin(minlevel, calculatedLots, symbol) 
      && enoughmargin(minlevel, NormalizeDouble(calculatedLots/2,2),symbol)) {
      Print("Insufficient margin for full trade. Half position opened instead.");
      calculatedLots=NormalizeDouble(calculatedLots/2,2);
      return calculatedLots;
   }
   if(!enoughmargin(minlevel, NormalizeDouble(calculatedLots/2,2),symbol)){
      Print("Insufficient margin.");
      return -1.0;
   }
   return calculatedLots;
}
To add comments, please log in or register