Hello!
In today’s lesson, we’ll write a profit() function in MQL4 to calculate the total profit (including swap and commission fees) of open orders by type (Buy or Sell).
double profit(string type) { double profit=0; for(int i=0; i<OrdersTotal(); i++) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) if(OrderSymbol()==_Symbol && OrderMagicNumber()==Magic) { if(OrderType()==OP_BUY && type== "OP_BUY") { profit+=OrderProfit()+OrderSwap()+OrderCommission(); } if(OrderType()==OP_SELL && type== "OP_SELL") { profit+=OrderProfit()+OrderSwap()+OrderCommission(); } } } return(profit); }
The profit function calculates the profit (or loss) of open orders that match the same symbol and Magic number, with the specified order type (OP_BUY or OP_SELL
). Below is a detailed explanation of this function:
- Input parameter:
type
: A string that specifies the type of order you want to calculate the profit for (OP_BUY or OP_SELL
).
- Local variable:
double profit = 0
: This variable is initialized with a default value of 0. It will store the total profit (or total loss) of the qualifying orders.
- Loop through open orders:
- The
for
loop runs through all open orders using theOrdersTotal()
function to get the total number of current orders. - For each order, the
OrderSelect()
function is used to select the current order by position (SELECT_BY_POS
) in the order list. - Then, it checks if the selected order has the same symbol (
OrderSymbol()
) and Magic number (OrderMagicNumber()
) as the specified pair and Magic number in the function. - Next, it checks whether the order type is OP_BUY and
type
is “OP_BUY”, or if the order type is OP_SELL andtype
is “OP_SELL”. If so, it calculates the total profit by adding the order profit, swap, and commission fees to theprofit
variable.
- The
- Return total profit:
- When the loop ends, the function returns the total profit (or total loss) of the matching open orders. If no orders are found or match the specified type, the function will return the default value of 0.
Note that you must make sure to call this function with the correct order type and verify the result before using the returned total profit in your trading strategy.