[MQL4 CODING] Target Revenue in Percentage using Account Balance and Equity

shanmugapradeep

Active Trader
Dec 18, 2020
112
4
34
38
Hello,



I am adding new feature in my EA, which close trade automatically when it fulfilled defined earning set by user and than it redefine with value again with new Account balance.



Example :


Account Balance = $1000


Target Percentage = 10% (10% of 1000$ = $100)


When Account balance is above $1100, close all the running trade whether it in positive or negative. Than it start again but now the Account balance is $1100 and 10% targeted percentage is $110. and it keep repeating.



To do this, i am trying like :



MQL4:
extern double Target_Percentage = 10;
 
double target_profits = AccountBalance() * (Target_Percentage * 0.01); //Calculating in Percentage
 
static double target_Capital = AccountBalance() + target_profits;  //Setting the value in static so it will not change on every tick.
 
if(AccountEquity() >= target_Capital) { //Comparing Account Equity with total targeted revenue i need.
 
CloseAllTrade();
Print("All the trade has been successfully closed as it reached Targeted Capital requirement and targeted capital redjusted automatically to new value based on new capital");
}


The problem is, i do not know how i can set new value to the static double target_Capital . If it static it value will be remained unchanged but i want to redefine static target_capital to new value ones it fulfilled previous targeted percentage requirement.
 

Enivid

Administrator
Staff member
Nov 30, 2008
18,623
1,367
144
Odesa
www.earnforex.com
After Print, recalculate your target_profits and target_Capital. The fact that the latter is static doesn't mean that you cannot change its value. It only means that the variable is preserved when its current scope ends and that the initialization on declaration doesn't repeat itself.
 

shanmugapradeep

Active Trader
Dec 18, 2020
112
4
34
38
After Print, recalculate your target_profits and target_Capital. The fact that the latter is static doesn't mean that you cannot change its value. It only means that the variable is preserved when its current scope ends and that the initialization on declaration doesn't repeat itself.
That won't work because i am using static double target_Capital

But i guess your suggesting like this

MQL4:
extern string inc_MoneyManagement = "***Money Management***";
extern bool Money_Management = FALSE;
enum MoneyManagement_enum {Fixed_Money, Balance_Percentage};
extern MoneyManagement_enum MoneyManagement_Type = Balance_Percentage;
extern double Target_Revenue = 1000.0;
double gTargeted_Revenue;
 
int OnInit() {
   if(MoneyManagement_Type == Balance_Percentage)
      gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
   else
      gTargeted_Revenue = Target_Revenue + AccountBalance();
}
 
void OnTick() {
 
if(Money_Management && AccountEquity() >= gTargeted_Revenue)
     {
 
      CloseOpenAndPendingTrades(BuyLimitMagic);
      CloseOpenAndPendingTrades(SellLimitMagic);
      CloseOpenAndPendingTrades(BuyStopMagic);
      CloseOpenAndPendingTrades(SellStopMagic);
 
      Print("All The Trade Closed due to it exceeded defined Money Management (Target Revenue) : " + AccountEquity());
 
      if(MoneyManagement_Type == Balance_Percentage)
         gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
      else
         gTargeted_Revenue = Target_Revenue + AccountBalance();
 
     }
}
 

Enivid

Administrator
Staff member
Nov 30, 2008
18,623
1,367
144
Odesa
www.earnforex.com
That won't work because i am using static double target_Capital

But i guess your suggesting like this

MQL4:
extern string inc_MoneyManagement = "***Money Management***";
extern bool Money_Management = FALSE;
enum MoneyManagement_enum {Fixed_Money, Balance_Percentage};
extern MoneyManagement_enum MoneyManagement_Type = Balance_Percentage;
extern double Target_Revenue = 1000.0;
double gTargeted_Revenue;
 
int OnInit() {
   if(MoneyManagement_Type == Balance_Percentage)
      gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
   else
      gTargeted_Revenue = Target_Revenue + AccountBalance();
}
 
void OnTick() {
 
if(Money_Management && AccountEquity() >= gTargeted_Revenue)
     {
 
      CloseOpenAndPendingTrades(BuyLimitMagic);
      CloseOpenAndPendingTrades(SellLimitMagic);
      CloseOpenAndPendingTrades(BuyStopMagic);
      CloseOpenAndPendingTrades(SellStopMagic);
 
      Print("All The Trade Closed due to it exceeded defined Money Management (Target Revenue) : " + AccountEquity());
 
      if(MoneyManagement_Type == Balance_Percentage)
         gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
      else
         gTargeted_Revenue = Target_Revenue + AccountBalance();
 
     }
}
You can also do that with a global variable as in this snippet, but as I have said, you can do it with a static variable. As I mentioned, a variable being static doesn't mean that you cannot change its value.
 

