Skip to content

PyMT5 Project MapΒΆ

Complete reference to project structure. Shows what is located where, what is user-facing vs internal, and how components are connected.


πŸ—‚οΈ Project OverviewΒΆ

PyMT5/
β”œβ”€β”€ πŸ“¦ package/ - Core package (portable)
β”‚   └── MetaRpcMT5/
β”‚       β”œβ”€β”€ helpers/mt5_account.py (Layer 1 - Foundation)
β”‚       β”œβ”€β”€ helpers/errors.py (Error handling & trade return codes)
β”‚       └── (Protobuf definitions)
β”‚   
β”‚
β”œβ”€β”€ πŸ“¦ src/pymt5/ - High-level API layers
β”‚   β”œβ”€β”€ mt5_service.py (Layer 2 - Wrappers)
β”‚   └── mt5_sugar.py (Layer 3 - Convenience)
β”‚
β”œβ”€β”€ πŸ‘€ User Code (Orchestrators, Examples)
β”œβ”€β”€ πŸ“ Documentation
└── βš™οΈ Configuration and build

External dependencies:
└── πŸ”Œ gRPC & Protobuf (Python packages)

πŸ“¦ Core API (Three-layer architecture)ΒΆ

What: Three-tier architecture for MT5 trading automation.

package/MetaRpcMT5/
β”œβ”€β”€ helpers/
β”‚   β”œβ”€β”€ mt5_account.py            <- LAYER 1: Low-level gRPC πŸ”₯ FOUNDATION
β”‚   β”‚   └── Direct gRPC calls to MT5 terminal
β”‚   β”‚   └── Connection management with retry logic
β”‚   β”‚   └── Proto Request/Response handling
β”‚   β”‚   └── Built-in connection resilience
β”‚   β”‚   └── Independent Python package (portable)
β”‚   β”‚   └── Class: MT5Account
β”‚   β”‚
β”‚   └── errors.py                 <- Error handling & trade result codes
β”‚       └── NotConnectedError exception (connection errors)
β”‚       └── ApiError wrapper (3-level: API/MQL/Trade)
β”‚       └── Trade return code constants & helpers
β”‚       └── Centralized error inspection methods
β”‚
β”œβ”€β”€ *_pb2.py                      <- Protobuf message definitions
β”œβ”€β”€ *_pb2_grpc.py                 <- gRPC service stubs
β”œβ”€β”€ mt5_term_api_*.py             <- MT5 API protocol definitions
└── __init__.py                   <- Package initialization

src/pymt5/
β”œβ”€β”€ mt5_service.py                <- LAYER 2: Wrapper methods
β”‚   └── Simplified signatures (no proto objects)
β”‚   └── Type conversion (proto β†’ Python types)
β”‚   └── Direct data return
β”‚   └── Extension methods for convenience
β”‚   └── Class: MT5Service
β”‚
└── mt5_sugar.py                  <- LAYER 3: Convenience layer πŸ”₯
    └── Auto-normalization (volumes, prices)
    └── Risk management (CalculateVolume, BuyByRisk)
    └── Points-based methods (BuyLimitPoints, etc.)
    └── Batch operations (CloseAll, CancelAll)
    └── Snapshots (GetAccountSnapshot, GetSymbolSnapshot)
    └── Smart helpers (conversions, limits)
    └── Class: MT5Sugar

package/pyproject.toml            <- Package configuration (dependencies, metadata)

Architecture flow:

MT5Sugar β†’ uses β†’ MT5Service β†’ uses β†’ MT5Account β†’ gRPC β†’ MT5 Terminal
       ↓                ↓                    ↓
src/pymt5/       src/pymt5/         package/MetaRpcMT5/helpers/

πŸ’‘ Creating Your Own Project:

For your own standalone project using PyMT5, you only need to import the package module:

from MetaRpcMT5 import MT5Account
from MetaRpcMT5.helpers.errors import ApiError, check_retcode

The package module contains everything you need to start:

  • βœ… All protobuf definitions (proto-generated code)
  • βœ… gRPC stubs and service contracts
  • βœ… MT5Account (Layer 1 - Foundation)
  • βœ… Independent Python package (can be used without src/)

This makes the package portable and easy to integrate into any Python project!

User decision:

  • Building your own app: Import package and use MT5Account directly
  • Learning/Examples: Use the full PyMT5 repo with all 3 layers
  • 95% of demo cases: Start with MT5Sugar (highest level, easiest)
  • Need wrappers: Move to MT5Service (without auto-normalization)
  • Need raw proto: Move to MT5Account (full control)

Built-in Reconnect ProtectionΒΆ

What: All low-level gRPC calls in MT5Account have automatic reconnection logic.

Two protection mechanisms:

1. Regular gRPC Calls (execute_with_reconnect)ΒΆ

All basic MT5Account methods (account info, trading operations, etc.) use built-in reconnection:

How it works:

  • Detects gRPC UNAVAILABLE status (server unreachable)

  • Detects terminal errors:

  • TERMINAL_INSTANCE_NOT_FOUND

  • TERMINAL_REGISTRY_TERMINAL_NOT_FOUND

  • On error: waits 0.5 seconds, reconnects, retries the call

  • Continues until success or cancellation

