Expert Advisors • Indicators • Scripts • Libraries

MQL.RobotFX.org is the biggest collection of MetaTrader expert advisors (MT5 & MT4), indicators, scripts and libraries that can be used to improve trading results, minimize risks or simply automate trading tasks

Metatrader 5 Expert Advisor | Count Positions from EA MQL5

CountPositions Module – Accurate Position Tracking for MetaTrader 5

The CountPositions Module is a fundamental component for any algorithmic system built in MetaTrader 5. Its primary purpose is to provide reliable, real-time tracking of the number of open positions for an Expert Advisor, separated by type (buy or sell) and filtered by symbol and Magic Number.

This module is ideal for EAs requiring strict control over active trades, such as grid systems, martingale strategies, portfolio management, risk-based systems, or simply preventing accidental duplicate trades.

Example of use this Code , integrated on an GUI

Photo for the article Count Positions from EA MQL5

Purpose

In automated trading, it is common for an EA to verify how many positions are currently open before placing a new order. This ensures:

  • No more trades are opened than the strategy allows

  • The system checks for existing trades before sending new ones

  • Buy and sell positions are counted independently

  • Only trades created by the EA (via Magic Number) are included

The module automates this process, providing accurate counts on every tick.

How It Works

1. Initialization of Counters

Two global variables store the number of BUY and SELL positions:

int Position_buy_count;
int Position_sell_count;

2. Magic Number Filter

Ensures that only the EA’s own positions are counted:

input long MagicNumber = 47836;


3. Execution on Every Tick

The module is triggered automatically with each market tick:

void OnTick() {
  CountPositions();
  Comment("Buy: " + (string)Position_buy_count + " || Sell: " + (string)Position_sell_count);
}

4. The Counting Algorithm

The core of the module is the CountPositions() function, which:

  • Resets the counters

  • Iterates through all open positions

  • Filters positions by both symbol and Magic Number

  • Classifies them as BUY or SELL

Positions are processed from last index to first:

for (int i = PositionsTotal() - 1; i >= 0; i--) {
    PositionGetTicket(i);
    string PositionSimbol = PositionGetString(POSITION_SYMBOL);
    long PositionMagicNumber = PositionGetInteger(POSITION_MAGIC);

    if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY && _Symbol == PositionSimbol && MagicNumber == PositionMagicNumber)
        Position_buy_count++;

    if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL && _Symbol == PositionSimbol && MagicNumber == PositionMagicNumber)
        Position_sell_count++;
}

Key Features

  • Real-time counting: Updated on every tick

  • Magic-Number-based filtering: Only the EA’s trades are counted

  • Clear separation of trade types: Independent BUY and SELL counters

  • High compatibility: Works with any trading system

  • Safe and optimized: Reverse iteration to avoid index issues


Usage Instructions

  1. Copy the module into your Expert Advisor.

  2. Set the Magic Number to match your EA.

  3. Call CountPositions() inside OnTick, OnTimer, or wherever your logic needs trade counting.

  4. Use Position_buy_count and Position_sell_count for decision-making.

  5. Optionally display the values using Comment() .


Recommended Use Cases

  • EAs that limit the number of trades per direction

  • Grid or martingale-style systems

  • Controlled hedging strategies

  • Bots that must verify existing positions before opening new ones

  • Risk-management modules requiring precise trade tracking


Important Notes

  • The module only counts positions from the current chart symbol ( _Symbol ).

  • If attached to EURUSD, it will not count trades on GBPUSD, XAUUSD, etc.

  • All counted trades must share the same Magic Number.







66033

Best MetaTrader Indicators + Profitable Expert Advisors