Sign inSign up

liberatti/mt5bridge

By liberatti

โ€ขUpdated about 5 hours ago

Headless Docker designed to run MetaTrader 5 (MT5), exposing all official methods through a REST API

Image
Languages & frameworks
Developer tools
0

593

liberatti/mt5bridge repository overview

MT5Bridge REST API

License Docker Sponsor

High-performance, modular, and headless Docker solution designed to run MetaTrader 5 (MT5) on Linux via WineHQ Staging, exposing all official MetaTrader 5 methods through a robust Python Flask REST API with built-in interactive Swagger UI / OpenAPI 3.0 documentation.

Based on the official MQL5 reference: MetaTrader 5 on Linuxโ .


โ โœจ Key Features

  • ๐Ÿณ Headless Linux Environment: Runs MT5 terminal silently using WineHQ Staging + Xvfb virtual display with zero GUI overhead.
  • ๐Ÿ“– Built-in Interactive Swagger UI: Full OpenAPI 3.0 documentation served at the root URL (/) with interactive "Try it out" request execution.
  • โšก Full MT5 Python API Coverage: 100% method compatibility for Account, Symbols, Depth of Market (DOM), Historical Rates & Ticks, Orders, Positions, and Deals.
  • ๐Ÿ› ๏ธ High-Level Trading Helpers: Simplified endpoints for opening market/pending orders, modifying SL/TP, and closing positions.
  • ๐Ÿงฑ Standardized JSON Schema: Predictable response structure and error handling powered by the nxcore framework.
  • ๐Ÿ”„ Auto-Recovery & Reconnect: Background connection watchdog, automated initialization, and persistent Wine prefix volumes.

โ ๐Ÿ—๏ธ Architecture Overview

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    Client Applications                    โ”‚
โ”‚   (Web Apps / Python Scripts / Trading Bots / Postman)    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ”‚ HTTP / REST (Port 5000)
                              โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                  Docker Container: mt5bridge              โ”‚
โ”‚                                                           โ”‚
โ”‚   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”‚
โ”‚   โ”‚  Swagger UI / OpenAPI 3.0 Documentation (/)       โ”‚   โ”‚
โ”‚   โ”‚  Flask REST API (Waitress Multi-threaded WSGI)    โ”‚   โ”‚
โ”‚   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ”‚
โ”‚                             โ”‚ TCP Socket (Port 22347)     โ”‚
โ”‚                             โ–ผ                             โ”‚
โ”‚   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”‚
โ”‚   โ”‚  RestGateway Expert Advisor (MQL5)                โ”‚   โ”‚
โ”‚   โ”‚  MetaTrader 5 Terminal 64-bit                     โ”‚   โ”‚
โ”‚   โ”‚  WineHQ Staging + Xvfb Display Server             โ”‚   โ”‚
โ”‚   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ”‚ TCP (Broker Protocol)
                              โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚             MetaTrader 5 Broker Trading Server            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

โ ๐Ÿ“– Swagger UI & Interactive Documentation

MT5Bridge comes with a pre-configured, interactive Swagger UI embedded directly into the service. You can explore all routes, review data models, inspect required query parameters, and execute live API requests directly from your browser.

Swagger UI Preview


โ ๐Ÿ› ๏ธ Quick Start

โ 1. Run with Docker CLI
# Pull the latest Docker image
docker pull liberatti/mt5bridge:latest

# Run container with your demo or live broker credentials
docker run -d --name mt5bridge \
  -p 5000:5000 \
  -e MT5_LOGIN=112728385 \
  -e MT5_PASSWORD=YourPassword \
  -e MT5_SERVER=MetaQuotes-Demo \
  -e MT5_STARTUP_SYMBOL=EURUSD \
  -e MT5_STARTUP_PERIOD=H1 \
  liberatti/mt5bridge:latest

Create or use the provided docker-compose.ymlโ :

volumes:
  mt5_data:
    driver: local

services:
  metatrader5:
    image: liberatti/mt5bridge:latest
    container_name: mt5bridge
    restart: unless-stopped
    ports:
      - "5000:5000"
    environment:
      - MT5_LOGIN=112728385
      - MT5_PASSWORD=YourPassword
      - MT5_SERVER=MetaQuotes-Demo
      - MT5_STARTUP_SYMBOL=EURUSD
      - MT5_STARTUP_PERIOD=H1
      - API_KEY=YourSecretApiKey
    volumes:
      - mt5_data:/home/mt5user/.mt5

Start the container in the background:

docker compose up -d

