Download MetaTrader 5
To add comments, please log in or register
Find out the most discussed Forum topics. Have a look at the Wall section!
1mathboy1 2015.02.27 04:32 

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.");
      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