Posts

Showing posts from October, 2026

​Hands-On Guide: Building an Automated Trade Journal and CSV Exporter in

 Keeping a meticulous trading journal is one of the most important habits of a successful systematic trader. However, manually writing down every entry, exit, profit, and loss in a spreadsheet is tedious and prone to human error. By writing a custom MQL5 function that automatically logs closed trade history directly into a structured CSV file, you can maintain a flawless performance journal effortlessly. In this hands-on tutorial, we will build a trade-logging script that tracks and exports closed order history in MetaTrader 5. --------------------------------------------------- 1. Why Automated Trade Journaling Matters Automated logging ensures: • Every single backtest or live execution is permanently recorded with exact timestamps. • You can easily import your CSV file into Microsoft Excel or Python pandas to analyze win rates, maximum drawdown, and profit factors offline. • You eliminate the emotional blind spots that come with manual record-keeping. ----------------------------...

​Hands-On Guide: Auto-Reconnecting WebSocket Streams in Python

 While REST APIs are great for periodic polling, real-time market tracking and streaming live tick data require WebSocket connections. However, network handshakes can drop unexpectedly due to mobile signal shifts or server heartbeats timing out. If your script doesn't handle disconnections automatically, it will crash and leave you blind to market movements. In this hands-on tutorial, we will build an auto-reconnecting WebSocket client loop in Python. --------------------------------------------------- 1. Why WebSockets Drop & How to Handle Them Unlike traditional HTTP request-response cycles, a WebSocket maintains a continuous persistent connection. When a drop occurs: • The socket raises a connection error or closed exception. • Instead of letting the script die, we wrap the connection inside a `while` loop combined with `try-except` blocks. • We implement an exponential backoff delay before attempting to reconnect so we don't spam the server. ----------------------------...

​Hands-On Guide: Automating Percentage Change Alerts with Python & Telegram

 Staring at price charts all day is exhausting and inefficient. Instead of manually monitoring assets for breakouts, you can write a lightweight Python script that calculates real-time percentage shifts and pushes instant alerts straight to your phone via Telegram when a threshold is breached. In this hands-on tutorial, we will build a percentage-change monitoring script optimized for mobile execution. --------------------------------------------------- 1. The Logic Behind Percentage Change Monitoring To catch sudden market momentum: • The script records a baseline reference price when it starts. • On every polling cycle, it compares the current market price against that baseline. • If the absolute percentage change exceeds your defined threshold (e.g., a 1.5% spike or drop), it triggers an instant Telegram notification and updates the baseline. --------------------------------------------------- 2. Complete Python Percentage Alert Script Open your terminal or development environme...

​Hands-On Guide: Building a Telegram Bot Command Listener in Python

 While receiving automated alerts on Telegram is great, being able to send commands *back* to your mobile scripts takes your automation to the next level. Imagine checking your account balance or stopping a running market scanner simply by typing a quick command inside your Telegram chat. In this hands-on tutorial, we will build a lightweight Python command listener using long-polling to control background scripts remotely. --------------------------------------------------- 1. How Telegram Long-Polling Works Instead of requiring a complex webhook server with a public IP address (which can be difficult to set up on a mobile device), our script uses a simple polling loop. It repeatedly asks Telegram’s servers if any new messages have arrived, parses the text command, and executes matching actions. --------------------------------------------------- 2. Complete Python Telegram Command Listener Script Open Termux or your preferred environment, create a new file named bot_listener.py, ...

​Hands-On Guide: Implementing Multi-Timeframe Trend Filters in

 Taking trades based purely on a single lower timeframe chart often leads to false breakouts caused by noisy market fluctuations. Professional algorithmic traders filter out bad signals by aligning their trades with the dominant trend of a higher timeframe (such as checking an H4 trend while trading on an M15 chart). In this hands-on tutorial, we will add a multi-timeframe Moving Average trend filter to our MQL5 Expert Advisor. --------------------------------------------------- 1. Why Multi-Timeframe Analysis Matters By verifying the broader market direction before executing a lower timeframe entry: • You prevent your EA from buying into a major downward trend or selling into a strong upward surge. • You drastically improve win rates by trading in harmony with institutional momentum. • It acts as an automatic filter during messy, choppy consolidation phases. --------------------------------------------------- 2. Implementing Higher Timeframe Checks in MQL5 Open your Expert Advisor...

