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;
}
Allow the use of cookies to log in to the MQL5.com website.
Please enable the necessary setting in your browser, otherwise you will not be able to log in.
You are signed in. Two-factor authentication has been disabled. Set it up again and scan a new QR code, or continue with two-factor authentication disabled.
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: