| .. | ||
| v3.00 | ||
| v3.01 | ||
| v3.02 | ||
| v3.03 | ||
| v3.04 | ||
| README.md | ||
Thivyam MC PA EA v3.00
Thivyam Multiple Candle Price Action EA – Advanced Version
Overview
Thivyam MC PA EA v3.00 is a robust and flexible MetaTrader 5 Expert Advisor that implements a multi-candle price action strategy, enhanced with dynamic risk management, advanced stop loss handling, and timeframe filtering. This version builds on previous releases by introducing new features and improvements for more precise and controlled trading.
Features
Core Features (from previous versions)
- EMA-Based Market Bias
Uses two EMAs (Fast and Slow) to determine bullish or bearish market bias. - Multi-Candle Price Action Strategy
Analyzes the last several candles to identify high-probability trade setups using the ThreeCandles and FourCandles logic. - Dynamic Lot Sizing
Calculates lot size automatically based on user-defined risk percentage and stop loss distance, ensuring risk per trade does not exceed the specified percentage of account balance. - Customizable Parameters
Configurable EMA periods, risk percentage, lot size, and take profit multiplier. - Timer-Based Execution
Uses a 1-second timer to periodically check for trade opportunities. - Logging
Provides detailed logs for debugging and monitoring. - Timeframe Skipping
Skips specified timeframes (such as M1, M5, H1, etc.) for both live trading and strategy testing, ensuring the EA only runs on relevant timeframes.
v3.04
- Improved Input Parameter Handling:
Enhanced theInputsHelper.mqhfile to better organize and document input parameters, including more descriptive groupings and comments for easier configuration. - Custom Enum Display for Inputs:
Added and documented the use of custom enums for input parameters, allowing for more user-friendly selection and mapping to MQL5 constants (such as filling modes). - Refined Trade Session Controls:
Improved the handling of active trading hours and minutes, making it easier to configure and control when the EA is allowed to trade. - Codebase Cleanup and Documentation:
Updated code comments and structure for better readability and maintainability, especially in input and configuration sections. - Minor Bug Fixes:
Addressed minor issues in parameter initialization and improved robustness in input validation.
v3.03
- Expanded and Structured Input Parameters:
The input parameters were reorganized and grouped usingsinput groupfor better clarity in the EA's input dialog, making configuration more intuitive. - Session Time Controls:
IntroducedHourEnumandMinuteEnumenums for precise control over the EA's active trading session start times. - Additional Trading Controls:
Added new input parameters such asMaxOpenTradesandOneOrderAtATimeto give users more flexibility in managing risk and trade frequency. - Filling Mode Input:
Added an input for selecting the order filling mode (FillingMode), allowing the user to choose between FOK, IOC, and RETURN modes directly from the EA's input parameters. - Parameter Documentation:
Improved inline documentation for each input parameter, making it easier for users to understand and configure the EA. - Preparations for Further Feature Expansion:
The code structure and input handling were updated to support future enhancements and more advanced trading logic.
v3.02
- Enhanced Trailing Stop Logic:
The trailing stop loss logic now uses recent candle statistics (such as M1 close and calculated SMA values) to set the new stop loss, making the trailing more adaptive to current market conditions. - Improved SL Calculation:
The new stop loss for BUY and SELL positions is now calculated usingm1Closeand the result ofGetPointsValue(vals[2]), providing a more dynamic and statistically informed SL adjustment. - Detailed Trade Info Logging:
When a stop loss is trailed, the EA logs detailed statistics (H-L, O-C, H-L SMA, O-C SMA, SL, SL ATR) to the chart and log, aiding in transparency and debugging. - Robustness and Error Handling:
Improved error handling and logging for failed SL trail attempts, ensuring issues are clearly reported. - Preparations for Further Statistical Trailing:
The code structure now supports more advanced trailing logic based on candle statistics, paving the way for future enhancements.
v3.01
- Stop Loss Trailing Feature:
Introduced a newTrailStopLossfunction that allows the EA to trail the stop loss to halfway between the open price and the current SL, but only once per trade and only after a new candle has formed since the trade was opened. This is tracked using a global variable for each ticket to ensure the trailing is performed only once per trade. - Refined Stop Loss Update Logic:
Improved theUpdateStopLossfunction to ensure SL is only updated once per trade on the first new candle after entry, using a global variable for each ticket. - Code Structure and Comments:
Enhanced code readability with better comments and clearer separation of trailing and updating SL logic. - Helper Functions for Debugging:
Added and improved helper functionsPrintTradeRequestandPrintTradeResultfor easier debugging and monitoring of trade requests and results, including printing current bid/ask/last prices. - General Code Cleanup:
Removed redundant code, improved variable naming, and ensured more robust error handling and logging throughout the trade management logic.
New & Improved in v3.00
- Advanced Stop Loss Handling (Cut SL to Half):
- The EA now supports the
CutSLToHalffeature, which automatically reduces the stop loss to half its original distance for all open positions, but only once per new candle after the trade is placed. - This is managed efficiently using the
ResetSLModifyCheckflag andlastSlUpdateCheckCandleTimeto ensure the SL update is performed only once per new candle.
- The EA now supports the
- Improved Candle Processing:
- The EA now processes four candles for more advanced price action logic, allowing for both ThreeCandles and FourCandles strategies to be used in tandem.
- Cleaner and More Efficient Timer Logic:
- The
OnTimer()function is optimized to check for new candles and only callUpdateStopLoss()when appropriate, preventing redundant SL updates and improving performance.
- The
- Enhanced Logging and Debugging:
- More informative log messages for trade placement and stop loss updates, aiding in monitoring and debugging.
- Timeframe Filtering Expanded:
- The list of skipped timeframes is now more comprehensive, covering a wide range of intraday and hourly frames to focus the EA on higher timeframes as desired.
How It Works
-
Initialization
- On startup, the EA checks if the current timeframe is in the skip list. If so, it prints a message and stops.
- Initializes the custom indicator handle for candle size analysis.
-
Timer Event (
OnTimer)- Every second, the EA:
- Retrieves the latest four candles.
- Runs the ThreeCandles and FourCandles strategies to check for trade opportunities.
- If a trade is placed, resets the SL modification flag.
- If the
CutSLToHalffeature is enabled and a new candle has formed, updates the stop loss for all open positions (only once per new candle).
- Every second, the EA:
-
Trade Management
- Trades are managed with dynamic lot sizing and advanced stop loss logic.
- The EA ensures only one SL modification per trade per new candle.
Inputs
| Parameter | Description | Example Value |
|---|---|---|
| Timeframe | Timeframe for EMA calculation and strategy logic | PERIOD_D1 |
| FastEMAPeriod | Period for the Fast EMA | 9 |
| SlowEMAPeriod | Period for the Slow EMA | 21 |
| RiskPercentage | Risk per trade (% of account balance) | 0.5 |
| LotSize | Fixed lot size (used if RiskPercentage is 0) | 0.01 |
| TakeProfit | Take profit multiplier (relative to risk) | 3 |
| CutSLToHalf | Enable/disable SL cut to half after new candle | true |
| logging | Enable or disable logging | true |
Project Structure
Thivyam_MC_PA
├── Experts
│ └── Thivyam_MC_PA.mq5 # Main Expert Advisor logic
├── Include
│ ├── EMAHelper.mqh # Functions for calculating EMAs
│ ├── TradeHelper.mqh # Functions for managing trades
│ ├── StrategyHelper.mqh # Functions for managing trading strategies
│ └── Utils.mqh # Utility functions for logging and data retrieval
│ ├── InputsHelper.mqh # Functions for declaring Inputs
└── README.md # Documentation for the project
├── Reports #--(Multiple files, as per tests conducted)
│ ├── ReportOptimizer.xml # Report file for optimization results
│ └── ReportTester.xml # Report file for strategy tester results
Changelog
v2.02
- SL Cut to Half Feature:
Added theCutSLToHalfoption and logic to automatically cut the stop loss to half its original distance for all open positions, but only once per new candle after the trade is placed. - Improved SL Update Logic:
The EA now tracks the last candle for which the SL update was performed (lastSlUpdateCheckCandleTime) and ensures the SL update is only triggered once per new candle. - Reset Flag for SL Modification:
Introduced theResetSLModifyCheckflag to prevent repeated SL modifications within the same candle. - Cleaner Timer Logic:
TheOnTimer()function now checks for new candles and only callsUpdateStopLoss()when appropriate, improving efficiency and preventing redundant SL updates. - Bug Fixes and Code Cleanups:
Fixed minor bugs and improved code structure for better maintainability and readability.
v2.01
- Timeframe Skipping for Strategy Tester:
Added logic inOnInit()to skip specified timeframes (such as M1, M5, etc.) during testing. The EA will not run or trade on these timeframes, ensuring more relevant and efficient backtesting. - Improved Initialization:
The EA now prints a message and returnsINIT_FAILEDif the current timeframe is in the skip list, preventing unnecessary execution. - Updated the Strategy Logic:
- The ThreeCandles and FourCandles functions now include checks for MaxTradePerSide.
- Updated the logic to check for FourCandles condition only when ThreeCandles condition is not met.
- Minor Code Cleanups:
Enhanced code comments and structure for better readability and maintainability.
v2.00
- Dynamic Lot Sizing:
Added automatic lot size calculation based on stop loss and risk percentage. - Improved Money Management:
Ensures risk per trade does not exceed the specified percentage of account balance. - Cleaner Parameter Handling:
Risk percentage and lot size are now both available; if risk is set to 0, fixed lot size is used. - Code Refactoring:
Improved modularity and maintainability by enhancing helper files and separating logic. - Documentation Update:
README and code comments updated for clarity and completeness.
v1.01
- New Candle Analysis:
- Added the
FourCandlesfunction call available inCStrategyHelperto analyze the last four candles for trade opportunities. - The EA now evaluates both
ThreeCandlesandFourCandlesstrategies in theOnTimer()function.
- Added the
- Enhanced Timer Logic:
- The
OnTimer()function now retrieves and processes data for four candles instead of three.
- The
- Code Cleanup:
- Improved readability by removing redundant comments and placeholders.
- Backward Compatibility:
- Retains all functionality from v1.00, ensuring no disruption to existing strategies.
v1.00
- Initial release with the following features:
- EMA-based market bias determination.
- Three-candle price action strategy.
- Timer-based execution with a 1-second interval.
- Logging for debugging and monitoring.
- Candle analysis for four candles. (trading logic not implemented yet)
Conclusion
This EA provides a systematic approach to trading using EMAs, allowing traders to automate their strategies and improve their trading efficiency. For further customization and enhancements, refer to the included helper files.
Usage
- Copy all files to their respective folders in your
MQL5directory. - Compile
Thivyam_MC_PA-v2.00.mq5in MetaEditor. - Attach the EA to a chart and set your preferred parameters.
- Monitor the Experts log for trade actions and debug information.
Disclaimer
This EA is provided for educational purposes only. Use at your own risk. Always test on a demo account before deploying to live trading.
Author
Developed by Rahul Dhangar
https://www.rahuldhangar.com