Problem Description
Solution
To programmatically retrieve your account balance and equity in MQL4, you utilize the native account information functions AccountBalance() and AccountEquity().
Below are two examples: a simple script to print the values to the terminal log, and a practical function demonstrating how to use Equity for dynamic position sizing (money management).
1. Simple Script to Retrieve Data
This script simply queries the trading server for the current state of the account and prints the results to the "Experts" tab in the terminal.
//+------------------------------------------------------------------+
//| GetAccountInfo_Script.mq4 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
#property script_show_inputs
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
// Retrieve Account Balance (Closed trades only)
double currentBalance = AccountBalance();
// Retrieve Account Equity (Balance + Floating Profit/Loss)
double currentEquity = AccountEquity();
// Calculate Floating P/L
double floatingPL = currentEquity - currentBalance;
// Output to the Experts log
Print("=========================================");
Print("Account Number: ", AccountNumber());
Print("Account Balance: ", DoubleToString(currentBalance, 2));
Print("Account Equity: ", DoubleToString(currentEquity, 2));
Print("Floating P/L: ", DoubleToString(floatingPL, 2));
Print("=========================================");
}
//+------------------------------------------------------------------+
2. Practical Application: Equity-Based Risk Management
In quantitative trading, it is best practice to calculate lot size based on Equity rather than Balance. If you are in a drawdown, using Equity forces the algorithm to reduce position sizes to protect the remaining capital.
Here is a robust function you can drop into an Expert Advisor:
//+------------------------------------------------------------------+
//| Helper Function: Calculate Lots based on Equity Risk |
//+------------------------------------------------------------------+
double GetLotSizeBasedOnEquity(double riskPercentage, double stopLossPips)
{
// 1. Get Current Equity
double equity = AccountEquity();
// 2. Calculate Risk Capital
double riskAmount = equity * (riskPercentage / 100.0);
// 3. Get Symbol Information
double tickValue = MarketInfo(Symbol(), MODE_TICKVALUE);
double point = MarketInfo(Symbol(), MODE_POINT);
double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
double minLot = MarketInfo(Symbol(), MODE_MINLOT);
double maxLot = MarketInfo(Symbol(), MODE_MAXLOT);
// Adjust for 3/5 digit brokers
double pipsToPoints = stopLossPips;
if(Digits == 3 || Digits == 5) pipsToPoints *= 10;
// 4. Calculate Raw Lot Size
// Formula: RiskAmount / (StopLossPoints * TickValue)
if(pipsToPoints == 0 || tickValue == 0) return(minLot); // Prevent division by zero
double rawLots = riskAmount / (pipsToPoints * tickValue);
// 5. Normalize to Broker Steps
double lots = MathFloor(rawLots / lotStep) * lotStep;
// 6. Cap against Min/Max limits
if(lots < minLot) lots = minLot;
if(lots > maxLot) lots = maxLot;
return(lots);
}
// Example Usage inside OnTick:
/*
void OnTick()
{
// Calculate lot size risking 2% of current Equity with a 50 pip Stop Loss
double tradeSize = GetLotSizeBasedOnEquity(2.0, 50);
// ... OrderSend logic here ...
}
*/
Key Differences
- AccountBalance(): Returns the amount of money in the account excluding open positions. It only changes when a trade is closed or a deposit/withdrawal occurs.
- AccountEquity(): Returns the actual value of the account at the current moment. Formula:
Balance + Floating Profit - Floating Loss.
Q&A
Q: Can I use AccountInfoDouble instead?
A: Yes. MQL4 was updated to include MQL5-style functions. You can use AccountInfoDouble(ACCOUNT_BALANCE) and AccountInfoDouble(ACCOUNT_EQUITY). However, AccountBalance() and AccountEquity() are the native MQL4 functions and are slightly faster to type and execute in the older environment.
Q: Does AccountEquity() include swap and commission costs?
A: Yes. Equity is calculated as Balance + (Floating Profit/Loss of all open positions). The floating profit/loss calculation includes the current bid/ask price difference, accrued swaps, and commissions charged immediately upon entry.
Q: Why does my Equity not update in the Strategy Tester?
A: In the Strategy Tester, AccountEquity() updates on every tick based on the simulated price movement. If you are running a test on "Open prices only," the equity will only update at the opening of a new bar. Ensure you are testing on "Every tick" for precise equity simulation.