# MoneyManagement.mqh

```//+------------------------------------------------------------------+
//|                                                       common.mq4 |
//|                                                http://esolvix.de |
//+------------------------------------------------------------------+

/**
* External Variables
*/
extern   double   Risk        =  0.02;

double   balance              =  0.00;
double   equity               =  0.00;
double   marginFree           =  0.00;
double   marginUsed           =  0.00;
double   marginUsedPercent    =  0.00;
double   marginUsablePercent  =  0.00;
double   profitLossPercentage =  0.00;

/**
* Calculate optimal lot size
* If sl has been set, calculate lot size according to stop loss,
* else use risk% of margin as lot size
*
* Parameter: sl, Stop Loss in Point-Value (e.g. 0.0050 = 50 pips)
*
*/
double lotsOptimized(double stoploss)
{
double lots;

// Set risk in correct boundaries
if (Risk < 0.001)
Risk = 0.001;
if (Risk > 0.50)
Risk = 0.50;

double leverage = MarketInfo(Symbol(),MODE_LOTSIZE) / MarketInfo(Symbol(),MODE_MARGINREQUIRED);

// Calculate used margin according to risk if stop loss is too small
if ((stoploss < MarketInfo(Symbol(),MODE_STOPLEVEL)) && (stoploss > 0))
{
lots = AccountEquity() * Risk * leverage / MarketInfo(Symbol(),MODE_LOTSIZE);
}
// Calculate lot, so that only Risk% of equity can be lost
else
{
// Translate stoploss to pip values
// if stoploss negative, make it positive
if (stoploss < 0)
stoploss = -stoploss / MarketInfo(Symbol(),MODE_POINT);
else
stoploss =stoploss / MarketInfo(Symbol(),MODE_POINT);

// Calculate the value of one pip per lot
double PipValuePerLot = MarketInfo(Symbol(),MODE_LOTSIZE) * MarketInfo(Symbol(),MODE_POINT);

// Calculate the needed value per pip to risk correct amount of capital according to sl size
double NeededPipValue = AccountEquity() * Risk / stoploss;

// Calculate the optimal lot size
lots = NeededPipValue / PipValuePerLot;
}

// Check if lot size is in correct boundaries
if (lots < MarketInfo(Symbol(),MODE_MINLOT))
lots = MarketInfo(Symbol(),MODE_MINLOT);
else if (lots > MarketInfo(Symbol(),MODE_MAXLOT))
lots = MarketInfo(Symbol(),MODE_MAXLOT);

return(lots);
}

/**
* Recalculates current free, used margin and other values
*/
double updateMoneyManager()
{
balance = AccountBalance();
equity = AccountEquity();

marginFree = AccountFreeMargin();
marginUsed = equity - marginFree;

marginUsedPercent = marginUsed / equity * 100;
marginUsablePercent = marginFree / equity * 100;

profitLossPercentage = AccountProfit() / balance * 100;
}```