​Hands-On Guide: Calculating Dynamic Lot Sizes Based on Account Equity in

One of the most dangerous mistakes beginner algorithmic traders make is hardcoding a fixed lot size (like 0.10 or 1.0) into their Expert Advisors. If your account equity changes or market volatility spikes, fixed lot sizing can expose your portfolio to uncontrolled drawdowns. Professional EAs calculate trade volume dynamically based on your account balance and a fixed risk percentage per trade. In this hands-on tutorial, we will build a dynamic lot-sizing function in MQL5 that calculates optimal trade volume based on your Stop Loss distance. --------------------------------------------------- 1. The Math Behind Risk-Based Lot Sizing To calculate safe position sizes automatically, our function accounts for three variables: • Account Equity: Total funds currently available in your trading account. • Risk Percentage: The maximum percentage of your equity you are willing to lose on a single trade (e.g., 1%). • Stop Loss Distance: The distance in points between your entry price and your Sto...

​Hands-On Guide: Exporting Python Market Data to CSV Files for Analysis

When running automated market scanners or price trackers, viewing terminal output in real time is helpful, but preserving that data for historical review, spreadsheet analysis, or offline testing is even better. Python's built-in CSV module allows you to save polled price data directly to structured files on your mobile device. In this hands-on tutorial, we will build a lightweight Python script that logs polled market metrics into a local CSV spreadsheet. --------------------------------------------------- 1. Why Store Data in CSV Format? Comma-Separated Values (CSV) is a universal data format. By saving your script's output to a CSV file: • You can transfer the log files easily to a desktop spreadsheet program (like Microsoft Excel or Google Sheets) for charting. • You maintain an offline historical record of market movements captured during your mobile scanner runs. • It requires zero external database setup, making it lightweight enough to run smoothly in Termux. ----------...

​Hands-On Guide: Adding Time Filters and Session Controls to Your MQL5 Expert Advisor

Market volatility changes drastically depending on the active trading session. Running an Expert Advisor during low-liquidity night sessions or right before major economic news releases can expose your account to erratic spreads and slippage. Adding a time filter to your MQL5 EA ensures your bot only executes trades during optimal market hours. In this hands-on guide, we will implement session control logic using MQL5 time structures. --------------------------------------------------- 1. Why Time Filters Matter in Algorithmic Trading Different trading sessions (such as London, New York, or Asian sessions) exhibit distinct price action characteristics. By restricting your EA to specific hours: • You avoid low-liquidity periods where spreads widen significantly. • You prevent your bot from taking entries during messy, range-bound overnight hours. • You can program automatic Friday afternoon exits to avoid weekend gap risks. --------------------------------------------------- 2. Implemen...

​Hands-On Guide: Building a Multi-Symbol Price Tracker with Python

Monitoring a single asset is fine for basic tests, but real-world trading and market analysis often require tracking multiple instruments simultaneously. Writing a multi-symbol polling script allows you to scan a watchlist of indices or currency pairs in a single execution loop. In this hands-on tutorial, we will build a lightweight Python script that iterates through a watchlist of symbols and evaluates price variations using a dictionary structure. --------------------------------------------------- 1. Structuring Your Watchlist with Python Dictionaries Instead of writing separate variables for every asset, we can store our symbols and target thresholds in a clean dictionary structure. This makes it easy to scale your script from two symbols to twenty without cluttering your code. --------------------------------------------------- 2. Complete Multi-Symbol Python Script Open Termux or your preferred development environment, create a new file named multi_tracker.py, and paste the foll...

​Hands-On Guide: Implementing a Dynamic Trailing Stop in Your MQL5 Expert Advisor

A static Stop Loss is crucial when entering a trade, but once a position moves significantly in your favor, keeping your stop loss fixed leaves potential profits on the table. A dynamic trailing stop automatically adjusts your Stop Loss closer to the current market price as the trade progresses. In this hands-on tutorial, we will upgrade our MQL5 Expert Advisor to include a trailing stop function that locks in gains during strong trends. --------------------------------------------------- 1. How a Trailing Stop Works in MQL5 A trailing stop operates by monitoring open positions on every tick: • For a Buy Trade: If the current Bid price rises above your open price by more than your trigger distance, the Stop Loss moves up to trail behind the price by a set number of points. • For a Sell Trade: If the current Ask price drops below your open price, the Stop Loss moves down to trail the market. --------------------------------------------------- 2. Implementing the Trailing Stop Function O...