Once running, navigate to http://localhost:5000/โ  to access the Swagger UI.


โ โš™๏ธ Configuration & Environment Variables

VariableDefaultDescription
MT5_LOGIN""MetaTrader 5 account login number
MT5_PASSWORD""MetaTrader 5 account master password
MT5_SERVERMetaQuotes-DemoBroker trade server hostname or label
MT5_INVESTOR""Investor (read-only) password (optional)
MT5_STARTUP_SYMBOLEURUSDDefault chart symbol initialized on startup
MT5_STARTUP_PERIODH1Default chart timeframe (M1, M5, M15, H1, D1, etc.)
SECURITY_ENABLEDtrueEnables or disables API authentication verification
API_KEY""Secret API key required in x-api-key HTTP request header
PORT5000HTTP port exposed by the REST API
HOST0.0.0.0Bind host for Flask/Waitress server
LOGLEVELINFOApplication log level (DEBUG, INFO, WARNING, ERROR)
THREADS8Worker threads for Waitress WSGI production server
MT5_STARTUP_TIMEOUT90Max seconds to wait for MT5 & EA gateway startup
SCREEN_RESOLUTION1024x768x24Resolution for virtual framebuffer display (Xvfb)

โ ๐Ÿ“ก API Reference & Endpoints

All responses follow a consistent nxcore structure:

// Success Response (HTTP 200)
{
  "code": 200,
  "data": { ... }
}

// Error Response (HTTP 400 / 500)
{
  "code": 400,
  "message": "Validation Error / Bad Request",
  "details": "...",
  "url": "http://localhost:5000/api/...",
  "method": "POST"
}

โ 1. System & Account (/api/...)
EndpointMethodUnderlying MT5 CallDescription
/api/versionGETmt5.version()Returns MT5 terminal build number, release date, and version string
/api/last_errorGETmt5.last_error()Retrieves the last recorded error code and description
/api/terminal_infoGETmt5.terminal_info()Terminal state (connected, trade enabled, paths, build)
/api/account_infoGETmt5.account_info()Account balance, equity, margin, free margin, leverage

โ 2. Symbols & Depth of Market (/api/...)
EndpointMethodUnderlying MT5 CallDescription
/api/symbols_totalGETmt5.symbols_total()Total number of financial instruments available on the server
/api/symbols_getGETmt5.symbols_get()Lists available symbols with optional filter (e.g. ?group=*EUR*)
/api/symbol_info/<symbol>GETmt5.symbol_info()Complete instrument specification (tick size, spread, contract size)
/api/symbol_info_tick/<symbol>GETmt5.symbol_info_tick()Real-time last tick (bid, ask, last, volume, timestamp)
/api/symbol_selectPOSTmt5.symbol_select()Adds/removes a symbol to/from the Market Watch window
/api/market_book_addPOSTmt5.market_book_add()Subscribes to Depth of Market (DOM / Order Book) updates
/api/market_book_get/<symbol>GETmt5.market_book_get()Returns current Level 2 DOM array for a symbol
/api/market_book_releasePOSTmt5.market_book_release()Unsubscribes from DOM updates for a symbol

โ 3. Market Data & Historical Rates (/api/...)
EndpointMethodQuery ParametersDescription
/api/copy_rates_fromGETsymbol, timeframe, date_from, countRetrieves historical bars starting from a specific date/time
/api/copy_rates_from_posGETsymbol, timeframe, start_pos, countRetrieves historical bars by offset index (0 = current bar)
/api/copy_rates_rangeGETsymbol, timeframe, date_from, date_toRetrieves historical bars within a date range
/api/copy_ticks_fromGETsymbol, date_from, count, flagsRetrieves raw tick history starting from a date
/api/copy_ticks_rangeGETsymbol, date_from, date_to, flagsRetrieves raw tick history within a date range

Supported Timeframes: M1, M2, M3, M4, M5, M6, M10, M12, M15, M20, M30, H1, H2, H3, H4, H6, H8, H12, D1, W1, MN1.


โ 4. Trading & Order Execution (/api/...)
EndpointMethodTypeDescription
/api/order_checkPOSTRawSimulates order placement and checks funds/margin requirement
/api/order_sendPOSTRawSends raw MqlTradeRequest structure to broker
/api/order_calc_marginPOSTUtilComputes required margin for an order type and volume
/api/order_calc_profitPOSTUtilCalculates estimated floating profit/loss
/api/orders_totalGETReadTotal count of active pending orders
/api/orders_getGETReadRetrieves pending orders with optional filter (?symbol=...&ticket=...)
/api/positions_totalGETReadTotal count of open market positions
/api/positions_getGETReadRetrieves open positions (?symbol=...&ticket=...)
/api/order/openPOSTHelperHigh-level order entry (BUY, SELL, BUY_LIMIT, SELL_STOP, etc.)
/api/order/closePOSTHelperCloses an open position by ticket with automated opposite order
/api/order/modifyPOSTHelperUpdates Stop Loss (sl) and Take Profit (tp) on open position
/api/order/<ticket>DELETEHelperCancels a pending order by ticket

