MarketAlert – Real-Time Market & Crypto News, Analysis & AlertsMarketAlert – Real-Time Market & Crypto News, Analysis & Alerts
Font ResizerAa
  • Crypto News
    • Altcoins
    • Bitcoin
    • Blockchain
    • DeFi
    • Ethereum
    • NFTs
    • Press Releases
    • Latest News
  • Blockchain Technology
    • Blockchain Developments
    • Blockchain Security
    • Layer 2 Solutions
    • Smart Contracts
  • Interviews
    • Crypto Investor Interviews
    • Developer Interviews
    • Founder Interviews
    • Industry Leader Insights
  • Regulations & Policies
    • Country-Specific Regulations
    • Crypto Taxation
    • Global Regulations
    • Government Policies
  • Learn
    • Crypto for Beginners
    • DeFi Guides
    • NFT Guides
    • Staking Guides
    • Trading Strategies
  • Research & Analysis
    • Blockchain Research
    • Coin Research
    • DeFi Research
    • Market Analysis
    • Regulation Reports
Reading: From Novice to Expert: Reporting EA — Setting up the work flow
Share
Font ResizerAa
MarketAlert – Real-Time Market & Crypto News, Analysis & AlertsMarketAlert – Real-Time Market & Crypto News, Analysis & Alerts
Search
  • Crypto News
    • Altcoins
    • Bitcoin
    • Blockchain
    • DeFi
    • Ethereum
    • NFTs
    • Press Releases
    • Latest News
  • Blockchain Technology
    • Blockchain Developments
    • Blockchain Security
    • Layer 2 Solutions
    • Smart Contracts
  • Interviews
    • Crypto Investor Interviews
    • Developer Interviews
    • Founder Interviews
    • Industry Leader Insights
  • Regulations & Policies
    • Country-Specific Regulations
    • Crypto Taxation
    • Global Regulations
    • Government Policies
  • Learn
    • Crypto for Beginners
    • DeFi Guides
    • NFT Guides
    • Staking Guides
    • Trading Strategies
  • Research & Analysis
    • Blockchain Research
    • Coin Research
    • DeFi Research
    • Market Analysis
    • Regulation Reports
Have an existing account? Sign In
Follow US
© Market Alert News. All Rights Reserved.
  • bitcoinBitcoin(BTC)$75,692.00-2.26%
  • ethereumEthereum(ETH)$2,352.58-3.24%
  • tetherTether(USDT)$1.000.00%
  • rippleXRP(XRP)$1.43-3.23%
  • binancecoinBNB(BNB)$630.35-1.96%
  • usd-coinUSDC(USDC)$1.000.00%
  • solanaSolana(SOL)$86.08-3.43%
  • tronTRON(TRX)$0.3293040.55%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.041.31%
  • dogecoinDogecoin(DOGE)$0.094972-5.19%
Trading Strategies

From Novice to Expert: Reporting EA — Setting up the work flow

Last updated: July 29, 2025 11:30 pm
Published: 9 months ago
Share

The inspiration for this concept arose when I started receiving daily trade confirmations from my broker via email. These summaries offered a clean, professional overview of trading activity and highlighted the potential for statistical performance analysis. While exploring the MetaTrader 5 terminal, I found that it includes a comprehensive reporting tool in its current build, capable of exporting detailed reports in both HTML and PDF formats. However, it lacks the functionality for automatic report delivery and centralized management. In this discussion, we aim to explore the role of trading reports, clarify the key terms they involve, and emphasize their practical importance to every trader seeking informed decision-making.

Ultimately, we plan to implement a custom reporting system using MQL5 in collaboration with Python and other external tools. This solution will generate detailed reports, ensure compatibility across multiple file formats, and support automated delivery through practical and reliable methods.

After examining the documents exported from MetaTrader 5, it became clear that they contain valuable insights and pre-calculated metrics that offer traders a mathematical view of their performance — information that can directly influence trading decisions and behavioral adjustments.

Currently, reports in MetaTrader 5 are typically obtained through manual navigation. However, when working with Expert Advisors (EAs), we have the opportunity to programmatically control the generation and delivery of these reports. While some brokers already send these automatically, our goal in this discussion is to develop a system that allows us to schedule report delivery according to our own preferences — customizing both the frequency and content.

As we work toward solving this, we’ll explore the practical importance of trading reports using one of my own experiences as an example. We’ll also examine common terms found in these reports and discuss how they can be used to improve both manual trading strategies and Expert Advisor performance evaluation.

In MetaTrader 5, you can access trading reports by selecting Reports from the View menu or by using the shortcut Alt+E. The report window displays various aspects of your trading activity in a clear, organized format. From this window, you also have the option to save your reports in either HTML or PDF format, as shown in the image below:

The illustration above highlights some of the key components typically found in trading reports. While this information is highly valuable, many traders tend to focus solely on charts and trade execution — often neglecting to review their performance records periodically. Gaining a clear understanding of these reports is essential, as it reinforces discipline and supports a healthier trading mindset by drawing insights from past activity.

After reviewing my trading report, I took the initiative to research the key terms it contained and compiled notes along with practical examples to make them easier to understand. In the next section, you’ll find five structured insights, each offering a quick yet meaningful explanation. These serve as a foundation for the implementation blueprint we’ll explore later in the article. By the time we transition into the technical build phase, the goal is to ensure a solid grasp of these report concepts. If you’re already familiar with them, feel free to skip ahead to the implementation stage.

At this stage, we proceed to set up our workflow. Thanks to the previous section, which provided an in-depth understanding of trading report terminology, you’ll find this part easier to follow with fewer unfamiliar concepts.

To accomplish the goal of this article, we will develop an Expert Advisor (EA) that handles data export and prepares the necessary logs. This EA will serve as a bridge between MetaTrader 5 (MQL5) and the Python libraries responsible for processing historical trading data and generating a final report in a portable format — similar to the reporting tools built into the MetaTrader 5 terminal.

We’ll begin by presenting a flow chart outlining the entire process, followed by a breakdown of the required tools and environment setup to get everything working. All components of this project are based on open-source technologies, ensuring accessibility for everyone.

To get started, make sure you have MetaTrader 5 installed on your system. Then proceed to set up the Python environment, which I’ll explain in detail later. Refer to the table below for a simplified list of requirements and tools used in this workflow.

At this stage, we begin developing the Expert Advisor (EA) as planned. I will guide you through each component of the code, explaining how they work together to form a complete and functional system. The goal is to build a robust EA that serves its intended purpose seamlessly. Follow along as we break the development process into clear, manageable steps, ensuring that each piece is easy to understand and contributes meaningfully to the final product.

In MetaEditor 5, open a new file and select the “Expert Advisor” template. I recommend removing any sections of the auto-generated code that are not relevant to our current development goals, so we can focus only on what matters. Follow the numbered steps below as we begin building the Expert Advisor step by step.

1. File Metadata and Compilation Directives

At the top of the file, the #property directives declare metadata for the Expert Advisor (EA). These properties include the copyright and link information, which appear in the MetaTrader 5 terminal’s “About” box, as well as the version number and strict compilation mode. The strict mode enforces more rigorous type checking and compilation rules, helping prevent subtle bugs by disallowing implicit casts and requiring explicit conversions.

2. Constants and Windows API Imports

The #define statements create symbolic names for commonly used constant values (SW_HIDE to hide console windows and INVALID_FILE_ATTRIBUTES for error checking). Following that, the code imports two Windows system libraries via #import: kernel32.dll for file-attribute functions (GetFileAttributesW) and shell32.dll for executing external processes (ShellExecuteW). By calling these native DLL functions, the EA extends MetaTrader 5’s built‑in capabilities to verify file existence and launch the Python interpreter.

3. User Inputs for Configuration

The input declarations expose customizable parameters in the EA’s settings dialog. Users can specify the absolute path to the Python executable (PythonPath), the Python script to run (ScriptPath), the hour and minute when the daily report should execute (ReportHour, ReportMinute), whether push notifications are sent (EnableEmail), and whether an initial test run occurs on startup (TestOnInit). Exposing these as inputs allows non‑programmers to tweak behavior without editing source code.