​Hands-On Guide: Building a Custom Moving Average Distance Indicator in MQL5

While built-in indicators in MetaTrader 5 cover the basics, creating your own custom indicators gives you complete control over how data is calculated and displayed on your charts.  In this hands-on tutorial, we will build a custom MQL5 indicator that measures the distance between price and a Moving Average, helping you spot overextended market conditions. --------------------------------------------------- 1. Creating a New Indicator in MetaEditor To start building your custom indicator: 1. Open MetaEditor (press F4 inside MT5). 2. Click New on the top toolbar to launch the MQL5 Wizard. 3. Select Indicator (template) and click Next. 4. Name your indicator (e.g., CustomMADistance), set your output parameters, and click Finish. --------------------------------------------------- 2. Understanding Indicator Properties & Buffers Custom indicators require special preprocessor directives and indicator buffers to draw lines or histograms on the chart window: • #property indicator_sepa...

​Hands-On Guide: Adding Automated Logging & Error Handling to Python Scripts

When running automated Python scripts—whether they are market scanners, Telegram alert bots, or data scrapers—unforeseen network drops or API rate limits can cause silent crashes. If your script stops running in the background without leaving a trace, you miss critical market events. In this hands-on guide, we will implement Python’s built-in logging module and robust exception handling to keep your scripts stable and trackable. --------------------------------------------------- 1. Why Use Logging Instead of Print Statements? While print() statements are great for quick terminal checks, they disappear when your terminal session closes. The Python logging module allows you to: • Write error messages and event timestamps directly to a local file (e.g., scanner.log). • Categorize logs by severity levels (INFO, WARNING, ERROR, CRITICAL). • Review execution history long after your script has run in the background. --------------------------------------------------- 2. Setting Up the Loggin...

​Hands-On Guide: Optimizing Mobile Data & Network Stability for MT5 & Python Scanners

When running automated trading bots, Python market scanners, or monitoring live MetaTrader 5 charts over mobile networks, connection stability is everything. A dropped data connection or high latency can delay order execution or break API polling loops. In this practical guide, we look at effective ways to optimize mobile data usage and ensure uninterrupted script execution on your phone or mobile hotspot setup. --------------------------------------------------- 1. Minimizing Data Usage in MetaTrader 5 Mobile data bundles can drain quickly if your trading terminal is overloaded with unnecessary visual data. You can drastically reduce data consumption by: • Reducing Max Bars in Chart: Go to Tools > Options > Charts in MT5 and lower the "Max bars in chart" setting (e.g., from 100,000 to 5,000). This stops the terminal from downloading massive chunks of historical data on every refresh. • Disabling Unused Symbols: Hide symbols you aren't actively trading or scanning f...

​Hands-On Review: Evaluating Budget Laptops for Running MetaTrader 5 & Development Tools

You don't need a high-end gaming rig to run algorithmic trading platforms, code editors, and mobile simulators. Many developers and traders rely on budget-friendly or refurbished laptops for daily work. But how do entry-level machines handle multi-window charting, compilation, and background background scripts? In this hands-on review, we test how budget laptop hardware handles MetaTrader 5, MetaEditor, and development environments under everyday workloads. --------------------------------------------------- 1. Hardware Bottlenecks: What Matters Most? When choosing or testing a budget laptop for coding and trading, three hardware components dictate performance: • Storage (SSD vs. HDD): An NVMe or SATA SSD is non-negotiable. Booting Windows, launching MT5 history data, and compiling MQL5 code on an old mechanical HDD leads to severe lag. • RAM Capacity: 4GB RAM is the bare minimum for web browsing, but upgrading to 8GB or higher ensures smooth switching between MT5 terminals, code e...

​Hands-On Guide: Backtesting and Optimizing Your MQL5 EA in MetaTrader 5

