Balance_Reset - MetaTrader 5 Library | MT5 EA Download - MetaTrader 5 Resources







I've made a major update to this library, which I use to optimize my expert advisors. This version is simplified, but you can easily extend it to include everyday tasks you might want to automate. For example, you can add a trading limit after a proprietary company challenge fails, or resume trading on Monday after a successful or failed challenge.
All changes and additions to the library are outlined at the end of the code. The framework is flexible and can be adapted to your specific needs, whether adding more complex trade limiting logic, scheduling trades, or fine-tuning performance based on optimization results.
Feel free to customize it further based on your daily tasks!
This library is designed specifically for testing Expert Advisors (EAs) in MetaTrader 5, with a special focus on proprietary company trading requirements. The goal is to simulate a trading environment where traders must meet certain profit and loss thresholds to pass the company's challenges. Whenever a specified profit or loss percentage is reached, the EA adjusts the account balance by resetting it to the initial value, which mimics the rules of many proprietary companies.
The following is the complete structure of the Expert Advisor using the BalanceReset.mqh library. This setup integrates the balance reset logic directly into the EA, while indicating it via the #include :
#include// Contains balance reset library //+------------------------------------------------------------------+ //|Expert initialization function | //+------------------------------------------------------------------+ Integer initialization () { Initialize balance(); // Initialize starting balance and return initialization successful ; } //+------------------------------------------------------------------+ //|Expert check function | //+------------------------------------------------------------------+ Blank check () { Check balance and reset(); // Check and reset balance based on threshold } //+----------------------------------------------------------------------------------+ //|Expert to initialize function | //+------------------------------------------------------------------+ Blank solution initialization ( constant integer reason) { PrintBalanceResetResults(); // Output the balance reset results to the log }
Adjustable profit and loss threshold
Enter double profit threshold = 8.0 ; // Profit threshold, default 8% Enter double the loss threshold = - 6.0 ; // Loss threshold, default is -6%
2.Initial balance initialization
Blank initializeBalance() { Initial balance = Account information double ( account balance ); // Store initial balance }
3. Balance reset logic
blank check balance and reset() { Double current balance = account information double ( account balance ); if (initial balance == 0 ) { Initial balance = current balance; // The first check mark stores the initial balance } Double profit percentage = (current balance - initial balance) / initial balance * 100.0 ; if (profit percentage >= profit threshold) { Double withdrawal amount = current balance - initial balance; if ( tester withdraw (withdrawal amount)) { Successful reset++; ArrayResize (Number of resets, array size (Number of resets) + 1 ); Number of resets [ array size (number of resets) - 1 ] = time current (); print ( "Profit has been reached and the balance has been reset to the initial value." ); } } if (profit percentage <= loss threshold) { Double deposit amount = initial balance - current balance; if ( tester deposit (deposit amount)) { Unsuccessful_reset++; ArrayResize (Number of resets, array size (Number of resets) + 1 ); Number of resets [ array size (number of resets) - 1 ] = time current (); print ( "Loss has been reached. Balance has been reset to initial value." ); } } }
4.Result record
Blank print balance reset result() { Print format ( "Number of successful profit resets: %d" , successful reset); Print format ( "Number of lost resets successfully: %d" , unsuccessful reset); for ( integer i = 1 ; i < array size (number of resets); i++) { Integer days_ Between_resets = (reset time[i] - reset time[i- 1 ]) / 86400 ; // One day 86400 seconds printing format ( "Number of days between reset %d and reset %d: %d days" , i, i + 1 , number of days between resets); } }

This library helps simulate trading environments that comply with the requirements of common proprietary trading firms. By resetting the balance when a predefined profit and loss threshold is reached, traders can test their strategies more efficiently and analyze the EA's performance according to proprietary company rules.
Notes on code changes and additions:
The new code includes several enhancements and additions compared to the old code. The following is a detailed description of the new and modified content:
New input parameters:
Maximum loss and minimum win:
Enter double the maximum loss = 1 ; // maximum loss Enter double min_won = 1 ; // minimum win
Purpose: These input parameters allow you to set the maximum allowed loss ( max_loss ) and the minimum number of required successful profit resets ( min_won ). They provide more control over optimization conditions.
Additional variables:
Reset status[]:
String reset status[]; // Array to store each reset status
Purpose: Added an array to store the status of each balance reset event ("Profit Reset" or "Loss Reset").
Stop optimization:
boolean stopoptimization = false ;
Purpose: Flag used to indicate when optimization should stop based on certain conditions.
boolean badresult= wrong ; // Flag indicating bad optimization results
Purpose: Mark the optimization results as unfavorable with a flag that can be used to influence the results in OnTester().
Modifications in CheckBalanceAndReset():
Recording reset status:
array resize (resetstate, arraysize (resetstate) + 1 ); // Resize array to record resetstate resetstate[ arraysize (resetstate) - 1 ] = "Profit Reset" ; // Record state
Purpose: When profit reset occurs, the status will be recorded in the reset_status[] array.
Use optimization stopping conditions to handle loss resets:
if ( tester deposits (deposit amount)) { Unsuccessful_reset++; // Increment counter for failed resets // Record reset time and status array resize (reset_status, array_size (reset_status) + 1 ); Reset state [ array size (reset state) - 1 ] = "Loss reset" ; { stopoptimization= true ; Check stop condition(); // Check whether optimization should be stopped } printFormat ( "Loss has been reached. Balance has been reset to initial value." ); }
Purpose: After a lost reset, the code now increments unsuccessful_resets, logs the status, sets stopOptimization to true, and calls CheckStopCondition() to determine if optimization should stop.
New function Check StopCondition():
blank check stop condition() { if (stop optimization) { print ( "Stop the current optimization process" ); bad result = true ; // mark result as bad testerStop (); } }
Purpose: This function checks if stopOptimization is true, if so, marks the result as an error and uses TesterStop() to stop the current optimization process.
New function OnTester():
double tester () { // If the number of successful resets is less than the required minimum or badResult is set if (successful_resets < min_won || badResult) { print ( "Optimization failed: Returning very unfavorable results." ); // Return a very unfavorable result to undermine the optimization process Return - 999999 ; } // Calculate the difference between successful and unsuccessful reset integer reset difference = successful reset - unsuccessful reset; // Check if difference is negative if (reset difference < 0 ) { print ( "There is a negative difference between successful and unsuccessful resets. Returns a very unfavorable result." ); // If the difference is negative, a very unfavorable result is returned - 999999 ; } // Output the difference to the log print format ( "Difference between reset success and failure: %d" , reset difference); // Return the difference as the result of the tester Returns the reset difference; }

Purpose: This feature provides custom criteria for the optimization process. It checks if the number of successful resets meets the minimum requirements or if the result is bad. It calculates the difference between successful and unsuccessful resets and returns that value, unless the difference is negative, in which case it returns a very unfavorable result that affects the optimizer.

Enhancements in PrintBalanceResetResults():
// Output the date of each reset and the number of days between them for ( integer i = 1 ; i < array size (number of resets); i++) { // Calculate the number of days between resets integer days_ Between_resets = (reset time[i] - reset time[i- 1 ]) / 86400 ; // 86400 seconds a day // Print reset date, status and the number of days between them print format ( "Reset %d: %s (%s), Reset %d: %s (%s), Interval days: %d days" , i, string time (reset time[i- 1 ], TIME_DATE ), reset state[i- 1 ], i + 1 , string time (reset time [i], TIME_DATE ), reset status [i], number of days between resets); }
Purpose: The function now not only outputs the number of resets, but also details each reset event including date, status, and number of days between resets. This provides a more comprehensive log of reset activity.
Variable initialization and usage:
Initial balance check:
if (initial balance == 0 ) { Initial balance = current balance; }
Purpose: Ensure initial_balance is set correctly on the first price change.
Profit percentage calculation:
Double profit percentage = (current balance - initial balance) / initial balance * 100.0 ;
Additional summary:
Controlling the optimization process:
Enhanced logging and tracing:
Integrate with the optimizer via OnTester():
Attachment download
📎 balancereset.mq5 (2.19 KB)
📎 balancereset.mqh (12.34 KB)
Source: MQL5 #52163
💡 Featured Recommendations
✍️ Latest by the author
- •
- •
- •
- •
- •
- •
📌 Popular topics
- •
- •
- •
- •
- •
- •
- •
- •
🔗 You May Be Interested In
- •
- •
- •
- •
- •
- •