Skip to content

A complete 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.

Notifications You must be signed in to change notification settings

trademetasync/Automated-Order-Management

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 

Repository files navigation

🏦 Professional Automated Order Management System

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.


πŸŽ₯ Video Tutorial

Watch the video

πŸ”§ Features

βœ… 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.


πŸ“¦ Requirements

  • 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)

βš™οΈ Installation

1. Clone the Repository

git clone https://github.com//trademetasync/Automated-Order-Management.git
cd Automated-Order-Management

2. Install Dependencies

pip install requests pandas numpy colorama

3. Set Environment Variables

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.


πŸš€ Usage

Run the System

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 βœ…

Interactive Menu

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: 

πŸ—οΈ Architecture Overview

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

πŸ’‘ Key Design Principles

1. Risk-First Mindset

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

2. Position Sizing Formula

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.

3. Connection Resilience

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

4. Audit Trail

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%

⚠️ Risk Management Rules

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.


πŸ› οΈ Extending the System

You can easily extend this system for your needs:

Add Email Alerts

import smtplib
# Send alert on emergency close

Integrate with Trading Strategy

# 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)

Add Database Logging

Log all trades to SQLite or PostgreSQL for performance analysis.

Implement Trailing Stop

Already included:

modifier.trailing_stop_management(ticket=123456, trail_distance=50, trail_step=10)

πŸ“ Project Structure

professional-oms/
β”œβ”€β”€ trading_system.py        # Main script
β”œβ”€β”€ trading_system.log       # Auto-generated log file
β”œβ”€β”€ requirements.txt         # Dependencies
└── README.md                # This file

πŸ“’ Disclaimer

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.


πŸ™Œ Support & Feedback

Found a bug? Want a new feature?
Open an issue or pull request on GitHub.

Follow for more professional trading infrastructure tutorials.


🏁 Final Notes

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.

About

A complete 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.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages