Monitoring margin capacity (how close to a margin call)

 

My expert adviser runs on a remote virtual private server so it sends four email reports per day giving the current state of the account.

One thing that it is useful to monitor in these emails is how close the expert adviser is to a margin call. If there is a margin call, open positions will be liquidated by the broker to avoid the account going negative, which is a very bad thing to happen.

I have called the closeness to a margin call "margin capacity". Its a value calculated from the point at which the broker will make a margin call, and from the available margin information.

For example, a margin capacity of x 10 or more would be comfortable, but x 3 would be worrying. In theory the margin call would occur at x 1, although I hope I never experience this.


Margin capacity can be calculated using the code below. The formula used assumes that the margin level is calculated as:-

100(FreeMargin/Margin+1)%


One of the pieces of information used in this formula is the account stopout level. This is the margin level value at or below which the broker will make a margin call. This will differ between brokers and accounts. I have not yet discovered how the margin (the used margin) is calculated - it seems to vary depending on the number of open positions and their current state. It appears to be recalculated by the broker upon each trade. Whilst it would be interesting to know the precise way in which it is calculated, for the purpose of working out margin capacity, it is not important.


double fm=AccountFreeMargin();

double am=AccountMargin();

double asl=AccountStopoutLevel();

double mc=0;

if((fm!=0)&&(am!=0)&&(asl!=0)) { mc=(((fm/am)+1)*(100/asl)); }


"MarginCapacity: x "+DoubleToStr(mc,2)+"\n"+ // report the margin capacity in a string within the email body


Checking the fm, am and mc values before making the calculation is important because with a bad connection one or more of these values could be zero, which would give an erroneous result for margin capacity. If this happens, this code reports margin capacity as zero. The test also avoids a divide-by-zero exception occurring, which would happen if am or asl were zero. But this does mean that, with no open trades at all (so that the margin is truly zero), the margin capacity will be reported as zero.