CSharpMT5 Project MapΒΆ
Complete project structure guide. Shows what's where, what's user-facing vs internal, and how components connect.
πΊοΈ Project OverviewΒΆ
CSharpMT5/
βββ π¦ Core API (Internal - 3 layers)
βββ π― User Code (Orchestrators, Presets, Examples)
βββ π Documentation
βββ βοΈ Configuration & Build
External Dependencies:
βββ π gRPC & Proto (NuGet packages)
π¦ Core API (Internal - Root Level)ΒΆ
What: Three-tier architecture for MT5 trading automation.
User interaction: Import and use, but typically don't modify.
/
βββ package/ β NuGet package source files (auto-generated)
β βββ Helpers/
β βββ MT5Account.cs β LAYER 1: Low-level gRPC
β βββ Direct gRPC calls to MT5 terminal
β βββ Connection management with retry logic
β βββ Proto Request/Response handling
β βββ Async/Sync method variants
β βββ Built-in connection resilience
β
βββ MT5Service.cs β LAYER 2: Wrapper methods
β βββ Simplified signatures (no proto objects)
β βββ Type conversions (proto β C# primitives)
β βββ Direct data returns
β βββ Extension methods for convenience
β
βββ MT5Sugar.cs β 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)
Errors/
βββ ConnectExceptionMT5.cs β Connection exception wrapper
Architecture flow:
User decision:
- 95% of cases: Start with
MT5Sugar(highest level, easiest) - Need wrappers: Drop to
MT5Service(no auto-normalization) - Need raw proto: Drop to
MT5Account(full control)
Documentation:
π― User Code (Your Trading Strategies)ΒΆ
Orchestrators (Examples\Orchestrators)ΒΆ
What: Pre-built trading strategy implementations.
Examples\Orchestrators\
βββ GridTradingOrchestrator.cs β Grid trading (range-bound markets)
βββ SimpleScalpingOrchestrator.cs β Quick scalping with tight stops
βββ QuickHedgeOrchestrator.cs β Hedging strategy (high volatility)
βββ NewsStraddleOrchestrator.cs β Breakout trading around news
βββ PendingBreakoutOrchestrator.cs β Pending orders for breakouts
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 template
- Modify for your strategy
- Test on demo account
How to run:
dotnet run grid # GridTradingOrchestrator
dotnet run scalping # SimpleScalpingOrchestrator
dotnet run hedge # QuickHedgeOrchestrator
dotnet run news # NewsStraddleOrchestrator
dotnet run breakout # PendingBreakoutOrchestrator
Documentation: Strategies.Master.Overview.md
Presets (Examples\Presets)ΒΆ
What: Multi-orchestrator combinations with adaptive logic based on market analysis.
User interaction: β Advanced usage - combine multiple strategies.
Purpose: Show how to:
- Chain multiple orchestrators
- Adaptive decision-making (volatility β strategy)
- Market condition analysis (simplified demo)
- Multi-phase trading sessions
- Performance tracking across phases
How to run:
Documentation: AdaptiveMarketModePreset.md
Examples (Examples)ΒΆ
What: Runnable examples demonstrating API usage at different layers.
User interaction: β Learning materials - run to understand APIs.
Examples\
βββ LowLevel\ β MT5Account examples (proto level)
β βββ Program.LowLevel.Positions.cs β Low-level position operations
β
βββ Service\ β MT5Service examples (wrapper level)
β βββ Program.Service.Positions.cs β Service layer positions demo
β
βββ Sugar\ β MT5Sugar examples (convenience level)
βββ Program.Sugar.MarketOrders.cs β Market orders demo
βββ Program.Sugar.PendingOrders.cs β Pending orders + retry logic demo
How to run:
dotnet run positions # Service layer positions
dotnet run market # Sugar market orders
dotnet run pendingorders # Sugar pending orders
Program.cs (Root)ΒΆ
What: Main entry point that routes dotnet run commands to appropriate examples/orchestrators/presets.
User interaction: π Runner + Documentation - launches everything.
Program.cs
βββ Main() β Entry point, parses args
βββ RouteCommand() β Maps aliases to runners
βββ RunOrchestrator() β Launches orchestrators
βββ RunPreset() β Launches presets
βββ RunExample() β Launches examples
βββ Header documentation β Complete command reference
How it works:
dotnet run grid
β
Program.cs Main(args) // args[0] = "grid"
β
RouteCommand("grid")
β
RunOrchestrator("grid")
β
GridTradingOrchestrator.RunAsync()
Purpose:
- Single entry point for all runnable code
- Command routing with aliases (grid, scalping, preset, etc.)
- Helpful error messages for unknown commands
- Ctrl+C handling for graceful shutdowns
Available commands: See header comment in Program.cs for complete list.
Helpers (Examples\Helpers)ΒΆ
What: Utility classes for examples and orchestrators.
Examples\Helpers\
βββ ConnectionHelper.cs β MT5 connection setup
βββ ProgressBarHelper.cs β Visual progress bars
ConnectionHelper:
// Build configuration from appsettings.json
var config = ConnectionHelper.BuildConfiguration();
// Create and connect to MT5
var account = await ConnectionHelper.CreateAndConnectAccountAsync(config);
var service = new MT5Service(account);
ProgressBarHelper:
// Visual countdown during orchestrator runtime
await ProgressBarHelper.ShowProgressBar(
durationSeconds: 60,
message: "Monitoring positions",
cancellationToken: cts.Token
);
π Documentation (docs)ΒΆ
What: Complete API and strategy documentation.
User interaction: π Read first! Comprehensive reference.
docs\
βββ index.md β β Homepage - project introduction
β
βββ Getting_Started.md β β Start here! Setup & first steps
β
βββ PROJECT_MAP.md β β This file - complete structure
β
βββ Glossary.md β β Terms and definitions
β
βββ MT5_For_Beginners.md β Creating demo account for testing
β
βββ Your_First_Project.ru.md β Your first project guide
β
βββ ReturnCodes_Reference_EN.md β Proto return codes reference
β
βββ UserCode_Sandbox_Guide.md β How to write custom strategies
β
βββ GRPC_STREAM_MANAGEMENT.md β Streaming subscriptions guide
β
βββ Sync_vs_Async.md β Async/sync patterns explained
β
βββ ProtobufInspector.README.EN.md β Protobuf inspector tool guide
β
βββ Strategies\ β Strategy documentation
β βββ Strategies.Master.Overview.md β β ALL orchestrators & presets
β βββ Orchestrators_EN\ β Individual orchestrator docs
β β βββ GridTradingOrchestrator.md
β β βββ GridTradingOrchestrator.HOW_IT_WORKS.md
β β βββ SimpleScalpingOrchestrator.md
β β βββ SimpleScalpingOrchestrator.HOW_IT_WORKS.md
β β βββ QuickHedgeOrchestrator.md
β β βββ QuickHedgeOrchestrator.HOW_IT_WORKS.md
β β βββ NewsStraddleOrchestrator.md
β β βββ NewsStraddleOrchestrator.HOW_IT_WORKS.md
β β βββ PendingBreakoutOrchestrator.md
β β βββ PendingBreakoutOrchestrator.HOW_IT_WORKS.md
β βββ Presets\
β βββ AdaptiveMarketModePreset.md
β
βββ API_Reference\ β API documentation
β βββ MT5Account.API.md β Layer 1 API reference
β βββ MT5Service.API.md β Layer 2 API reference
β βββ MT5Sugar.API.md β Layer 3 API reference
β
βββ MT5Account\ β Low-level proto API docs
β βββ MT5Account.Master.Overview.md β β Complete API reference
β βββ 1. Account_information\ β Account methods
β βββ 2. Symbol_information\ β Symbol/market data methods
β βββ 3. Position_Orders_Information\ β Position/order methods
β βββ 4. Trading_Operations\ β Trading execution methods
β βββ 5. Market_Depth(DOM)\ β Market depth methods
β βββ 6. Additional_Methods\ β Additional helpers
β βββ 7. Streaming_Methods\ β Real-time subscriptions
β
βββ MT5Service\ β Service layer method docs
β βββ MT5Service.Overview.md β β Complete Service API reference
β βββ Account_Convenience_Methods.md β Account helper methods
β βββ Symbol_Convenience_Methods.md β Symbol helper methods
β βββ Trading_Convenience_Methods.md β Trading helper methods
β βββ History_Convenience_Methods.md β History helper methods
β
βββ MT5Sugar\ β Sugar layer method docs
βββ MT5Sugar.API_Overview.md β β Complete Sugar API reference
βββ 1. Infrastructure\ β Core infrastructure methods
βββ 2. Snapshots\ β Account/Symbol snapshots
βββ 3. Normalization_Utils\ β Price/volume normalization
βββ 4. History_Helpers\ β History retrieval helpers
βββ 5. Streams_Helpers\ β Bounded streaming methods
βββ 6. Trading_Market_Pending\ β Market & pending orders
βββ 8. Volume_Price_Utils\ β Volume calculation & pricing
βββ 9. Pending_ByPoints\ β Pending orders by points
βββ 10. Market_ByRisk\ β Market orders by risk
βββ 11. Bulk_Convenience\ β Bulk operations (close/cancel all)
βββ 12. Market_Depth_DOM\ β Market depth (DOM) methods
βββ 13. Order_Validation\ β Pre-flight order validation
βββ 14. Session_Time\ β Trading session info
βββ 15. Position_Monitoring\ β Position monitoring & stats
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 every file
π gRPC & Proto (NuGet Dependencies)ΒΆ
What: Protocol Buffer and gRPC libraries for MT5 terminal communication.
User interaction: π Reference only - managed by NuGet.
Key NuGet packages:
Grpc.Net.Client- gRPC client libraryGoogle.Protobuf- Protocol Buffers runtimeGrpc.Tools- Proto compilation tools
How it works:
- NuGet restores packages on build
- Proto files compiled by Grpc.Tools (if present)
- Generated C# classes available for import
- MT5Account layer uses proto-generated types
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-facing)
ββ Orchestrators (strategy implementations)
ββ Presets (multi-strategy combinations)
ββ Examples (learning materials)
β
β uses
β
MT5Sugar (Layer 3 - Convenience)
ββ Auto-normalization
ββ Risk management
ββ Points-based methods
ββ Batch operations
β
β uses
β
MT5Service (Layer 2 - Wrappers)
ββ Direct data returns
ββ Type conversions
ββ Simplified signatures
β
β uses
β
MT5Account (Layer 1 - Low-level)
ββ Proto Request/Response
ββ gRPC communication
ββ Connection management
ββ Auto-reconnection
β
β gRPC
β
MT5 Gateway (mt5term) or MT5 Terminal
ββ MetaTrader 5 with gRPC server
π File Naming ConventionsΒΆ
Core API (Root Level)ΒΆ
MT5Account- Layer 1 (low-level gRPC, located inpackage/Helpers/MT5Account.cs)MT5Service.cs- Layer 2 (wrapper methods)MT5Sugar.cs- Layer 3 (convenience API)*ExceptionMT5.cs- Exception types
User Code (Examples)ΒΆ
*Orchestrator.cs- Single-strategy implementations*Preset.cs- Multi-strategy combinationsProgram.*.cs- Runnable examples at different layers*Helper.cs- Utility classes (ConnectionHelper, ProgressBarHelper)
Documentation (docs)ΒΆ
*.Master.Overview.md- Complete category overviews*.Overview.md- Section overviewsMethodName.md- Individual method documentation*.HOW_IT_WORKS.md- Algorithm explanations
π What to Modify vs What to Leave AloneΒΆ
β MODIFY (User Code)ΒΆ
Examples\Orchestrators\ β Copy and customize for your strategies
Examples\Presets\ β Create your own multi-strategy systems
Examples\LowLevel\ β Add your own low-level examples
Examples\Service\ β Add your own service examples
Examples\Sugar\ β Add your own sugar examples
Examples\Helpers\ β Add your own helper utilities
Config\appsettings.json β Configure for your MT5 terminal/gateway
Program.cs β Add new command routing if needed
README.md β Update with your changes
π READ (Core API)ΒΆ
package/Helpers/MT5Account.cs β Use but don't modify (import and call)
MT5Service.cs β Use but don't modify
MT5Sugar.cs β Use but don't modify
docs\ β Reference documentation
π LEAVE ALONE (Generated/Build)ΒΆ
package\ β NuGet package source (auto-generated by CI/CD)
bin\ β Compiled assemblies (auto-generated)
obj\ β Intermediate build files (auto-generated)
.vs\ β Visual Studio cache (auto-generated)
*.csproj.user β User-specific project settings
Note about package/ folder:
This folder contains decompiled source code from the NuGet package and is automatically generated by GitLab Runner during CI/CD builds. It includes:
package/Helpers/MT5Account.cs- Core gRPC layerpackage/Helpers/ApiExceptionMT5.cs,ConnectExceptionMT5.cs- Exception classes- Proto-generated files:
Mt5TermApiAccountHelper.cs,Mt5TermApiMarketInfo.cs,Mt5TermApiConnection.cs, etc. - gRPC client stubs:
Mt5-term-api-*Grpc.csfiles - Error types:
MrpcMt5Error.cs - Project files:
MetaRPC.MT5.csproj,MetaRPC.MT5.sln
β οΈ Do not manually modify files in package/ - changes will be overwritten on next CI/CD run. This folder is included in the repository for transparency and debugging purposes.
π― Project PhilosophyΒΆ
Goal: Make MT5 trading automation accessible through progressive complexity.
Three-tier design:
- Low-level (MT5Account): Full control, proto/gRPC
- Wrapper (MT5Service): Simplified method calls
- Convenience (MT5Sugar): Auto-everything, batteries included
User code:
- Orchestrators: Pre-built strategy templates
- Presets: Multi-strategy adaptive systems
- Examples: Learning materials at all layers
Start high (MT5Sugar), drop down only when needed.
π οΈ TroubleshootingΒΆ
Build IssuesΒΆ
# Clean and rebuild
dotnet clean
dotnet build
# Restore NuGet packages
dotnet restore
# Check .NET version
dotnet --version # Should be 8.0 or higher
Connection IssuesΒΆ
1. Check appsettings.json (host, port, credentials)
2. Verify MT5 terminal/gateway is running
3. Check firewall/antivirus isn't blocking port
4. Try different port if 5555 is in use
5. Check MT5 terminal logs for errors
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. Check broker allows your strategy type (hedging, etc.)
π Performance ConsiderationsΒΆ
Connection ManagementΒΆ
- Single gRPC connection shared across operations
- Built-in automatic 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 throughout for non-blocking I/O
- CancellationToken for graceful shutdowns
- Proper cleanup in finally blocks
π Best PracticesΒΆ
Code OrganizationΒΆ
β
DO: Separate concerns (analysis, execution, monitoring)
β
DO: Use async/await for all I/O operations
β
DO: Add comprehensive error handling
β
DO: Document your strategy logic clearly
β
DO: Use ProgressBarHelper for long-running operations
β DON'T: Mix strategy logic with API calls
β DON'T: Use Thread.Sleep (use await Task.Delay)
β 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 results
β
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 lot sizes 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, understand the code thoroughly, and implement proper risk management before considering live trading.
"Trade safe, code clean, and may your async operations always complete successfully."