shanmugapradeep

Active Trader
Dec 18, 2020
112
4
34
38
No, static is more like a "local" global variable. It doesn't expire with the local scope.
Got it. I am facing new problem. when EA Deinit on chart change, automatic disconnect/reconnect broker server, etc. it set new values to gTargeted_Revenue; without achieving the result.

To solve this, i am making a new file which store the value and use it. I am trying something like this. Not sure what i am missing here.


MQL4:
extern string inc_MoneyManagement = "***Money Management***";
extern bool Money_Management = FALSE;
enum MoneyManagement_enum {Fixed_Money, Balance_Percentage};
extern MoneyManagement_enum MoneyManagement_Type = Balance_Percentage;
extern double Target_Revenue = 1000.0;
double gTargeted_Revenue;
 
// File to store gTargeted_Revenue value
string FileName = _Symbol+"targeted_revenue.txt";
 
int OnInit() {
   // Load gTargeted_Revenue value from file if it exists
   if (FileIsExist(FileName)) {
      int fileHandle = FileOpen(FileName, FILE_READ);
      gTargeted_Revenue = FileReadDouble(fileHandle);
      FileClose(fileHandle);
   } else {
      // Calculate gTargeted_Revenue if file doesn't exist
      if(MoneyManagement_Type == Balance_Percentage)
         gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
      else
         gTargeted_Revenue = Target_Revenue + AccountBalance();
   }
}
 
void OnTick() {
   if(Money_Management && AccountEquity() >= gTargeted_Revenue) {
      for (int i = OrdersTotal() - 1; i >= 0; i--) {
         if (OrderSelect(i, SELECT_BY_POS)==false) continue;
         if (OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3, clrNONE) == false)
            Print("Order close failed for ticket ", OrderTicket());
      }
 
      Print("All The Trade Closed due to it exceeded defined Money Management (Target Revenue) : " + AccountEquity());
 
      // Update gTargeted_Revenue value
      if(MoneyManagement_Type == Balance_Percentage)
         gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
      else
         gTargeted_Revenue = Target_Revenue + AccountBalance();
 
      // Save gTargeted_Revenue value to file
      int fileHandle = FileOpen(FileName, FILE_WRITE);
      FileWriteDouble(fileHandle, gTargeted_Revenue);
      FileClose(fileHandle);
   }
}
 

Enivid

Administrator
Staff member
Nov 30, 2008
18,623
1,367
144
Odesa
www.earnforex.com
Got it. I am facing new problem. when EA Deinit on chart change, automatic disconnect/reconnect broker server, etc. it set new values to gTargeted_Revenue; without achieving the result.

To solve this, i am making a new file which store the value and use it. I am trying something like this. Not sure what i am missing here.


MQL4:
extern string inc_MoneyManagement = "***Money Management***";
extern bool Money_Management = FALSE;
enum MoneyManagement_enum {Fixed_Money, Balance_Percentage};
extern MoneyManagement_enum MoneyManagement_Type = Balance_Percentage;
extern double Target_Revenue = 1000.0;
double gTargeted_Revenue;
 
// File to store gTargeted_Revenue value
string FileName = _Symbol+"targeted_revenue.txt";
 
int OnInit() {
   // Load gTargeted_Revenue value from file if it exists
   if (FileIsExist(FileName)) {
      int fileHandle = FileOpen(FileName, FILE_READ);
      gTargeted_Revenue = FileReadDouble(fileHandle);
      FileClose(fileHandle);
   } else {
      // Calculate gTargeted_Revenue if file doesn't exist
      if(MoneyManagement_Type == Balance_Percentage)
         gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
      else
         gTargeted_Revenue = Target_Revenue + AccountBalance();
   }
}
 