What this means for you:

  • No manual reconnection needed
  • Network hiccups handled automatically
  • Terminal restarts recovered seamlessly

Example:

# This call automatically reconnects if connection is lost
balance = await account.account_info_double(
    account_info_pb2.AccountInfoDoublePropertyType.ACCOUNT_BALANCE
)
# If connection drops: auto-reconnect β†’ retry β†’ return result

2. Streaming Calls (execute_stream_with_reconnect)ΒΆ

Streaming methods (position updates, tick streams, trade events) have separate stream-specific protection:

How it works:

  • Same error detection (UNAVAILABLE, terminal not found)
  • Properly closes existing stream before reconnecting
  • Reopens stream after reconnection
  • Continues yielding data transparently

What this means for you:

  • Stream interruptions handled automatically
  • No data loss on reconnection
  • Seamless continuation of real-time data

Example:

# Stream automatically recovers from connection issues
async for trade in account.on_trade(cancellation_event):
    print(f"Trade: {trade}")
    # If connection drops: stream closes β†’ reconnect β†’ stream reopens β†’ continues

Important notes:

  • Both mechanisms require valid connection parameters (host/port or server_name)
  • Reconnection uses the same credentials from initial connection
  • Use cancellation_event to stop retry loops
  • 0.5 second delay between retry attempts prevents server overload

πŸ‘€ User Code (Your Trading Strategies)ΒΆ

Orchestrators (examples/4_orchestrators/)ΒΆ

What: Ready-made trading strategy implementations.

examples/4_orchestrators/
β”œβ”€β”€ 11_trailing_stop.py           <- Trailing stop (price following)
β”œβ”€β”€ 12_position_scaler.py         <- Position scaling
β”œβ”€β”€ 13_grid_trader.py             <- Grid trading (sideways markets)
β”œβ”€β”€ 14_risk_manager.py            <- Risk manager
└── 15_portfolio_rebalancer.py    <- Portfolio rebalancing

Purpose: Educational examples showing complete strategy workflows:

  • Entry logic (risk-based volume where applicable)
  • Position monitoring with progress bars
  • Exit management and cleanup
  • Performance tracking (balance, equity, P/L)
  • Configurable parameters via properties

How to use:

  1. Study existing orchestrators
  2. Copy one as a template
  3. Modify for your strategy
  4. Test on demo account

How to run:

python examples/main.py 11         # Trailing Stop
python examples/main.py trailing    # Same with alias
python examples/main.py scaler      # Position Scaler
python examples/main.py grid        # Grid Trader
python examples/main.py risk        # Risk Manager
python examples/main.py rebalancer  # Portfolio Rebalancer

Documentation: - Orchestrator documentation files: See source code comments in each .py file - Usage examples included directly in the Python files


Examples (examples/)ΒΆ

What: Runnable examples demonstrating API usage at different layers.

User interaction: βœ… Learning materials - run to understand the API.

examples/
β”œβ”€β”€ 0_common/                          <- Common utilities
β”‚   β”œβ”€β”€ settings.json                  <- Connection configuration
β”‚   β”œβ”€β”€ demo_helpers.py                <- Helper functions for demos
β”‚   β”œβ”€β”€ progress_bar.py                <- Progress bar utilities
β”‚   └── 16_protobuf_inspector.py       <- Protobuf structure inspector
β”‚
β”œβ”€β”€ 1_lowlevel/                        <- MT5Account examples (proto level) πŸ”₯ FOUNDATION
β”‚   β”œβ”€β”€ 01_general_operations.py       <- General operations (connection, account, symbols)
β”‚   β”œβ”€β”€ 02_trading_operations.py       <- Trading operations (orders, positions)
β”‚   └── 03_streaming_methods.py        <- Streaming methods (real-time subscriptions)
β”‚
β”œβ”€β”€ 2_service/                         <- MT5Service examples (wrapper level)
β”‚   β”œβ”€β”€ 04_service_demo.py             <- Service API demonstration
β”‚   └── 05_service_streaming.py        <- Service streaming methods
β”‚
β”œβ”€β”€ 3_sugar/                           <- MT5Sugar examples (convenience level)
β”‚   β”œβ”€β”€ 06_sugar_basics.py             <- Sugar API basics (balance, prices)
β”‚   β”œβ”€β”€ 07_sugar_trading.py            <- Trading (market/limit orders)
β”‚   β”œβ”€β”€ 08_sugar_positions.py          <- Position management
β”‚   β”œβ”€β”€ 09_sugar_history.py            <- History and statistics
β”‚   └── 10_sugar_advanced.py           <- Advanced Sugar capabilities
β”‚
β”œβ”€β”€ 4_orchestrators/                   <- Strategy implementations
β”‚   └── (see Orchestrators section above)
β”‚
β”œβ”€β”€ 5_usercode/                        <- User code sandbox
β”‚   └── 17_usercode.py                 <- Your custom strategies
β”‚
└── main.py                            <- Main entry point with menu

How to run:

# Low-level examples (MT5Account - FOUNDATION OF EVERYTHING)
python examples/main.py 1              # General operations
python examples/main.py lowlevel01     # Same with alias
python examples/main.py 2              # Trading operations
python examples/main.py 3              # Streaming methods

# Service examples (MT5Service - wrappers)
python examples/main.py 4              # Service API demo
python examples/main.py service        # Same with alias
python examples/main.py 5              # Service streaming methods

# Sugar examples (MT5Sugar - convenience API)
python examples/main.py 6              # Sugar basics
python examples/main.py sugar06        # Same with alias
python examples/main.py 7              # Sugar trading
python examples/main.py 8              # Sugar positions
python examples/main.py 9              # Sugar history
python examples/main.py 10             # Advanced Sugar

# UserCode (your code)
python examples/main.py 17             # Custom strategies
python examples/main.py usercode       # Same with alias

# Interactive menu
python examples/main.py                # Show menu with all options


main.py (examples/)ΒΆ

What: Main entry point that routes commands to corresponding examples/orchestrators.

User interaction: πŸ“‹ Runner + Documentation - launches everything.

main.py
β”œβ”€β”€ main()                              <- Entry point, parses arguments
β”œβ”€β”€ execute_command()                   <- Maps aliases to runners
β”œβ”€β”€ main_loop()                         <- Interactive menu loop
└── Documentation in header             <- Full command reference

How it works:

python main.py grid
    ↓
main(args)  # args[1] = "grid"
    ↓
execute_command("grid")
    ↓
import and run grid orchestrator
    ↓
GridTrader.main()

Purpose:

  • Single entry point for all runnable code
  • Command routing with aliases (grid, trailing, etc.)
  • Interactive menu mode when no arguments provided
  • Helpful error messages for unknown commands
  • Ctrl+C handling for graceful shutdown

Available commands: See header comment in main.py for full list.


Helpers (examples/0_common/)ΒΆ

What: Utilities for examples and orchestrators.

examples/0_common/
β”œβ”€β”€ settings.json                 <- MT5 connection configuration
β”œβ”€β”€ demo_helpers.py               <- Connection setup & error handling
β”œβ”€β”€ progress_bar.py               <- Visual progress bars
└── 16_protobuf_inspector.py      <- Protobuf structure inspector (runnable)

demo_helpers.py:

# Load configuration from settings.json
settings = load_settings()

# Create and connect to MT5
account = await create_and_connect_mt5(settings)

# Error handling helpers
print_if_error(response)
check_retcode(response)
print_success("Order placed successfully")

progress_bar.py:

# Visual countdown during orchestrator operation
bar = TimeProgressBar(
    total_seconds=60,
    message="Monitoring positions"
)
# Update progress in a loop
bar.update(elapsed_seconds)
# Finish when done
bar.finish()

settings.json structure:

{
  "user": 12345678,
  "password": "YourPassword",
  "host": "mt5.mrpc.pro",
  "port": 443,
  "grpc_server": "mt5.mrpc.pro:443",
  "mt_cluster": "MetaQuotes-Demo",
  "test_symbol": "EURUSD",
  "test_volume": 0.01
}

ProtobufInspector:

# Inspect protobuf structures for debugging
python examples/main.py 16
python examples/main.py inspect


πŸ“ Documentation (docs/)ΒΆ

What: Complete API and strategy documentation.

User interaction: πŸ“– Read first! Comprehensive reference.

docs/
β”œβ”€β”€ index.md                           <- Home page - project introduction
β”‚
β”œβ”€β”€ mkdocs.yml                         <- MkDocs configuration
β”œβ”€β”€ styles/custom.css                  <- Custom theme (ocean aurora)
β”œβ”€β”€ javascripts/ux.js                  <- Interactive features
β”‚
β”œβ”€β”€ All_Guides/                        <- Guides
β”‚   β”œβ”€β”€ MT5_For_Beginners.md           <- πŸ”₯ Demo account registration
β”‚   β”œβ”€β”€ GETTING_STARTED.md             <- πŸ”₯ Start here! Setup and first steps
β”‚   β”œβ”€β”€ Your_First_Project.md          <- Your first project
β”‚   β”œβ”€β”€ GLOSSARY.md                    <- πŸ”₯ Terms and definitions
β”‚   β”œβ”€β”€ GRPC_STREAM_MANAGEMENT.md      <- Managing streaming subscriptions
β”‚   β”œβ”€β”€ RETURN_CODES_REFERENCE.md      <- Proto return code reference
β”‚   β”œβ”€β”€ ENUMS_USAGE_REFERENCE.md       <- Enums and constants guide
β”‚   β”œβ”€β”€ PROTOBUF_INSPECTOR_GUIDE.md    <- Protobuf inspector tool
β”‚   └── USERCODE_SANDBOX_GUIDE.md      <- How to write custom strategies
β”‚
β”œβ”€β”€ PROJECT_MAP.md                     <- πŸ”₯ This file - complete structure
β”‚
β”œβ”€β”€ API_Reference/                     <- Concise API documentation
β”‚   β”œβ”€β”€ MT5Account.md                  <- πŸ”₯ Layer 1 API (foundation) β†’ from package/MetaRpcMT5/helpers/mt5_account.py
β”‚   β”œβ”€β”€ MT5Service.md                  <- Layer 2 API β†’ from src/pymt5/mt5_service.py
β”‚   └── MT5Sugar.md                    <- Layer 3 API β†’ from src/pymt5/mt5_sugar.py
β”‚
β”œβ”€β”€ MT5Account/                        <- πŸ”₯ FOUNDATION - Detailed Layer 1 documentation
β”‚   β”œβ”€β”€ MT5Account.Master.Overview.md  <- πŸ”₯ Complete API reference
β”‚   β”‚
β”‚   β”œβ”€β”€ 1. Account_Information/        <- Account methods (~4 files)
β”‚   β”‚   β”œβ”€β”€ Account_Information.Overview.md  <- Section overview
β”‚   β”‚   β”œβ”€β”€ account_info_double.md     <- Get account double parameters
β”‚   β”‚   β”œβ”€β”€ account_info_integer.md    <- Get account integer parameters
β”‚   β”‚   β”œβ”€β”€ account_info_string.md     <- Get account string parameters
β”‚   β”‚   β”œβ”€β”€ account_summary.md         <- Complete account summary
β”‚   β”‚   └── πŸ’‘ Each example linked with examples/1_lowlevel
β”‚   β”‚
β”‚   β”œβ”€β”€ 2. Symbol_Information/         <- Symbol/market data methods (~13 files)
β”‚   β”‚   β”œβ”€β”€ Symbol_Information.Overview.md  <- Section overview
β”‚   β”‚   β”œβ”€β”€ symbol_info_tick.md        <- Current symbol tick
β”‚   β”‚   β”œβ”€β”€ symbol_info_double.md      <- Symbol double parameters
β”‚   β”‚   β”œβ”€β”€ symbols_total.md           <- Total symbols count
β”‚   β”‚   β”œβ”€β”€ symbol_exist.md            <- Check if symbol exists
β”‚   β”‚   β”œβ”€β”€ symbol_is_synchronized.md  <- Check synchronization
β”‚   β”‚   └── ...                        <- And other symbol methods
β”‚   β”‚   └── πŸ’‘ Examples in examples/1_lowlevel
β”‚   β”‚
β”‚   β”œβ”€β”€ 3. Positions_Orders/           <- Position/order methods (~6 files)
β”‚   β”‚   β”œβ”€β”€ Positions_Orders.Overview.md  <- Section overview
β”‚   β”‚   β”œβ”€β”€ opened_orders.md           <- List of open orders
β”‚   β”‚   β”œβ”€β”€ positions_total.md         <- Total positions count
β”‚   β”‚   β”œβ”€β”€ positions_history.md       <- Position history
β”‚   β”‚   └── ...                        <- And other position methods
β”‚   β”‚   └── πŸ’‘ Examples in examples/1_lowlevel
β”‚   β”‚
β”‚   β”œβ”€β”€ 4. Market_Depth/               <- Market depth methods (~3 files)
β”‚   β”‚   β”œβ”€β”€ Market_Depth.Overview.md   <- Section overview
β”‚   β”‚   β”œβ”€β”€ market_book_add.md         <- Subscribe to market depth
β”‚   β”‚   β”œβ”€β”€ market_book_get.md         <- Get market depth data
β”‚   β”‚   └── market_book_release.md     <- Unsubscribe from market depth
β”‚   β”‚
β”‚   β”œβ”€β”€ 5. Trading_Operations/         <- Trading operation methods (~7 files)
β”‚   β”‚   β”œβ”€β”€ Trading_Operations.Overview.md  <- Section overview
β”‚   β”‚   β”œβ”€β”€ order_send.md              <- Send order (main method)
β”‚   β”‚   β”œβ”€β”€ order_check.md             <- Check order before sending
β”‚   β”‚   β”œβ”€β”€ order_calc_margin.md       <- Calculate margin
β”‚   β”‚   β”œβ”€β”€ order_calc_profit.md       <- Calculate profit
β”‚   β”‚   β”œβ”€β”€ order_close.md             <- Close position
β”‚   β”‚   β”œβ”€β”€ order_modify.md            <- Modify order/position
β”‚   β”‚   └── πŸ’‘ Examples in examples/1_lowlevel/02_trading_operations.py
β”‚   β”‚
β”‚   β”œβ”€β”€ 6. Streaming_Methods/          <- Real-time subscription methods (~5 files)
β”‚   β”‚   β”œβ”€β”€ Streaming_Methods.Overview.md  <- Section overview
β”‚   β”‚   β”œβ”€β”€ on_symbol_tick.md          <- Subscribe to symbol ticks
β”‚   β”‚   β”œβ”€β”€ on_trade.md                <- Subscribe to trade events
β”‚   β”‚   β”œβ”€β”€ on_position_profit.md      <- Subscribe to profit changes
β”‚   β”‚   β”œβ”€β”€ on_trade_transaction.md    <- Subscribe to trade transactions
β”‚   β”‚   └── ...                        <- And other streaming methods
β”‚   β”‚   └── πŸ’‘ Stream management examples in All_Guides/GRPC_STREAM_MANAGEMENT
β”‚   β”‚
β”‚   └── HOW_IT_WORK/                   <- Detailed algorithm explanations
β”‚       β”œβ”€β”€ 1. Account_information_HOW/
β”‚       β”œβ”€β”€ 2. Symbol_information_HOW/
β”‚       β”œβ”€β”€ 3. Position_Orders_Information_HOW/
β”‚       β”œβ”€β”€ 4. Market_Depth(DOM)_HOW/
β”‚       β”œβ”€β”€ 5. Trading_Operations_HOW/
β”‚       └── 6. Streaming_Methods_HOW/
β”‚
β”œβ”€β”€ MT5Service/                        <- Service level method documentation
β”‚   β”œβ”€β”€ MT5Service.Overview.md          <- πŸ”₯ Complete Service API reference
β”‚   β”œβ”€β”€ 1. Account_Information.md      <- Account helper methods
β”‚   β”œβ”€β”€ 2. Symbol_Information.md       <- Symbol helper methods
β”‚   β”œβ”€β”€ 3. Positions_Orders.md         <- Position/order helper methods
β”‚   β”œβ”€β”€ 4. Market_Depth.md             <- Market depth helper methods
β”‚   β”œβ”€β”€ 5. Trading_Operations.md       <- Trading helper methods
β”‚   └── 6. Streaming_Methods.md        <- Streaming helper methods
β”‚
└── MT5Sugar/                          <- Sugar level method documentation
    β”œβ”€β”€ MT5Sugar.Master.Overview.md     <- πŸ”₯ Complete Sugar API reference
    β”‚
    β”œβ”€β”€ 1. Connection/                  <- Connection methods (~3 files)
    β”‚   β”œβ”€β”€ quick_connect.md            <- Quick connection
    β”‚   β”œβ”€β”€ is_connected.md             <- Check connection
    β”‚   └── ping.md                    <- Connection test
    β”‚
    β”œβ”€β”€ 2. Account_Properties/          <- Account properties (~7 files)
    β”‚   β”œβ”€β”€ get_balance.md              <- Get balance
    β”‚   β”œβ”€β”€ get_equity.md               <- Get equity
    β”‚   β”œβ”€β”€ get_free_margin.md          <- Free margin
    β”‚   └── ...                        <- And other account methods
    β”‚
    β”œβ”€β”€ 3. Prices_Quotes/               <- Prices and quotes (~5 files)
    β”‚   β”œβ”€β”€ get_bid.md                  <- Get Bid
    β”‚   β”œβ”€β”€ get_ask.md                  <- Get Ask
    β”‚   β”œβ”€β”€ get_spread.md               <- Get spread
    β”‚   └── ...                        <- And other price methods
    β”‚
    β”œβ”€β”€ 4. Simple_Trading/              <- Simple trading (~6 files)
    β”‚   β”œβ”€β”€ buy_market.md               <- Buy at market
    β”‚   β”œβ”€β”€ sell_market.md              <- Sell at market
    β”‚   β”œβ”€β”€ buy_limit.md                <- Buy Limit order
    β”‚   └── ...                        <- And other simple orders
    β”‚
    β”œβ”€β”€ 5. Trading_With_SLTP/           <- Trading with SL/TP (~4 files)
    β”‚   β”œβ”€β”€ buy_market_with_sltp.md     <- Buy with SL/TP
    β”‚   β”œβ”€β”€ sell_market_with_sltp.md    <- Sell with SL/TP
    β”‚   └── ...                        <- And other orders with SL/TP
    β”‚
    β”œβ”€β”€ 6. Position_Management/         <- Position management (~6 files)
    β”‚   β”œβ”€β”€ close_position.md           <- Close position
    β”‚   β”œβ”€β”€ close_all_positions.md      <- Close all positions
    β”‚   β”œβ”€β”€ modify_position_sltp.md     <- Modify SL/TP
    β”‚   └── ...                        <- And other management methods
    β”‚
    β”œβ”€β”€ 7. Position_Information/        <- Position information (~7 files)
    β”‚   β”œβ”€β”€ has_open_position.md        <- Has open position
    β”‚   β”œβ”€β”€ count_open_positions.md     <- Count positions
    β”‚   β”œβ”€β”€ get_position_by_ticket.md   <- Get position by ticket
    β”‚   └── ...                        <- And other information methods
    β”‚
    β”œβ”€β”€ 8. History_Statistics/          <- History and statistics (~3 files)
    β”‚   β”œβ”€β”€ get_deals.md                <- Get deals
    β”‚   β”œβ”€β”€ get_profit.md               <- Get profit
    β”‚   β”œβ”€β”€ get_daily_stats.md          <- Daily statistics
    β”‚   └── ...                        <- And other history methods
    β”‚
    β”œβ”€β”€ 9. Symbol_Information/          <- Symbol information (~4 files)
    β”‚   β”œβ”€β”€ get_symbol_info.md          <- Complete symbol information
    β”‚   β”œβ”€β”€ get_all_symbols.md          <- All available symbols
    β”‚   └── ...                        <- And other symbol methods
    β”‚
    └── 10. Risk_Management/            <- Risk management (~4 files)
        β”œβ”€β”€ calculate_position_size.md  <- Calculate position size
        β”œβ”€β”€ can_open_position.md        <- Can open position
        └── ...                        <- And other risk methods

