Connect and disconnect
All members below belong to MT5API (namespace mtapi.mt5).
Constructors
MT5API(ulong user, string password, string host, int port)
Creates a client for one MT5 account. Nothing is sent yet. Call Connect next.
user: the MT5 login number.password: the account password (trading or investor).host,port: address of the broker's MT5 access server.- Throws: nothing at creation.
var api = new MT5API(12345678, "password", "broker.example.com", 443);
MT5API(ulong user, string password, string server, byte[] pfxFile = null, string pfxFilePassword = null)
Creates a client from the broker server name (for example "Broker-Server"). The library looks the name up and fills in the access addresses.
server: the broker server name as shown in MT5.pfxFile,pfxFilePassword: client certificate bytes and password, only if your broker requires one.- Throws:
ArgumentNullExceptionifserveris null.ServerNotFoundExceptionif the name cannot be resolved.
var api = new MT5API(12345678, "password", "Broker-Server");
MT5API(ulong user, string password, string host, int port, byte[] pfxFile = null, string pfxFilePassword = null)
Same as the host and port form, with an optional client certificate.
MT5API(ulong user, string password, string host, int port, string proxyHost, int proxyPort, string proxyUser, string proxyPassword, ProxyTypes type)
Creates a client that connects through a proxy. Sets ProxyEnable to true.
type:ProxyTypes.Https,Socks4orSocks5(Nonealso exists).
MT5API()
Creates an empty client. Set User, Password, Host and Port yourself before Connect.
Connecting
void Connect()
Logs in and loads the account, symbols and open positions. Blocks until done or until ConnectTimeout passes.
- Throws:
ServerException(wrong login or password:CodeisMsg.INVALID_ACCOUNTor similar),ConnectException(for exampleKazaTrade: no ApiKey setwhenapi.ApiKeyis not set, or local addresses blocked),OperationCanceledExceptionorTimeoutExceptionon timeout,ProxyExceptionfor proxy problems.
try { api.Connect(); }
catch (ServerException ex) { Console.WriteLine($"Login refused: {ex.Code}"); }Task ConnectAsync()
Task ConnectAsync(int timeoutMs)
Task ConnectAsync(CancellationToken cancellation)
Async forms of Connect. The first uses ConnectTimeout. Same errors as Connect.
void Disconnect()
Stops the connection and clears the loaded symbols. Call it when you are done. After Disconnect, use a new MT5API object or call Connect again.
bool Connected { get; }
True while the login is active and the socket is open.
event OnConnectProgress
See events.md.
Settings
Set these before Connect. They are public fields or properties.
| Name | Type | Default | Meaning |
|---|---|---|---|
ApiKey | string | empty | Your key. Copy it from your Developer page and set it before Connect. Empty means Connect fails. |
LoginIdWebServerTimeout | int ms | 10000 | Timeout for one call to the login service. |
ConnectTimeout | int ms | 30000 | Total time Connect may take. |
ConnectTimeoutForOneClusterMember | int ms | 20000 | Time for one broker access address before trying the next. |
UseConnectTask | bool | true | Use the task-based connect path. |
DisallowLocalConnections | bool | false | Refuse broker addresses that start with 192.168. or 10.. |
ExecutionTimeout | int ms | 30000 | How long OrderSend, OrderClose and OrderModify wait for the server. |
GetQuoteTimeoutMs | int ms | 10000 | Wait used by market watch and tick-value helpers. |
DownloadOrderHistoryTimeout | int ms | 30000 | Wait for a history download. |
ProcessEventTimeoutMs | int ms | 30000 | Time an event handler may run. |
NoServerMessagesTimeout | int ms | 30000 | Present, but this build does not read it. |
PlacedType | PlacedType | Default | Default "placed by" tag on your orders. |
ProxyEnable, ProxyHost, ProxyPort, ProxyUser, ProxyPassword, ProxyType | off | Proxy settings. The proxy constructor sets them. | |
OtpPassword | string | null | One-time password, if the account uses one. |
ProcessServerMessagesInThread | bool | false | Present, but this build does not read it. |
DisconnectOnSymbolUpdate | bool | false | Drop the link when the broker changes symbol settings (checked only after the first 30 seconds of a login). |
EnableAllOrderUpdates | bool | false | Also raise OnOrderUpdate for started, filled and cancelling steps. |
User, Password, Host, Port | from constructor | Login details. | |
PfxFile, PfxFilePassword | byte[], string | null | Client certificate. |
api.ConnectTimeout = 45000;
Server and cluster information
ServerRec ClusterSummary { get; }
Name and company of the broker server, plus its time zone (TimeZone in minutes, DST in hours). Null before the server is known.
Dictionary<AccessInfo, AddressRec[]> ClusterMembers { get; }
The access servers of the broker cluster. Null before the server is known.
ClusterDetails ClusterDetails()
Returns the cluster as General (a ServerRec) and Servers (name to addresses). Returns null when unknown.
DateTime ServerTime { get; }
The current time on the broker server, worked out from the server's time zone.
int ServerTimeZoneInMinutes { get; }
Server offset from UTC in minutes, including daylight saving.
short ServerBuild { get; }
MT5 server build number.
- Throws:
ConnectExceptionif not connected.
DateTime ConnectTime { get; }
When the current login finished.
DateTime LastServerMessageTime
When the last message came from the server.
long BytesReceived { get; }
Bytes received from the broker on this login. Zero when not connected.
static int PingHost(string host, int port = 443)
Opens a TCP connection to host:port and returns a rough number. Use it only to compare addresses with each other; it is not an exact round trip time in milliseconds.
- Throws:
SocketExceptionif the host cannot be reached.
Broker server list files
static Server[] LoadServersDat(string path)
static Server[] LoadServersDat(byte[] bytes)
Reads an MT5 servers.dat file and returns its servers.
static byte[] SaveServersDat(Server[] servers)
Writes servers back to servers.dat format.