void OnTick() {
   if(Money_Management && AccountEquity() >= gTargeted_Revenue) {
      for (int i = OrdersTotal() - 1; i >= 0; i--) {
         if (OrderSelect(i, SELECT_BY_POS)==false) continue;
         if (OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3, clrNONE) == false)
            Print("Order close failed for ticket ", OrderTicket());
      }
 
      Print("All The Trade Closed due to it exceeded defined Money Management (Target Revenue) : " + AccountEquity());
 
      // Update gTargeted_Revenue value
      if(MoneyManagement_Type == Balance_Percentage)
         gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
      else
         gTargeted_Revenue = Target_Revenue + AccountBalance();
 
      // Save gTargeted_Revenue value to file
      int fileHandle = FileOpen(FileName, FILE_WRITE);
      FileWriteDouble(fileHandle, gTargeted_Revenue);
      FileClose(fileHandle);
   }
}
You need to check file handles when using FileOpen, and also check the results for FileWriteDouble/FileReadDouble. Then use GetLastError() to output the error code if something is wrong.

I guess that you need FILE_BIN flag for reading and writing doubles.
 

shanmugapradeep

Active Trader
Dec 18, 2020
112
4
34
38
You need to check file handles when using FileOpen, and also check the results for FileWriteDouble/FileReadDouble. Then use GetLastError() to output the error code if something is wrong.

I guess that you need FILE_BIN flag for reading and writing doubles.

I founded the error, it because i am reading and rewriting the file but i am not creating it on starting. I am trying like this but when i open the file it an empty, it does not have any value

I am getting, 5011 Error

MQL4:
extern string inc_MoneyManagement = "***Money Management***";
extern bool Money_Management = FALSE;
enum MoneyManagement_enum {Fixed_Money, Balance_Percentage};
extern MoneyManagement_enum MoneyManagement_Type = Balance_Percentage;
extern double Target_Revenue = 1000.0;
double gTargeted_Revenue;
 
// File to store gTargeted_Revenue value
string FileName = _Symbol+"targeted_revenue.txt";
 
int OnInit() {
   // Load gTargeted_Revenue value from file if it exists
   int fileHandle = FileOpen(FileName, FILE_READ);
   if (fileHandle != INVALID_HANDLE) {
      gTargeted_Revenue = FileReadDouble(fileHandle);
      FileClose(fileHandle);
      Print("Loaded gTargeted_Revenue from file: ", gTargeted_Revenue);
   } else {
      // Create a new file and calculate gTargeted_Revenue
      ResetLastError();
      fileHandle = FileOpen(FileName, FILE_WRITE);
      if (fileHandle != INVALID_HANDLE) {
         if(MoneyManagement_Type == Balance_Percentage)
            gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
         else
            gTargeted_Revenue = Target_Revenue + AccountBalance();
 
         FileWriteDouble(fileHandle, gTargeted_Revenue);
         FileClose(fileHandle);
         Print("Created new file and wrote gTargeted_Revenue: ", gTargeted_Revenue);
         Print(" File creation Error : " + GetLastError());
      } else {
         Print("Failed to create file: ", FileName);
         // Handle file creation failure here
      }
   }
}
 
 
void OnTick() {
   if(Money_Management && AccountEquity() >= gTargeted_Revenue) {
      for (int i = OrdersTotal() - 1; i >= 0; i--) {
         if (OrderSelect(i, SELECT_BY_POS)==false) continue;
         if (OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3, clrNONE) == false)
            Print("Order close failed for ticket ", OrderTicket());
      }
 
      Print("All The Trade Closed due to it exceeded defined Money Management (Target Revenue) : " + AccountEquity());
 
      // Update gTargeted_Revenue value
      if(MoneyManagement_Type == Balance_Percentage)
         gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
      else
         gTargeted_Revenue = Target_Revenue + AccountBalance();
 
      // Save gTargeted_Revenue value to file
      int fileHandle = FileOpen(FileName, FILE_WRITE);
      if (fileHandle != INVALID_HANDLE) {
         FileWriteDouble(fileHandle, gTargeted_Revenue);
         FileClose(fileHandle);
      } else {
         Print("Failed to open file for writing: ", FileName);
         // Handle file writing failure here
      }
   }
}
 
Last edited:

Enivid

Administrator
Staff member
Nov 30, 2008
18,623
1,367
144
Odesa
www.earnforex.com
I am getting, 5011 Error
Are you still getting that error? Error 5011 (ERR_FILE_NOT_BIN) means that you are trying to use a read/write function intended for binary files after opening the file as a non-binary one. As I have said, you need to add the FILE_BIN flag to your file-opening calls.
 

shanmugapradeep