4. Global State Management

A single global variable, lastRunTime, stores the timestamp of the most recent successful report execution. By comparing TimeCurrent() against lastRunTime, the EA ensures that the report only runs once every 24 hours, even though the timer callback checks more frequently.

5. Initialization Logic (OnInit)

The OnInit() function performs all startup routines. First, it prints status messages to the Experts log. It checks file attributes for the Python executable and script and prints warnings if they’re missing. It then tests write permissions by creating, writing, closing, and deleting a dummy file in the MQL5Files directory. Next, it sets up a recurring timer event every 30 seconds via EventSetTimer(30). Finally, if TestOnInit is true, it calls RunDailyExport() immediately to validate the full export-and-Python workflow, recording the current time in lastRunTime.

6. Deinitialization Logic (OnDeinit)

When the EA is removed or the platform shuts down, OnDeinit() is invoked. Its sole responsibility is to clean up by killing the timer (EventKillTimer()) and logging a deinitialization message. Properly releasing timer resources prevents orphaned callbacks and potential crashes.

7. Timer Callback for Scheduling (OnTimer)

Every 30 seconds, OnTimer() runs and retrieves the current hour and minute through the MqlDateTime struct. It checks whether the current time matches or exceeds the configured report time (ReportHour, ReportMinute), and whether at least 86 400 seconds (24 hours) have elapsed since lastRunTime. This double‑check ensures the report runs once daily at or after the scheduled minute.

8. Main Workflow: Export and Python Invocation (RunDailyExport)

This helper function automates the extraction of deal history into a CSV file. It selects all history within the past 30 days (HistorySelect), iterates through each deal ticket, retrieves properties (time, type, symbol, volume, price, profit, commission, swap) using HistoryDealGet* functions, and writes them as comma‑separated values with FileWrite. After outputting a header row, the loop constructs each line using DoubleToString and TimeToString, ensuring consistent numeric precision and timestamp formatting. Proper error checking on FileOpen prevents silent failures.

10. Shell Command Wrapper (ShellExecute)

The ShellExecute function serves as a thin wrapper around the imported ShellExecuteW API call. By standardizing the invocation of cmd.exe, it hides the native API’s complexity and always uses SW_HIDE to suppress console windows. Returning the integer result code allows the EA to detect and log potential errors in launching external commands

We begin by setting up Python and installing the required libraries. First, open the Command Prompt and run the necessary installation commands. After that, you can prepare your Python script using a text editor. I personally prefer Notepad++, an open-source tool, but you’re free to use any Python IDE of your choice.

Setting Up

1. To prepare the Python side, start by installing a recent Python 3.x interpreter (e.g. 3.10 or 3.12). Create and activate a virtual environment in your project folder:

2. Once activated, install the required packages with:

3. If you plan to send email alerts, also install an SMTP library such as yagmail or use Python’s built‑in smtplib.

Now it’s time to develop the Python script. We’ll proceed through the following steps to implement each part.

1. Script Header and Imports

The script begins with a Unix‑style shebang to allow execution on systems that respect it, followed by imports of key libraries:

2. Main Workflow: Argument Validation and File Checks

The main(csv_path) function is the orchestrator. It prints the CSV file being processed and immediately verifies that the file exists, raising a FileNotFoundError if not. This mirrors the MQL5 EA’s own preflight checks for the Python executable and script paths.

3. Loading and Parsing the CSV

Using pandas.read_csv, the script loads the trade-history CSV produced by the EA. It then converts the ‘Time’ column to datetime objects with pd.to_datetime, ensuring subsequent time‑based calculations are accurate. This parallels the EA’s formatting of times with TimeToString.

4. Computing Summary Analytics

The script aggregates key performance metrics into a report dictionary:

These metrics match the EA’s CSV contents and allow the PDF to summarize exactly what was exported.

5. Generating the PDF Report

