A production-grade, institutional-level trading engine for MetaTrader 5 using the MetaSync API
This repository contains a complete, professional-grade Order Management System (OMS) designed for algorithmic traders who demand reliability, risk control, and real-time monitoring. Built with Python, this system connects directly to your MetaTrader 5 (MT5) account via the MetaSync API, enabling full automation of trade execution, position management, and emergency risk controls.
Unlike simple "trading bots," this system is engineered like those used by hedge funds and professional trading desks β with robust error handling, real-time risk enforcement, heartbeat monitoring, and a live color-coded dashboard.
Whether you're building a strategy or managing live capital, this OMS provides the infrastructure to trade safely and professionally.
β
Risk-Based Position Sizing
Automatically calculates lot size based on account balance, stop-loss distance, and configurable risk percentage (e.g., 1%).
β
Multiple Order Types
Supports market, limit, and stop orders with full validation and slippage control.
β
Real-Time Account Monitoring
Continuously tracks equity, margin, free margin, and margin level.
β
Institutional Risk Management
Enforces strict limits:
- Max daily loss
- Max open positions
- Margin call protection
- Drawdown control
β
Emergency Shutdown Protocol
One-click or automatic emergency close of all positions when risk thresholds are breached.
β
Dynamic Trade Management
Modify stop-loss and take-profit levels in real time, including trailing stops and breakeven logic.
β
Live Interactive Dashboard
Color-coded terminal UI showing:
- Account overview
- Open positions
- Risk alerts
- Execution performance
- System status
β
Professional Error Handling & Logging
Full audit trail with structured logging to both console and trading_system.log
.
β
Heartbeat Connection Monitoring
Auto-detects connection drops and validates connectivity every 5 minutes.
β
Secure Configuration
Uses environment variables for API keys and MT5 credentials β no hardcoded secrets.
- Python 3.8+
- An active MetaSync API key from RapidAPI
- A MetaTrader 5 account (demo or live)
- Basic understanding of forex/CFD trading concepts (lots, pips, SL/TP)
git clone https://github.com//trademetasync/Automated-Order-Management.git
cd Automated-Order-Management
pip install requests pandas numpy colorama
Create a .env
file or export variables in your shell:
export RAPIDAPI_KEY="your_rapidapi_key_here"
export MT5_LOGIN="123456"
export MT5_PASSWORD="your_mt5_password"
export MT5_SERVER="ICMarketsSC-Demo" # Or your broker's server
π Never commit credentials to version control.
python order_manager.py
Youβll see a live dashboard with color-coded status indicators:
========================================================
π¦ INSTITUTIONAL ORDER MANAGEMENT SYSTEM
β° 2025-04-05 14:30:22 | π‘ Connected
========================================================
π° ACCOUNT OVERVIEW
ββββββββββββββββββββββββββββββββββββββββββββββββββ
Balance: $10,000.00
Equity: $10,012.50
Profit: +$12.50
Free Margin: $8,200.00
Margin Level: 540.2%
Currency: USD
Leverage: 1:500
π OPEN POSITIONS (2)
ββββββββββββββββββββββββββββββββββββββββββββββββββ
Ticket Symbol Type Volume Open Current SL TP P&L
ββββββββββββββββββββββββββββββββββββββββββββββββββ
123456 EURUSD buy 0.50 1.08500 1.08620 β β +$60.00
123457 GBPUSD sell 0.30 1.26000 1.25950 β β +$15.00
β οΈ RISK MANAGEMENT
ββββββββββββββββββββββββββββββββββββββββββββββββββ
- No active violations β
π ACTIVE ALERTS
ββββββββββββββββββββββββββββββββββββββββββββββββββ
- No active alerts β
Use the command menu to:
- Place market or pending orders
- Close individual positions
- Trigger emergency shutdown
- View system status
1. Place Market Order 2. Place Pending Order
3. Close Position 4. Modify Position
5. Emergency Close All 6. System Status
0. Exit System
Enter command:
The system is built using a modular, class-based architecture for maintainability and scalability.
Component | Responsibility |
---|---|
MT5ConnectionManager |
Handles API connection, authentication, and heartbeat monitoring |
AccountMonitor |
Fetches and validates account data; enforces margin and drawdown rules |
PositionManager |
Tracks all open trades; calculates portfolio exposure |
OrderExecutionEngine |
Places orders with risk-based sizing and slippage control |
RiskManager |
Enforces pre-trade checks and monitors for violations |
OrderModificationSystem |
Modifies SL/TP, implements trailing stops |
TradingDashboard |
Renders real-time, color-coded UI |
InstitutionalTradingSystem |
Main controller that orchestrates all components |
Every trade is validated against:
- Max position count
- Daily loss limit
- Margin level
- Symbol concentration
if self.risk_manager.check_pre_trade_risk(order_request)['overall'] is False:
logger.error("β Trade blocked by risk system")
return None
Uses the professional formula:
Position Size = (Account Balance Γ Risk %) / (Stop Distance in Pips Γ Pip Value)
Example: Risking 1% ($100) with a 100-pip stop on EURUSD β ~1 lot.
The system doesnβt assume connectivity:
def is_connected(self) -> bool:
if not self.connected: return False
if time_since_heartbeat() > 300: # 5 min
return self._test_connection()
return True
Every action is logged:
2025-04-05 14:30:22 - __main__ - INFO - Connected to MT5: ICMarketsSC-Demo
2025-04-05 14:31:05 - __main__ - INFO - Order executed: EURUSD 0.5 lots in 0.452s
2025-04-05 14:32:10 - __main__ - WARNING - Low margin level: 195.3%
Rule | Threshold | Action |
---|---|---|
Margin Level | < 200% | Warning |
Drawdown | > 10% of balance | Alert |
Free Margin | < $1,000 or 20% of balance | Alert |
Daily Loss | > $1,000 | Emergency close trigger |
Position Size | > 5.0 lots | Warning |
Missing SL | Any open position | Immediate alert |
These values are configurable in the
RiskManager
class.
You can easily extend this system for your needs:
import smtplib
# Send alert on emergency close
# Replace interactive mode with automated signals
if my_strategy.signal == "BUY":
system.place_trade("EURUSD", OrderType.MARKET_BUY, risk_pct=1.0, stop_loss=sl, take_profit=tp)
Log all trades to SQLite or PostgreSQL for performance analysis.
Already included:
modifier.trailing_stop_management(ticket=123456, trail_distance=50, trail_step=10)
professional-oms/
βββ trading_system.py # Main script
βββ trading_system.log # Auto-generated log file
βββ requirements.txt # Dependencies
βββ README.md # This file
This software is for educational and informational purposes only.
Trading forex, CFDs, or any financial instruments involves significant risk of loss.
The author is not responsible for any losses incurred from the use of this code.
Always test in a demo environment before using with real capital.
Use at your own risk.
Found a bug? Want a new feature?
Open an issue or pull request on GitHub.
Follow for more professional trading infrastructure tutorials.
This isnβt just a script β itβs trading infrastructure.
Use it as a foundation for your strategies, and trade with the discipline of a professional.
Trade safe. Trade smart. Keep coding.