Active Trader
Dec 18, 2020
112
4
34
38
Are you still getting that error?
Yes. I added File type FILE_READ | FILE_TXT but still something is missing out.

MQL4:
extern string inc_MoneyManagement = "***Money Management***";
extern bool Money_Management = FALSE;
enum MoneyManagement_enum {Fixed_Money, Balance_Percentage};
extern MoneyManagement_enum MoneyManagement_Type = Balance_Percentage;
extern double Target_Revenue = 1000.0;
double gTargeted_Revenue;
 
// File to store gTargeted_Revenue value
string MM_File = _Symbol+"targeted_revenue.txt";
 
int OnInit() {
   // Load gTargeted_Revenue value from file if it exists
   int fileHandle = FileOpen(MM_File, FILE_READ);
   if (fileHandle != INVALID_HANDLE) {
      gTargeted_Revenue = FileReadDouble(fileHandle);
      FileClose(fileHandle);
      Print("Loaded gTargeted_Revenue from file: ", gTargeted_Revenue);
   } else {
      // Create a new file and calculate gTargeted_Revenue
      ResetLastError();
      fileHandle = FileOpen(MM_File, FILE_WRITE);
      if (fileHandle != INVALID_HANDLE) {
         if(MoneyManagement_Type == Balance_Percentage)
            gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
         else
            gTargeted_Revenue = Target_Revenue + AccountBalance();
 
         FileWriteDouble(fileHandle, gTargeted_Revenue);
         FileClose(fileHandle);
         Print("Created new file and wrote gTargeted_Revenue: ", gTargeted_Revenue);
         Print(" File creation Error : " + GetLastError());
      } else {
         Print("Failed to create file: ", MM_File);
         // Handle file creation failure here
      }
   }
}
 
 
void OnTick() {
   if(Money_Management && AccountEquity() >= gTargeted_Revenue) {
      for (int i = OrdersTotal() - 1; i >= 0; i--) {
         if (OrderSelect(i, SELECT_BY_POS)==false) continue;
         if (OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3, clrNONE) == false)
            Print("Order close failed for ticket ", OrderTicket());
      }
 
      Print("All The Trade Closed due to it exceeded defined Money Management (Target Revenue) : " + AccountEquity());
 
      // Update gTargeted_Revenue value
      if(MoneyManagement_Type == Balance_Percentage)
         gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
      else
         gTargeted_Revenue = Target_Revenue + AccountBalance();
 
      // Save gTargeted_Revenue value to file
      int fileHandle = FileOpen(MM_File, FILE_WRITE);
      if (fileHandle != INVALID_HANDLE) {
         FileWriteDouble(fileHandle, gTargeted_Revenue);
         FileClose(fileHandle);
      } else {
         Print("Failed to open file for writing: ", MM_File);
         // Handle file writing failure here
      }
   }
}
 

Enivid

Administrator
Staff member
Nov 30, 2008
18,623
1,367
144
Odesa
www.earnforex.com
Yes. I added File type FILE_READ | FILE_TXT but still something is missing out.

MQL4:
extern string inc_MoneyManagement = "***Money Management***";
extern bool Money_Management = FALSE;
enum MoneyManagement_enum {Fixed_Money, Balance_Percentage};
extern MoneyManagement_enum MoneyManagement_Type = Balance_Percentage;
extern double Target_Revenue = 1000.0;
double gTargeted_Revenue;
 
// File to store gTargeted_Revenue value
string MM_File = _Symbol+"targeted_revenue.txt";
 