Structure:

  • Each method has its own .md file with examples
  • Overview files (*.Overview.md, *.Master.Overview.md) provide navigation
  • HOW_IT_WORK/ folders explain algorithms step by step
  • Links between related methods
  • Usage examples in each file

πŸ”₯ Important about MT5Account:

  • FOUNDATION OF EVERYTHING - all methods here are the foundation
  • Each documentation example is linked with real code
  • Understanding MT5Account is critical for effective use of MT5Service and MT5Sugar

πŸ”Œ gRPC & Proto (Python packages)ΒΆ

What: Protocol Buffer and gRPC libraries for communication with MT5 terminal.

User interaction: πŸ“‹ Reference only - managed via pip.

Key dependencies:

  • grpcio - gRPC client
  • grpcio-tools - gRPC tools for Python
  • protobuf - Protocol Buffers runtime

Package structure:

package/
└── MetaRpcMT5/
    β”œβ”€β”€ helpers/
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   β”œβ”€β”€ mt5_account.py      <- Layer 1 implementation
    β”‚   └── errors.py           <- Error handling utilities
    β”‚
    β”œβ”€β”€ __init__.py             <- Package initialization
    β”œβ”€β”€ *_pb2.py                <- Generated protobuf code
    β”œβ”€β”€ *_grpc_pb2.py           <- Generated gRPC stubs
    └── mt5_term_api_*.py       <- MT5 API protocol definitions

