- void OnTick()
- {
- static int last_total_positions = -1; // The last total number of open positions
- static MqlTradeRequest last_request = {0}; // The last trade request made
- static MqlTradeResult last_result = {0}; // The last trade result received
- // Retrieve the total number of open positions
- int total_positions = PositionsTotal();
- // Check if there are any open positions
- if (total_positions > 0)
- {
- // Check if the total number of open positions has changed
- if (total_positions != last_total_positions)
- {
- // Print the new total number of open positions in the Experts log
- Print("Total open positions: ", total_positions);
- // Update the last total number of open positions received
- last_total_positions = total_positions;
- }
- // Loop through all open positions
- for (int i = 0; i < total_positions; i++)
- {
- // Get the ticket number for the current position
- ulong ticket = PositionGetTicket(i);
- // Check if we already made a request for this position
- if (last_request.action == TRADE_ACTION_DEAL && last_request.order == ticket)
- {
- // Check if we received a result for the previous request
- if (last_result.retcode == TRADE_RETCODE_DONE)
- {
- // Get the P/L for the current position from the trade result
- double profit = last_result.profit;
- // Convert the P/L to a string
- string profit_str = DoubleToString(profit, Digits);
- // Create the JSON payload for the WebSocket server
- string payload = "{"ticket": " + IntegerToString(ticket) + ", "profit": " + profit_str + "}";
- // Send the P/L to the WebSocket server
- WebRequest(websocket_handle, "SEND", payload, "", "");
- // Print the new P/L in the Experts log
- Print("Position ticket: ", ticket, ", P/L: ", profit_str);
- // Reset the last request and result variables
- last_request.action = 0;
- last_request.order = 0;
- last_result.retcode = 0;
- last_result.order = 0;
- last_result.volume = 0;
- last_result.price = 0;
- }
- }
- else
- {
- // Make a trade request to get the P/L for the current position
- MqlTradeRequest request;
- ZeroMemory(&request, sizeof(request));
- request.action = TRADE_ACTION_DEAL;
- request.symbol = PositionGetSymbol(i);
- request.order = ticket;
- request.type = ORDER_TYPE_SELL;
- request.volume = PositionGetDouble(POSITION_IDENTIFIER, POSITION_VOLUME);
- request.price = SymbolInfoDouble(request.symbol, SYMBOL_ASK);
- request.sl = PositionGetDouble(POSITION_IDENTIFIER, POSITION_SL);
- request.tp = PositionGetDouble(POSITION_IDENTIFIER, POSITION_TP);
- // Send the trade request to the server
- int result = OrderSend(request, last_result);
- // Check if the trade request was successful
- if (result > 0)
- {
- // Update the last trade request made
- last_request = request;
- }
- else
- {
- // Print the error message in the Experts log
- Print("Trade request error: ", ErrorDescription(GetLastError()));
- }
- }
- }
- }
- }