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:
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
packageand 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
UNAVAILABLEstatus (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_eventto 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:
- Study existing orchestrators
- Copy one as a template
- Modify for your strategy
- 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
.mdfile 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 clientgrpcio-tools- gRPC tools for Pythonprotobuf- 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:
package/is an independent Python package- Contains both proto-generated code and MT5Account implementation
- Can be imported separately as a package
- MT5Service and MT5Sugar import from package
- 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 definitionspackage/MetaRpcMT5/*_pb2_grpc.py- gRPC service stubs
Layers 2-3 (High-level wrappers):
src/pymt5/mt5_service.py- Wrapper methodssrc/pymt5/mt5_sugar.py- Convenience API
Package configuration:
package/pyproject.toml- Package dependencies and metadata
User Code (examples/)ΒΆ
NN_name.py- Numbered examples and strategiesmain.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 overviewsMethodName.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:
- Low level (MT5Account): Full control, proto/gRPC π₯ FOUNDATION OF EVERYTHING
- Wrappers (MT5Service): Simplified method calls
- 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."