On randomly large values of required margin.

 

Greetings,

 I was trying to program an EA that moves 22% of my  free margin for every trade it opens. Only one position is open at a time and the only positions opened are those from the EA.

The code I used for finding out the size of the trade was this one:

int AdjustLot(){
   double sizePosition =AccountFreeMargin()*0.22; //slice of free margin used in every new trade
   double step = MarketInfo(Symbol(),MODE_LOTSTEP); //smaller increment possible in a position size
   double lotSize =MarketInfo(Symbol(),MODE_MARGINREQUIRED); //how much do i need for each lot
   double lots = MathFloor(sizePosition/(lotSize*step))*step; //number of lots
   Print("Adjusting trade size for ",lots," lots!");
   return(lots);
 }

 And the this function gets called right before I open a new poisiton. For example:

//A old position is close right before here
while(true){//keep trying to send the new order until accepted!
    lots=AdjustLots();
    RefreshRates();
    if(OrderSend(Symbol(),OP_BUY,lots,Ask,3,Ask-1000*Point,Ask+1000*Point,"sending order",magicN,0,Green)>=0){
        break; //Stop trying when the order is accepted!
    }else{
        erro=GetLastError();
        Print("Error ",erro,".");
    }
}//end of while
 The EA only closes a short position if it will open a long one and vice-versa.

 The problem is: Most of the times the locked margin is  just what i expected (22%). But there are times that the locked margin is almost the double of what I expected. Any ideas of why it happens? My bet is there is something wrong with the timing of the communication with the server, but I don't know what it is.


 

Your calculation is for the margin to open. Then as a trade goes against (including the initial spread on a buy) the margin used increases until stop out.

Your method will wipe your account very quickly.

If what you really want is to limit your risk to a percentage of the account, see my code.

 

Hi,

Thanks for the help. I'm aware that the margin will increase. But it was weird that the initial margin was very different from times to times. Example: I have 95000 USD free in a demo account. Since i'm trading 22% of it, I use 20900 USD as margin for a long position, which corresponds to X lots. A day later, the EA reverses the position. It closes the long position with something around 10 USD profit only and opens a short position of X lots, but this time, something around 41800USD are used as margin. In both trades a pip had the same value but the margin locked for the trade was almost two times bigger. Have you seen this problem before?