How it works:

  1. package/ is an independent Python package
  2. Contains both proto-generated code and MT5Account implementation
  3. Can be imported separately as a package
  4. MT5Service and MT5Sugar import from package
  5. All layers use proto-generated types from package

Proto-generated types:

  • mt5_term_api_* - Trading API types
  • Request/Response message types
  • Enum definitions
  • Service contracts

Purpose:

  • Define gRPC service contracts
  • Type-safe communication with MT5 terminal
  • Used by MT5Account layer
  • Hidden by MT5Service and MT5Sugar layers

πŸ“Š Component Interaction DiagramΒΆ

YOUR CODE (User)
  β”œβ”€ Orchestrators (strategy implementations)
  └─ Examples (learning materials)
                  β”‚
                  β”‚ uses
                  ↓
MT5Sugar (Layer 3 - Convenience)
  πŸ“ Location: src/pymt5/mt5_sugar.py
  β”œβ”€ Auto-normalization
  β”œβ”€ Risk management
  β”œβ”€ Points-based methods
  └─ Batch operations
                  β”‚
                  β”‚ uses
                  ↓
MT5Service (Layer 2 - Wrappers)
  πŸ“ Location: src/pymt5/mt5_service.py
  β”œβ”€ Direct data return
  β”œβ”€ Type conversion
  └─ Simplified signatures
                  β”‚
                  β”‚ uses
                  ↓
MT5Account (Layer 1 - Low level) πŸ”₯ FOUNDATION
  πŸ“ Location: package/MetaRpcMT5/helpers/mt5_account.py
  β”œβ”€ Proto Request/Response
  β”œβ”€ gRPC communication
  β”œβ”€ Connection management
  β”œβ”€ Auto-reconnection
  └─ Independent Python package (portable)
                  β”‚
                  β”‚ gRPC
                  ↓
MT5 Gateway (mt5term) or MT5 Terminal
  └─ MetaTrader 5 with gRPC server

πŸ” File Naming ConventionsΒΆ

Core API (Multi-location)ΒΆ

Layer 1 (Foundation):

  • package/MetaRpcMT5/helpers/mt5_account.py - Low-level gRPC (independent package)
  • package/MetaRpcMT5/helpers/errors.py - Error handling utilities