The script builds the output path in the same MQL5Files directory as the CSV, naming the PDF by date. It then calls generate_pdf(report, pdf_file). This dovetails with the EA’s logging of Python output and the expectation that any artifacts (both CSV and PDF) land in the common files folder.

6. PDF Construction with FPDF

The generate_pdf function uses FPDF’s simple API: creating a document, adding a page, setting the font, and writing lines for each metric. The ln=True parameter moves to the next line automatically. This modular helper keeps PDF formatting concerns separate from data logic.

7. Maintenance: Cleaning Up Old Reports

To prevent disk bloat, clean_old_reports deletes any PDF older than a configurable number of days (default 30). It only runs when the EA invokes the script on Sundays (weekday() == 6) and receives the CSV path in sys.argv[1], ensuring it targets the correct directory. This maintenance parallels the EA’s own date‑based naming and 24‑hour gating logic.

8. Script Entry Point and Error Handling

The if __name__ == “__main__”: block enforces usage of exactly one argument (the full path to the CSV). It wraps the call to main in a try/except to catch any exception, print a traceback, and exit with a non‑zero code — just as the EA captures Python’s stdout/stderr and surface any errors into its own logs. Optional maintenance is run weekly before exiting.

Interplay Between MetaTrader 5 EA and Python Script

In this section, we deploy the Reporting EA onto a MetaTrader 5 chart. On a Windows computer, it’s essential to enable DLL imports to allow external process execution. During testing, the EA successfully achieved its goal: exporting trading history as a CSV file and triggering the Python script responsible for processing the data. The script then generates the required report metrics and exports them as a polished PDF document, ready to be sent via email or archived for review.

The Expert Log shown above reveals an initialization attempt of the Reporting EA, where the system failed to locate the specified Python executable and script. This happened because the file paths were deliberately renamed in the code (e.g., C:path_topython.exe and C:path_toreports_processor.py) for demonstration or placeholder purposes. As a result, the EA could not execute the Python script or generate the expected log output (ProcLog_20250724.txt). Despite this, the EA successfully confirmed write permissions and exported the trading history as a CSV file.

This test highlights the importance of correctly configuring file paths in your EA — pointing to the actual Python interpreter and processing script — to ensure seamless end-to-end report generation. Always double-check and use valid, absolute paths that match your local system setup to avoid such issues and unlock the full functionality of the reporting tool.

This discussion focused primarily on understanding trading reports, setting up a functional workflow, and developing the tools necessary for delivering custom trading reports in a portable document format (PDF). The final stages of sending the generated PDF via email have been reserved for a future publication, to avoid overwhelming this presentation. However, the PDF generation process — based on the exported CSV — was successfully handled using Python libraries. Further enhancements, such as including charts and advanced reporting features, will be introduced in the next discussion.

Now that both the Expert Advisor and its corresponding Python script are complete, we are well-positioned to achieve even more. In summary, this project solves the challenge of receiving scheduled, customizable trading reports with clarity-focused features that aid user understanding. Just as bookkeeping is essential for any business, regular reporting is vital in trading — it promotes performance awareness, discipline, and psychological growth for traders.

Read more on mql5.com

This news is powered by mql5.com mql5.com

Share this:

  • Share on X (Opens in new window) X
  • Share on Facebook (Opens in new window) Facebook

Like this:

Like Loading...

Related

$PNFPP | ($PNFPP) Trading Report (PNFPP)
Gen Z work culture, explained; Why Hyderabad’s cafes are going OTT
Galaxy & Co. Eye Biggest Solana Treasury With $1 Billion Bet
Nordic Power Prices Climb As Drier Weather Saps Hydropower
VelorGain Introduces New User-Insight Framework as Demand for Transparent Trading Experiences Rises in 2025

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Email Copy Link Print
Previous Article Pyth Network brings Hong Kong stock prices onchain for global access
Next Article How to Use ChatGPT Agent to Automate Your Crypto Trading Strategy in Minutes
© Market Alert News. All Rights Reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Prove your humanity


Lost your password?

%d