Skip to main content

Production-grade Python MT5 trading infrastructure library

Project description

MT5Forge

Production-grade Python trading infrastructure for MetaTrader 5.

MT5Forge is a modular framework that transforms the raw MetaTrader 5 Python API into a structured, extensible, and production-ready trading platform.

Instead of writing trading bots that directly interact with MT5, developers build strategies on top of MT5Forge while the framework handles:

  • MT5 connectivity
  • Session management
  • Market data
  • Order execution
  • Risk management
  • Trade lifecycle
  • Notifications
  • Monitoring
  • Logging
  • Backtesting

Why MT5Forge?

Most trading bots eventually become difficult to maintain because strategy logic becomes tightly coupled with:

  • MT5 API calls
  • Risk management
  • Trade management
  • Notifications
  • Error handling

MT5Forge separates these concerns.

Your strategy only decides:

BUY
SELL
HOLD

Everything else is managed by the framework.


Features

Trading Infrastructure

  • MT5 connection management
  • Automatic reconnection
  • Session validation
  • Broker health monitoring

Market Data

  • Candlestick retrieval
  • Tick feeds
  • Spread monitoring
  • Symbol information
  • Market hours detection

Order Execution

  • Market orders
  • Pending orders
  • Order modification
  • Partial close support
  • Retry policies

Risk Management

  • Dynamic lot sizing
  • Drawdown protection
  • Daily loss limits
  • Exposure controls
  • Margin validation

Trade Management

  • Take profit management
  • Stop loss management
  • Trailing stops
  • Breakeven automation
  • Trade lifecycle tracking

Strategies

Built-in strategies:

  • Moving Average Crossover
  • MACD
  • Hedge Recovery

Notifications

Supported channels:

  • Telegram
  • Discord
  • Slack
  • Email
  • Webhooks
  • Console
  • File Logging

Backtesting

  • Historical replay
  • Slippage simulation
  • Spread simulation
  • Performance analytics

Installation

Requirements

  • Python 3.11+
  • Windows 10 or Windows 11
  • MetaTrader 5 Terminal installed

Install from PyPI

pip install mt5forge

or

uv add mt5forge

Development Installation

git clone https://github.com/NeuroFx-Algotrading/mt5forge.git

cd mt5forge

uv sync

uv pip install -e ".[dev]"

Quick Start

Step 1 – Create Credentials

from mt5forge.connection import MT5Credentials

credentials = MT5Credentials(
    account=12345678,
    password="your_password",
    server="YourBroker-Demo",
)

Step 2 – Load Configuration

from mt5forge.config import ConfigLoader

config = ConfigLoader.from_toml(
    "mt5forge.config.toml"
)

Step 3 – Create Engine

from mt5forge import TradingEngine

engine = TradingEngine(config)

Step 4 – Login

engine.login(credentials)

Step 5 – Start Trading

engine.start()

First Strategy

from mt5forge.strategies import (
    MACrossoverStrategy,
    MACrossoverConfig,
)

strategy = MACrossoverStrategy(
    MACrossoverConfig(
        fast_ma=21,
        slow_ma=50,
        trend_ma=200,
    )
)

engine.register_strategy(strategy)
engine.start()

Market Data Example

from mt5forge.market import MarketDataFeed

feed = MarketDataFeed()

candles = feed.get_candles(
    symbol="EURUSD",
    timeframe="H1",
    count=500,
)

print(candles.tail())

Order Execution Example

from mt5forge.orders import OrderRequest
from mt5forge.enums import OrderType

request = OrderRequest(
    symbol="EURUSD",
    order_type=OrderType.BUY,
    lot=0.10,
)

result = engine.order_manager.place_market_order(
    request
)

print(result.success)

Custom Strategy Example

from mt5forge.strategies import (
    StrategyBase,
    Signal,
    SignalDirection,
)

class MyStrategy(StrategyBase):

    name = "my_strategy"

    def on_candle(
        self,
        symbol,
        timeframe,
        candles,
    ):
        if condition:
            return Signal(
                direction=SignalDirection.BUY,
                symbol=symbol,
            )

        return None

Telegram Notifications

from mt5forge.notifications.channels import (
    TelegramChannel,
)

channel = TelegramChannel(
    config.notifications.telegram
)

engine.notification_bus.register_channel(
    channel
)

Running a Backtest

from datetime import datetime

from mt5forge.backtest import (
    BacktestRunner,
)

runner = BacktestRunner(config)

result = runner.run(
    strategy=strategy,
    symbol="EURUSD",
    timeframe="H1",
    start=datetime(2024, 1, 1),
    end=datetime(2024, 12, 31),
)

print(result.net_profit)
print(result.win_rate)

Project Structure

mt5forge/
├── core/
├── connection/
├── market/
├── orders/
├── positions/
├── risk/
├── trade/
├── hedge/
├── conditions/
├── indicators/
├── strategies/
├── backtest/
├── notifications/
├── monitoring/
├── logging/
└── config/

Documentation

Additional documentation is available in:

docs/
├── architecture.md
├── strategy_guide.md
├── risk_management.md
├── notification_channels.md
├── backtesting_guide.md
└── api_reference.md

Running Tests

uv run pytest

Coverage:

uv run pytest --cov=mt5forge

Contributing

uv run ruff check .

uv run mypy mt5forge

uv run pytest

Please ensure all tests pass before submitting changes.


Security

Never commit:

  • Broker passwords
  • API keys
  • Telegram bot tokens
  • SMTP credentials

Use environment variables or secure secret storage.


License

MIT License


Disclaimer

This software executes real trades and can result in financial loss.

Always test strategies in a demo environment before deploying to a live account.

Use at your own risk.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mt5forge-1.0.2.tar.gz (56.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mt5forge-1.0.2-py3-none-any.whl (84.8 kB view details)

Uploaded Python 3

File details

Details for the file mt5forge-1.0.2.tar.gz.

File metadata

  • Download URL: mt5forge-1.0.2.tar.gz
  • Upload date:
  • Size: 56.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for mt5forge-1.0.2.tar.gz
Algorithm Hash digest
SHA256 9d3ae3f82e3f30ed640dd2ac1cd83f3c7ac578eb875c5169c859fda44feb099a
MD5 6a36085b767886abf19248d133a0aa1d
BLAKE2b-256 0b483de8b7b7f9ba3f8f1f4cd929510c97e161a4f87422b0c31c43fd446d9798

See more details on using hashes here.

File details

Details for the file mt5forge-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: mt5forge-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 84.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for mt5forge-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 3aad8c473b9f4dea82d7b6c3a939f3f4b0e8f068b81488cbbd9ea33492ccd98e
MD5 bcf5f331a05aef038ec2a40d739cd053
BLAKE2b-256 31363bd259657de6162039ec5532e4e3aa46de10964ab59a9444249b4e648ab0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page