GoMT5 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ΒΆ
GoMT5/
βββ π¦ package/ - Independent module (portable)
β βββ Helpers/MT5Account.go (Layer 1 - Foundation)
β βββ Helpers/errors.go (Error handling & trade return codes)
β βββ Proto definitions (*.pb.go)
β βββ gRPC stubs (*_grpc.pb.go)
β
βββ π¦ examples/mt5/ - High-level API layers
β βββ MT5Service.go (Layer 2 - Wrappers)
β βββ MT5Sugar.go (Layer 3 - Convenience)
β
βββ π― User Code (Orchestrators, Presets, Examples)
βββ π Documentation
βββ βοΈ Configuration and build
External dependencies:
βββ π gRPC & Proto (Go modules)
π¦ Core API (Three-layer architecture)ΒΆ
What: Three-tier architecture for MT5 trading automation.
User interaction: Import and use, but typically don't modify.
package/Helpers/
βββ MT5Account.go β 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 Go module (portable)
β
βββ errors.go β Error handling & trade result codes
βββ ErrNotConnected sentinel error
βββ ApiError wrapper (3-level: API/MQL/Trade)
βββ Trade return code constants & helpers
βββ Centralized error inspection methods
examples/mt5/
βββ MT5Service.go β LAYER 2: Wrapper methods
β βββ Simplified signatures (no proto objects)
β βββ Type conversion (proto β Go primitives)
β βββ Direct data return
β βββ Extension methods for convenience
β
βββ MT5Sugar.go β 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)
go.mod / go.sum β Module dependencies
Architecture flow:
MT5Sugar β uses β MT5Service β uses β MT5Account β gRPC β MT5 Terminal
β β β
examples/mt5/ examples/mt5/ package/Helpers/
π‘ Creating Your Own Project:
For your own standalone project using GoMT5, 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 Go module (can be used without examples/)
This makes the package portable and easy to integrate into any Go project!
User decision:
- Building your own app: Import
packageand use MT5Account directly - Learning/Examples: Use the full GoMT5 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)
Documentation:
- MT5Account API Reference β FOUNDATION OF EVERYTHING
- MT5Service API Reference
- MT5Sugar API Reference
π― User Code (Your Trading Strategies)ΒΆ
Orchestrators (examples/demos/orchestrators/)ΒΆ
What: Ready-made trading strategy implementations.
examples/demos/orchestrators/
βββ 13_grid_trader.go β Grid trading (sideways markets)
βββ 11_trailing_stop.go β Trailing stop (price following)
βββ 12_position_scaler.go β Position scaling
βββ 14_risk_manager.go β Risk manager
βββ 15_portfolio_rebalancer.go β Portfolio rebalancing
βββ orchestrators.go β Base interface/functionality
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:
go run examples/demos/main.go grid # Grid Trader
go run examples/demos/main.go trailing # Trailing Stop
go run examples/demos/main.go scaler # Position Scaler
go run examples/demos/main.go risk # Risk Manager
go run examples/demos/main.go portfolio # Portfolio Rebalancer
Documentation: - Grid Trader - Trailing Stop - Position Scaler - Risk Manager - Portfolio Rebalancer
Presets (examples/demos/presets/)ΒΆ
What: Combinations of multiple orchestrators with adaptive logic based on market analysis.
User interaction: β Advanced usage - combine multiple strategies.
Purpose: Demonstrate how to:
- Combine multiple orchestrators
- Adaptive decision making (volatility β strategy)
- Market condition analysis (simplified demo)
- Multi-phase trading sessions
- Performance tracking by phases
How to run:
go run examples/demos/main.go preset # Adaptive Market Preset
go run examples/demos/main.go adaptive # Same thing
Examples (examples/demos/)ΒΆ
What: Runnable examples demonstrating API usage at different layers.
User interaction: β Learning materials - run to understand the API.
examples/demos/
βββ lowlevel/ β MT5Account examples (proto level) β FOUNDATION
β βββ 01_general_operations.go β General operations (connection, account, symbols)
β βββ 02_trading_operations.go β Trading operations (orders, positions)
β βββ 03_streaming_methods.go β Streaming methods (real-time subscriptions)
β
βββ service/ β MT5Service examples (wrapper level)
β βββ 04_service_demo.go β Service API demonstration
β βββ 05_service_streaming.go β Service streaming methods
β
βββ sugar/ β MT5Sugar examples (convenience level)
β βββ 06_sugar_basics.go β Sugar API basics (balance, prices)
β βββ 07_sugar_trading.go β Trading (market/limit orders)
β βββ 08_sugar_positions.go β Position management
β βββ 09_sugar_history.go β History and statistics
β βββ 10_sugar_advanced.go β Advanced Sugar capabilities
β
βββ usercode/ β User code sandbox
βββ 18_usercode.go β Your custom strategies
How to run:
# Low-level examples (MT5Account - FOUNDATION OF EVERYTHING)
go run examples/demos/main.go lowlevel01 # General operations
go run examples/demos/main.go lowlevel02 # Trading operations
go run examples/demos/main.go lowlevel03 # Streaming methods
# Service examples (MT5Service - wrappers)
go run examples/demos/main.go service04 # Service API demo
go run examples/demos/main.go service05 # Service streaming methods
# Sugar examples (MT5Sugar - convenience API)
go run examples/demos/main.go sugar06 # Sugar basics
go run examples/demos/main.go sugar07 # Sugar trading
go run examples/demos/main.go sugar08 # Sugar positions
go run examples/demos/main.go sugar09 # Sugar history
go run examples/demos/main.go sugar10 # Advanced Sugar
# UserCode (your code)
go run examples/demos/main.go usercode # Custom strategies
main.go (examples/demos/)ΒΆ
What: Main entry point that routes go run commands to corresponding examples/orchestrators/presets.
User interaction: π Runner + Documentation - launches everything.
main.go
βββ main() β Entry point, parses arguments
βββ RouteCommand() β Maps aliases to runners
βββ RunOrchestrator() β Launches orchestrators
βββ RunPreset() β Launches presets
βββ RunExample() β Launches examples
βββ Documentation in header β Full command reference
How it works:
go run examples/demos/main.go grid
β
main(args) // args[0] = "grid"
β
RouteCommand("grid")
β
RunOrchestrator("grid")
β
GridTrader.Run()
Purpose:
- Single entry point for all runnable code
- Command routing with aliases (grid, trailing, preset, etc.)
- Helpful error messages for unknown commands
- Ctrl+C handling for graceful shutdown
Available commands: See header comment in main.go for full list.
Helpers (examples/demos/helpers/)ΒΆ
What: Utilities for examples and orchestrators.
examples/demos/helpers/
βββ connection.go β MT5 connection setup
βββ error_helper.go β Error handling and return codes
βββ progress_bar.go β Visual progress bars
βββ 17_protobuf_inspector.go β Protobuf structure inspector (runnable)
ConnectionHelper:
// Create and connect to MT5
account, err := connection.CreateAndConnect(host, port, user, password)
service := mt5.NewMT5Service(account)
sugar := mt5.NewMT5Sugar(service)
ProgressBarHelper:
// Visual countdown during orchestrator operation
helpers.ShowProgressBar(
durationSeconds: 60,
message: "Monitoring positions",
ctx: ctx,
)
ErrorHelper:
// Check return codes and handle errors
if !helpers.IsSuccess(returnCode) {
helpers.PrintError(returnCode, "Order placement failed")
}
ProtobufInspector:
π 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
β βββ 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
β β (slightly enhanced for better navigation)
β βββ MT5Account.md β β Layer 1 API (foundation of everything) β from package/Helpers/MT5Account.go
β βββ MT5Service.md β Layer 2 API β from examples/mt5/MT5Service.go
β βββ MT5Sugar.md β Layer 3 API β from examples/mt5/MT5Sugar.go
β
βββ MT5Account/ β β FOUNDATION OF EVERYTHING - Detailed Layer 1 documentation
β βββ MT5Account.Master.Overview.md β β Complete API reference
β β
β βββ 1. Account_information/ β Account methods (~4 files)
β β βββ AccountInfoDouble.md β Get account double parameters
β β βββ AccountSummary.md β Complete account summary
β β βββ ... β And other account methods
β β βββ π‘ Each example linked with examples/demos/lowlevel
β β
β βββ 2. Symbol_information/ β Symbol/market data methods (~9 files)
β β βββ SymbolInfoTick.md β Current symbol tick
β β βββ SymbolInfoDouble.md β Symbol double parameters
β β βββ SymbolsTotal.md β Total symbols count
β β βββ ... β And other symbol methods
β β βββ π‘ Examples in examples/demos/lowlevel
β β
β βββ 3. Position_Orders_Information/ β Position/order methods (~6 files)
β β βββ OpenedOrders.md β List of open orders
β β βββ PositionsTotal.md β Total positions count
β β βββ ... β And other position methods
β β βββ π‘ Examples in examples/demos/lowlevel
β β
β βββ 4. Trading_Operations/ β Trading operation methods (~7 files)
β β βββ OrderSend.md β Send order (main method)
β β βββ OrderCheck.md β Check order before sending
β β βββ OrderCalcMargin.md β Calculate margin
β β βββ OrderCalcProfit.md β Calculate profit
β β βββ ... β And other trading methods
β β βββ π‘ Examples in examples/demos/lowlevel/02_trading_operations.go
β β
β βββ 5. Market_Depth(DOM)/ β Market depth methods (~4 files)
β β βββ MarketBookAdd.md β Subscribe to market depth
β β βββ MarketBookGet.md β Get market depth data
β β βββ ... β And other DOM methods
β β
β βββ 6. Additional_Methods/ β Additional methods (~5 files)
β β βββ SymbolInfoMarginRate.md β Symbol margin rates
β β βββ SymbolInfoSessionQuote.md β Quote trading sessions
β β βββ ... β And other auxiliary methods
β β
β βββ 7. Streaming_Methods/ β Real-time subscription methods
β βββ OnSymbolTick.md β Subscribe to symbol ticks
β βββ OnTrade.md β Subscribe to trade events
β βββ OnPositionProfit.md β Subscribe to profit changes
β βββ ... β And other streaming methods
β βββ π‘ Stream management examples in All_Guides/GRPC_STREAM_MANAGEMENT
β
βββ MT5Service/ β Service level method documentation
β βββ MT5Service.Overview.md β β Complete Service API reference
β βββ 1. Account_Methods.md β Account helper methods
β βββ 2. Symbol_Methods.md β Symbol helper methods
β βββ 3. Position_Orders_Methods.md β Position/order helper methods
β βββ 4. Trading_Methods.md β Trading helper methods
β βββ 5. MarketDepth_Methods.md β Market depth helper methods
β βββ 6. Streaming_Methods.md β Streaming helper methods
β
βββ MT5Sugar/ β Sugar level method documentation
β βββ MT5Sugar.API_Overview.md β β Complete Sugar API reference
β β
β βββ 1. Connection/ β Connection methods (~3 files)
β β βββ QuickConnect.md β Quick connection
β β βββ IsConnected.md β Check connection
β β βββ Ping.md β Connection test
β β
β βββ 2. Balance_Margin/ β Balance and margin (~6 files)
β β βββ GetBalance.md β Get balance
β β βββ GetEquity.md β Get equity
β β βββ GetFreeMargin.md β Free margin
β β βββ ... β And other balance methods
β β
β βββ 3. Prices_Quotes/ β Prices and quotes (~5 files)
β β βββ GetBid.md β Get Bid
β β βββ GetAsk.md β Get Ask
β β βββ GetSpread.md β Get spread
β β βββ ... β And other price methods
β β
β βββ 4. Simple_Trading/ β Simple trading (~6 files)
β β βββ BuyMarket.md β Buy at market
β β βββ SellMarket.md β Sell at market
β β βββ BuyLimit.md β Buy Limit order
β β βββ ... β And other simple orders
β β
β βββ 5. Trading_SLTP/ β Trading with SL/TP (~4 files)
β β βββ BuyMarketWithSLTP.md β Buy with SL/TP
β β βββ SellMarketWithSLTP.md β Sell with SL/TP
β β βββ ... β And other orders with SL/TP
β β
β βββ 6. Position_Management/ β Position management (~7 files)
β β βββ ClosePosition.md β Close position
β β βββ CloseAllPositions.md β Close all positions
β β βββ ModifyPositionSLTP.md β Modify SL/TP
β β βββ ... β And other management methods
β β
β βββ 7. Position_Information/ β Position information (~7 files)
β β βββ HasOpenPosition.md β Has open position
β β βββ CountOpenPositions.md β Count positions
β β βββ GetPositionTickets.md β Get position tickets
β β βββ ... β And other information methods
β β
β βββ 8. History_Statistics/ β History and statistics (~10 files)
β β βββ GetDealsToday.md β Deals today
β β βββ GetProfitThisWeek.md β Profit this week
β β βββ GetDealsDateRange.md β Deals for period
β β βββ ... β And other history methods
β β
β βββ 9. Symbol_Information/ β Symbol information (~6 files)
β β βββ GetSymbolInfo.md β Complete symbol information
β β βββ GetAllSymbols.md β All available symbols
β β βββ ... β And other symbol methods
β β
β βββ 10. Risk_Management/ β Risk management (~4 files)
β β βββ CalculatePositionSize.md β Calculate position size
β β βββ CanOpenPosition.md β Can open position
β β βββ ... β And other risk methods
β β
β βββ 11. Trading_Helpers/ β Trading helpers (~3 files)
β β βββ BuyMarketWithPips.md β Buy with SL/TP in pips
β β βββ CalculateSLTP.md β Calculate SL/TP
β β βββ ... β And other helpers
β β
β βββ 12. Account_Information/ β Account information (~4 files)
β βββ AccountInfo.md β Account information
β βββ GetDailyStats.md β Daily statistics
β βββ ... β And other account methods
β
βββ Orchestrators/ β Strategy documentation
βββ 13_Grid_trader.md β Grid trading
βββ 11_Trailing_stop.md β Trailing stop
βββ 12_Position_scaler.md β Position scaling
βββ 14_Risk_manager.md β Risk manager
βββ 15_Portfolio_rebalancer.md β Portfolio rebalancing
βββ 16_AdaptiveOrchestratorPreset.md β Adaptive preset
βββ Strategies.Master.Overview.md β Complete strategy overview
Structure:
- Each method has its own
.mdfile with examples - Overview files (
*.Master.Overview.md) provide navigation HOW_IT_WORKS.mdfiles 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 in examples/demos/lowlevel/
- Understanding MT5Account is critical for effective use of MT5Service and MT5Sugar
π gRPC & Proto (Go modules)ΒΆ
What: Protocol Buffer and gRPC libraries for communication with MT5 terminal.
User interaction: π Reference only - managed via Go modules.
Key dependencies:
google.golang.org/grpc- gRPC clientgoogle.golang.org/protobuf- Protocol Buffers runtimegithub.com/MetaRPC/GoMT5/package- MT5 Proto definitions (independent module)
Package structure:
package/
βββ Helpers/
β βββ MT5Account.go β Layer 1 implementation
βββ *.pb.go β Generated protobuf code
βββ *_grpc.pb.go β Generated gRPC stubs
βββ go.mod β Independent module
βββ go.sum β Module dependencies
How it works:
package/is an independent Go module- Contains both proto-generated code and MT5Account implementation
- Can be imported separately:
github.com/MetaRPC/GoMT5/package - MT5Service and MT5Sugar import from package module
- 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)
ββ Presets (multi-strategies)
ββ Examples (learning materials)
β
β uses
β
MT5Sugar (Layer 3 - Convenience)
ββ Auto-normalization
ββ Risk management
ββ Points-based methods
ββ Batch operations
β
β uses
β
MT5Service (Layer 2 - Wrappers)
ββ Direct data return
ββ Type conversion
ββ Simplified signatures
β
β uses
β
MT5Account (Layer 1 - Low level) β FOUNDATION
π Location: package/Helpers/MT5Account.go
ββ Proto Request/Response
ββ gRPC communication
ββ Connection management
ββ Auto-reconnection
ββ Independent Go module (portable)
β
β gRPC
β
MT5 Gateway (mt5term) or MT5 Terminal
ββ MetaTrader 5 with gRPC server
π File Naming ConventionsΒΆ
Core API (Multi-location)ΒΆ
Layer 1 (Foundation):
- package/Helpers/MT5Account.go - Low-level gRPC (independent module)
Layers 2-3 (High-level wrappers):
- examples/mt5/MT5Service.go - Wrapper methods
- examples/mt5/MT5Sugar.go - Convenience API
- go.mod / go.sum - Dependencies
User Code (examples/demos/)ΒΆ
*_orchestrator.go/NN_name.go- Single strategy implementations*_preset.go- Multi-strategiesmain.go- Entry point and command router*_helper.go- Utilities (connection, error, progress_bar)
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/demos/usercode/18_usercode.go β β SANDBOX - start writing your code here!
All 3 API levels already initialized and ready.
Run: go run main.go 18
Other files for modification:
examples/demos/orchestrators/ β Copy and customize for your strategies
examples/demos/presets/ β Create your multi-strategies
examples/demos/lowlevel/ β Add your low-level examples
examples/demos/service/ β Add your service examples
examples/demos/sugar/ β Add your sugar examples
examples/demos/usercode/ β Create your custom files alongside 18_usercode.go
examples/demos/config/ β Configure for your MT5 terminal/gateway
examples/demos/main.go β Add new command routing if needed
README.md β Update with your changes
π READ (Core API)ΒΆ
package/Helpers/MT5Account.go β Use but don't modify (import and call) β FOUNDATION
examples/mt5/MT5Service.go β Use but don't modify
examples/mt5/MT5Sugar.go β Use but don't modify
docs/ β Reference documentation
π LEAVE ALONE (Generated/Build)ΒΆ
.vscode/ β VS Code settings
go.work.sum β Go workspace (auto-generated)
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)
π― 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
- Presets: Adaptive multi-strategies
- Examples: Learning materials at all levels
π οΈ TroubleshootingΒΆ
Build IssuesΒΆ
# Clean and rebuild
go clean
go build ./...
# Restore modules
go mod tidy
go mod download
# Check Go version
go version # Should be 1.21 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.)
π 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
- Context for graceful shutdown
- Proper cleanup in defer blocks
π Best PracticesΒΆ
Code OrganizationΒΆ
β
DO: Separate concerns (analysis, execution, monitoring)
β
DO: Use context for lifecycle management
β
DO: Add comprehensive error handling
β
DO: Document your strategy logic clearly
β
DO: Use ProgressBarHelper for long operations
β DON'T: Mix strategy logic with API calls
β DON'T: Use time.Sleep (use time.After with 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
π‘ Remember: This is an educational project. All orchestrators and presets 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."