MetaTrader Trading Tools
Showing 10034 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.

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.

Trading strategy Heads or Tails

The "Heads or Tails" trading strategy belongs to the category of high-risk short-term trading approaches, used primarily in the stock market and the Forex market. Its name is derived from the randomness of decision-making, similar to tossing a coin ("heads" — buy the asset, "tails" — sell). This strategy is based exclusively on intuitive decisions or random signals and ignores fundamental market analysis factors.

How does the strategy work?

The strategy is structured as follows:

  1. Instrument Selection: The trader chooses a financial instrument (stock, currency, commodity).
  2. Decision Making: The decision to buy or sell is made randomly, for example, by tossing a coin or using another method to choose between two possible actions.
  3. Closing the Trade: The trade is closed automatically after a predetermined time or upon reaching a specific profit or loss level.

This strategy does not require a deep understanding of market mechanisms and analytics, but it also does not imply a serious approach to risk management.

Disadvantages of the strategy:
  1. High Level of Risk:
    • Relying solely on luck significantly increases the probability of losses. The strategy ignores any objective indicators and recommendations, increasing the chances of capital loss.
  2. Lack of Risk Control:
    • Since buying or selling occurs absolutely randomly, there is no possibility for rational capital management, risk assessment, or asset allocation.
  3. Impossibility of Long-Term Success:
    • Even if individual trades are profitable due to luck, in the long term such a strategy is more likely to lead to significant losses.
  4. Short-Lived Results:
    • Positive results are only possible under favorable market conditions and with a large number of small successful trades, which is extremely rare in practice.
Application of the Strategy:

The strategy is more suitable for novice traders who want to familiarize themselves with the principles of exchange platforms and try trading without deep knowledge of technical analysis. However, professionals use this strategy extremely rarely, preferring scientifically based approaches that account for price behavior, trading volume, and companies' fundamental indicators.

For experienced investors, this strategy represents more of an experimental method for testing hypotheses, rather than a stable way to earn money.

Thus, although the strategy is simple and accessible to every beginner, it carries significant risks and practically has no chance of generating sustainable income in the long term.

Let's consider the main block of the random position opening signal:

Here, the condition for the absence of open positions is checked. Variable b denotes the number of long ("buy") positions, variable s — short ("sell") positions. If the sum of both equals zero (b + s = 0), it means there is not a single open position.

Inside the condition block triggered previously, a random number is checked. The ::MathRand() function generates a pseudo-random number from 0 to 32767 inclusive. Then this number is divided modulo by 2 (% 2) — if the remainder is 0, the next block is executed.

If the random number is even (the remainder of division by 2 equals 0), the trading robot opens a long position (buy) with a volume of iLots. After successfully opening the position, the function execution is interrupted by the return operator.

If the random number was odd (the remainder of division by 2 differed from zero), a short position (sell) with a volume of iLots is opened, and the further execution of the function is also terminated.

Final logic of the fragment:
  • The presence of the trader's open positions is checked.
  • If there are no open positions, a random trade direction is chosen: either buy (long), or sell (short).
  • An opened trade automatically stops the further operation of the function.

Thus, this code is a simple example of an algorithm that makes the decision to open a market position randomly.

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 .

MT4 Telegram Trade Notifier (Bot API) — Deal Alerts

Key Features

  • Sends alerts on executed deals (TRADE_TRANSACTION_DEAL_ADD)

  • Optional filter: BUY/SELL only

  • UTF-8 URL encoding (supports Vietnamese & emojis)

  • Optional disable web page preview

  • Simple inputs: Bot Token, Chat ID, timeout, prefix

Setup

  1. Get your target chat id (user/group) or use @channelusername.

  2. In MetaTrader 4: Tools → Options → Expert Advisors Enable ā€œAllow WebRequest for listed URLā€ and add:

  3. Attach the EA to any chart and set:

    • InpBotToken

    • InpChatId

Notes / Troubleshooting

  • If WebRequest fails, check network/firewall/DNS and ensure the URL is allowed in MT4 options.

Inputs

  • InpChatId: chat id or @channelusername

  • InpSendTestOnInit: send a test message when EA starts

  • InpNotifyBuySellOnly: notify only BUY/SELL deals

  • InpTimeoutMs: WebRequest timeout

  • InpMsgPrefix: message prefix

RatioZigZag

A modification of the ZigZag indicator, where the reversal moment is determined not by a fixed percentage, but by reaching a specified ratio of the current price to the last local extremum.

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