int OnInit() {
   // Load gTargeted_Revenue value from file if it exists
   int fileHandle = FileOpen(MM_File, FILE_READ);
   if (fileHandle != INVALID_HANDLE) {
      gTargeted_Revenue = FileReadDouble(fileHandle);
      FileClose(fileHandle);
      Print("Loaded gTargeted_Revenue from file: ", gTargeted_Revenue);
   } else {
      // Create a new file and calculate gTargeted_Revenue
      ResetLastError();
      fileHandle = FileOpen(MM_File, FILE_WRITE);
      if (fileHandle != INVALID_HANDLE) {
         if(MoneyManagement_Type == Balance_Percentage)
            gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
         else
            gTargeted_Revenue = Target_Revenue + AccountBalance();
 
         FileWriteDouble(fileHandle, gTargeted_Revenue);
         FileClose(fileHandle);
         Print("Created new file and wrote gTargeted_Revenue: ", gTargeted_Revenue);
         Print(" File creation Error : " + GetLastError());
      } else {
         Print("Failed to create file: ", MM_File);
         // Handle file creation failure here
      }
   }
}
 
 
void OnTick() {
   if(Money_Management && AccountEquity() >= gTargeted_Revenue) {
      for (int i = OrdersTotal() - 1; i >= 0; i--) {
         if (OrderSelect(i, SELECT_BY_POS)==false) continue;
         if (OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3, clrNONE) == false)
            Print("Order close failed for ticket ", OrderTicket());
      }
 
      Print("All The Trade Closed due to it exceeded defined Money Management (Target Revenue) : " + AccountEquity());
 
      // Update gTargeted_Revenue value
      if(MoneyManagement_Type == Balance_Percentage)
         gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
      else
         gTargeted_Revenue = Target_Revenue + AccountBalance();
 
      // Save gTargeted_Revenue value to file
      int fileHandle = FileOpen(MM_File, FILE_WRITE);
      if (fileHandle != INVALID_HANDLE) {
         FileWriteDouble(fileHandle, gTargeted_Revenue);
         FileClose(fileHandle);
      } else {
         Print("Failed to open file for writing: ", MM_File);
         // Handle file writing failure here
      }
   }
}
Sorry, but I don't see any file type flags in your FileOpen calls. Also, you cannot use FileWriteDouble and FileReadDouble on text/csv files. You can only use them on binary files. Hence I'm asking you to use FILE_BIN flags.
 

shanmugapradeep

Active Trader
Dec 18, 2020
112
4
34
38
Sorry, but I don't see any file type flags in your FileOpen calls. Also, you cannot use FileWriteDouble and FileReadDouble on text/csv files. You can only use them on binary files. Hence I'm asking you to use FILE_BIN flags.
Sorry but i did not understand clearly what your trying to say. Not an experienced coder. Confused about File Bin. can you give me a sample code how i should write this.
 

Enivid

Administrator
Staff member
Nov 30, 2008
18,623
1,367
144
Odesa
www.earnforex.com

shanmugapradeep

Active Trader
Dec 18, 2020
112
4
34
38
MQL5:
FileOpen(MM_File, FILE_READ|FILE_BIN);
FileOpen(MM_File, FILE_WRITE|FILE_BIN);

You can actually see some good examples in the help file for FileWriteDouble/FileReadDouble:
https://docs.mql4.com/files/filewritedouble
Like this


MQL4:
int OnInit() {
   // Load gTargeted_Revenue value from file if it exists
   int fileHandle = FileOpen(FileName, FILE_READ|FILE_BIN);
   if (fileHandle != INVALID_HANDLE) {
      gTargeted_Revenue = FileReadDouble(fileHandle);
      FileClose(fileHandle);
   } else {
      // Create a new file and calculate gTargeted_Revenue
      fileHandle = FileOpen(FileName, FILE_WRITE|FILE_BIN);
      if (fileHandle != INVALID_HANDLE) {
         if(MoneyManagement_Type == Balance_Percentage)
            gTargeted_Revenue = (1 + Target_Revenue/100) * AccountBalance();
         else
            gTargeted_Revenue = Target_Revenue + AccountBalance();
 
         FileWriteDouble(fileHandle, gTargeted_Revenue);
         FileClose(fileHandle);
      } else {
         Print("Failed to create file: ", FileName);
         // Handle file creation failure here
      }
   }
   return INIT_SUCCEEDED;
}
 
void OnTick() {
   // Update gTargeted_Revenue value if necessary
   double newTargetedRevenue;
   if(Money_Management && AccountEquity() >= gTargeted_Revenue) {
      if(MoneyManagement_Type == Balance_Percentage)
         newTargetedRevenue = (1 + Target_Revenue/100) * AccountBalance();
      else
         newTargetedRevenue = Target_Revenue + AccountBalance();
 
      if(newTargetedRevenue != gTargeted_Revenue) {
         gTargeted_Revenue = newTargetedRevenue;
 
         // Save gTargeted_Revenue value to file
         int fileHandle = FileOpen(FileName, FILE_WRITE|FILE_BIN);
         if (fileHandle != INVALID_HANDLE) {
            FileWriteDouble(fileHandle, gTargeted_Revenue);
            FileClose(fileHandle);
         } else {
            Print("Failed to open file for writing: ", FileName);
            // Handle file writing failure here
         }
      }
   }
}