21 January 2024

In MQL5, when initiating a buy order, the platform typically uses lot size as a measure. However, there are instances where you might prefer to specify the amount in currency rather than lots. In this example, we illustrate this approach by considering an investment of 1000 units of currency.

The first step involves obtaining the current price of the symbol being traded. Subsequently, we calculate the corresponding lot size that can be acquired with the specified currency amount, rounding down to the nearest whole number. If the calculated lot size is zero, indicating insufficient funds, the purchase is not executed.

It's important to note a couple of considerations in this example. Firstly, we avoid the use of fractional lots. Additionally, symbols traded on the platform may involve different currencies with varying values, and as of now, the code does not account for these variations or make any exceptions based on the currency differences.

Source code viewer
  1. double amountPerTrade = 1000;
  2. double symbolPrice = SymbolInfoDouble(Symbol(), SYMBOL_BID);
  3. double lot = MathFloor(amountPerTrade / symbolPrice);
  4.  
  5. if (lot > 0) {
  6. m_trade.Buy(lot, NULL, m_symbol.Ask());
  7. }
Programming Language: MQL5