Writing an Expert Advisor (EA) is only half the battle. Before deploying any trading bot to a live or demo account, you must test how its logic performs against historical market data across different market conditions. In this hands-on guide, we will walk through setting up the MetaTrader 5 Strategy Tester, running historical backtests, and analyzing performance reports. --------------------------------------------------- 1. Opening the Strategy Tester in MT5 To access the testing environment: 1. Open MetaTrader 5 on your desktop. 2. Press Ctrl + R (or navigate to View > Strategy Tester) to open the testing panel at the bottom of your screen. 3. Select your compiled EA file (e.g., RiskManagedEA.ex5) from the Settings tab. --------------------------------------------------- 2. Configuring Test Parameters Proper configuration ensures your backtest reflects realistic trading conditions: • Symbol: Choose the exact instrument you built the EA for (e.g., Forex pairs or Synthetic Indices)...

​Hands-On Guide: Adding Stop Loss, Take Profit, and Trade Execution to Your MQL5 EA

A trading signal is only as good as the risk management backing it up. While detecting crossovers or indicator levels in MQL5 is essential, an Expert Advisor must be able to open trades automatically while protecting your account with strict Stop Loss (SL) and Take Profit (TP) parameters. In this hands-on tutorial, we will upgrade our MQL5 Expert Advisor by integrating the standard CTrade execution class to handle order placement, lot sizing, and automatic SL/TP calculations. --------------------------------------------------- 1. Introducing the CTrade Class in MQL5 MetaTrader 5 simplifies trade execution through the built-in Trade library. Instead of constructing complex MqlTradeRequest structures manually, we import the CTrade class from <Trade\Trade.mqh>. This gives us access to clean, high-level functions like: • trade.Buy() - Opens a long position with specified SL/TP. • trade.Sell() - Opens a short position with specified SL/TP. ---------------------------------------------...

​Hands-On Guide: Connecting a Python Market Scanner to Telegram Bot Alerts

Running a market scanner on Termux is efficient, but checking terminal logs manually defeats the purpose of automation. The most effective setup sends real-time push notifications straight to your mobile device via a custom Telegram Bot. In this practical guide, we will set up a Telegram Bot using BotFather and integrate its API into our Termux Python script. --------------------------------------------------- 1. Creating Your Bot with BotFather To set up a dedicated alert bot on Telegram: 1. Open the Telegram app and search for @BotFather. 2. Start a chat and send the command: /newbot 3. Follow the prompts to set a display name and unique username (e.g., MyMarketAlert_bot). 4. BotFather will generate an HTTP API Token (e.g., 123456789:ABCdefGhIJKlmNoPQ-RSTuvw). Save this token securely. --------------------------------------------------- 2. Finding Your Telegram Chat ID Your bot needs to know where to send the alerts: 1. Search for @userinfobot or @raw_data_bot in Telegram and tap Sta...

​Hands-On Guide: Setting Up a Python Mobile Market Scanner on Android (Termux)

Monitoring market conditions 24/7 directly from a desktop isn't always practical when you are on the move. Fortunately, modern Android devices have enough processing power to run background Python scripts that scan technical setups and deliver real-time notifications straight to your phone. In this practical tutorial, we will set up Termux—a Linux terminal emulator for Android—and write a lightweight Python market scanner. --------------------------------------------------- 1. Installing Termux & Prerequisites To turn your mobile device into a Python execution environment: 1. Download and install Termux from the F-Droid store (recommended for updated packages). 2. Open Termux and run the package update command:    pkg update && pkg upgrade -y 3. Install Python and basic development utilities:    pkg install python git -y 4. Verify your Python installation by typing:    python --version --------------------------------------------------- 2. Insta...

Hands-On Guide: Building Your First Moving Average EA in MQL5 (MetaEditor)

 Automating your trading strategy eliminates emotional bias and allows for seamless execution. In MetaTrader 5 (MT5), Expert Advisors (EAs) are created using the MQL5 programming language inside the built-in MetaEditor IDE. In this step-by-step tutorial, we will write a simple Moving Average Crossover Expert Advisor that detects trend changes and generates trading signals automatically. --------------------------------------------------- 1. Setting Up MetaEditor in MT5 To start writing your EA: 1. Open MetaTrader 5 on your desktop. 2. Press F4 on your keyboard (or click Tools > MetaQuotes Language Editor). 3. In MetaEditor, click New on the top toolbar. 4. Select Expert Advisor (template) and click Next. 5. Name your EA (e.g., SimpleMACrossover) and click Finish. --------------------------------------------------- 2. Understanding the Core MQL5 Structure Every MQL5 Expert Advisor relies on three primary event functions: • OnInit(): Executes once when the EA is attached to a char...