最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

metatrader5 - Identifying positions to concatenate numeric values (such as integers and doubles) with strings - Stack Overflow

programmeradmin0浏览0评论

I am developing an Expert Advisor (EA) in MetaTrader 5 (MT5) to monitor floating profits and close positions when a certain profit threshold is reached.
I encounter implicit conversion errors when trying to concatenate numeric values (such as integers and doubles) with strings for output to the log.

The error message during compilation:

pgsql
Copy
Edit
implicit conversion from 'number' to 'string'  floatingprofit.mq5  56  46
implicit conversion from 'number' to 'string'  floatingprofit.mq5  17  42

Code Overview:

I am trying to iterate over all open positions, calculate the total floating profit, and close the positions if the total floating profit exceeds a threshold. In the process, I am attempting to print information such as the total number of positions, individual position profits, and ticket numbers.

Problem:

When concatenating numeric values (e.g., IntegerToString() or DoubleToString()) with strings for printing purposes, I get the following implicit conversion errors:
Line 56: When concatenating the floating profit with strings for printing.
Line 17: When printing the number of open positions.

Example Code Snippet:

mq5
Copy
Edit
Print("Total open positions: " + total_positions);  // Error: implicit conversion
Print("Position #" + i + " Ticket: " + ticket + " Profit: " + position_profit);  // Error: implicit conversion

What I Tried:

  • IntegerToString() and DoubleToString() for explicit conversion, but the error still occurs.
  • Ensured correct use of the + operator for string concatenation.

Expected Outcome:

Position details (like ticket numbers and profits) should be printed in the log.

Environment:

  • MetaTrader 5 (MT5)
  • MQL5 scripting language

The last code I compiled. No errors. It's only calculating profit for first position accurately, all following positions for same symbol are seen as the first.

#include <Trade\Trade.mqh>
CTrade trade;

input double ProfitThreshold = 5.00; // Set your profit threshold here

// Function to calculate the total floating profit
double CalculateFloatingProfit() {
    double total_profit = 0.0;
    int total_positions = PositionsTotal();
    
    // Debugging: Check how many positions are open
    string total_positions_str = IntegerToString(total_positions);
    Print("Total open positions: " + total_positions_str);

    for (int i = 0; i < total_positions; i++) {
        if (PositionSelect(Symbol())) {
            double position_profit = PositionGetDouble(POSITION_PROFIT);
            total_profit += position_profit;
            string position_profit_str = DoubleToString(position_profit, 2);
            Print("Position #" + IntegerToString(i) + " Profit: " + position_profit_str);
        } else {
            // If PositionSelect fails, print the index
            Print("Failed to select position at index: " + IntegerToString(i));
        }
    }
    return total_profit;
}

int OnInit() {
    Print("EA initialized successfully");
    return INIT_SUCCEEDED;
}

void OnDeinit(const int reason) {
    string reason_str = IntegerToString(reason); // Explicit conversion of integer to string
    Print("EA deinitialized, reason: " + reason_str);
}

void OnTick() {
    double floating_profit = CalculateFloatingProfit();

    // Convert floating profit to string explicitly
    string floating_profit_str = DoubleToString(floating_profit, 2); 

    // Print total floating profit
    Print("Current total floating profit: " + floating_profit_str);

    // If the floating profit exceeds the threshold, close all positions
    if (floating_profit >= ProfitThreshold) {
        Print("Floating profit threshold reached. Closing all positions.");

        int total_positions = PositionsTotal();
        for (int i = total_positions - 1; i >= 0; i--) {
            if (PositionSelect(Symbol())) {
                ulong ticket = PositionGetInteger(POSITION_TICKET);
                string ticket_str = IntegerToString((int)ticket); // Convert ticket number to string explicitly

                bool result = trade.PositionClose(ticket);
                if (result) {
                    Print("Position " + ticket_str + " closed successfully.");
                } else {
                    int error_code = GetLastError();
                    string error_code_str = IntegerToString(error_code); // Convert error code to string
                    Print("Failed to close position " + ticket_str + ". Error: " + error_code_str);
                }
            } else {
                Print("Failed to select position " + IntegerToString(i));
            }
        }
        Print("All positions closed as floating profit reached: " + floating_profit_str);
    }
}

I am developing an Expert Advisor (EA) in MetaTrader 5 (MT5) to monitor floating profits and close positions when a certain profit threshold is reached.
I encounter implicit conversion errors when trying to concatenate numeric values (such as integers and doubles) with strings for output to the log.

The error message during compilation:

pgsql
Copy
Edit
implicit conversion from 'number' to 'string'  floatingprofit.mq5  56  46
implicit conversion from 'number' to 'string'  floatingprofit.mq5  17  42

Code Overview:

I am trying to iterate over all open positions, calculate the total floating profit, and close the positions if the total floating profit exceeds a threshold. In the process, I am attempting to print information such as the total number of positions, individual position profits, and ticket numbers.

