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/soham-stack/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-0.1.0.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-0.1.0-py3-none-any.whl (84.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: mt5forge-0.1.0.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-0.1.0.tar.gz
Algorithm Hash digest
SHA256 7a0d25641bf44e7779169023b7c658201fdeb791e1cba709b30d9db61d8a706b
MD5 f3f4a1d689fa6b275bfacfb361429b90
BLAKE2b-256 bb5f11f8617bd215c4a2741ea0cde314b81547cecf431a3faa9ed762b7d7e8d4

See more details on using hashes here.

File details

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

File metadata

  • Download URL: mt5forge-0.1.0-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-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 798ee59cb68c69953caa190ade9f9159678cbd7a9f914fc0fb2f8c185d969021
MD5 6f4d1d449dc188bcb6101f1f25d27385
BLAKE2b-256 27950108baafd1091a740b362067b03a5e62dc7bb5d09e6ff649e4e6a2ee1b2d

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