โ 5. Historical Orders & Deals (/api/...)
EndpointMethodQuery ParametersDescription
/api/history_orders_totalGETdate_from, date_toReturns total number of orders in trading history
/api/history_orders_getGETdate_from, date_to, group, ticket, positionRetrieves historical closed/canceled orders
/api/history_deals_totalGETdate_from, date_toReturns total number of executed transactions (deals)
/api/history_deals_getGETdate_from, date_to, group, ticket, positionRetrieves deal records (executions, commissions, swaps, profits)

โ ๐Ÿ’ป Code Examples

โ Python Example (requests)
import os
import requests

BASE_URL = "http://localhost:5000/api"
API_KEY = os.environ.get("API_KEY", "YourSecretApiKey")
HEADERS = {"x-api-key": API_KEY}

# 1. Check account balance & equity
account = requests.get(f"{BASE_URL}/account_info", headers=HEADERS).json()
print("Balance:", account["data"]["balance"], "Equity:", account["data"]["equity"])

# 2. Get real-time price tick
tick = requests.get(f"{BASE_URL}/symbol_info_tick/EURUSD", headers=HEADERS).json()
print("EURUSD Bid:", tick["data"]["bid"], "Ask:", tick["data"]["ask"])

# 3. Open a Market Buy Position
buy_res = requests.post(f"{BASE_URL}/order/open", headers=HEADERS, json={
    "symbol": "EURUSD",
    "order_type": "BUY",
    "volume": 0.01,
    "sl": 1.0500,
    "tp": 1.1000,
    "comment": "MT5Bridge Buy Order"
}).json()
print("Order Response:", buy_res)

# 4. List open positions
positions = requests.get(f"{BASE_URL}/positions_get", headers=HEADERS).json()
print("Open Positions:", positions["data"])
โ cURL Example
# Get MT5 version
curl -X GET "http://localhost:5000/api/version" \
  -H "x-api-key: YourSecretApiKey"

# Get EURUSD live tick
curl -X GET "http://localhost:5000/api/symbol_info_tick/EURUSD" \
  -H "x-api-key: YourSecretApiKey"

# Open Market Buy Order (0.01 lots)
curl -X POST "http://localhost:5000/api/order/open" \
  -H "Content-Type: application/json" \
  -H "x-api-key: YourSecretApiKey" \
  -d '{
    "symbol": "EURUSD",
    "order_type": "BUY",
    "volume": 0.01,
    "comment": "Test Order"
  }'

โ ๐Ÿ’ก Free Demo Account Setup

  1. Open a free demo account through the MetaTrader Web Terminalโ  or the MetaTrader 5 app.
  2. Select the standard MetaQuotes-Demo server.
  3. Configure your account credentials (MT5_LOGIN and MT5_PASSWORD) in docker-compose.ymlโ .

โ ๐Ÿงช Automated Testing Suite

The repository includes an automated integration test script (test_api.py) that validates the complete API lifecycle, tests all endpoint categories, and performs a live test trade:

# Run the test suite with API Key authentication
python test_api.py --url http://localhost:5000 --api-key "YourSecretApiKey" --symbol EURUSD --volume 0.01

# Or authenticate using environment variable
export API_KEY="YourSecretApiKey"
python test_api.py --url http://localhost:5000 --symbol EURUSD --volume 0.01

Available arguments:

  • --url: Base URL of the running API (default: http://localhost:5000 or API_URL env).
  • --api-key: API key sent in the x-api-key header (default: API_KEY env or empty).
  • --symbol: Symbol used for test orders and data retrieval (default: EURUSD).
  • --volume: Trading lot size (default: 0.01).
  • --no-close: Keeps the test position open instead of automatically closing it.

โ ๐Ÿ“„ License

This project is licensed under the Apache License 2.0 - see the LICENSEโ  file for details.

Tag summary

Content type

Image

Digest

sha256:fc30f5fdcโ€ฆ

Size

1.1 GB

Last updated

about 5 hours ago

docker pull liberatti/mt5bridge