MtApi Documentation

repository·master·Indexed 20 days ago

https://github.com/vdemydiuk/mtapi

A .NET bridge for MetaTrader (MT4/MT5) that enables C# applications to execute MQL commands and receive trading events via WebSockets. It provides a WebSocket framework for local and remote connections, duplicating standard MQL interfaces. The library includes monitoring tools like ModifiedOrdersMonitor and TradeMonitor, as well as support for MT4 (x86) and MT5 (x64) platforms.

Tokens
7.5K
Snippets
16
Records
26
Agent score
72%

What's inside MtApi

  1. What is MtApi

    master
    MtApi is a .NET API that acts as a bridge between MetaTrader (MetaQuotes) terminals and .NET applications. It does not connect to MT servers directly; instead, it executes MQL commands and functions via an MtApi Expert Advisor (EA) linked to a MetaTrader chart. The project uses a WebSocket framework to provide flexible connections, supporting both local and remote (via TCP) connection types. Most API functions duplicate the standard MQL interface.
  2. MTInterface Project Overview

    master

    MTInterface is a Dynamic Link Library (DLL) project generated by AppWizard. The project is structured as a VC++ project containing the core logic for the MTConnector component.

    Key files in the project include:

    • MTConnector.cpp: The primary source file for the DLL implementation.
    • MTConnector.h: The header file containing the class declarations.
    • MTConnector.vcxproj: The main Visual C++ project file defining platforms, configurations, and features.
    • AssemblyInfo.cpp: Used for defining custom assembly metadata attributes.

    Note for Developers: When reviewing the generated source code, look for TODO: comments. These markers indicate specific locations where you are expected to add custom logic or customize the implementation to meet your requirements.

  3. How MtMonitorBase and IMonitorTrigger work together

    master

    Monitors in mtapi are used to observe changes in MT4 structs. To create a monitor, you must inherit from MtMonitorBase, which requires an instance of MtApiClient and an IMonitorTrigger.

    The SyncTrigger Concept

    When instantiating a monitor, you can set the SyncTrigger flag (via constructor or property).

    • If SyncTrigger is true: Calling Start() or Stop() on the monitor will automatically call Start() or Stop() on the underlying IMonitorTrigger.
    • Warning: If multiple monitors share the same IMonitorTrigger instance, setting SyncTrigger to true on one of them will stop the trigger for all monitors sharing it.

    IMonitorTrigger

    An IMonitorTrigger defines the frequency or condition under which the monitor checks if its criteria are met. Available built-in triggers include:

    • NewBarTrigger: Triggers when a new bar starts.
    • TimeElapsedTrigger: Triggers after a specified TimeSpan has elapsed.
    var fooTrigger = new FooTrigger();
    var fooMonitor = new FooMonitor(apiClient, fooTrigger, true);
    var barMonitor = new FooMonitor(apiClient, fooTrigger, false);
    
    fooTrigger.Start();
    barMonitor.Start();
    fooMonitor.Start();
    
    fooMonitor.Stop(); // Because SyncTrigger = true, fooTrigger.Stop() is called, which also stops barMonitor.
  4. Data handling limitations in JSONlab

    master

    When using JSONlab for data serialization and processing, be aware of the following behavioral constraints:

    • Dimensionality: 3D or higher dimensional cell/struct-arrays are automatically converted to 2D arrays.
    • Classes: The library cannot handle MATLAB classes.
    • Logical Arrays: The saveubjson function currently converts logical arrays into uint8 ([U]) arrays.
    • UBJSON Support: saveubjson does not yet support arbitrary data ([H] in the UBJSON specification).
    • Character Encoding: When processing names with multi-byte characters, MATLAB and Octave may produce different field names. To achieve consistent results in MATLAB, use: feature('DefaultCharacterSet','latin1')
  5. How logging levels and outputs work

    master

    The logging4matlab module allows for independent control over two output streams: the Command Window (terminal) and a Log File.

    • Command Window Output: Controlled by commandWindowLevel. If a message's level is lower than this threshold, it will not appear in the terminal.
    • File Output: Controlled by logLevel. If a message's level is lower than this threshold, it will not be written to the file. File logging is only active if a path has been provided via getLogger or setFileName.
    • Log Format: Every log entry follows the pattern: [CallerName] [Timestamp] [Level] [Message]. The timestamp format is YYYY-MM-DD HH:MM:SS,mmm by default.
  6. Work with Universal Binary JSON (UBJSON)

    master

    JSONlab supports UBJSON, a binary format optimized for compact size and performance, especially for large datasets containing complex binary data. This avoids accuracy loss during text conversion.

    • Encoding: Use saveubjson(rootname, obj, filename) or saveubjson(rootname, obj, opt) to convert MATLAB objects to UBJSON.
    • Decoding: Use loadubjson(fname, opt) to parse a UBJSON file or string into MATLAB structures.

    Common Options for UBJSON:

    • opt.ArrayToStruct: 1 to represent arrays as structs with metadata (supports sparse and complex arrays).
    • opt.ParseLogical: 1 to use true/false for logical elements.
    • opt.ForceRootName: 1 to use the variable name as the root object name.
    a = struct('node', [1 9 10; 2 1 1.2], 'elem', [9 1; 1 2; 2 3], 'face', [9 01 2; 1 2 3; NaN, Inf, -Inf], 'author', 'FangQ');
    
    % Save to UBJSON file
    saveubjson('mesh', a, 'meshdata.ubj');
    
    % Load UBJSON file
    data = loadubjson('meshdata.ubj');
  7. Modify MQL Expert Advisor (EA) source code

    master

    If you need to change the source code of the MQL Expert Advisor, you must recompile it using MetaEditor.

    Before recompiling, you must place the following MQL library files into your MetaEditor Include folder:

    • hash.mqh
    • json.mqh

    Typical MetaEditor include path: C:\Users\<username>\AppData\Roaming\MetaQuotes\Terminal\<terminal-hash>\MQL5\Include\

  8. Contribute to JSONlab via Subversion

    master

    JSONlab is an open-source project. To contribute changes, follow these steps:

    1. Download the source code using the Subversion repository:
      svn checkout svn://svn.code.sf.net/p/iso2mesh/code/trunk/jsonlab jsonlab
    2. Make your changes to the files.
    3. Generate a patch file from the root directory of JSONlab:
      svn diff > yourname_featurename.patch
    4. Submit your patch by emailing the .patch file to the maintainer, Qianqian Fang.
    svn checkout svn://svn.code.sf.net/p/iso2mesh/code/trunk/jsonlab jsonlab
    svn diff > yourname_featurename.patch
  9. Build MtApi for MT4 or MT5

    master

    To build the solution using Visual Studio 2022 and .NET 8, follow the configuration requirements for your target platform:

    For MT4

    1. Set the build configuration to x86.
    2. Build the MtApiInstaller project. This will automatically build MtApi, MtClient, MtService, and MTConnector.

    For MT5

    1. Set the build configuration to x64 (or x86 for 32-bit MT5).
    2. Build the MtApi5Installer project. This will automatically build MtApi5, MtClient, MtService, and MT5Connector.

    Output Locations

    • Binaries: ../build/
    • Installers (*.msi): ../build/installers/
    • DLL Libraries (*.dll): ../bin/
    • Pre-compiled MQL files (*.ex4): .. ql4\ or .. ql5\
  10. Install JSONlab in MATLAB or Octave

    master

    To install JSONlab, download or unzip the package to a local folder and add that folder to your MATLAB or Octave path.

    To add the path temporarily for the current session, use addpath. To make it permanent, use the pathtool command, browse to the JSONlab root folder, add it, and save. Finally, run rehash to update the function list.

    To verify the installation, run which loadjson. If it returns a file path, the installation was successful.

    % Temporary path addition
    addpath('/path/to/jsonlab');
    
    % Verify installation
    rehash;
    which loadjson