MtApi Documentation
repository·master·Indexed 20 days ago
https://github.com/vdemydiuk/mtapiA .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.
What's inside MtApi
- 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.
MTInterface Project Overview
masterMTInterface is a Dynamic Link Library (DLL) project generated by AppWizard. The project is structured as a VC++ project containing the core logic for the
MTConnectorcomponent.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.How MtMonitorBase and IMonitorTrigger work together
masterMonitors in
mtapiare used to observe changes in MT4 structs. To create a monitor, you must inherit fromMtMonitorBase, which requires an instance ofMtApiClientand anIMonitorTrigger.The SyncTrigger Concept
When instantiating a monitor, you can set the
SyncTriggerflag (via constructor or property).- If
SyncTriggeristrue: CallingStart()orStop()on the monitor will automatically callStart()orStop()on the underlyingIMonitorTrigger. - Warning: If multiple monitors share the same
IMonitorTriggerinstance, settingSyncTriggertotrueon one of them will stop the trigger for all monitors sharing it.
IMonitorTrigger
An
IMonitorTriggerdefines 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 specifiedTimeSpanhas 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.- If
Data handling limitations in JSONlab
masterWhen 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
saveubjsonfunction currently converts logical arrays intouint8([U]) arrays. - UBJSON Support:
saveubjsondoes 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')
How logging levels and outputs work
masterThe
logging4matlabmodule 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 apathhas been provided viagetLoggerorsetFileName. - Log Format: Every log entry follows the pattern:
[CallerName] [Timestamp] [Level] [Message]. The timestamp format isYYYY-MM-DD HH:MM:SS,mmmby default.
- Command Window Output: Controlled by
Work with Universal Binary JSON (UBJSON)
masterJSONlab 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)orsaveubjson(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:1to represent arrays as structs with metadata (supports sparse and complex arrays).opt.ParseLogical:1to usetrue/falsefor logical elements.opt.ForceRootName:1to 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');- Encoding: Use
Modify MQL Expert Advisor (EA) source code
masterIf 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
Includefolder:hash.mqhjson.mqh
Typical MetaEditor include path:
C:\Users\<username>\AppData\Roaming\MetaQuotes\Terminal\<terminal-hash>\MQL5\Include\Set up Slack notifications in Matlab
masterTo use these functions, you must first configure a Slack Incoming Webhook for your team.
- Create the integration via Slack's services page and copy the generated Webhook URL.
- Clone the
SlackMatlabrepository. - Add the repository's root directory to your Matlab path using the
pathtoolcommand. - Use the Webhook URL as a string argument when calling
SendSlackNotification.
Get support for JSONlab via the iso2mesh mailing list
masterIf you have questions or suggestions regarding JSONlab, you can report them via the iso2mesh mailing list:
http://groups.google.com/group/iso2mesh-users?hl=en&pli=1
Note: You must subscribe to the mailing list in order to post messages.
Contribute to JSONlab via Subversion
masterJSONlab is an open-source project. To contribute changes, follow these steps:
- Download the source code using the Subversion repository:
svn checkout svn://svn.code.sf.net/p/iso2mesh/code/trunk/jsonlab jsonlab - Make your changes to the files.
- Generate a patch file from the root directory of JSONlab:
svn diff > yourname_featurename.patch - Submit your patch by emailing the
.patchfile to the maintainer, Qianqian Fang.
svn checkout svn://svn.code.sf.net/p/iso2mesh/code/trunk/jsonlab jsonlab svn diff > yourname_featurename.patch- Download the source code using the Subversion repository:
Build MtApi for MT4 or MT5
masterTo build the solution using Visual Studio 2022 and .NET 8, follow the configuration requirements for your target platform:
For MT4
- Set the build configuration to
x86. - Build the
MtApiInstallerproject. This will automatically buildMtApi,MtClient,MtService, andMTConnector.
For MT5
- Set the build configuration to
x64(orx86for 32-bit MT5). - Build the
MtApi5Installerproject. This will automatically buildMtApi5,MtClient,MtService, andMT5Connector.
Output Locations
- Binaries:
../build/ - Installers (*.msi):
../build/installers/ - DLL Libraries (*.dll):
../bin/ - Pre-compiled MQL files (*.ex4):
.. ql4\or.. ql5\
- Set the build configuration to
Install JSONlab in MATLAB or Octave
masterTo 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 thepathtoolcommand, browse to the JSONlab root folder, add it, and save. Finally, runrehashto 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