Problem:

When concatenating numeric values (e.g., IntegerToString() or DoubleToString()) with strings for printing purposes, I get the following implicit conversion errors:
Line 56: When concatenating the floating profit with strings for printing.
Line 17: When printing the number of open positions.

Example Code Snippet:

mq5
Copy
Edit
Print("Total open positions: " + total_positions);  // Error: implicit conversion
Print("Position #" + i + " Ticket: " + ticket + " Profit: " + position_profit);  // Error: implicit conversion

What I Tried:

  • IntegerToString() and DoubleToString() for explicit conversion, but the error still occurs.
  • Ensured correct use of the + operator for string concatenation.

Expected Outcome:

Position details (like ticket numbers and profits) should be printed in the log.

Environment:

  • MetaTrader 5 (MT5)
  • MQL5 scripting language

The last code I compiled. No errors. It's only calculating profit for first position accurately, all following positions for same symbol are seen as the first.

#include <Trade\Trade.mqh>
CTrade trade;

input double ProfitThreshold = 5.00; // Set your profit threshold here

// Function to calculate the total floating profit
double CalculateFloatingProfit() {
    double total_profit = 0.0;
    int total_positions = PositionsTotal();
    
    // Debugging: Check how many positions are open
    string total_positions_str = IntegerToString(total_positions);
    Print("Total open positions: " + total_positions_str);

    for (int i = 0; i < total_positions; i++) {
        if (PositionSelect(Symbol())) {
            double position_profit = PositionGetDouble(POSITION_PROFIT);
            total_profit += position_profit;
            string position_profit_str = DoubleToString(position_profit, 2);
            Print("Position #" + IntegerToString(i) + " Profit: " + position_profit_str);
        } else {
            // If PositionSelect fails, print the index
            Print("Failed to select position at index: " + IntegerToString(i));
        }
    }
    return total_profit;
}

int OnInit() {
    Print("EA initialized successfully");
    return INIT_SUCCEEDED;
}

void OnDeinit(const int reason) {
    string reason_str = IntegerToString(reason); // Explicit conversion of integer to string
    Print("EA deinitialized, reason: " + reason_str);
}

void OnTick() {
    double floating_profit = CalculateFloatingProfit();

    // Convert floating profit to string explicitly
    string floating_profit_str = DoubleToString(floating_profit, 2); 

    // Print total floating profit
    Print("Current total floating profit: " + floating_profit_str);

    // If the floating profit exceeds the threshold, close all positions
    if (floating_profit >= ProfitThreshold) {
        Print("Floating profit threshold reached. Closing all positions.");

        int total_positions = PositionsTotal();
        for (int i = total_positions - 1; i >= 0; i--) {
            if (PositionSelect(Symbol())) {
                ulong ticket = PositionGetInteger(POSITION_TICKET);
                string ticket_str = IntegerToString((int)ticket); // Convert ticket number to string explicitly

                bool result = trade.PositionClose(ticket);
                if (result) {
                    Print("Position " + ticket_str + " closed successfully.");
                } else {
                    int error_code = GetLastError();
                    string error_code_str = IntegerToString(error_code); // Convert error code to string
                    Print("Failed to close position " + ticket_str + ". Error: " + error_code_str);
                }
            } else {
                Print("Failed to select position " + IntegerToString(i));
            }
        }
        Print("All positions closed as floating profit reached: " + floating_profit_str);
    }
}

Share Improve this question edited Feb 12 at 22:37 CommunityBot 11 silver badge asked Feb 4 at 11:59 Gibran C PointersGibran C Pointers 132 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

The below code does not work as you expecete:

for (int i = 0; i < total_positions; i++)
    if (PositionSelect(Symbol())) 

To select individual positions, use the following code:

ulong ticket ;
 for ( int i = 0 ; i < num_open_position ; i++) // iterate over all open positions
      if((ticket = PositionGetTicket(i) ) > 0 )
         if(PositionSelectByTicket(ticket) )    
            {
            ulong  magic                      = PositionGetInteger(POSITION_MAGIC)           ;
            double profit                     = PositionGetDouble(POSITION_PROFIT)           ; 
            double volume                     = PositionGetDouble(POSITION_VOLUME)           ;
            double price_open                 = PositionGetDouble(POSITION_PRICE_OPEN)       ;   
            double stop_loss                  = PositionGetDouble(POSITION_SL)               ;   
            double take_profit                = PositionGetDouble(POSITION_TP)               ;   
            long   type                       = PositionGetInteger(POSITION_TYPE)            ;
            string symbol                     = PositionGetString(POSITION_SYMBOL)           ; 
            datetime open_time                = (datetime)PositionGetInteger(POSITION_TIME)  ;
                                                       
           }    

 

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论