Protobuf (Generated):

  • package/MetaRpcMT5/*_pb2.py - Protobuf message definitions
  • package/MetaRpcMT5/*_pb2_grpc.py - gRPC service stubs

Layers 2-3 (High-level wrappers):

  • src/pymt5/mt5_service.py - Wrapper methods
  • src/pymt5/mt5_sugar.py - Convenience API

Package configuration:

  • package/pyproject.toml - Package dependencies and metadata

User Code (examples/)ΒΆ

  • NN_name.py - Numbered examples and strategies
  • main.py - Entry point and command router
  • *_helpers.py - Utilities (demo_helpers, progress_bar)
  • settings.json - Configuration

Documentation (docs/)ΒΆ

  • *.Master.Overview.md - Complete category overviews
  • *.Overview.md - Section overviews
  • MethodName.md - Individual method documentation
  • *_HOW.md - Algorithm explanations

πŸ“ What to Modify vs What to Leave AloneΒΆ

βœ… MODIFY (User Code)ΒΆ

Recommended starting point:

examples/5_usercode/17_usercode.py  <- πŸ”₯ SANDBOX - start writing your code here!
                                       All 3 API levels already initialized and ready.
                                       Run: python main.py 17

Other files for modification:

examples/4_orchestrators/     <- Copy and customize for your strategies
examples/1_lowlevel/          <- Add your low-level examples
examples/2_service/           <- Add your service examples
examples/3_sugar/             <- Add your sugar examples
examples/5_usercode/          <- Create your custom files alongside 17_usercode.py
examples/0_common/settings.json  <- Configure for your MT5 terminal/gateway
examples/main.py              <- Add new command routing if needed
README.md                     <- Update with your changes

πŸ“– READ (Core API)ΒΆ

package/MetaRpcMT5/helpers/mt5_account.py  <- Use but don't modify (import and call) πŸ”₯ FOUNDATION
package/MetaRpcMT5/helpers/errors.py       <- Use but don't modify
src/pymt5/mt5_service.py        <- Use but don't modify
src/pymt5/mt5_sugar.py          <- Use but don't modify
docs/                           <- Reference documentation

πŸ”’ LEAVE ALONE (Generated/Build)ΒΆ

.vscode/                       <- VS Code settings
package/MetaRpcMT5/*_pb2.py    <- Auto-generated protobuf code
package/MetaRpcMT5/*_pb2_grpc.py  <- Auto-generated gRPC stubs
docs/site/                     <- Built documentation (auto-generated by MkDocs)
docs/styles/                   <- Documentation theme (don't change without understanding)
docs/javascripts/              <- Documentation scripts (don't change without understanding)
__pycache__/                   <- Python bytecode cache (auto-generated)
*.pyc                          <- Python compiled files (auto-generated)

πŸ‘€ Project PhilosophyΒΆ

Goal: Make MT5 trading automation accessible through progressive complexity.

Three-tier design:

  1. Low level (MT5Account): Full control, proto/gRPC πŸ”₯ FOUNDATION OF EVERYTHING
  2. Wrappers (MT5Service): Simplified method calls
  3. Convenience (MT5Sugar): Auto-everything, batteries included

User code:

  • Orchestrators: Ready-made strategy templates
  • Examples: Learning materials at all levels

πŸ› οΈ TroubleshootingΒΆ

Installation IssuesΒΆ

# Clean and reinstall
pip uninstall MetaRpcMT5
pip install --upgrade pip

# Install package in development mode
pip install -e package/

# Or install specific dependencies
pip install grpcio grpcio-tools protobuf

# Check Python version
python --version   # Should be 3.8 or higher

Runtime IssuesΒΆ

1. Always test on demo account first
2. Check return codes (10009 = success, 10031 = connection error)
3. Monitor console output for errors
4. Use retry logic for intermittent issues
5. Verify broker allows your strategy type (hedging, etc.)
6. Check that MT5 terminal is running and gRPC server is active

Common ErrorsΒΆ

# Connection error
Error: ConnectExceptionMT5
Fix: Check MT5 terminal is running, verify settings.json

# Import error
Error: ModuleNotFoundError: No module named 'MetaRpcMT5'
Fix: pip install -e package/ (from project root)

# Return code 10004 (invalid request)
Fix: Check order parameters (volume, price, symbol)

# Return code 10031 (connection timeout)
Fix: Check network, verify grpc_server in settings.json

πŸ“Š Performance ConsiderationsΒΆ

Connection ManagementΒΆ

  • Single gRPC connection shared across operations
  • Built-in auto-reconnection handles temporary failures
  • Retry logic with exponential backoff (1s β†’ 2s β†’ 4s)

Rate LimitingΒΆ

  • 3-second delays between order placements (demo examples)
  • Gateway may enforce additional rate limits
  • Adjust delays based on broker requirements

Resource UsageΒΆ

  • Async/await everywhere for non-blocking I/O
  • Proper cleanup in try/finally blocks
  • Context managers for resource management

πŸ“‹ Best PracticesΒΆ

Code OrganizationΒΆ

βœ… DO: Separate concerns (analysis, execution, monitoring)
βœ… DO: Add comprehensive error handling
βœ… DO: Document your strategy logic clearly
βœ… DO: Use progress bars for long operations
βœ… DO: Use async/await for concurrent operations

❌ DON'T: Mix strategy logic with API calls
❌ DON'T: Use time.sleep without context
❌ DON'T: Ignore return codes
❌ DON'T: Test on live accounts without extensive demo testing

Strategy DevelopmentΒΆ

βœ… DO: Start with existing orchestrator as template
βœ… DO: Test each component separately
βœ… DO: Log all trading decisions and outcomes
βœ… DO: Use demo accounts for development
βœ… DO: Implement proper risk management

❌ DON'T: Over-optimize on limited data
❌ DON'T: Ignore edge cases and failures
❌ DON'T: Use fixed lots without risk calculation
❌ DON'T: Deploy without backtesting and forward testing

Python-Specific Best PracticesΒΆ

βœ… DO: Use type hints for better IDE support
βœ… DO: Follow PEP 8 style guidelines
βœ… DO: Use dataclasses for data structures
βœ… DO: Use f-strings for string formatting
βœ… DO: Use pathlib for file paths

❌ DON'T: Use mutable default arguments
❌ DON'T: Catch Exception without re-raising
❌ DON'T: Use global variables in strategies
❌ DON'T: Forget to close streams and connections

πŸ“¦ Project File TreeΒΆ

PyMT5/
β”‚
β”œβ”€β”€ .github/                           <- GitHub configuration
β”œβ”€β”€ .vscode/                           <- VS Code settings
β”‚   β”œβ”€β”€ launch.json
β”‚   └── settings.json
β”‚
β”œβ”€β”€ docs/                              <- Documentation (see Documentation section above)
β”‚   β”œβ”€β”€ index.md
β”‚   β”œβ”€β”€ mkdocs.yml
β”‚   β”œβ”€β”€ All_Guides/
β”‚   β”œβ”€β”€ API_Reference/
β”‚   β”œβ”€β”€ MT5Account/
β”‚   β”œβ”€β”€ MT5Service/
β”‚   β”œβ”€β”€ MT5Sugar/
β”‚   β”œβ”€β”€ Guide_Images/
β”‚   β”œβ”€β”€ includes/
β”‚   β”œβ”€β”€ javascripts/
β”‚   └── styles/
β”‚
β”œβ”€β”€ examples/                          <- Examples and user code (see Examples section above)
β”‚   β”œβ”€β”€ 0_common/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ settings.json              <- πŸ”₯ Connection configuration
β”‚   β”‚   β”œβ”€β”€ demo_helpers.py
β”‚   β”‚   β”œβ”€β”€ progress_bar.py
β”‚   β”‚   └── 16_protobuf_inspector.py
β”‚   β”‚
β”‚   β”œβ”€β”€ 1_lowlevel/                    <- πŸ”₯ FOUNDATION examples
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ 01_general_operations.py
β”‚   β”‚   β”œβ”€β”€ 02_trading_operations.py
β”‚   β”‚   └── 03_streaming_methods.py
β”‚   β”‚
β”‚   β”œβ”€β”€ 2_service/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ 04_service_demo.py
β”‚   β”‚   └── 05_service_streaming.py
β”‚   β”‚
β”‚   β”œβ”€β”€ 3_sugar/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ 06_sugar_basics.py
β”‚   β”‚   β”œβ”€β”€ 07_sugar_trading.py
β”‚   β”‚   β”œβ”€β”€ 08_sugar_positions.py
β”‚   β”‚   β”œβ”€β”€ 09_sugar_history.py
β”‚   β”‚   └── 10_sugar_advanced.py
β”‚   β”‚
β”‚   β”œβ”€β”€ 4_orchestrators/
β”‚   β”‚   β”œβ”€β”€ 11_trailing_stop.py
β”‚   β”‚   β”œβ”€β”€ 12_position_scaler.py
β”‚   β”‚   β”œβ”€β”€ 13_grid_trader.py
β”‚   β”‚   β”œβ”€β”€ 14_risk_manager.py
β”‚   β”‚   └── 15_portfolio_rebalancer.py
β”‚   β”‚
β”‚   β”œβ”€β”€ 5_usercode/
β”‚   β”‚   └── 17_usercode.py             <- πŸ”₯ START HERE for your code
β”‚   β”‚
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── main.py                        <- πŸ”₯ Main entry point
β”‚
β”œβ”€β”€ package/                           <- Core package (portable)
β”‚   └── MetaRpcMT5/                    <- Package root
β”‚       β”œβ”€β”€ helpers/
β”‚       β”‚   β”œβ”€β”€ __init__.py
β”‚       β”‚   β”œβ”€β”€ mt5_account.py         <- πŸ”₯ FOUNDATION - Layer 1
β”‚       β”‚   └── errors.py              <- Error handling
β”‚       β”‚
β”‚       β”œβ”€β”€ __init__.py
β”‚       β”œβ”€β”€ *_pb2.py                   <- Generated protobuf code (11 files)
β”‚       └── *_pb2_grpc.py              <- Generated gRPC stubs (11 files)
β”‚                 
β”‚
β”œβ”€β”€ src/                               <- High-level API layers
β”‚   └── pymt5/
β”‚       β”œβ”€β”€ __init__.py
β”‚       β”œβ”€β”€ mt5_service.py             <- Layer 2 - Wrappers
β”‚       └── mt5_sugar.py               <- Layer 3 - Convenience
β”‚
β”œβ”€β”€ .gitignore                         <- Git ignore patterns
β”œβ”€β”€ mkdocs.yml                         <- MkDocs configuration
└── README.md                          <- Project readme

πŸ’‘ Remember: This is an educational project. All orchestrators are demonstration examples, not production-ready trading systems. Always test on demo accounts, thoroughly understand the code, and implement proper risk management before considering live trading.


"Trade safely, code cleanly, and may your gRPC connections always be stable."