MetaTrader Trading Tools
Showing 7620 results in this view

ShowTradeLines Service

The service provides more descriptive and intuitive representation of open positions and related deals on charts than it's offered by the terminal by default. Specifically you can see the time(s) and price(s) of opening trade and optionally other deals, such as partial close or adding volume to a position in a netting account.

The service monitors account state for open positions and creates graphical objects on an active chart (shown on top or maximized) if its symbol corresponds to at least one of existing positions.

Inputs

  • TimeInterval (seconds) - 5 by default;
  • LinePrefix - common prefix for on chart objects, such as "TradeTag";
  • LineColorProfit - color for lines of profitable positions (clrDodgerBlue);
  • LineColorLoss - color for lines of lossy positions (clrCoral);
  • LineStyle - drawing style of lines (STYLE_DASHDOT);
  • LineWidth - width of lines (1);
  • LineType - type of lines - OBJ_TREND (default) or OBJ_VLINE;
  • ShowDeals - option to show arrows for deals (true);
  • KeepLinesOnCharts - option to keep graphical objects on chart after position is closed (false);
  • Logging - output or not main events to log (true);

The service registers all objects added on chart in the list of the global variables. This helps the program to detect which objects to remove when a position is closed and KeepLinesOnCharts is false. If KeepLinesOnCharts is true, the service keeps corresponding objects on charts (they are left for manual control by user), but in any case the relevant global variables (describing closed positions and their deals) are removed upon position closure.

All objects receive textual descriptions with most important properties of positions and deals, which can be seen in tooltips (on mouse hover) and right on the chart (if corresponding option is enabled in the chart's settings).

Price Action Intraday Trading - Expert for MT5

Price Action Day Trader EA

Core Trading Logic

The EA analyzes price action on every new bar and executes trades based on three primary setups:

  • Pin Bar (Rejection): Identifies price rejection at key levels with customizable wick-to-body ratios.

  • Engulfing Candles (Momentum): Captures reversals when a large candle completely overcomes the previous price action.

  • Inside Bar Breakouts (Consolidation): Trades the breakout of a mother bar, signaling the continuation or reversal of a trend.

  • Trend Filter: A dual EMA (default 20/50) ensures the EA only enters trades in the direction of the medium-term momentum.

  • S/R Context: Integrated Support and Resistance lookback allows the EA to validate signals based on historical price levels.

Key Features
  • Dynamic Risk Management: Automatically calculates lot sizes based on a percentage of account balance (default 1.5%).

  • Safety Protections: Includes a Max Daily Loss limit (3%) to protect capital during volatile market days.

  • Trade Evolution: Features an automatic Break-Even trigger and a Trailing Stop to lock in profits as the trade moves in your favor.

  • Time Control: Built-in session filter allows you to define specific trading hours and automatically close positions at the end of the day.

  • Auto-Detection Filling Mode: Sophisticated order execution logic that automatically detects and adapts to your broker's filling mode (FOK, IOC, or Return).

Input Parameters
  • RiskPercent: Percentage of balance to risk per trade.

  • StopLossPips: Fixed stop loss distance.

  • TakeProfitRatio: Target profit relative to the stop loss (e.g., 2.0 = 2:1 R:R).

  • PinBarRatio: Minimum wick-to-body ratio for pin bar detection.

  • SRLookback: Number of bars used to calculate Support and Resistance levels.

  • Fast/Slow MA: Periods for the EMA trend filter.

  • Start/End Hour: Time window for opening new positions.

Recommendations
  • Timeframes: Optimized for M15, H1, and H4.

  • Symbols: Works best on major pairs (EURUSD, GBPUSD) and XAUUSD.

  • Optimization: It is recommended to optimize the StopLossPips and PinBarRatio based on the specific volatility of your chosen instrument.

Сode that records balance and equity charts and calculates additional optimization criteria

I decided to share the code from a large project designed in a separate library.

If you have access to the Expert Advisor code, you can save balance and equity charts and calculate additional optimization criteria by adding additional code from this library.Download the Advanced Optimization Report Saver.mqh file from attached link and save it to the terminal folder \MQL5\Include\Add the code that connects the downloaded file: (you can add it below the last line of your Expert Advisor code or anywhere else)

Then, you need to add calls to the exported functions to the existing functions in your Expert Advisor: (if there are no functions, add them)

save_Add functions, allow you to add your own criteria that you want to include to your Report:

For example, let's add this code to the Moving Average Expert Advisor from the Examples folder (...\MQL5\Experts\Examples\Moving Average\Moving Average.mq5). First, copy the original Expert Advisor and name it Moving Average Charts.mq5. Now, add the code from the instructions above to it.The changes are only at the very end of the code, starting from the OnTick() function after CheckForOpen(); line:

As you can see, it's quite simple and only takes a couple of minutes.After that, you can run the optimization:

The last screenshot shows that the connected code added 2 parameters:

  1. Save Statistics - enables or disables the collection of statistics
  2. Pixels in balance and equity charts - specifies the number of pixels in the width of mini-charts.

Once the optimization is complete, you can create a report (using a program that parses saved frames) and see the following:

If there are more than 20 lines, only 3 horizontal lines of average values will be displayed: 3 on top and 3 on the bottom.100 lines are difficult to perceive, so you need to reduce their number.You to use input variables not with the same step, but with a scale through an enumerator (enum), for example: 1,2,3,5,7,10,15,20,30,50,70,100 - there will be only 12 lines instead of 100.

You can download the enum version of the Expert Advisor from attached files.Instead of 1000 optimization passes, there will be 120, and the calculation time will be ~8 times faster, and the file size will be ~8 times smaller.The result is more visible:

The result with MovingPeriod = 15 stands out immediately, with the highest average line and the highest maximum.However, as is often the case, the best results on the backtest are not the best on the forward test.Your program that parses saved frames can display Charts like this:

And additional criteria like this:

If you have a code for other interesting criteria, you can suggest them for adding to the library.

Binary tradng based on candle colors

This indicator serves as a demonstration that one can send trade signals utilizing MT5 global variables.

It is up to the reader to implement the "real trading" part, for testing purpose you might want to check the following blog  (Binomo Trading using MT5 Terminal)Please note, for best result, one shall use the 5 seconds chart of any asset.Candle colors are counted and majority colors will determine the trade to place, CALL or PUT, which can be reversed in the indicator settings. In the reverse case, the minority colors will determine the trade to place.

One can verify the global variables used by pressing F3 to display MT5 Global Variables as shown in the following figure.

Good luck and enjoy.

VR Locker Lite - Trading strategy based on a positive lock

What is locking?

Locking is a situation where a trader simultaneously holds a long (LONG) and a short (SHORT) position of equal volume on the same asset. As a result:

  • Market risk is neutralized: profit or loss on one position is offset by the opposite movement of the other.
  • The position value is "frozen": the net financial result ceases to depend on market fluctuations.

The presented VR Locker Lite trading algorithm demonstrates working with one positive lock:

Operation algorithm:

  1. The trading robot immediately opens two positions: a buy (BUY) and a sell (SELL).
  2. Using averaging, the trading robot "widens" the buy (BUY) and sell (SELL) positions.
Options for further work with the lock:
  1. The simplest one - simply close the lock and start the entire trading cycle anew.
  2. Unlock the lock - leave one of the positions for a longer period and "let the profit grow".
  3. Enable a trailing stop for one of the positions or for both simultaneously.
  4. Move one of the positions to breakeven and "let the profit grow".
  5. Start the algorithm on another financial instrument or with another MagicNumber to create another positive lock.

Important things not to forget:

  1. Double commissions and swaps: You pay a commission for opening and (in the future) closing two positions instead of one. In forex, there may be a negative swap (rollover fee) on one of the positions.
  2. Capital lock-up: The margin (collateral) for the locked position is still frozen. You cannot use these funds for other trades.
  3. Complication of analysis: You still have to decide which side of the lock to close and when. This is often more difficult than the initial entry.

EA Duplicate Detector

Allow the EA to determine whether there are duplicate EAs on the chart based on conditions.

Expert.mqh comes from the library written by fxsaber at .

Project Template Generator

Technical Overview

ProjectTemplateGen.mq5 is a MetaTrader 5 script utility that automates the creation of standardized Expert Advisor project structures. It implements programmatic file system operations within MQL5's security constraints while establishing a consistent foundation for scalable trading system development.

Core Capabilities
  • Programmatic File Operations: Demonstrates MQL5's file handling API for creating directories and writing structured content
  • Template-Based Generation: Produces ready-to-compile MQL5 source files with proper event handler skeletons
  • Configurable Output: Allows runtime customization through input parameters without modifying source code
  • Sandbox Compliance: Operates within MetaTrader 5's secure execution environment
Implementation Details

File Operations Architecture

The script implements a modular approach to file creation, with distinct functions handling different aspects of project generation:

Generated Project Structure

Key Technical Components

1. Dynamic Path Construction

  • Uses relative paths compliant with MQL5 sandbox restrictions
  • Demonstrates string concatenation for dynamic file system navigation

2. Robust File Creation with Error Handling

  • Implements comprehensive error checking for file operations
  • Provides meaningful error messages with system error codes
  • Ensures proper resource cleanup with FileClose() calls

3. Structured Content Generation

  • Generates syntactically valid MQL5 code
  • Maintains consistent formatting and coding standards
  • Creates compilable boilerplate code

Usage Instructions

Basic Operation

  • Compilation: Compile ProjectTemplateGen.mq5 in MetaEditor (F7)
  • Execution: Drag script from Navigator onto any chart
  • Configuration: Set parameters in the input dialog:
  • ProjectName: Destination folder and file naming
  • CreateIncludeFile: Toggle header file generation
  • Output: Check Experts tab for generation status and path information

Post-Generation Workflow

The script creates projects in MQL5\Files\[ProjectName]\ due to MQL5 script security restrictions.

Complete the setup by:

  1. Manually moving the folder to MQL5\Experts\
  2. Opening the main .mq5 file in MetaEditor
  3. Implementing your trading logic in the provided function skeletons

Expansion Opportunities for Advanced Workflows

Scalability Enhancements

  1. Multi-File Templates: Extend to generate indicator scripts, library files, or resource manifests
  2. Configuration Files: Add JSON/XML configuration file generation for parameter management
  3. Build Scripts: Incorporate batch compilation or dependency management files

Code:   

Sideways Martingale

Backtest EURUSD 01/03/2025 - 20/01/2026 Timeframe M5 (ONNX AI training specifically for M5-M15) Backtest GBPUSD 01/03/2025 - 20/01/2026 Timeframe M5 (ONNX AI training specifically for M5-M15)

1. General Overview

SidewaysMartingale is an Expert Advisor designed to trade sideways (range-bound) markets using a martingale recovery strategy, enhanced with an AI-based trend detector implemented via an ONNX model.

The EA combines:

  • AI trend classification (Sideway / Bullish / Bearish)

  • Envelopes indicator for range-based entries

  • Controlled martingale position scaling

  • Profit-based basket closing

  • Margin-based emergency stop

The core idea is:

Trade only when the market is statistically classified as sideways, and avoid adding martingale positions when a strong trend is detected.

2. AI Trend Detector (ONNX Integration) ONNX Model Output

The ONNX model returns:

  • A predicted label (not directly used)

  • A probability vector with three probabilities:

These probabilities are extracted as:

float prob_side = prob_data[0].values[0]; float prob_bull = prob_data[0].values[1]; float prob_bear = prob_data[0].values[2];

3. Feature Engineering (AI Inputs)

The EA feeds 9 engineered features into the ONNX model:

These features allow the AI model to detect:

  • Market volatility

  • Trend strength

  • Time-based behavioral patterns

  • Price structure behavior

4. Sideways Market Detection Logic

A market is considered sideways when:

bool is_sideway = (prob_side >= InpAISidewayThreshold);

Example:

  • If InpAISidewayThreshold = 0.70

  • Then at least 70% confidence is required to classify the market as sideways

👉 No new trades are opened unless this condition is met

5. Entry Logic (Scalping in Range)

The EA uses Envelopes to detect range extremes.

Buy Entry

if(price_close <= lower[0] && is_sideway)

  • Price touches or breaks the lower envelope

  • AI confirms a sideways market

  • Opens a BUY position

Sell Entry

else if(price_close >= upper[0] && is_sideway)

  • Price touches or breaks the upper envelope

  • AI confirms a sideways market

  • Opens a SELL position

💡 This ensures trades are taken only at range extremes during non-trending conditions.

6. Martingale Recovery Logic

When positions already exist, the EA applies a distance-based martingale:

  • New position is opened only if price moves away by a defined pip distance

  • Lot size increases using a multiplier ( LotMultiplier )

  • Maximum number of trades is limited ( MaxTradesInSeries )

Distance Check

if(dist >= reqDist)

7. AI Safety Filter for Martingale

This is a critical risk control mechanism.

Before adding a new martingale position, the EA checks:

If current series is BUY

if(s_seriesType == POSITION_TYPE_BUY && prob_bear >= InpAISafetyThreshold) return;

If current series is SELL

if(s_seriesType == POSITION_TYPE_SELL && prob_bull >= InpAISafetyThreshold) return;

🔒 Meaning:

  • If AI detects a strong opposite trend

  • And confidence exceeds InpAISafetyThreshold

  • Martingale expansion is stopped

This prevents:

  • Martingale during strong breakouts

  • Deep drawdowns caused by trend continuation

8. Profit Target & Basket Closing

The EA monitors total floating profit across all positions:

if(totalProfitUSD >= TakeProfitTargetUSD)

Once reached:

  • All positions are closed

  • Martingale series is reset

  • EA waits for a new sideways setup

This approach treats all positions as one basket trade.

9. Risk Management Margin-Based Emergency Stop

if(((bal - eq)/bal)*100.0 >= StopLossByMarginPercent)

If equity drawdown exceeds a defined percentage:

  • All positions are immediately closed

  • Prevents margin call scenarios

10. Strategy Summary

Market Structure Onnx

Backtest XAUUSD 01/03/2025 - 20/01/2026 Timeframe H1 Backtest EURUSD 01/03/2025 - 21/01/2026 Timeframe H1 1. Overall Concept

This strategy combines machine learning–based market structure classification with rule-based trade execution. An ONNX model is used to classify the current market structure, while classical technical analysis (moving average trend filter, Fibonacci retracement, ATR, and risk–reward rules) is used to manage entries, exits, and risk.

The system is designed to:

  • Trade only at structurally meaningful pullback levels

  • Avoid overtrading by allowing only one active trade or pending order

  • Use probability confidence filtering from the AI model

  • Apply risk-reward–based trailing stop management

2. Market Structure Classification Using AI

An ONNX model ( market_structure.onnx ) is loaded during initialization. On every new bar, the model predicts the current market structure state.

Input Features

The model receives six normalized features:

  1. Momentum change Price difference between the current close and the close 5 bars ago, normalized by ATR.

  2. Distance to recent swing high Difference between the highest high in the last 50 bars and the current close, normalized by ATR.

  3. Distance to recent swing low Difference between the current close and the lowest low in the last 50 bars, normalized by ATR.

  4. Relative tick volume Current tick volume compared to the average tick volume of the last 20 bars.

  5. Candle body strength Difference between close and open price, normalized by ATR.

  6. Time feature (hour of day) Encodes intraday session behavior.

These features allow the model to infer trend strength, pullback depth, volatility, volume context, and session timing.

3. Model Output and Confidence Filtering

The ONNX model outputs:

  • A predicted label representing market structure state (e.g., higher high, higher low, lower high, lower low)

  • A probability score for the predicted class

A trade signal is considered valid only if:

  • The prediction confidence is above the defined threshold (default 0.65)

  • The signal aligns with the higher-timeframe trend filter

This ensures that low-confidence or noisy signals are ignored.

4. Trend Direction Filter

A 50-period Simple Moving Average (SMA) is used as a directional filter:

  • Bullish bias: price is above the SMA

  • Bearish bias: price is below the SMA

Trade directions are constrained as follows:

  • Bullish market structure signals are allowed only in bullish trend

  • Bearish market structure signals are allowed only in bearish trend

This prevents counter-trend entries.

5. Entry Logic Using Fibonacci Retracement

Instead of market orders, the strategy uses pending limit orders at Fibonacci retracement levels.

Pivot Detection

Recent swing high and swing low are detected using a pivot-based method that scans historical highs and lows.

Fibonacci Entry
  • Entry is placed at a predefined Fibonacci retracement level (default 61.8%)

  • This targets pullbacks within a valid market structure, not breakouts

Order Types
  • Buy Limit in bullish conditions

  • Sell Limit in bearish conditions

Each pending order has:

  • Fixed lot size

  • Stop Loss beyond the structure invalidation level

  • Take Profit based on a fixed Risk-Reward ratio (default 1:2)

  • Expiration time to avoid stale orders

6. Risk Management and Trade Limitation

The strategy enforces strict exposure control:

  • Only one open position or one pending order at a time

  • No stacking or martingale behavior

  • Stop Loss is always defined at entry

Risk is structurally bounded by:

  • Market structure invalidation

  • ATR-normalized distance

  • Fixed RR ratio

7. Trailing Stop Based on Risk-Reward Progress

Once a position is active, a Risk-Reward–based trailing stop is applied:

  • Trailing activates after price reaches a predefined fraction of the TP distance

  • Stop Loss is moved progressively toward breakeven and beyond

  • Trailing logic is symmetric for buy and sell positions

This approach:

  • Protects partial profits

  • Allows winners to extend

  • Avoids premature stop-outs caused by noise

8. Visual Feedback

When a trade setup is created:

  • A Fibonacci object is drawn on the chart

  • The object is automatically removed once all trades and pending orders are cleared

This helps visually confirm:

  • Market structure

  • Entry logic

  • Retracement validity

9. Summary of the Methodology

In summary, this strategy follows a hybrid AI + rule-based methodology:

  1. AI classifies market structure using normalized, context-aware features

  2. High-confidence predictions are filtered by trend direction

  3. Trades are executed only at Fibonacci pullbacks within structure

  4. Risk is controlled using fixed RR and structural stop placement

  5. Profits are managed dynamically using RR-based trailing stops

The result is a disciplined, structure-driven trading system that uses AI for decision support rather than blind automation.

TrendMomentumEA

TrendMomentumEA is a professional Expert Advisor for MetaTrader 5 designed to trade trending and momentum moves in the market using a combination of EMA, RSI, and Stochastic indicators. It is optimized for high-probability trades during the London and New York trading sessions.

Key Features
  • Trend Detection: Trades only when price is above EMA50 and EMA200 for buys, and below EMA50 and EMA200 for sells.

  • Momentum Confirmation: Uses RSI and Stochastic %K/%D crossovers to confirm entry signals.

  • Candle Confirmation: Trades are opened only after the last closed candle meets trend and momentum criteria.

  • Session Filter: Automatically trades only during London and New York sessions (configurable by broker server time).

  • Position Management: Only opens one trade at a time per symbol and Magic Number to avoid conflicts.

  • Risk Management: Configurable lot size, stop loss, and take profit.

How It Works
  1. The EA monitors the last closed candle to identify the current trend using EMA50 and EMA200.

  2. If a trend exists, it checks RSI levels and Stochastic crossover for momentum confirmation.

  3. Once all conditions are met, it opens a buy or sell trade with pre-defined stop loss and take profit.

  4. Trades are filtered by session, ensuring the EA only operates during high liquidity periods.

Recommended Settings
  • Symbols: Major Forex pairs (EURUSD, GBPUSD, USDJPY), indices, commodities.

  • Timeframes: M15, H1 are ideal; compatible with other timeframes.

  • Input Parameters:

    • EMA50 and EMA200 periods

    • RSI period and thresholds

    • Stochastic %K, %D, and slowing

    • Stop Loss and Take Profit in points

    • London and New York session times

Advantages
  • Avoids trading in sideways markets by combining trend and momentum filters.

  • Reduces risk with Magic Number filtering and single-position logic.

  • Works on any MT5 broker, supporting 3-, 4-, or 5-digit quotes.

Notes & Disclaimer
  • Ensure broker server time is aligned with session inputs.

  • Test on a demo account before live trading.

  • Designed for trend-following and swing trades, not scalping.

  • Past performance does not guarantee future results.

SuperTrend Quant Pro Elite: Adaptive Statistical Trend Engine

The Quant Edge Traditional SuperTrend indicators suffer from "lag" and "whipsaws" because they use static multipliers. SuperTrend Quant Pro Elite solves this by using a Z-Score Normalization algorithm. It dynamically adjusts the trend-tracking sensitivity based on current market volatility, effectively widening the gap during spikes and tightening it during stable moves.

Key Technical Features:

  • Adaptive Volatility Engine: Uses statistical Z-Score analysis to auto-adjust the ATR multiplier in real-time.

  • Volume Confluence (VSA): Signals are only "Confirmed" when tick volume exceeds institutional averages, helping you avoid low-liquidity traps.

  • Regime Detection: The indicator automatically identifies "Trending" (Solid Line) vs. "Choppy" (Dotted Line) environments using built-in ADX logic.

  • Built-in MTF Scanner: A professional dashboard tracks the trend status across M15, M30, H1, H4, and D1 simultaneously on your current chart.

  • Performance Metrics: Displays real-time Edge Probability (Win Rate) and Profit Factor based on the current timeframe's history.

Interpretation of Signals:

  • Green Line/Arrow: Bullish momentum established. Look for Buy opportunities.

  • Red Line/Arrow: Bearish momentum established. Look for Sell opportunities.

  • Star (★) Icon: High-conviction signal where Volume and Trend Strength align.

  • Dotted Line: Market is in a ranging/choppy phase; exercise caution.

Recommended Setup:

  • Symbols: Works best on major Forex pairs (EURUSD, GBPUSD), Indices (US30, GER40), and Gold (XAUUSD).

  • Timeframes: Optimized for M15 and H1 for day trading; H4 and D1 for swing trading.

Position Size Pro Lite: Interactive Risk Calculator Panel

Basic Risk Calculator is a professional trading utility designed to solve the most common problem in manual trading: Position Sizing. Instead of guessing your lot size, this tool calculates the exact volume you need based on your specific risk appetite, ensuring you never over-leverage your account.

🎯 WHAT IT DOES A sleek, on-chart control panel that instantly calculates your lot size. It takes your account balance, preferred risk percentage, and stop loss distance to give you a precise volume for your next trade.

KEY FEATURES

  • Real-time Position Sizing: Calculate lots instantly as you type.

  • Automatic Balance Detection: Pulls your current account balance automatically.

  • Dynamic Pip Valuation: Works on all symbols (Forex, Gold, Oil, Indices) by calculating the specific tick value.

  • Safety Lot Rounding: Rounds lot sizes to your broker's specific "Lot Step" (e.g., 0.01).

  • Interactive GUI: A clean, draggable panel that doesn't clutter your chart.

  • Risk in Currency: See exactly how many dollars (or your account currency) you are risking.

  • Zero Lag: Lightweight, event-driven code that won't slow down your platform.

🛡️ SAFETY FIRST The calculator ensures that the lot size never exceeds your broker's maximum allowed volume and never goes below the minimum lot size, preventing execution errors.

💡 PERFECT FOR ✓ Manual traders, Scalpers, and Day Traders. ✓ New traders learning the importance of the "1% Risk Rule." ✓ Prop Firm traders who must stay within strict drawdown limits.

  1. Price Mode Toggle: Switch instantly between Live Current Price or Specific Price entry for pending orders.

  2. Auto-Refresh System: Real-time updates every 2 seconds with a dedicated ON/OFF toggle.

  3. Risk Preset Buttons: Instant 1%, 2%, and 3% buttons—no more manual typing.

  4. Take Profit Calculator: Full profit potential display based on your TP pips.

  5. Risk:Reward Ratio: Live display of your R:R Ratio (e.g., 1:2.00) for every trade.

  6. Tick-Sync Technology: In Current Price mode, the entry price updates automatically with every market tick.

  7. Premium UI: Polished, larger dashboard (280x480) with a professional Navy/SeaGreen color scheme.

  8. SL Price Field: Dedicated input for exact stop loss price levels.

  9. Smart Workflow: Read-only fields auto-lock/unlock based on your selected mode for a mistake-proof experience.

🚀 SUPER EASY TO USE

  1. Drag the EA onto any chart.

  2. Enter your Risk % and SL in Pips.

  3. Click CALCULATE.

📥 INSTALLATION INSTRUCTIONS

  1. Download the .mq5 file.

  2. In MT5, press F4 to open MetaEditor.

  3. Right-click the Experts folder -> Open Folder.

  4. Copy the file into this folder and Refresh the Navigator in MT5.

  5. Attach to chart; ensure "Algo Trading" are enabled.

TESTED & RELIABLE 100% accurate tick value calculations for Forex, Metals, and CFDs.

⭐⭐⭐⭐⭐ PLEASE RATE IF HELPFUL! ⭐⭐⭐⭐⭐ If this calculator saves you time, please leave a 5-star review to support more free tools!