Skip to content

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:

MT5Sugar β†’ uses β†’ MT5Service β†’ uses β†’ MT5Account β†’ gRPC β†’ MT5 Terminal

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:

  1. Study existing orchestrators
  2. Copy one as template
  3. Modify for your strategy
  4. 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.

Examples\Presets\
└── AdaptiveMarketModePreset.cs    ← Intelligent multi-strategy system

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:

dotnet run preset       # AdaptiveMarketModePreset
dotnet run adaptive     # Same as above

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 .md file with examples
  • Overview files (*.Master.Overview.md) provide navigation
  • HOW_IT_WORKS.md files 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 library
  • Google.Protobuf - Protocol Buffers runtime
  • Grpc.Tools - Proto compilation tools

How it works:

  1. NuGet restores packages on build
  2. Proto files compiled by Grpc.Tools (if present)
  3. Generated C# classes available for import
  4. 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 in package/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 combinations
  • Program.*.cs - Runnable examples at different layers
  • *Helper.cs - Utility classes (ConnectionHelper, ProgressBarHelper)

Documentation (docs)ΒΆ

  • *.Master.Overview.md - Complete category overviews
  • *.Overview.md - Section overviews
  • MethodName.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 layer
  • package/Helpers/ApiExceptionMT5.cs, ConnectExceptionMT5.cs - Exception classes
  • Proto-generated files: Mt5TermApiAccountHelper.cs, Mt5TermApiMarketInfo.cs, Mt5TermApiConnection.cs, etc.
  • gRPC client stubs: Mt5-term-api-*Grpc.cs files
  • 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:

  1. Low-level (MT5Account): Full control, proto/gRPC
  2. Wrapper (MT5Service): Simplified method calls
  3. 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."