Introduction
MTsocketAPI is a full-featured expert advisor for Metatrader 5 platform (Metatrader 4 here).
Features:
- Stream tick data or OHLC data (with your selected timeframe) in your custom script or application.
- Send market, limit or stop orders, from your custom script or application.
- Retrieve information from symbols, MT5 accounts, MT5 terminal…
- Retrieve data from indicators like Moving Average, RSI…
- Retrieve trade history (you can export the data to CSV).
- And much more…
Installation
Follow the next steps to install MTsocketAPI in your Metatrader application:
First, you must download our API from here
Open you Metatrader application and go to File > Open Data Folder:
You will see something like this:
Then go to MQL5 > Experts folder and paste here the file MTsocketAPI.ex5 downloaded previously.
To load the new Expert Advisor you must restart the Metatrader application.
After the restart, you can see MTsocketAPI in the Expert Advisors folder:
That’s it!
It was successfully installed!
Run the MTsocketsAPI Expert Advisor
After install the MTsocketAPI.ex5 file (detailed instuctions here) we need start the API to enable the communication between Metratrader 5 and any tcp client.
There are 2 ways of run the MTsocketAPI Expert Advisor:
- Double click MTsocketAPI from the Experts box
- Drag and drop MTsocketAPI to any chart
Any of these two method will launch a screen like this:
Enable “Allow Algo Trading” and then click on the Dependencies tab:
Note: MTsocketAPI needs the ws2_32.dll to work with sockets.
And finally, click OK to start MTsocketAPI.
Important: You must click the “Algo Trading” button to enable MTsocketAPI to work with orders:
If you only use MTsocketAPI to read data you don’t need to enable “Algo Trading”
Note: To make sure that MTsocketAPI started successfully, you can check the Metatrader 5 Experts tab:
Basic Usage with TELNET
MTsocketAPI opens two TCP ports by default:
- TCP 77 (Commands): You can use this port for send commands and receive MTsocketAPI replies.
- TCP 78 (Data): You can use this port to receive tick prices or OHLC prices for the selected Timeframe
Note: You can connect multiple clients to TCP 78 (data) port
You can use any tool, script or application to start sending commands. For example:
- Telnet command
- PuTTY or any other telnet tool
- Java
- .NET Core / .NET Framework / PowerShell
- Python
- C / C++
- NodeJS
- R
- Any software that can use sockets (TCP)
You can connect to default port TCP/77 to start sending queries to MTsocketAPI using TELNET:
telnet localhost 77
Then paste the following code:
{"MSG": "HELP"}
And finally hit Enter and you will get a list of available commands:
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
{"MSG":"HELP"}
{"MSG":"HELP","AVAILABLE_COMMANDS":["TRACK_PRICES","TRACK_OHLC","CUSTOM_INDICATOR","MA_INDICATOR","ATR_INDICATOR","SYMBOL_INFO","SYMBOL_LIST","TERMINAL_INFO","ACCOUNT_STATUS","QUOTE","ORDER_SEND","ORDER_MODIFY","ORDER_CLOSE","ORDER_LIST","TRADE_HISTORY","EXIT"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
If you want to get more information about each command:
{"MSG": "HELP","COMMAND":"QUOTE"}
Reply:
{
"MSG":"HELP",
"COMMAND":"QUOTE",
"DESCRIPTION":"Get Quote from a SYMBOL",
"MANDATORY_TAGS":["SYMBOL (String)"],
"OPTIONAL_TAGS":[null],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
We can see that the command QUOTE has a mandatory tag named SYMBOL and this tag accepts strings only.
Let’s see an example:
Example 1: Get Price from a symbol
If we want to view the current EUR/USD price:
{"MSG": "QUOTE", "SYMBOL": "EURUSD"}
Important: Please check with your broker that the symbol name exists. Some brokers use EURUSD, EURUSD.fx, EUR/USD… You can see the symbols names using SYMBOL_LIST command.
Reply:
{
"MSG":"QUOTE",
"SYMBOL":"EURUSD",
"ASK":0.99739,
"BID":0.99736,
"FLAGS":2,
"TIME":"2022.04.11 12:15:31.0",
"VOLUME":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
Note: You can also subscribe to one or more symbols and MTsocketAPI will start streaming tick (TRACK_PRICES command) or OHLC (TRACK_OHLC command) data over the port TCP 78 (data). See the following Examples.
Example 2: Send new Order
You want to place a 0.01 lots Buy Order (at market) on EURUSD:
{"MSG": "ORDER_SEND","SYMBOL": "EURUSD","TYPE":"ORDER_TYPE_BUY","VOLUME": 0.01}
Reply:
{
"MSG":"ORDER_SEND",
"COMMENT":"Request executed",
"DEAL":"2008856776",
"ORDER":"2012142352",
"PRICE":0.99746000,
"REQUEST_ID":"1",
"RETCODE":"10009",
"RETCODE_EXTERNAL":0,
"VOLUME":0.01000000,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
As you can see, we received the ticket number assigned to our order.
Note: SEND_ORDER command accepts limit orders, SL, TP… Please check the documentation here.
Example 3: Close Orders
Now if we want to close our newly created order:
{"MSG": "ORDER_CLOSE", "TICKET": 2012142352}
And this is the reply:
{
"MSG":"ORDER_CLOSE",
"TICKET":2012142352,
"TYPE":"FULLY_CLOSED",
"VOLUME":0.01,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Example 4: Get Order History
Finally, let’s check the closed price and profit for this order:
{"MSG":"TRADE_HISTORY","FROM_DATE":"2022/09/19 09:20:00", "TO_DATE":"2022/09/19 16:30:00", "MODE":"POSITIONS"}
Note: You can use any date format accepted by MT5. More info.
Reply:
{
"MSG":"TRADE_HISTORY",
"POSITIONS":[
{
"OPEN_TIME":"2022.09.19 12:49:05.146",
"SYMBOL":"EURUSD",
"TICKET":2012142352,
"TYPE":"BUY",
"VOLUME":0.01,
"PRICE_OPEN":0.99746000,
"MAGIC":0,
"COMMENT":null,
"CLOSE_TIME":"2022.09.19 12:50:22.145",
"PRICE_CLOSE":0.99718000,
"PROFIT":-0.28,
"COMMISSION":-0.06,
"SWAP":0.00,
"SL":0.00000,
"TP":0.00000
}
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Now we disconnect from MTsocketAPI softly:
{"MSG": "EXIT"}
Reply:
Bye
Here you can see the Full API Command List
Advanced MTsocketAPI Configuration
MTsocketAPI listens on ports:
- TCP 77 (Commands)
- TCP 78 (Data)
We can change these ports used by MTsocketAPI using the Input tab:
If we have multiple Metatrader 5 applications running on the same machine we will need to use different ports.
For example, if we have 4 Metatrader applications running in the same machine we can use the following ports:
MT5 (1) | MT5 (2) | MT5 (3) | MT5 (4) | |
---|---|---|---|---|
Command TCP Port | 71 | 73 | 75 | 77 |
Data TCP Port | 72 | 74 | 76 | 78 |
Note: Always check in the Expert tab if the new selected ports were opened successfully:
The Account Precision Digits variable is used to show the account balance, etc with this number of digits. Don’t change this value if you are not sure about the implications.
License Installation
MTsocketAPI is freely to use for demo accounts only. If you want to use the API for trading with live accounts you must purchase a license. To undestand the licensing options click here.
After the license purchase, the user only need to copy the license file to the Files folder and restart the Metatrader application to unlock the features purchased.
License Installation Steps
First, go to File -> Open Data Folder
Then, browse to MQL5 -> Files and paste here the file License.txt
Finally, restart the Metratrader application.
MTsocketAPI Version History
5.38
February 25, 2025
Fixed an issue with the CHANGE field.
5.37
January 09, 2025
Added SYMBOL_INFO command and “ASYNC” tag added to ORDER_SEND, ORDER_MODIFY and ORDER_CLOSE commands.
5.36
November 29, 2024
Added ‘change’ field to ORDER_LIST and TRADE_HISTORY commands. Furthermore, when the TRADE_HISTORY command is in POSITIONS mode, only closed positions will be displayed.
5.35
August 27, 2024
Fixed an issue when managing charts and using the API at the same time.
5.34
August 19, 2024
Improved SESSION_QUOTE and SESSION_TRADE tags from the SYMBOL_INFO command.
5.33
July 11, 2024
Added TRACK_MBOOK command.
5.32
July 9, 2024
License update for allowing brokers with incorrect tag identification.
5.31
July 3, 2024
Added SESSION_QUOTE and SESSION_TRADE tags to the SYMBOL_INFO command.
5.30
June 11, 2024
Updated TRACK_OHLC command to stream multiple symbols with different timeframes.
5.29
June 3, 2024
QUOTE command adds symbol to watch list automatically.
5.28
May 17, 2024
Added InstitutionalPlus licensing.
5.27
May 3, 2024
Added CALENDAR_LIST command.
5.26
March 6, 2024
Added more checks on json input data to avoid accepting malformed json messages.
5.25
February 26, 2024
The MTsocketAPI license can use used on demo accounts with the same enabled features.
5.24
February 21, 2024
Fixed licensing issue with some broker accounts.
5.23
February 12, 2024
Improved licensing for Institutional clients.
5.22
January 30, 2024
Fixed licensing issue with some clients running demo accounts.
5.21
January 5, 2024
Added TYPE tag to the commands ORDER_SEND, ORDER_MODIFY and ORDER_CLOSE.
5.20
December 14, 2023
Updated TIME -> OPEN_TIME tag when retrieving ORDER_LIST json data.
5.19
November 29, 2023
Fixed a small bug with the ResetLastError() function.
5.18
November 16, 2023
Update TYPE tag using the ORDER_LIST command.
5.17
November 14, 2023
Added more information when the terminal application is not configured properly.
5.16
September 25, 2023
Fixed type inconsistency between ORDER_SEND and ORDER_CLOSE.
5.15
September 22, 2023
Fixed performance issue when sending bulk json messages.
5.14
September 21, 2023
Added more information when the order is closed.
5.13
September 20, 2023
Code improvements.
5.12
September 20, 2023
Fixed symbol contract size.
5.11
September 20, 2023
Fixed “incorrect filling type” error with some brokers.
5.10
September 11, 2023
Performance improvement using events.
MTsocketAPI Commands
MTsocketAPI accepts commands on port TCP 77. We can use any programming language or a tool like PuTTY to start sending commands.
Important: You must send JSON commands in a single line like this:
{"MSG":"HELP"}
and the result will be returned in a single line:
{"MSG":"HELP","AVAILABLE_COMMANDS":["ACCOUNT_STATUS","ATR_INDICATOR","CUSTOM_INDICATOR","EXIT","MA_INDICATOR","ORDER_SEND","ORDER_MODIFY","ORDER_CLOSE","ORDER_LIST","PRICE_HISTORY","QUOTE","SYMBOL_INFO","SYMBOL_LIST","TERMINAL_INFO","TRACK_OHLC","TRACK_PRICES","TRADE_HISTORY"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error","DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"}
Note: In the documentation, we will show JSON messages with the beauty format applied in order to facilitate the clear presentation of the information.
Note: Every reply from the API will include the tags ERROR_ID and ERROR_DESCRIPTION. If ERROR_ID = 0 we are sure that the command was processed correctly by Metatrader but if ERROR_ID is not 0 then the ERROR_DESCRIPTION tag will include information about the error.
Available commands:
- HELP
- ACCOUNT_STATUS
- ATR_INDICATOR
- CALENDAR_LIST
- CUSTOM_INDICATOR
- EXIT
- MA_INDICATOR
- ORDER_SEND
- ORDER_MODIFY
- ORDER_CLOSE
- ORDER_LIST
- PRICE_HISTORY
- QUOTE
- SYMBOL_INFO
- SYMBOL_LIST
- TERMINAL_INFO
- TRACK_MBOOK
- TRACK_PRICES
- TRACK_OHLC
- TRACK_TRADE_EVENTS
- TRADE_HISTORY
HELP Command
Single Line command (necessary for MTsocketAPI):
Example:
{"MSG":"HELP"}
Same command in Beauty Format:
{
"MSG":"HELP"
}
MTsocketAPI reply:
{
"MSG":"HELP",
"AVAILABLE_COMMANDS":[
"TRACK_PRICES",
"TRACK_OHLC",
"CUSTOM_INDICATOR",
"MA_INDICATOR",
"ATR_INDICATOR",
"SYMBOL_INFO",
"SYMBOL_LIST",
"TERMINAL_INFO",
"ACCOUNT_STATUS",
"QUOTE",
"ORDER_SEND",
"ORDER_MODIFY",
"ORDER_CLOSE",
"OPENED_POSITIONS",
"TRADE_HISTORY",
"EXIT"
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
To get information for the command SYMBOL_INFO:
{"MSG":"HELP","COMMAND": "SYMBOL_INFO"}
Same command in beauty format:
{
"MSG":"HELP",
"COMMAND": "SYMBOL_INFO"
}
MTsocketAPI reply:
{
"MSG":"HELP",
"COMMAND":"SYMBOL_INFO",
"DESCRIPTION":"Get information from the requested SYMBOL",
"MANDATORY_TAGS":["SYMBOL (String)"],
"OPTIONAL_TAGS":[null],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
Important: You must always send JSON commands in a single line like this:
{"MSG":"HELP"}
ACCOUNT_STATUS Command
Get account information
Help:
{ "MSG":"HELP", "COMMAND":"ACCOUNT_STATUS", "DESCRIPTION":"Get the current account status", "MANDATORY_TAGS":[null], "OPTIONAL_TAGS":[null] }
Example:
Single Line command (necessary for MTsocketAPI):
{"MSG":"ACCOUNT_STATUS"}
Same command in Beauty Format:
{
"MSG":"ACCOUNT_STATUS"
}
MTsocketAPI reply:
{
"MSG":"ACCOUNT_STATUS",
"COMPANY":"Any Company",
"CURRENCY":"EUR",
"NAME":"Any Name",
"SERVER":"AnyServer-Demo",
"LOGIN":123456789,
"TRADE_MODE":0,
"LEVERAGE":200,
"LIMIT_ORDERS":400,
"MARGIN_SO_MODE":0,
"TRADE_ALLOWED":1,
"TRADE_EXPERT":1,
"BALANCE":10013.69,
"CREDIT":0.00,
"PROFIT":0.00,
"EQUITY":10013.69,
"MARGIN":0.00,
"MARGIN_FREE":10013.69,
"MARGIN_LEVEL":0.00,
"MARGIN_SO_CAL":100.00,
"MARGIN_SO_SO":50.00,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully",
"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"
}
ATR_INDICATOR Command
Get data from a the ATR indicator using the iATR function
Help:
{ "MSG":"HELP", "COMMAND":"ATR_INDICATOR", "DESCRIPTION":"Get data from a the ATR indicator using the iATR function", "MANDATORY_TAGS":[ "SYMBOL (String)", "TIMEFRAME (String)", "PERIOD (Integer)", "SHIFT (Integer)" ], "OPTIONAL_TAGS":[null] }
Example:
Single Line command (necessary for MTsocketAPI):
{"MSG":"ATR_INDICATOR", "SYMBOL":"EURUSD", "TIMEFRAME":"PERIOD_M1", "PERIOD":14}
Same command in Beauty Format:
{
"MSG":"ATR_INDICATOR",
"SYMBOL":"EURUSD",
"TIMEFRAME":"PERIOD_M1",
"PERIOD":14
}
MTsocketAPI reply:
{
"MSG":"ATR_INDICATOR",
"DATA_VALUES":[
0.000215
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully",
"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"
}
Note: We can retrieve the last X values using the NUM tag.
CALENDAR_LIST Command
Get calendar events
Help:
{ "MSG":"HELP", "COMMAND":"CALENDAR_LIST", "DESCRIPTION":"Receive calendar events", "MANDATORY_TAGS":[ "FROM_DATE (String)", "TO_DATE (String)" ], "OPTIONAL_TAGS":[ "CURRENCY (String)", "COUNTRY_CODE (String)" ], "ERROR_ID":0, "ERROR_DESCRIPTION":"The operation completed successfully" }
Note:
CURRENCY (String): Country currency code name. “EUR”, “USD” and so on.
COUNTRY_CODE (String): Country code name (ISO 3166-1 alpha-2). “US”, “FR” and so on.
Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"CALENDAR_LIST","FROM_DATE":"2024.05.03","TO_DATE":"2024.05.04","CURRENCY":"USD"}
Same command in Beauty Format:
{
"MSG":"CALENDAR_LIST",
"FROM_DATE":"2024.05.03",
"TO_DATE":"2024.05.04",
"CURRENCY":"USD"
}
MTsocketAPI reply:
{
"MSG":"CALENDAR_LIST",
"EVENTS":[
{
"TIME":"2024.05.03 15:30:00",
"EVENT_COUNTRY_ID":840,
"EVENT_DIGITS":1,
"EVENT_CODE":"unemployment-rate",
"EVENT_FREQUENCY":"CALENDAR_FREQUENCY_MONTH",
"EVENT_ID":840030015,
"EVENT_IMPORTANCE":"CALENDAR_IMPORTANCE_MODERATE",
"EVENT_MULTIPLIER":"CALENDAR_MULTIPLIER_NONE",
"EVENT_NAME":"Unemployment Rate",
"EVENT_SECTOR":"CALENDAR_SECTOR_JOBS",
"EVENT_SOURCE_URL":"https:\/\/www.bls.gov",
"EVENT_TIME_MODE":"CALENDAR_TIMEMODE_DATETIME",
"EVENT_TYPE":"CALENDAR_TYPE_INDICATOR",
"EVENT_UNIT":"CALENDAR_UNIT_PERCENT",
"ACTUAL_VALUE":3.9000,
"FORECAST_VALUE":3.7000,
"PREVIOUS_VALUE":3.8000,
"IMPACT_TYPE":"CALENDAR_UNIT_CURRENCY",
"REVISION":0,
"PERIOD":"2024.04.01 00:00:00"
},
{
"TIME":"2024.05.03 15:30:00",
"EVENT_COUNTRY_ID":840,
"EVENT_DIGITS":0,
"EVENT_CODE":"nonfarm-payrolls",
"EVENT_FREQUENCY":"CALENDAR_FREQUENCY_MONTH",
"EVENT_ID":840030016,
"EVENT_IMPORTANCE":"CALENDAR_IMPORTANCE_HIGH",
"EVENT_MULTIPLIER":"CALENDAR_MULTIPLIER_THOUSANDS",
"EVENT_NAME":"Nonfarm Payrolls",
"EVENT_SECTOR":"CALENDAR_SECTOR_JOBS",
"EVENT_SOURCE_URL":"https:\/\/www.bls.gov",
"EVENT_TIME_MODE":"CALENDAR_TIMEMODE_DATETIME",
"EVENT_TYPE":"CALENDAR_TYPE_INDICATOR",
"EVENT_UNIT":"CALENDAR_UNIT_JOB",
"ACTUAL_VALUE":175.0000,
"FORECAST_VALUE":197.0000,
"PREVIOUS_VALUE":303.0000,
"REVISED_VALUE":315.0000,
"IMPACT_TYPE":"CALENDAR_UNIT_CURRENCY",
"REVISION":0,
"PERIOD":"2024.04.01 00:00:00"
},
...
{
"TIME":"2024.05.03 22:30:00",
"EVENT_COUNTRY_ID":840,
"EVENT_DIGITS":1,
"EVENT_CODE":"cftc-nasdaq-100-non-commercial-net-positions",
"EVENT_FREQUENCY":"CALENDAR_FREQUENCY_WEEK",
"EVENT_ID":840520011,
"EVENT_IMPORTANCE":"CALENDAR_IMPORTANCE_LOW",
"EVENT_MULTIPLIER":"CALENDAR_MULTIPLIER_THOUSANDS",
"EVENT_NAME":"CFTC Nasdaq 100 Non-Commercial Net Positions",
"EVENT_SECTOR":"CALENDAR_SECTOR_MARKET",
"EVENT_SOURCE_URL":"https:\/\/www.cftc.gov\/",
"EVENT_TIME_MODE":"CALENDAR_TIMEMODE_DATETIME",
"EVENT_TYPE":"CALENDAR_TYPE_INDICATOR",
"EVENT_UNIT":"CALENDAR_UNIT_POSITION",
"PREVIOUS_VALUE":6.1000,
"IMPACT_TYPE":"CALENDAR_UNIT_NONE",
"REVISION":0,
"PERIOD":"2024.04.30 00:00:00"
}
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
CUSTOM_INDICATOR Command
Get data from a custom indicator using the Metatrader iCustom function
Help:
{ "MSG":"HELP", "COMMAND":"CUSTOM_INDICATOR", "DESCRIPTION":"Get data from a custom indicator using the iCustom function", "MANDATORY_TAGS":[ "SYMBOL (String)", "TIMEFRAME (String)", "INDICATOR_NAME (String)" ], "OPTIONAL_TAGS":[ "PARAM1", "PARAM2", "PARAM3", "PARAM4", "NUM (Integer)", "INDEX (Integer)" ], "ERROR_ID":0, "ERROR_DESCRIPTION":"The operation completed successfully", "DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)" }
Example:
Single Line command (necessary for MTsocketAPI):
{"MSG":"CUSTOM_INDICATOR","SYMBOL":"EURUSD","TIMEFRAME":"PERIOD_M5","INDICATOR_NAME":"Examples\\OsMA","PARAM1":12,"PARAM2":26,"PARAM3":9,"PARAM4":"PRICE_CLOSE"}
Same command in Beauty Format:
{
"MSG":"CUSTOM_INDICATOR",
"SYMBOL":"EURUSD",
"TIMEFRAME":"PERIOD_M5",
"INDICATOR_NAME":"Examples\\OsMA",
"PARAM1":12,
"PARAM2":26,
"PARAM3":9,
"PARAM4":"PRICE_CLOSE"
}
MTsocketAPI reply:
{
"MSG":"CUSTOM_INDICATOR",
"DATA_VALUES":[
-0.0000061
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Exit Command
Disconnects from TCP 77 port (Command)
Help:
{ "MSG":"HELP", "COMMAND":"EXIT", "DESCRIPTION":"Command to close the actual connection", "MANDATORY_TAGS":[null], "OPTIONAL_TAGS":[null] }
Example:
Single Line command (necessary for MTsocketAPI):
{"MSG":"EXIT"}
Same command in Beauty Format:
{
"MSG":"EXIT"
}
MTsocketAPI reply:
Bye
MA_INDICATOR Command
Get data from the Moving Average Metatrader function iMA
Help:
{ "MSG":"HELP", "COMMAND":"MA_INDICATOR", "DESCRIPTION":"Get data from a the Moving Average indicator using the iMA function", "MANDATORY_TAGS":[ "SYMBOL (String)", "TIMEFRAME (String)", "MA_PERIOD (Integer)", "MA_SHIFT (Integer)", "MA_METHOD (String)", "APPLIED_PRICE (String)" ], "OPTIONAL_TAGS":[ "NUM (Integer)" ], "ERROR_ID":0, "ERROR_DESCRIPTION":"The operation completed successfully" }
Example:
Single Line command (necessary for MTsocketAPI):
{"MSG":"MA_INDICATOR","SYMBOL":"EURUSD","TIMEFRAME":"PERIOD_M5","MA_PERIOD":14,"MA_SHIFT":0,"MA_METHOD":"MODE_SMA","APPLIED_PRICE":"PRICE_CLOSE"}
Same command in Beauty Format:
{
"MSG":"MA_INDICATOR",
"SYMBOL":"EURUSD",
"TIMEFRAME":"PERIOD_M5",
"MA_PERIOD":14,
"MA_SHIFT":0,
"MA_METHOD":"MODE_SMA",
"APPLIED_PRICE":"PRICE_CLOSE"
}
MTsocketAPI reply:
{
"MSG":"MA_INDICATOR",
"DATA_VALUES":[
0.997320
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
ORDER_SEND Command
Send market or limit orders
Help:
{ "MSG":"HELP", "COMMAND":"ORDER_SEND", "DESCRIPTION":"Send a pending or market order to the current account", "MANDATORY_TAGS_MARKET":[ "SYMBOL (String)", "VOLUME (Double)", "TYPE (String)" ], "OPTIONAL_TAGS_MARKET":[ "PRICE (Double)", "SLIPPAGE", "SL (Double)", "TP (Double)", "COMMENT (String)", "MAGIC (Integer)", "EXPIRATION (String)", "TYPE_FILLING (String)", "ASYNC (Boolean)" ], "MANDATORY_TAGS_PENDING":[ "SYMBOL (String)", "VOLUME (Double)", "TYPE (String)", "PRICE (Double)" ], "OPTIONAL_TAGS_PENDING":[ "SLIPPAGE (Integer)", "SL (Double)", "TP (Double)", "COMMENT (String)", "MAGIC (Integer)", "EXPIRATION (String)", "TYPE_FILLING (String)", "ASYNC (Boolean)" ], "ERROR_ID":0, "ERROR_DESCRIPTION":"The operation completed successfully" }
Market Order Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"ORDER_SEND", "SYMBOL":"EURUSD", "VOLUME": 0.01, "TYPE":"ORDER_TYPE_BUY"}
Same command in Beauty Format:
{
"MSG":"ORDER_SEND",
"SYMBOL":"EURUSD",
"VOLUME": 0.01,
"TYPE": "ORDER_TYPE_BUY"
}
TYPE values:
- ORDER_TYPE_BUY
- ORDER_TYPE_SELL
- ORDER_TYPE_BUY_LIMIT
- ORDER_TYPE_SELL_LIMIT
- ORDER_TYPE_BUY_STOP
- ORDER_TYPE_SELL_STOP
TYPE_FILLING values (optional):
- SYMBOL_FILLING_FOK
- SYMBOL_FILLING_IOC
- SYMBOL_FILLING_BOC
MTsocketAPI reply:
{
"MSG":"ORDER_SEND",
"RETCODE":10009,
"DEAL":2015118899,
"ORDER":2020570482,
"VOLUME":0.10,
"PRICE":1.064930,
"BID":1.064890,
"ASK":1.064930,
"REQUEST_ID":3136973152,
"RETCODE_EXTERNAL":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Limit Order Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"ORDER_SEND","SYMBOL":"EURUSD","VOLUME":0.02,"SL":1.08,"TYPE":"ORDER_TYPE_SELL_LIMIT","PRICE":1.07,"EXPIRATION":"2022.09.19 19:38"}
Same command in Beauty Format:
{
"MSG":"ORDER_SEND",
"SYMBOL":"EURUSD",
"VOLUME":0.02,
"SL":1.08,
"TYPE":"ORDER_TYPE_SELL_LIMIT",
"PRICE":1.07,
"EXPIRATION":"2022.09.19 19:38"
}
Important: EXPIRATION tag value must be at least 10 minutes over the actual broker time.
MTsocketAPI reply:
{
"MSG":"ORDER_SEND",
"RETCODE":10013,
"DEAL":0,
"ORDER":0,
"VOLUME":0.00,
"PRICE":0.000000,
"BID":0.000000,
"ASK":0.000000,
"REQUEST_ID":0,
"RETCODE_EXTERNAL":0,
"ERROR_ID":4756,
"ERROR_DESCRIPTION":"Trade request sending failed"
}
ORDER_INFO Command
Get information from a pending or opened order
Help:
{ "MSG":"HELP", "COMMAND":"ORDER_INFO", "DESCRIPTION":"Get information from a pending or opened order using the TICKET number", "MANDATORY_TAGS":[ "TICKET (Integer)" ], "OPTIONAL_TAGS":[null], "ERROR_ID":0, "ERROR_DESCRIPTION":"The operation completed successfully" }
Example:
Single Line command (necessary for MTsocketAPI):
{"MSG":"ORDER_INFO", "TICKET":3217392064}
Same command in Beauty Format:
{
"MSG":"ORDER_INFO",
"TICKET":3217392064
}
MTsocketAPI reply:
{
"MSG":"ORDER_INFO",
"OPENED":[
{
"TICKET":3217392064,
"OPEN_TIME":"2025.01.09 20:29:03.135",
"TIME_UPDATE":"2025.01.09 20:29:03.135",
"TYPE":"ORDER_TYPE_BUY",
"MAGIC":0,
"IDENTIFIER":3217392064,
"REASON":0,
"VOLUME":0.01,
"PRICE_OPEN":1.02993,
"SL":0.00000,
"TP":0.00000,
"PRICE_CURRENT":1.03009,
"SWAP":0.00,
"PROFIT":0.16,
"SYMBOL":"EURUSD",
"COMMENT":null,
"EXTERNAL_ID":null,
"CHANGE":0.02
}
],
"PENDING":[],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
ORDER_MODIFY Command
Change SL or TP for market or limit orders
Help:
{ "MSG":"HELP", "COMMAND":"ORDER_MODIFY", "DESCRIPTION":"Modify any order using the TICKET number", "MANDATORY_TAGS":[ "TICKET (Integer)" ], "OPTIONAL_TAGS":[ "PRICE (Double)", "SL (Double)", "TP (Double)", "EXPIRATION (String)", "ASYNC (Boolean)" ], "ERROR_ID":0, "ERROR_DESCRIPTION":"The operation completed successfully", "DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)" }
Example:
Single Line command (necessary for MTsocketAPI):
{"MSG":"ORDER_MODIFY", "TICKET":6549871, "SL":1.002, "TP":0}
Same command in Beauty Format:
{
"MSG":"ORDER_MODIFY",
"TICKET":2012142959,
"SL":1.002
}
MTsocketAPI reply:
{
"MSG":"ORDER_MODIFY",
"TICKET":2012142959,
"RETCODE":10009,
"DEAL":0,
"ORDER":0,
"VOLUME":0.00,
"PRICE":0.000000,
"BID":0.000000,
"ASK":0.000000,
"REQUEST_ID":3136973156,
"RETCODE_EXTERNAL":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Important: If you send the SL or TP tag, the value will be updated but if you send the SL or TP tag assigned to 0 then the SL or TP will be removed.
ORDER_CLOSE Command
Close partially or fully an order using the ticket number. Also it closes stop or limit orders.
Help:
{ "MSG":"HELP", "COMMAND":"ORDER_CLOSE", "DESCRIPTION":"Close any order using the TICKET number", "MANDATORY_TAGS":[ "TICKET (Integer)" ], "OPTIONAL_TAGS":[ "VOLUME (Double)", "PRICE (Double)", "SLIPPAGE (Double)", "ASYNC (Boolean)" ], "ERROR_ID":0, "ERROR_DESCRIPTION":"The operation completed successfully" }
Example:
Fully close MT5 order
Single Line command (necessary for MTsocketAPI):
{"MSG":"ORDER_CLOSE", "TICKET":10058965}
Same command in Beauty Format:
{
"MSG": "ORDER_CLOSE",
"TICKET": 2020570871
}
MTsocketAPI reply:
{
"MSG":"ORDER_CLOSE",
"TICKET":2020570871,
"TYPE":"FULLY_CLOSED",
"RETCODE":10009,
"DEAL":2015119294,
"ORDER":2020570914,
"VOLUME":0.10,
"PRICE":1.064990,
"BID":1.064990,
"ASK":1.065030,
"REQUEST_ID":3136973157,
"RETCODE_EXTERNAL":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully",
"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"
}
Partially close MT5 order
Single Line command (necessary for MTsocketAPI):
{"MSG":"ORDER_CLOSE", "TICKET":6549871, "VOLUME": 0.01}
Same command in Beauty Format:
{
"MSG":"ORDER_CLOSE",
"TICKET":2012142959,
"VOLUME": 0.02
}
MTsocketAPI reply:
{
"MSG":"ORDER_CLOSE",
"TICKET":2012142959,
"TYPE":"PARTIALLY_CLOSED",
"RETCODE":10009,
"DEAL":2015119329,
"ORDER":2020570959,
"VOLUME":0.02,
"PRICE":1.065180,
"BID":1.065180,
"ASK":1.065220,
"REQUEST_ID":3136973159,
"RETCODE_EXTERNAL":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully",
"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"
}
ORDER_LIST Command
Get a list of opened and pending orders
Help:
{ "MSG":"HELP", "COMMAND":"ORDER_LIST", "DESCRIPTION":"Get a list of current opened/pending orders", "MANDATORY_TAGS":[null], "OPTIONAL_TAGS":[null] }
Example:
Single Line command (necessary for MTsocketAPI):
{"MSG":"ORDER_LIST"}
Same command in Beauty Format:
{
"MSG":"ORDER_LIST"
}
MTsocketAPI reply:
{
"MSG": "ORDER_LIST",
"COUNT": 1,
"OPENED": [
{
"TICKET": 3242463796,
"OPEN_TIME": "2025.01.17 10:40:00.45",
"TIME_UPDATE": "2025.01.17 10:40:00.45",
"TYPE": "ORDER_TYPE_BUY",
"MAGIC": 0,
"IDENTIFIER": 3242463796,
"REASON": 3,
"VOLUME": 0.03,
"PRICE_OPEN": 1.02959,
"SL": 1.02,
"TP": 0,
"PRICE_CURRENT": 1.02987,
"SWAP": 0,
"PROFIT": 0.84,
"SYMBOL": "EURUSD",
"COMMENT": null,
"EXTERNAL_ID": null,
"CHANGE": 0.03
}
],
"PENDING": [],
"ERROR_ID": 0,
"ERROR_DESCRIPTION": "The operation completed successfully"
}
PRICE_HISTORY Command
Gets history data of prices (Open, High, Low, Close) of a specified symbol-period.
Help:
{ "MSG":"HELP", "COMMAND":"PRICE_HISTORY", "DESCRIPTION":"Gets price history data of a specified symbol-period", "MANDATORY_TAGS":[ "SYMBOL (String)", "TIMEFRAME (String)", "FROM_DATE (String)", "TO_DATE (String)" ], "OPTIONAL_TAGS":[ null ], "ERROR_ID":0, "ERROR_DESCRIPTION":"no error" }
Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"PRICE_HISTORY", "SYMBOL":"EURUSD", "TIMEFRAME":"PERIOD_H1", "FROM_DATE":"2023/08/02 07:00:00", "TO_DATE": "2023/08/02 10:00:00"}
Same command in Beauty Format:
{
"MSG":"PRICE_HISTORY",
"SYMBOL":"EURUSD",
"TIMEFRAME":"PERIOD_H1",
"FROM_DATE":"2023/08/01 07:00:00",
"TO_DATE":"2023/08/02 13:00:00"
}
MTsocketAPI reply:
{
"MSG":"PRICE_HISTORY",
"SYMBOL":"EURUSD",
"TIMEFRAME":"PERIOD_H1",
"RATES":[
{
"TIME":"2023.08.02 10:00:00",
"OPEN":1.09800,
"HIGH":1.09801,
"LOW":1.09679,
"CLOSE":1.09784,
"REAL_VOLUME":0,
"TICK_VOLUME":2431,
"SPREAD":0
},
{
"TIME":"2023.08.02 09:00:00",
"OPEN":1.09838,
"HIGH":1.09845,
"LOW":1.09759,
"CLOSE":1.09801,
"REAL_VOLUME":0,
"TICK_VOLUME":2538,
"SPREAD":0
},
{
"TIME":"2023.08.02 08:00:00",
"OPEN":1.09901,
"HIGH":1.09923,
"LOW":1.09756,
"CLOSE":1.09839,
"REAL_VOLUME":0,
"TICK_VOLUME":3722,
"SPREAD":0
},
{
"TIME":"2023.08.02 07:00:00",
"OPEN":1.09896,
"HIGH":1.09969,
"LOW":1.09815,
"CLOSE":1.09896,
"REAL_VOLUME":0,
"TICK_VOLUME":3872,
"SPREAD":0
}
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error",
"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"
}
Note: Be careful with this command. If you retrieve millions of rows from MT5 the performance may worsen visibly while processing a big amount of data.
Important: If you haven’t downloaded that symbol/timeframe data before, MT5 does not yet have the data downloaded. Then it will return an error and it will start download it. You must ask for the data again until you don’t receive any error.
QUOTE Command
Get prices (Ask / Bid) from a symbol
Help:
{ "MSG":"HELP", "COMMAND":"QUOTE", "DESCRIPTION":"Get Quote from a SYMBOL", "MANDATORY_TAGS":[ "SYMBOL (String)" ], "OPTIONAL_TAGS":[null], "ERROR_ID":0, "ERROR_DESCRIPTION":"The operation completed successfully" }
Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"QUOTE", "SYMBOL":"EURUSD"}
Same command in Beauty Format:
{
"MSG":"QUOTE",
"SYMBOL":"EURUSD"
}
MTsocketAPI reply:
{
"MSG":"QUOTE",
"SYMBOL":"EURUSD",
"ASK":0.99708,
"BID":0.99704,
"FLAGS":2,
"TIME":"2022.09.19 14:05:45.717",
"VOLUME":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
SYMBOL_INFO Command
Get Symbol Information
Help:
{ "MSG":"HELP", "COMMAND":"SYMBOL_INFO", "DESCRIPTION":"Get information from the requested SYMBOL", "MANDATORY_TAGS":[ "SYMBOL (String)" ], "OPTIONAL_TAGS":[null], "ERROR_ID":0, "ERROR_DESCRIPTION":"The operation completed successfully", "DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)" }
Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"SYMBOL_INFO", "SYMBOL":"EURUSD"}
Same command in Beauty Format:
{
"MSG":"SYMBOL_INFO",
"SYMBOL":"EURUSD"
}
MTsocketAPI reply:
{
"MSG":"SYMBOL_INFO",
"NAME":"EURUSD",
"TIME":"2024.08.20 21:09:08",
"DIGITS":5,
"SPREAD_FLOAT":1,
"SPREAD":4,
"TRADE_CALC_MODE":5,
"TRADE_MODE":0,
"START_TIME":0,
"EXPIRATION_TIME":0,
"TRADE_STOPS_LEVEL":1,
"TRADE_FREEZE_LEVEL":1,
"TRADE_EXEMODE":2,
"SWAP_MODE":1,
"SWAP_ROLLOVER3DAYS":3,
"POINT":0.00001000,
"TRADE_TICK_VALUE":0.08994828,
"TRADE_TICK_VALUE_PROFIT":0.08994828,
"TRADE_TICK_VALUE_LOSS":0.08995152,
"TRADE_TICK_SIZE":0.00001000,
"TRADE_CONTRACT_SIZE":10000.00000000,
"VOLUME_MIN":0.10000000,
"VOLUME_MAX":100.00000000,
"VOLUME_STEP":0.10000000,
"VOLUME_LIMIT":0.00000000,
"SWAP_LONG":-15.50000000,
"SWAP_SHORT":-6.90000000,
"MARGIN_INITIAL":0.00000000,
"MARGIN_MAINTENANCE":0.00000000,
"CURRENCY_BASE":"EUR",
"CURRENCY_PROFIT":"USD",
"CURRENCY_MARGIN":"EUR",
"DESCRIPTION":"Euro vs. United States Dollar",
"PATH":"Forex\\FX-Majors\\EURUSD",
"SESSION_QUOTE":[
{
"SUNDAY":"22:05-24:00"
},
{
"MONDAY":"00:00-22:00, 22:05-24:00"
},
{
"TUESDAY":"00:00-22:00, 22:05-24:00"
},
{
"WEDNESDAY":"00:00-22:00, 22:05-24:00"
},
{
"THURSDAY":"00:00-22:00, 22:05-24:00"
},
{
"FRIDAY":"00:00-22:00"
}
],
"SESSION_TRADE":[
{
"SUNDAY":"22:05-24:00"
},
{
"MONDAY":"00:00-22:00, 22:05-24:00"
},
{
"TUESDAY":"00:00-22:00, 22:05-24:00"
},
{
"WEDNESDAY":"00:00-22:00, 22:05-24:00"
},
{
"THURSDAY":"00:00-22:00, 22:05-24:00"
},
{
"FRIDAY":"00:00-22:00"
}
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Note: Information about each field can be read here.
SYMBOL_LIST Command
Get symbol list from the broker
Help:
{ "MSG":"HELP", "COMMAND":"SYMBOL_LIST", "DESCRIPTION":"Get the symbol list from the current broker", "MANDATORY_TAGS":[null], "OPTIONAL_TAGS":[null] }
Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"SYMBOL_LIST"}
Same command in Beauty Format:
{
"MSG":"SYMBOL_LIST"
}
MTsocketAPI reply:
{
"MSG":"SYMBOL_LIST",
"SYMBOLS":[
{
"NAME":"AUDCAD",
"TRADE_MODE":4,
"DESCRIPTION":"Australian Dollar vs Canadian Dollar",
"PATH":"Forex\\AUDCAD"
},
{
"NAME":"AUDCHF",
"TRADE_MODE":4,
"DESCRIPTION":"Australian Dollar vs Swiss Franc",
"PATH":"Forex\\AUDCHF"
},
{
"NAME":"AUDJPY",
"TRADE_MODE":4,
"DESCRIPTION":"Australian Dollar vs Japanese Yen",
"PATH":"Forex\\AUDJPY"
},
{
"NAME":"AUDNZD",
"TRADE_MODE":4,
"DESCRIPTION":"Australian Dollar vs New Zealand Dollar",
"PATH":"Forex\\AUDNZD"
},
{
"NAME":"AUDUSD",
"TRADE_MODE":4,
"DESCRIPTION":"Australian Dollar vs US Dollar",
"PATH":"Forex\\AUDUSD"
},
....
....
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Note: Information about each field can be read here.
TERMINAL_INFO Command
Get information from the Metatrader terminal application
Help:
{ "MSG":"HELP", "COMMAND":"TERMINAL_INFO", "DESCRIPTION":"Get information about the MT4 Terminal application", "MANDATORY_TAGS":[null], "OPTIONAL_TAGS":[null] }
Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"TERMINAL_INFO"}
Same command in Beauty Format:
{
"MSG":"TERMINAL_INFO"
}
MTsocketAPI reply:
{
"MSG":"TERMINAL_INFO",
"LANGUAGE":"English",
"COMPANY":"Any Company",
"NAME":"Any Company MetaTrader 5",
"PATH":"C:\\Program Files\\Darwinex MetaTrader 5",
"DATA_PATH":"C:\\Users\\user1\\AppData\\Roaming\\MetaQuotes\\Terminal\\6C3C6A1FDFSFSF21BF8028",
"COMMONDATA_PATH":"C:\\Users\\user1\\AppData\\Roaming\\MetaQuotes\\Terminal\\Common",
"BUILD":3440,
"COMMUNITY_ACCOUNT":0,
"COMMUNITY_CONNECTION":0,
"CONNECTED":1,
"DLLS_ALLOWED":1,
"TRADE_ALLOWED":1,
"EMAIL_ENABLED":0,
"FTP_ENABLED":0,
"NOTIFICATIONS_ENABLED":0,
"MAXBARS":100000,
"MQID":0,
"CODEPAGE":0,
"CPU_CORES":8,
"DISK_SPACE":15361,
"MEMORY_PHYSICAL":8060,
"MEMORY_TOTAL":16120,
"MEMORY_AVAILABLE":15729,
"MEMORY_USED":391,
"SCREEN_DPI":96,
"PING_LAST":37515,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully",
"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"
}
Note: Information about each field can be read here.
TRACK_MBOOK Command
We send this command to TCP/77 and MTsocketAPI will start streaming Depth of Market (DOM) over the data port (default TCP/78):
Help:
{ "MSG":"HELP", "COMMAND":"TRACK_MBOOK", "DESCRIPTION":"Receive Market Depth in realtime for the subscribed symbols", "MANDATORY_TAGS":[ "SYMBOLS (ARRAY STRING)" ], "OPTIONAL_TAGS":[ null ] }
Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"TRACK_MBOOK", "SYMBOLS":["EURUSD"]}
Same command in Beauty Format:
{
"MSG":"TRACK_MBOOK",
"SYMBOLS":["EURUSD"]
}
MTsocketAPI reply:
{
"MSG":"TRACK_MBOOK",
"SUCCESS":["EURUSD"],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Now we can connect to default TCP 78 port to see the data:
$ telnet localhost 78
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
{"MSG":"TRACK_MBOOK","SYMBOL":"EURUSD","MARKET_BOOK":[{"PRICE":1.08467,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08464,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08463,"VOLUME":12,"VOLUMEREAL":12.50,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08462,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08459,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08458,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08455,"VOLUME":5,"VOLUMEREAL":5.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08454,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08453,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08450,"VOLUME":11,"VOLUMEREAL":11.00,"TYPE":"BOOK_TYPE_BUY"}]}
{"MSG":"TRACK_MBOOK","SYMBOL":"EURUSD","MARKET_BOOK":[{"PRICE":1.08472,"VOLUME":5,"VOLUMEREAL":5.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08467,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08464,"VOLUME":20,"VOLUMEREAL":20.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08462,"VOLUME":5,"VOLUMEREAL":5.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08459,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08458,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08455,"VOLUME":5,"VOLUMEREAL":5.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08454,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08453,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08451,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_BUY"}]}
{"MSG":"TRACK_MBOOK","SYMBOL":"EURUSD","MARKET_BOOK":[{"PRICE":1.08472,"VOLUME":5,"VOLUMEREAL":5.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08467,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08464,"VOLUME":20,"VOLUMEREAL":20.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08462,"VOLUME":5,"VOLUMEREAL":5.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08459,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08458,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08455,"VOLUME":15,"VOLUMEREAL":15.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08453,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08450,"VOLUME":11,"VOLUMEREAL":11.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08446,"VOLUME":5,"VOLUMEREAL":5.00,"TYPE":"BOOK_TYPE_BUY"}]}
{"MSG":"TRACK_MBOOK","SYMBOL":"EURUSD","MARKET_BOOK":[{"PRICE":1.08467,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08464,"VOLUME":20,"VOLUMEREAL":20.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08463,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08462,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08459,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08458,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08455,"VOLUME":15,"VOLUMEREAL":15.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08453,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08450,"VOLUME":11,"VOLUMEREAL":11.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08446,"VOLUME":5,"VOLUMEREAL":5.00,"TYPE":"BOOK_TYPE_BUY"}]}
{"MSG":"TRACK_MBOOK","SYMBOL":"EURUSD","MARKET_BOOK":[{"PRICE":1.08472,"VOLUME":5,"VOLUMEREAL":5.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08467,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08464,"VOLUME":20,"VOLUMEREAL":20.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08462,"VOLUME":5,"VOLUMEREAL":5.00,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08459,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_SELL"},{"PRICE":1.08458,"VOLUME":2,"VOLUMEREAL":2.50,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08456,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08455,"VOLUME":5,"VOLUMEREAL":5.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08453,"VOLUME":10,"VOLUMEREAL":10.00,"TYPE":"BOOK_TYPE_BUY"},{"PRICE":1.08450,"VOLUME":11,"VOLUMEREAL":11.00,"TYPE":"BOOK_TYPE_BUY"}]}
Important: You must request DOM data using the port TCP/77 and MTsocketAPI will stream Market Depth data on port TCP/78.
Note: You can connect multiple clients to TCP/78 port and all of them will receive DOM data.
TRACK_PRICES Command
We send this command to TCP/77 and MTsocketAPI will start streaming tick prices over the data port (default TCP/78):
Help:
{ "MSG":"HELP", "COMMAND":"TRACK_PRICES", "DESCRIPTION":"Receive prices in real-time for the subscribed symbols", "MANDATORY_TAGS":["SYMBOLS (ARRAY STRING)"], "OPTIONAL_TAGS":[null] }
Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"TRACK_PRICES", "SYMBOLS":["EURUSD"]}
Same command in Beauty Format:
{
"MSG":"TRACK_PRICES",
"SYMBOLS":["EURUSD"]
}
MTsocketAPI reply:
{
"MSG":"TRACK_PRICES",
"SUCCESS":["EURUSD"],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Now we can connect to default TCP 78 port to see the prices:
$ telnet localhost 78
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
{"MSG":"TRACK_PRICES","TIME":"2022.04.12 08:16:35","SYMBOL":"EURUSD","ASK":1.08594,"BID":1.08592,"VOLUME":16246}
{"MSG":"TRACK_PRICES","TIME":"2022.04.12 08:16:35","SYMBOL":"EURUSD","ASK":1.08595,"BID":1.08592,"VOLUME":16247}
{"MSG":"TRACK_PRICES","TIME":"2022.04.12 08:16:36","SYMBOL":"EURUSD","ASK":1.08594,"BID":1.08592,"VOLUME":16248}
{"MSG":"TRACK_PRICES","TIME":"2022.04.12 08:16:37","SYMBOL":"EURUSD","ASK":1.08595,"BID":1.08592,"VOLUME":16249}
{"MSG":"TRACK_PRICES","TIME":"2022.04.12 08:16:40","SYMBOL":"EURUSD","ASK":1.08598,"BID":1.08596,"VOLUME":16249}
{"MSG":"TRACK_PRICES","TIME":"2022.04.12 08:16:41","SYMBOL":"EURUSD","ASK":1.08599,"BID":1.08596,"VOLUME":16251}
{"MSG":"TRACK_PRICES","TIME":"2022.04.12 08:16:42","SYMBOL":"EURUSD","ASK":1.08597,"BID":1.08595,"VOLUME":16252}
{"MSG":"TRACK_PRICES","TIME":"2022.04.12 08:16:42","SYMBOL":"EURUSD","ASK":1.08599,"BID":1.08597,"VOLUME":16253}
Important: You must request tick data using the port TCP/77 and MTsocketAPI will stream prices on port TCP/78.
Note: You can connect multiple clients to TCP/78 port and all of them will receive the tick data.
TRACK_OHLC Command
Start or Stop streaming OHLC prices using the data port (default TCP 78) for a selected TIMEFRAME.
Help:
{ "MSG":"HELP", "COMMAND":"TRACK_OHLC", "DESCRIPTION":"Receive prices in OHLC for any TIMEFRAME in the configured DATA port", "MANDATORY_TAGS":[ { "OHLC":[ [ "TIMEFRAME (STRING)", "SYMBOL (STRING)", "DEPTH (Integer) = 1 (Default)" ] ] } ], "OPTIONAL_TAGS":[null] }
Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"TRACK_OHLC","OHLC":[{"TIMEFRAME":"PERIOD_M1","SYMBOL":"EURUSD"},{"TIMEFRAME":"PERIOD_M5","SYMBOL":"GBPUSD","DEPTH":3}]}
Same command in Beauty Format:
{
"MSG":"TRACK_OHLC",
"OHLC":[
{
"TIMEFRAME":"PERIOD_M1",
"SYMBOL":"EURUSD"
},
{
"TIMEFRAME":"PERIOD_M5",
"SYMBOL":"GBPUSD",
"DEPTH":3
}
]
}
TIMEFRAME values:
- PERIOD_M1
- PERIOD_M2
- PERIOD_M3
- PERIOD_M4
- PERIOD_M5
- PERIOD_M6
- PERIOD_M10
- PERIOD_M12
- PERIOD_M15
- PERIOD_M20
- PERIOD_M30
- PERIOD_H1
- PERIOD_H2
- PERIOD_H3
- PERIOD_H4
- PERIOD_H6
- PERIOD_H8
- PERIOD_H12
- PERIOD_D1
- PERIOD_W1
- PERIOD_MN1
Note: There is an optional tag:
- DEPTH (Integer)
By default DEPTH = 1 When a new bar arrives MTsocketAPI it will retrieve the last closed bar. If you use DEPTH = 5, then when a new bar arrives MTsocketAPI it will retrieve the last 5 closed bars of your selected TIMEFRAME.
Note: If you select PERIOD_M1 you will receive OHLC data every minute when a new price tick arrives but if you select PERIOD_H1, then you will receive OHLC data every hour.
MTsocketAPI reply:
{
"MSG":"TRACK_OHLC",
"SUCCESS":["GBPUSD","EURUSD"],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
If we connect to default data port TCP/78 then we can see every minute a new quote for EURUSD and GBPUSD:
$ telnet localhost 78
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
{"MSG":"TRACK_OHLC","SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2024.06.12 19:31:00","OPEN":1.08435,"HIGH":1.08441,"LOW":1.08433,"CLOSE":1.08437,"TICK_VOLUME":41}]}
{"MSG":"TRACK_OHLC","SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2024.06.12 19:32:00","OPEN":1.08438,"HIGH":1.08463,"LOW":1.08437,"CLOSE":1.08463,"TICK_VOLUME":28}]}
{"MSG":"TRACK_OHLC","SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2024.06.12 19:33:00","OPEN":1.08462,"HIGH":1.08482,"LOW":1.08462,"CLOSE":1.08470,"TICK_VOLUME":43}]}
{"MSG":"TRACK_OHLC","SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2024.06.12 19:34:00","OPEN":1.08471,"HIGH":1.08473,"LOW":1.08464,"CLOSE":1.08470,"TICK_VOLUME":20}]}
{"MSG":"TRACK_OHLC","SYMBOL":"GBPUSD","PERIOD":"PERIOD_M5","OHLC":[{"TIME":"2024.06.12 19:30:00","OPEN":1.28446,"HIGH":1.28485,"LOW":1.28445,"CLOSE":1.28475,"TICK_VOLUME":149},{"TIME":"2024.06.12 19:25:00","OPEN":1.28455,"HIGH":1.28466,"LOW":1.28436,"CLOSE":1.28445,"TICK_VOLUME":170},{"TIME":"2024.06.12 19:20:00","OPEN":1.28492,"HIGH":1.28503,"LOW":1.28449,"CLOSE":1.28455,"TICK_VOLUME":150}]}
{"MSG":"TRACK_OHLC","SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2024.06.12 19:35:00","OPEN":1.08469,"HIGH":1.08476,"LOW":1.08457,"CLOSE":1.08457,"TICK_VOLUME":39}]}
{"MSG":"TRACK_OHLC","SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2024.06.12 19:36:00","OPEN":1.08457,"HIGH":1.08458,"LOW":1.08455,"CLOSE":1.08457,"TICK_VOLUME":14}]}
{"MSG":"TRACK_OHLC","SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2024.06.12 19:37:00","OPEN":1.08459,"HIGH":1.08462,"LOW":1.08441,"CLOSE":1.08441,"TICK_VOLUME":40}]}
{"MSG":"TRACK_OHLC","SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2024.06.12 19:38:00","OPEN":1.08441,"HIGH":1.08442,"LOW":1.08428,"CLOSE":1.08434,"TICK_VOLUME":32}]}
{"MSG":"TRACK_OHLC","SYMBOL":"GBPUSD","PERIOD":"PERIOD_M5","OHLC":[{"TIME":"2024.06.12 19:35:00","OPEN":1.28470,"HIGH":1.28479,"LOW":1.28413,"CLOSE":1.28422,"TICK_VOLUME":165},{"TIME":"2024.06.12 19:30:00","OPEN":1.28446,"HIGH":1.28485,"LOW":1.28445,"CLOSE":1.28475,"TICK_VOLUME":149},{"TIME":"2024.06.12 19:25:00","OPEN":1.28455,"HIGH":1.28466,"LOW":1.28436,"CLOSE":1.28445,"TICK_VOLUME":170}]}
{"MSG":"TRACK_OHLC","SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2024.06.12 19:39:00","OPEN":1.08435,"HIGH":1.08449,"LOW":1.08435,"CLOSE":1.08442,"TICK_VOLUME":27}]}
{"MSG":"TRACK_OHLC","SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2024.06.12 19:40:00","OPEN":1.08443,"HIGH":1.08448,"LOW":1.08437,"CLOSE":1.08443,"TICK_VOLUME":27}]}
Stop receiving OHLC data:
{
"MSG":"TRACK_OHLC",
"OHLC":[]
}
TRACK_TRADE_EVENTS Command
We send this command to TCP/77 and MTsocketAPI will start streaming order events over the data port (default TCP/78):
Help:
{ "MSG":"HELP", "COMMAND":"TRACK_TRADE_EVENTS", "DESCRIPTION":"Receive trade events in the configured DATA port", "MANDATORY_TAGS":[null], "OPTIONAL_TAGS":["ENABLED (Boolean)"] }
Example
Single Line command (necessary for MTsocketAPI) give us the actual state:
{"MSG":"TRACK_TRADE_EVENTS"}
Same command in Beauty Format:
{
"MSG":"TRACK_TRADE_EVENTS"
}
MTsocketAPI reply:
{
"MSG":"TRACK_TRADE_EVENTS",
"ENABLED":false,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
If we want to start receiving trade events:
{
"MSG":"TRACK_TRADE_EVENTS",
"ENABLED":true
}
Now we can connect to default TCP 78 port to see the order events when a new order is open/closed/modified…
$ telnet localhost 78
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
{"MSG":"TRACK_TRADE_EVENTS","TRADE_TRANSACTION":{"DEAL":0,"DEAL_TYPE":"DEAL_TYPE_BUY","ORDER":2293361403,"ORDER_STATE":"ORDER_STATE_STARTED","ORDER_TYPE":"ORDER_TYPE_BUY","POSITION":0,"POSITION_BY":0,"PRICE":0.00000000,"PRICE_SL":0.00000000,"PRICE_TP":0.00000000,"PRICE_TRIGGER":0.00000000,"SYMBOL":"SPX500_m","TIME_EXPIRATION":"1970.01.01 00:00:00","TIME_TYPE":"ORDER_TIME_GTC","TYPE":"TRADE_TRANSACTION_ORDER_ADD","VOLUME":0.03000000},"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"}
{"MSG":"TRACK_TRADE_EVENTS","TRADE_TRANSACTION":{"DEAL":0,"DEAL_TYPE":"DEAL_TYPE_BUY","ORDER":2293361403,"ORDER_STATE":"ORDER_STATE_REQUEST_ADD","ORDER_TYPE":"ORDER_TYPE_BUY","POSITION":0,"POSITION_BY":0,"PRICE":0.00000000,"PRICE_SL":0.00000000,"PRICE_TP":0.00000000,"PRICE_TRIGGER":0.00000000,"SYMBOL":"SPX500_m","TIME_EXPIRATION":"1970.01.01 00:00:00","TIME_TYPE":"ORDER_TIME_GTC","TYPE":"TRADE_TRANSACTION_ORDER_UPDATE","VOLUME":0.03000000},"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"}
{"MSG":"TRACK_TRADE_EVENTS","TRADE_TRANSACTION":{"DEAL":0,"DEAL_TYPE":"DEAL_TYPE_BUY","ORDER":0,"ORDER_STATE":"ORDER_STATE_STARTED","ORDER_TYPE":"ORDER_TYPE_BUY","POSITION":0,"POSITION_BY":0,"PRICE":0.00000000,"PRICE_SL":0.00000000,"PRICE_TP":0.00000000,"PRICE_TRIGGER":0.00000000,"SYMBOL":null,"TIME_EXPIRATION":"1970.01.01 00:00:00","TIME_TYPE":"ORDER_TIME_GTC","TYPE":"TRADE_TRANSACTION_REQUEST","VOLUME":0.00000000},"TRADE_REQUEST":{"ACTION":"TRADE_ACTION_DEAL","COMMENT":null,"DEVIATION":0,"EXPIRATION":"1970.01.01 00:00:00","MAGIC":0,"ORDER":2293361403,"POSITION":0,"POSITION_BY":0,"PRICE":0.00000000,"SL":0.00000000,"STOPLIMIT":0.00000000,"SYMBOL":"SPX500_m","TP":0.00000000,"TYPE":"ORDER_TYPE_BUY","TYPE_FILLING":"ORDER_FILLING_FOK","TYPE_TIME":"ORDER_TIME_GTC","VOLUME":0.03000000},"TRADE_RESULT":{"ASK":0.00000000,"BID":0.00000000,"COMMENT":null,"DEAL":0,"ORDER":2293361403,"PRICE":0.00000000,"REQUEST_ID":3967966209,"RETCODE":10008,"RETCODE_EXTERNAL":0,"VOLUME":0.00000000},"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"}
{"MSG":"TRACK_TRADE_EVENTS","TRADE_TRANSACTION":{"DEAL":0,"DEAL_TYPE":"DEAL_TYPE_BUY","ORDER":2293361403,"ORDER_STATE":"ORDER_STATE_PLACED","ORDER_TYPE":"ORDER_TYPE_BUY","POSITION":0,"POSITION_BY":0,"PRICE":0.00000000,"PRICE_SL":0.00000000,"PRICE_TP":0.00000000,"PRICE_TRIGGER":0.00000000,"SYMBOL":"SPX500_m","TIME_EXPIRATION":"1970.01.01 00:00:00","TIME_TYPE":"ORDER_TIME_GTC","TYPE":"TRADE_TRANSACTION_ORDER_UPDATE","VOLUME":0.03000000},"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"}
{"MSG":"TRACK_TRADE_EVENTS","TRADE_TRANSACTION":{"DEAL":0,"DEAL_TYPE":"DEAL_TYPE_BUY","ORDER":0,"ORDER_STATE":"ORDER_STATE_STARTED","ORDER_TYPE":"ORDER_TYPE_BUY","POSITION":0,"POSITION_BY":0,"PRICE":0.00000000,"PRICE_SL":0.00000000,"PRICE_TP":0.00000000,"PRICE_TRIGGER":0.00000000,"SYMBOL":null,"TIME_EXPIRATION":"1970.01.01 00:00:00","TIME_TYPE":"ORDER_TIME_GTC","TYPE":"TRADE_TRANSACTION_REQUEST","VOLUME":0.00000000},"TRADE_REQUEST":{"ACTION":"TRADE_ACTION_DEAL","COMMENT":null,"DEVIATION":0,"EXPIRATION":"1970.01.01 00:00:00","MAGIC":0,"ORDER":0,"POSITION":0,"POSITION_BY":0,"PRICE":0.00000000,"SL":0.00000000,"STOPLIMIT":0.00000000,"SYMBOL":"SPX500_m","TP":0.00000000,"TYPE":"ORDER_TYPE_BUY","TYPE_FILLING":"ORDER_FILLING_FOK","TYPE_TIME":"ORDER_TIME_GTC","VOLUME":0.03000000},"TRADE_RESULT":{"ASK":0.00000000,"BID":0.00000000,"COMMENT":null,"DEAL":0,"ORDER":2293361403,"PRICE":0.00000000,"REQUEST_ID":3967966209,"RETCODE":10009,"RETCODE_EXTERNAL":0,"VOLUME":0.03000000},"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"}
{"MSG":"TRACK_TRADE_EVENTS","TRADE_TRANSACTION":{"DEAL":2282203801,"DEAL_TYPE":"DEAL_TYPE_BUY","ORDER":2293361403,"ORDER_STATE":"ORDER_STATE_STARTED","ORDER_TYPE":"ORDER_TYPE_BUY","POSITION":2293361403,"POSITION_BY":0,"PRICE":4459.30000000,"PRICE_SL":0.00000000,"PRICE_TP":0.00000000,"PRICE_TRIGGER":0.00000000,"SYMBOL":"SPX500_m","TIME_EXPIRATION":"1970.01.01 00:00:00","TIME_TYPE":"ORDER_TIME_GTC","TYPE":"TRADE_TRANSACTION_DEAL_ADD","VOLUME":0.03000000},"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"}
{"MSG":"TRACK_TRADE_EVENTS","TRADE_TRANSACTION":{"DEAL":0,"DEAL_TYPE":"DEAL_TYPE_BUY","ORDER":2293361403,"ORDER_STATE":"ORDER_STATE_FILLED","ORDER_TYPE":"ORDER_TYPE_BUY","POSITION":2293361403,"POSITION_BY":0,"PRICE":0.00000000,"PRICE_SL":0.00000000,"PRICE_TP":0.00000000,"PRICE_TRIGGER":0.00000000,"SYMBOL":"SPX500_m","TIME_EXPIRATION":"1970.01.01 00:00:00","TIME_TYPE":"ORDER_TIME_GTC","TYPE":"TRADE_TRANSACTION_ORDER_DELETE","VOLUME":0.00000000},"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"}
{"MSG":"TRACK_TRADE_EVENTS","TRADE_TRANSACTION":{"DEAL":0,"DEAL_TYPE":"DEAL_TYPE_BUY","ORDER":2293361403,"ORDER_STATE":"ORDER_STATE_FILLED","ORDER_TYPE":"ORDER_TYPE_BUY","POSITION":2293361403,"POSITION_BY":0,"PRICE":0.00000000,"PRICE_SL":0.00000000,"PRICE_TP":0.00000000,"PRICE_TRIGGER":0.00000000,"SYMBOL":"SPX500_m","TIME_EXPIRATION":"1970.01.01 00:00:00","TIME_TYPE":"ORDER_TIME_GTC","TYPE":"TRADE_TRANSACTION_HISTORY_ADD","VOLUME":0.00000000},"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"}
Important: You must request order events data using the port TCP/77 and MTsocketAPI will stream order events on port TCP/78.
Note: You can connect multiple clients to TCP/78 port and all of them will receive the order events data.
TRADE_HISTORY Command
Get a list of closed trades
Help:
{ "MSG":"HELP", "COMMAND":"TRADE_HISTORY", "DESCRIPTION":"Get a list of closed orders", "MANDATORY_TAGS":[ "FROM_DATE (String)", "TO_DATE (String)", "MODE (String)" ], "OPTIONAL_TAGS":[null], "ERROR_ID":0, "ERROR_DESCRIPTION":"The operation completed successfully" }
MODE values:
- POSITIONS
- DEALS
- ORDERS
- ORDERS_DEALS
Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"TRADE_HISTORY", "FROM_DATE":"2022/09/19 07:00:00", "TO_DATE": "2022/09/19 13:35:00","MODE":"POSITIONS"}
Same command in Beauty Format:
{
"MSG":"TRADE_HISTORY",
"FROM_DATE":"2022/09/19 07:00:00",
"TO_DATE":"2022/09/19 13:35:00",
"MODE":"POSITIONS"
}
MTsocketAPI reply:
{
"MSG": "TRADE_HISTORY",
"MODE": "POSITIONS",
"POSITIONS": [
{
"OPEN_TIME": "2025.01.15 20:51:41.117",
"SYMBOL": "EURUSD",
"TICKET": 3236195358,
"TYPE": "BUY",
"VOLUME": 0.02,
"PRICE_OPEN": 1.02913,
"MAGIC": 0,
"COMMENT": null,
"CLOSE_TIME": "2025.01.15 20:54:24.928",
"PRICE_CLOSE": 1.029205,
"PROFIT": 0.15,
"COMMISSION": 0,
"SWAP": 0,
"SL": 0,
"TP": 0,
"CHANGE": 0.01
}
],
"ERROR_ID": 0,
"ERROR_DESCRIPTION": "The operation completed successfully"
}
MTsocketAPI Full Code Examples
We provide some tested code examples that can be used freely. All the following examples were tested on a Windows 11 and Ubuntu 20 computers.
Python
WARNING: All these source codes are only examples used for testing. We don’t provide any guarantee or responsibility about it. Use these examples at your own risk.
Examples using python 3.6.8
Basic Examples for MT5 (for MT4 click here)
Example 1: Get actual EURUSD price from MT5 using Python
import socket
import sys
import json
buffer_size = 326582
host = "127.0.0.1"
port = 77 # Default command port used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3) # 3 seconds timeout if we don't receive response from the API
s.connect((host, port))
s.sendall(b'{"MSG": "QUOTE", "SYMBOL": "EURUSD"}\r\n')
print(s.recv(buffer_size).decode('ascii'))
Reply:
{
"MSG":"QUOTE",
"SYMBOL":"EURUSD",
"ASK":1.08293,
"BID":1.08291,
"FLAGS":6,
"TIME":"2022.04.13 08:33:48.0",
"VOLUME":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Example 2: Send Order to MT5 using Python
import socket
import sys
import json
buffer_size = 326582
host = "127.0.0.1"
port = 77 # Default command port used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3) # 3 seconds timeout if we don't receive response from the API
s.connect((host, port))
s.sendall(b'{"MSG": "ORDER_SEND", "SYMBOL": "EURUSD","TYPE":"ORDER_TYPE_BUY","VOLUME":0.02}\r\n')
print(s.recv(buffer_size).decode('ascii'))
Reply:
{"MSG":"ORDER_SEND","RETCODE":10009,"DEAL":2015119247,"ORDER":2020570871,"VOLUME":0.10,"PRICE":1.064860,"BID":1.064830,"ASK":1.064860,"REQUEST_ID":3136973155,"RETCODE_EXTERNAL":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Example 3: Stream actual EURUSD price from MT5 using Python
import socket
import sys
import json
buffer_size = 326582
s_cmd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_cmd.settimeout(3) # 3 seconds timeout if we don't receive response from the API
s_cmd.connect(("127.0.0.1", 77)) # Command port
s_cmd.sendall(b'{"MSG": "TRACK_PRICES", "SYMBOLS": ["EURUSD"]}\r\n')
print(s_cmd.recv(buffer_size).decode('ascii'))
s_data = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_data.connect(("127.0.0.1", 78)) # Data port for receiving prices
while True:
print(s_data.recv(buffer_size).decode('ascii'))
Reply:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
{"TIME":"2022.04.13 09:08:02","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08384,"VOLUME":18404}
{"TIME":"2022.04.13 09:08:03","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08385,"VOLUME":18405}
{"TIME":"2022.04.13 09:08:03","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08384,"VOLUME":18407}
{"TIME":"2022.04.13 09:08:04","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08380,"VOLUME":18408}
{"TIME":"2022.04.13 09:08:05","SYMBOL":"EURUSD","ASK":1.08384,"BID":1.08382,"VOLUME":18408}
{"TIME":"2022.04.13 09:08:05","SYMBOL":"EURUSD","ASK":1.08385,"BID":1.08382,"VOLUME":18410}
{"TIME":"2022.04.13 09:08:06","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08381,"VOLUME":18411}
{"TIME":"2022.04.13 09:08:06","SYMBOL":"EURUSD","ASK":1.08384,"BID":1.08381,"VOLUME":18411}
{"TIME":"2022.04.13 09:08:07","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08381,"VOLUME":18412}
...
Advanced Examples
Example 1: Get actual EURUSD price from MT5 (using JSON library) with Python
import socket
import sys
import json
buffer_size = 326582
def SendCommand(farg):
dataToSend = json.dumps(farg) + "\r\n"
s.send(dataToSend.encode('ascii'))
return json.loads(s.recv(buffer_size).decode('ascii'))
host = "127.0.0.1"
port = 77 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3) # 3 seconds timeout if API does not respond
s.connect((host, port))
JSONobject = {}
JSONobject['MSG'] = 'QUOTE'
JSONobject['SYMBOL'] = 'EURUSD' # Symbol is case sensitive
JSONresult = SendCommand(JSONobject)
print('RAW JSON message received:',JSONresult)
print('Symbol:',JSONresult['SYMBOL'])
print('Ask:',JSONresult['ASK'])
print('Bid:',JSONresult['BID'])
Reply:
RAW JSON message received: {'MSG': 'QUOTE', 'SYMBOL': 'EURUSD', 'ASK': 1.08308, 'BID': 1.08306, 'FLAGS': 6, 'TIME': '2022.04.13 09:18:32.0', 'VOLUME': 0, 'ERROR_ID': 0, 'ERROR_DESCRIPTION': 'The operation completed successfully'}
Symbol: EURUSD
Ask: 1.08308
Bid: 1.08306
Example 2: Stream OHLC data from MT5 (using JSON library) with Python
import socket
import sys
import json
buffer_size = 326582
def SendCommand(farg):
dataToSend = json.dumps(farg) + "\r\n"
s_cmd.send(dataToSend.encode('ascii'))
return json.loads(s_cmd.recv(buffer_size).decode('ascii'))
s_cmd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_cmd.settimeout(3)
s_cmd.connect(("127.0.0.1", 77)) # Command port
s_data = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_data.connect(("127.0.0.1", 78)) # Data port
JSONobject = {}
subJSONobject = {}
subJSONobject['SYMBOL'] = 'EURUSD'
subJSONobject['TIMEFRAME'] = 'PERIOD_M1'
subJSONobject['DEPTH'] = 1
JSONobject['MSG'] = 'TRACK_OHLC'
JSONobject['OHLC'] = [subJSONobject]
JSONresult = SendCommand(JSONobject)
print('RAW JSON message received:',JSONresult)
while True:
dataReceived = s_data.recv(buffer_size).decode('ascii')
#print('RAW data received:',dataReceived)
JSONprice = json.loads(dataReceived)
if JSONprice["MSG"] == "TRACK_OHLC":
print("Time:",JSONprice['OHLC'][0]['TIME'],"Symbol:",JSONprice['SYMBOL'],"Open:",JSONprice['OHLC'][0]['OPEN'],"Close:",JSONprice['OHLC'][0]['CLOSE'],"High:",JSONprice['OHLC'][0]['HIGH'],"Low:",JSONprice['OHLC'][0]['LOW'])
Reply:
RAW JSON message received: {'MSG': 'TRACK_OHLC', 'SUCCESS': ['EURUSD'], 'ERROR_ID': 0, 'ERROR_DESCRIPTION': 'The operation completed successfully'}
Time: 2022.04.13 09:48:00 Symbol: EURUSD Open: 1.08346 Close: 1.0835 High: 1.08356 Low: 1.08335
Time: 2022.04.13 09:49:00 Symbol: EURUSD Open: 1.08351 Close: 1.08352 High: 1.08353 Low: 1.08343
Time: 2022.04.13 09:50:00 Symbol: EURUSD Open: 1.08352 Close: 1.08346 High: 1.08356 Low: 1.08341
Time: 2022.04.13 09:51:00 Symbol: EURUSD Open: 1.08348 Close: 1.08341 High: 1.08353 Low: 1.08338
Time: 2022.04.13 09:52:00 Symbol: EURUSD Open: 1.08342 Close: 1.08327 High: 1.08343 Low: 1.08322
Time: 2022.04.13 09:53:00 Symbol: EURUSD Open: 1.08324 Close: 1.08321 High: 1.08329 Low: 1.08311
Time: 2022.04.13 09:54:00 Symbol: EURUSD Open: 1.08322 Close: 1.08344 High: 1.08345 Low: 1.08322
Time: 2022.04.13 09:55:00 Symbol: EURUSD Open: 1.08345 Close: 1.08357 High: 1.08359 Low: 1.08339
Example 3: Export Trade History from MT5 to a CSV file using Python
# Example 3 (Advanced) - Export Trade History from MT5 to a CSV file
#
# PREREQUISITE: Install MTsocketAPI in your Metatrader 5 using the following link https://www.mtsocketapi.com/doc5/installation.html
#
# WARNING: All these source codes are only examples for testing purposes.
# WARNING: We don’t provide any guarantee or responsibility about it.
# WARNING: Use these examples at your own risk.
import socket
import sys
import json
import csv
buffer_size = 326582
def SendCommand(farg):
dataToSend = json.dumps(farg) + "\r\n"
s.send(dataToSend.encode('ascii'))
return json.loads(s.recv(buffer_size).decode('ascii'))
host = "127.0.0.1"
port = 77 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3) # 3 seconds timeout if API does not respond
s.connect((host, port))
JSONobject = {}
JSONobject['MSG'] = 'TRADE_HISTORY'
JSONobject['MODE'] = 'POSITIONS'
JSONobject['FROM_DATE'] = '2023/08/23 00:00:00'
JSONobject['TO_DATE'] = '2023/08/25 00:00:00'
JSONresult = SendCommand(JSONobject)
#print('RAW JSON message received:',JSONresult)
header = ['SYMBOL', 'MAGIC', 'TICKET', 'OPEN_TIME','CLOSE_TIME','PRICE_OPEN','PRICE_CLOSE','TYPE','LOTS','STOP_LOSS','TAKE_PROFIT','SWAP','COMMISSION','COMMENT','PROFIT']
f = open('History.csv', 'w')
writer = csv.writer(f)
writer.writerow(header)
for item in JSONresult['POSITIONS']:
print('Exported order:',item['TICKET'])
row = [item['SYMBOL'],item['MAGIC'],item['TICKET'],item['OPEN_TIME'],item['CLOSE_TIME'],item['PRICE_OPEN'],item['PRICE_CLOSE'],item['TYPE'],item['VOLUME'],item['SL'],item['TP'],item['SWAP'],item['COMMISSION'],item['COMMENT'],item['PROFIT']]
writer.writerow(row)
f.close()
print('Exported successfully!')
Reply:
Exported order: 2295465108
Exported order: 2295467196
Exported order: 2295467197
Exported order: 2295532403
Exported successfully!
Have you found any bug or error? Please notify us.
Java
WARNING: All these source codes are only examples used for testing. We don’t provide any guarantee or responsibility about it. Use these examples at your own risk.
Basic Examples for MT5 (for MT4 click here)
Example 1: Get actual EURUSD price from MT5 using Java
getQuote.java
import java.net.*;
import java.io.*;
/**
*
* $ javac getQuote.java (Compile)
* $ java getQuote (Run)
*
**/
class getQuote
{
public static void main(String[] args)
{
try
{
Socket socket = new Socket("localhost", 77);
OutputStream output = socket.getOutputStream();
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
String jsonString;
writer.write("{\"MSG\":\"QUOTE\",\"SYMBOL\":\"EURUSD\"}\r\n");
writer.flush();
jsonString = reader.readLine();
System.out.println(jsonString);
}
catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
}
catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}
Reply:
{"MSG":"QUOTE","SYMBOL":"EURUSD","ASK":0.99891,"BID":0.99890,"FLAGS":4,"TIME":"2022.09.19 15:37:14.45","VOLUME":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Example 2: Send Order to MT5 using Java
sendOrder.java
import java.net.*;
import java.io.*;
/**
* $ javac sendOrder.java (Compile)
* $ java sendOrder (Run)
*
* */
class sendOrder
{
public static void main(String[] args)
{
try
{
Socket socket = new Socket("localhost", 77);
OutputStream output = socket.getOutputStream();
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
String jsonString;
writer.write("{\"MSG\":\"ORDER_SEND\",\"SYMBOL\":\"EURUSD\",\"VOLUME\":0.02,\"TYPE\":\"ORDER_TYPE_BUY\"}\r\n");
writer.flush();
jsonString = reader.readLine();
System.out.println(jsonString);
}
catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
}
catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}
Reply:
{"MSG":"ORDER_SEND","RETCODE":10009,"DEAL":2015119247,"ORDER":2020570871,"VOLUME":0.10,"PRICE":1.064860,"BID":1.064830,"ASK":1.064860,"REQUEST_ID":3136973155,"RETCODE_EXTERNAL":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Example 3: Stream actual EURUSD price from MT5 using Java
streamPrices.java
import java.net.*;
import java.io.*;
/**
* $ javac streamPrices.java (Compile)
* $ java streamPrices (Run)
**/
class streamPrices
{
public static void main(String[] args)
{
try
{
Socket socket_cmd = new Socket("localhost", 77);
Socket socket_data = new Socket("localhost", 78);
OutputStream output_cmd = socket_cmd.getOutputStream();
InputStream input_cmd = socket_cmd.getInputStream();
InputStream input_data = socket_data.getInputStream();
BufferedReader reader_cmd = new BufferedReader(new InputStreamReader(input_cmd));
BufferedReader reader_data = new BufferedReader(new InputStreamReader(input_data));
BufferedWriter writer_cmd = new BufferedWriter(new OutputStreamWriter(output_cmd));
String jsonString;
writer_cmd.write("{\"MSG\":\"TRACK_PRICES\",\"SYMBOLS\":[\"EURUSD\"]}\r\n");
writer_cmd.flush();
jsonString = reader_cmd.readLine();
System.out.println(jsonString);
while ((jsonString = reader_data.readLine()) != null) {
System.out.println(jsonString);
}
}
catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
}
catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}
Reply:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfullyr"}
{"TIME":"2022.04.18 12:28:31","SYMBOL":"EURUSD","ASK":1.08088,"BID":1.08085,"VOLUME":24073}
{"TIME":"2022.04.18 12:28:36","SYMBOL":"EURUSD","ASK":1.08088,"BID":1.08084,"VOLUME":24073}
{"TIME":"2022.04.18 12:28:37","SYMBOL":"EURUSD","ASK":1.08087,"BID":1.08083,"VOLUME":24075}
{"TIME":"2022.04.18 12:28:43","SYMBOL":"EURUSD","ASK":1.08087,"BID":1.08084,"VOLUME":24076}
{"TIME":"2022.04.18 12:28:44","SYMBOL":"EURUSD","ASK":1.08088,"BID":1.08084,"VOLUME":24076}
{"TIME":"2022.04.18 12:28:45","SYMBOL":"EURUSD","ASK":1.08087,"BID":1.08084,"VOLUME":24078}
Advanced Examples
Example 1: Get actual EURUSD price from MT5 (using JSON library) using Java
getQuoteJSON.java
import java.net.*;
import java.io.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* $ javac -cp .:json-simple-1.1.1.jar getQuoteJSON.java (Compile)
* $ java -cp .:json-simple-1.1.1.jar getQuoteJSON (Run)
* */
class getQuoteJSON
{
public static void main(String[] args)
{
try
{
Socket socket = new Socket("localhost", 77);
OutputStream output = socket.getOutputStream();
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
String jsonString;
JSONObject jo = new JSONObject();
jo.put("MSG","QUOTE");
jo.put("SYMBOL","EURUSD");
writer.write(jo.toString() + "\r\n");
writer.flush();
jsonString = reader.readLine();
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(jsonString);
System.out.println("Time: " + json.get("TIME") + " Symbol: " + json.get("SYMBOL") + " Ask: " + json.get("ASK"));
}
catch(ParseException pe) {
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
}
catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}
Reply:
Time: 2022.04.18 12:45:03.0 Symbol: EURUSD Ask: 1.08068
Example 2: Stream OHLC data from MT5 (using JSON library) with Java
getStreamJSON.java
import java.net.*;
import java.io.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* $ javac -cp .:json-simple-1.1.1.jar getStreamJSON.java
* $ java -cp .:json-simple-1.1.1.jar getStreamJSON
* */
class getStreamJSON
{
public static void main(String[] args)
{
try
{
Socket socket_cmd = new Socket("localhost", 77);
Socket socket_data = new Socket("localhost", 78);
OutputStream output_cmd = socket_cmd.getOutputStream();
InputStream input_cmd = socket_cmd.getInputStream();
InputStream input_data = socket_data.getInputStream();
BufferedReader reader_cmd = new BufferedReader(new InputStreamReader(input_cmd));
BufferedReader reader_data = new BufferedReader(new InputStreamReader(input_data));
BufferedWriter writer_cmd = new BufferedWriter(new OutputStreamWriter(output_cmd));
JSONArray ja = new JSONArray();
JSONObject jj = new JSONObject();
jj.put("SYMBOL","EURUSD");
jj.put("TIMEFRAME","PERIOD_M1")
jj.put("DEPTH",1)
ja.add(jj);
JSONObject jo = new JSONObject();
jo.put("MSG","TRACK_OHLC");
jo.put("OHLC",ja);
//System.out.println(jo.toString());
writer_cmd.write(jo.toString() + "\r\n");
writer_cmd.flush();
String jsonString;
while ((jsonString = reader_data.readLine()) != null) {
//System.out.println(jsonString);
JSONParser parser = new JSONParser();
JSONObject jso = (JSONObject) parser.parse(jsonString);
if (jso.containsKey("OHLC")) {
JSONArray jarr= (JSONArray)jso.get("OHLC");
JSONObject jelem= (JSONObject)jarr.get(0);
System.out.println("Time: " + jelem.get("TIME") + " Symbol: " + jso.get("SYMBOL") + " Open: " + jelem.get("OPEN") + " Close: " + jelem.get("CLOSE") + " High: " + jelem.get("HIGH") + " Low: " + jelem.get("LOW"));
}
}
}
catch(ParseException pe) {
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
}
catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}
Reply when a new candle closes:
Time: 2022.04.18 13:24:00 Symbol: EURUSD Open: 1.08060 Close: 1.08050 High: 1.08061 Low: 1.08043
Time: 2022.04.18 13:25:00 Symbol: EURUSD Open: 1.08049 Close: 1.08053 High: 1.08061 Low: 1.08049
Time: 2022.04.18 13:26:00 Symbol: EURUSD Open: 1.08052 Close: 1.08059 High: 1.08059 Low: 1.08050
Example 3: Export Trade History from MT5 to a CSV file using Java
getHistory.java
import java.net.*;
import java.io.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* $ javac -cp .:json-simple-1.1.1.jar getHistory.java
* $ java -cp .:json-simple-1.1.1.jar getHistory
* */
class getHistory
{
public static void main(String[] args)
{
try
{
Socket socket = new Socket("localhost", 77);
OutputStream output = socket.getOutputStream();
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
String jsonString;
JSONObject jo = new JSONObject();
jo.put("MSG","TRADE_HISTORY");
jo.put("FROM_DATE","2022/09/19 07:00:00");
jo.put("TO_DATE","2022/09/21 00:00:00");
jo.put("MODE","POSITIONS"); //MODES: POSITIONS, ORDERS, DEALS and ORDERS_DEALS
//System.out.println(jo.toString());
writer.write(jo.toString() + "\r\n");
writer.flush();
jsonString = reader.readLine();
System.out.println(jsonString);
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(jsonString);
//JSONArray jarr= (JSONArray)json.get("POSITIONS");
JSONArray jarr= (JSONArray)json.get(jo.get("MODE").toString());
System.out.println("Creating file...");
FileWriter myFile = new FileWriter("tradeHistory.csv");
myFile.write("OPEN_TIME,CLOSE_TIME,TICKET,SYMBOL,MAGIC,PRICE_OPEN,PRICE_CLOSE,TYPE,LOTS,STOP_LOSS,TAKE_PROFIT,SWAP,COMMISSION,COMMENT,PROFIT\r\n");
for(int i = 0; i < jarr.size(); i++) {
JSONObject item = (JSONObject) jarr.get(i);
//System.out.println(Integer.toString(i) + " " + item.get("OPEN_TIME"));
myFile.write(item.get("OPEN_TIME").toString() + "," +
item.get("CLOSE_TIME").toString() + "," +
item.get("TICKET").toString() + "," +
item.get("SYMBOL").toString() + "," +
item.get("MAGIC").toString() + "," +
item.get("PRICE_OPEN").toString() + "," +
item.get("PRICE_CLOSE").toString() + "," +
item.get("TYPE").toString() + "," +
item.get("VOLUME").toString() + "," +
item.get("SL").toString() + "," +
item.get("TP").toString() + "," +
item.get("SWAP").toString() + "," +
item.get("COMMISSION").toString() + "," +
item.get("COMMENT") + "," +
item.get("PROFIT").toString() +
"\r\n");
}
myFile.close();
System.out.println("tradeHistory.csv created!");
}
catch(ParseException pe) {
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
}
catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}
Reply:
{"MSG":"TRADE_HISTORY","POSITIONS":[{"OPEN_TIME":"2022.09.19 12:49:05.146","SYMBOL":"EURUSD","TICKET":2012142352,"TYPE":"BUY","VOLUME":0.01,"PRICE_OPEN":0.99746000,"MAGIC":0,"COMMENT":null,"CLOSE_TIME":"2022.09.19 12:50:22.145","PRICE_CLOSE":0.99718000,"PROFIT":-0.28,"COMMISSION":-0.06,"SWAP":0.00,"SL":0.00000,"TP":0.00000},{"OPEN_TIME":"2022.09.19 13:40:13.563","SYMBOL":"EURUSD","TICKET":2012142959,"TYPE":"BUY","VOLUME":0.06,"PRICE_OPEN":0.99776000,"MAGIC":0,"COMMENT":null,"CLOSE_TIME":"2022.09.20 09:37:33.573","PRICE_CLOSE":1.00064500,"PROFIT":17.25,"COMMISSION":-0.31,"SWAP":0.00,"SL":0.99665,"TP":0.00000},{"OPEN_TIME":"2022.09.19 14:46:16.477","SYMBOL":"EURUSD","TICKET":2012143954,"TYPE":"BUY","VOLUME":0.03,"PRICE_OPEN":0.99925000,"MAGIC":0,"COMMENT":null,"CLOSE_TIME":"2022.09.20 09:37:33.55","PRICE_CLOSE":1.00360000,"PROFIT":13.00,"COMMISSION":-0.16,"SWAP":0.00,"SL":0.00000,"TP":0.00000},{"OPEN_TIME":"2022.09.19 14:47:43.642","SYMBOL":"EURUSD","TICKET":2012143985,"TYPE":"BUY","VOLUME":0.03,"PRICE_OPEN":0.99974000,"MAGIC":0,"COMMENT":null,"CLOSE_TIME":"2022.09.20 09:37:32.518","PRICE_CLOSE":1.00361000,"PROFIT":11.57,"COMMISSION":-0.16,"SWAP":0.00,"SL":0.00000,"TP":0.00000},{"OPEN_TIME":"2022.09.19 14:48:40.278","SYMBOL":"EURUSD","TICKET":2012144006,"TYPE":"BUY","VOLUME":0.03,"PRICE_OPEN":0.99974000,"MAGIC":0,"COMMENT":null,"CLOSE_TIME":"2022.09.20 09:37:31.968","PRICE_CLOSE":1.00361000,"PROFIT":11.57,"COMMISSION":-0.16,"SWAP":0.00,"SL":0.00000,"TP":0.00000},{"OPEN_TIME":"2022.09.19 14:57:32.452","SYMBOL":"EURUSD","TICKET":2012144150,"TYPE":"BUY","VOLUME":0.02,"PRICE_OPEN":0.99860000,"MAGIC":0,"COMMENT":null,"CLOSE_TIME":"2022.09.20 09:37:31.206","PRICE_CLOSE":1.00359000,"PROFIT":9.94,"COMMISSION":-0.10,"SWAP":0.00,"SL":0.00000,"TP":0.00000}],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully","DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"}
Creating file...
tradeHistory.csv created!
If we open the tradeHistory.csv:
OPEN_TIME,CLOSE_TIME,TICKET,SYMBOL,MAGIC,PRICE_OPEN,PRICE_CLOSE,TYPE,LOTS,STOP_LOSS,TAKE_PROFIT,SWAP,COMMISSION,COMMENT,PROFIT
2022.09.19 12:49:05.146,2022.09.19 12:50:22.145,2012142352,EURUSD,0,0.99746,0.99718,BUY,0.01,0.0,0.0,0.0,-0.06,null,-0.28
2022.09.19 13:40:13.563,2022.09.20 09:37:33.573,2012142959,EURUSD,0,0.99776,1.000645,BUY,0.06,0.99665,0.0,0.0,-0.31,null,17.25
2022.09.19 14:46:16.477,2022.09.20 09:37:33.55,2012143954,EURUSD,0,0.99925,1.0036,BUY,0.03,0.0,0.0,0.0,-0.16,null,13.0
2022.09.19 14:47:43.642,2022.09.20 09:37:32.518,2012143985,EURUSD,0,0.99974,1.00361,BUY,0.03,0.0,0.0,0.0,-0.16,null,11.57
2022.09.19 14:48:40.278,2022.09.20 09:37:31.968,2012144006,EURUSD,0,0.99974,1.00361,BUY,0.03,0.0,0.0,0.0,-0.16,null,11.57
2022.09.19 14:57:32.452,2022.09.20 09:37:31.206,2012144150,EURUSD,0,0.9986,1.00359,BUY,0.02,0.0,0.0,0.0,-0.1,null,9.94
Have you found any bug or error? Please notify us.
C# (.Net Core 7)
WARNING: All these source codes are only examples used for testing. We don’t provide any guarantee or responsibility about it. Use these examples at your own risk.
New MTsocketAPI C# Library: MTsocketAPI4.dll / MTsocketAPI5.dll
Example 1: Get actual EURUSD price from MT5 with new MTsocketAPI C# library:
using MTsocketAPI.MT5;
namespace Test
{
internal class Program
{
static void Main(string[] args)
{
try
{
Terminal mt5 = new Terminal();
if (!mt5.Connect())
{
Console.WriteLine("Connect failed. Please check that MTsocketAPI is running");
return;
}
Quote quote = mt5.GetQuote("EURUSD");
Console.WriteLine(quote.TIME + " Ask: " + quote.ASK + " Bid: " + quote.BID);
Console.WriteLine("Finished!");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
return;
}
}
}
}
Reply:
2024.02.27 19:08:37.858 Ask: 1.08529 Bid: 1.08527
Example 2: Send Order to MT5 with MTsocketAPI C# library:
using MTsocketAPI.MT5;
namespace Test
{
internal class Program
{
static void Main(string[] args)
{
try
{
Terminal mt5 = new Terminal();
if (!mt5.Connect())
{
Console.WriteLine("Connect failed. Please check that MTsocketAPI is running");
return;
}
TradeResult result = mt5.SendOrder("EURUSD", 0.01, OrderType.ORDER_TYPE_BUY);
if (result.RETCODE == (long)TradeRetCode.TRADE_RETCODE_DONE)
Console.WriteLine("Request completed!. Order: " + result.ORDER);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
return;
}
}
}
}
Reply:
Request completed. Order: 145579904
Example 3: Stream actual EURUSD price from MT5 with C#
using MTsocketAPI.MT5;
namespace Test
{
internal class Program
{
static void Main(string[] args)
{
try
{
Terminal mt5 = new Terminal();
mt5.OnPrice += Mt5_OnPrice;
if (!mt5.Connect())
{
Console.WriteLine("Connect failed. Please check that MTsocketAPI is running");
return;
}
mt5.TrackPrices(new List<string>() { "EURUSD","GBPUSD" });
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
return;
}
}
private static void Mt5_OnPrice(object? sender, Quote e)
{
Console.WriteLine("Quote: " + e.ToString());
}
}
}
Reply:
Quote: {"SYMBOL":"GBPUSD","ASK":1.26898,"BID":1.26889,"FLAGS":0,"TIME":"2024.02.27 19:39:09.015","VOLUME":56353}
Quote: {"SYMBOL":"GBPUSD","ASK":1.26898,"BID":1.26889,"FLAGS":0,"TIME":"2024.02.27 19:39:09.015","VOLUME":56353}
Quote: {"SYMBOL":"EURUSD","ASK":1.08539,"BID":1.08534,"FLAGS":0,"TIME":"2024.02.27 19:39:09.343","VOLUME":58261}
Quote: {"SYMBOL":"EURUSD","ASK":1.08538,"BID":1.08534,"FLAGS":0,"TIME":"2024.02.27 19:39:09.598","VOLUME":58261}
Quote: {"SYMBOL":"GBPUSD","ASK":1.26898,"BID":1.26888,"FLAGS":0,"TIME":"2024.02.27 19:39:10.358","VOLUME":56354}
Quote: {"SYMBOL":"EURUSD","ASK":1.08538,"BID":1.08533,"FLAGS":0,"TIME":"2024.02.27 19:39:11.278","VOLUME":58262}
Quote: {"SYMBOL":"GBPUSD","ASK":1.26898,"BID":1.26889,"FLAGS":0,"TIME":"2024.02.27 19:39:12.030","VOLUME":56355}
Quote: {"SYMBOL":"GBPUSD","ASK":1.26897,"BID":1.26889,"FLAGS":0,"TIME":"2024.02.27 19:39:12.324","VOLUME":56355}
Quote: {"SYMBOL":"GBPUSD","ASK":1.26897,"BID":1.26892,"FLAGS":0,"TIME":"2024.02.27 19:39:12.470","VOLUME":56356}
Quote: {"SYMBOL":"EURUSD","ASK":1.08539,"BID":1.08533,"FLAGS":0,"TIME":"2024.02.27 19:39:12.487","VOLUME":58262}
Quote: {"SYMBOL":"EURUSD","ASK":1.08538,"BID":1.08533,"FLAGS":0,"TIME":"2024.02.27 19:39:12.646","VOLUME":58262}
Quote: {"SYMBOL":"GBPUSD","ASK":1.26898,"BID":1.26892,"FLAGS":0,"TIME":"2024.02.27 19:39:12.698","VOLUME":56356}
Basic Examples for MT5 (for MT4 click here)
Example 1: Get actual EURUSD price from MT5 with C#
using System;
using System.Net.Sockets;
namespace ConsoleApp
{
internal class Program
{
static int bufferLen = 8192;
static void Main(string[] args)
{
TcpClient tcpClient = new TcpClient("127.0.0.1",77);
Byte[] data = System.Text.Encoding.ASCII.GetBytes("{\"MSG\":\"QUOTE\",\"SYMBOL\":\"EURUSD\"}\r\n");
NetworkStream stream = tcpClient.GetStream();
stream.Write(data, 0, data.Length);
data = new Byte[bufferLen];
String responseData = String.Empty;
int bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine(responseData);
stream.Close();
tcpClient.Close();
}
}
}
Reply:
{
"MSG":"QUOTE",
"SYMBOL":"EURUSD",
"ASK":1.08263,
"BID":1.08261,
"FLAGS":6,
"TIME":"2022.04.13 12:01:48.0",
"VOLUME":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Example 2: Send Order to MT5 with C#
using System;
using System.Net.Sockets;
namespace ConsoleApp
{
internal class Program
{
static int bufferLen = 8192;
static void Main(string[] args)
{
TcpClient tcpClient = new TcpClient("127.0.0.1",77);
Byte[] data = System.Text.Encoding.ASCII.GetBytes("{\"MSG\":\"ORDER_SEND\",\"SYMBOL\":\"EURUSD\",\"VOLUME\":0.02,\"TYPE\":\"ORDER_TYPE_SELL\"}\r\n");
NetworkStream stream = tcpClient.GetStream();
stream.Write(data, 0, data.Length);
data = new Byte[bufferLen];
String responseData = String.Empty;
int bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine(responseData);
stream.Close();
tcpClient.Close();
}
}
}
Reply:
{"MSG":"ORDER_SEND","RETCODE":10009,"DEAL":2015119247,"ORDER":2020570871,"VOLUME":0.10,"PRICE":1.064860,"BID":1.064830,"ASK":1.064860,"REQUEST_ID":3136973155,"RETCODE_EXTERNAL":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Example 3: Stream actual EURUSD price from MT5 with C#
using System;
using System.Net.Sockets;
namespace ConsoleApp
{
internal class Program
{
static int bufferLen = 8192;
static void Main(string[] args)
{
TcpClient tcpClient_cmd = new TcpClient("127.0.0.1", 77);
TcpClient tcpClient_data = new TcpClient("127.0.0.1", 78);
Byte[] data = System.Text.Encoding.ASCII.GetBytes("{\"MSG\":\"TRACK_PRICES\",\"SYMBOLS\":[\"EURUSD\"]}\r\n");
NetworkStream stream_cmd = tcpClient_cmd.GetStream();
NetworkStream stream_data = tcpClient_data.GetStream();
stream_cmd.Write(data, 0, data.Length);
data = new Byte[bufferLen];
String responseData = String.Empty;
int bytes = stream_cmd.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine(responseData);
do
{
bytes = stream_data.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine(responseData);
} while (true);
stream_cmd.Close();
stream_data.Close();
tcpClient_cmd.Close();
tcpClient_data.Close();
}
}
}
Reply:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
{"TIME":"2022.04.19 11:45:51","SYMBOL":"EURUSD","ASK":1.07878,"BID":1.07876,"VOLUME":32111}
{"TIME":"2022.04.19 11:45:52","SYMBOL":"EURUSD","ASK":1.07878,"BID":1.07877,"VOLUME":32113}
{"TIME":"2022.04.19 11:45:53","SYMBOL":"EURUSD","ASK":1.07878,"BID":1.07876,"VOLUME":32114}
{"TIME":"2022.04.19 11:45:55","SYMBOL":"EURUSD","ASK":1.07876,"BID":1.07874,"VOLUME":32114}
{"TIME":"2022.04.19 11:45:56","SYMBOL":"EURUSD","ASK":1.07875,"BID":1.07872,"VOLUME":32115}
{"TIME":"2022.04.19 11:45:57","SYMBOL":"EURUSD","ASK":1.07875,"BID":1.07873,"VOLUME":32117}
{"TIME":"2022.04.19 11:46:00","SYMBOL":"EURUSD","ASK":1.07878,"BID":1.07877,"VOLUME":32118}
{"TIME":"2022.04.19 11:46:01","SYMBOL":"EURUSD","ASK":1.07878,"BID":1.07875,"VOLUME":32119}
{"TIME":"2022.04.19 11:46:01","SYMBOL":"EURUSD","ASK":1.07877,"BID":1.07874,"VOLUME":32120}
{"TIME":"2022.04.19 11:46:02","SYMBOL":"EURUSD","ASK":1.07875,"BID":1.07873,"VOLUME":32121}
{"TIME":"2022.04.19 11:46:03","SYMBOL":"EURUSD","ASK":1.07876,"BID":1.07873,"VOLUME":32121}
Advanced Examples
Example 1: Get actual EURUSD price from MT5 (using JSON library) with C#
using System;
using System.Net.Sockets;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ConsoleApp
{
internal class Program
{
static int bufferLen = 8192;
static void Main(string[] args)
{
TcpClient tcpClient = new TcpClient("127.0.0.1", 77);
JObject jo = new JObject();
jo["MSG"] = "QUOTE";
jo["SYMBOL"] = "EURUSD";
Byte[] data = System.Text.Encoding.ASCII.GetBytes(jo.ToString(Formatting.None) + "\r\n");
NetworkStream stream = tcpClient.GetStream();
stream.Write(data, 0, data.Length);
data = new Byte[bufferLen];
String responseData = String.Empty;
int bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
JObject jresult = JsonConvert.DeserializeObject<JObject>(responseData);
Console.WriteLine("Symbol: {0} Ask: {1} Bid: {2} Time: {3}", jresult["SYMBOL"], jresult["ASK"], jresult["BID"], jresult["TIME"]);
stream.Close();
tcpClient.Close();
}
}
}
Reply:
Symbol: EURUSD Ask: 1.07934 Bid: 1.07931 Time: 2022.04.19 12:02:28.0
Example 2: Stream OHLC data from MT5 (using JSON library) with C#
using System;
using System.Net.Sockets;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ConsoleApp
{
internal class Program
{
static int bufferLen = 8192;
static void Main(string[] args)
{
TcpClient tcpClient_cmd = new TcpClient("127.0.0.1", 77);
TcpClient tcpClient_data = new TcpClient("127.0.0.1", 78);
JObject jObj = new JObject();
jObj["MSG"] = "TRACK_OHLC";
JArray ja = new JArray();
JObject jo = new JObject();
jo["SYMBOL"] = "EURUSD";
jo["TIMEFRAME"] = "PERIOD_M1";
jo["DEPTH"] = 1;
ja.Add(jo);
jObj["OHLC"] = ja;
Byte[] data = System.Text.Encoding.ASCII.GetBytes(jObj.ToString(Newtonsoft.Json.Formatting.None) + "\r\n");
NetworkStream stream_cmd = tcpClient_cmd.GetStream();
NetworkStream stream_data = tcpClient_data.GetStream();
stream_cmd.Write(data, 0, data.Length);
data = new Byte[bufferLen];
String responseData = String.Empty;
int bytes = stream_cmd.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine(responseData);
do
{
bytes = stream_data.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine(responseData);
} while (true);
stream_cmd.Close();
stream_data.Close();
tcpClient_cmd.Close();
tcpClient_data.Close();
}
}
}
Reply:
{"MSG":"TRACK_OHLC","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Time: 2022.04.19 12:15:00 Symbol: EURUSD Open: 1.07865 Close: 1.07854 High: 1.07867 Low: 1.07854
Time: 2022.04.19 12:16:00 Symbol: EURUSD Open: 1.07855 Close: 1.07874 High: 1.07879 Low: 1.07855
Time: 2022.04.19 12:17:00 Symbol: EURUSD Open: 1.07880 Close: 1.07867 High: 1.07881 Low: 1.07860
Time: 2022.04.19 12:18:00 Symbol: EURUSD Open: 1.07869 Close: 1.07870 High: 1.07872 Low: 1.07859
Time: 2022.04.19 12:19:00 Symbol: EURUSD Open: 1.07871 Close: 1.07868 High: 1.07872 Low: 1.07868
Time: 2022.04.19 12:20:00 Symbol: EURUSD Open: 1.07867 Close: 1.07877 High: 1.07878 Low: 1.07867
Time: 2022.04.19 12:21:00 Symbol: EURUSD Open: 1.07878 Close: 1.07883 High: 1.07884 Low: 1.07869
Example 3: Export Trade History from MT5 to a CSV file with C#
using System;
using System.Net.Sockets;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ConsoleApp
{
internal class Program
{
static int bufferLen = 8192;
static void Main(string[] args)
{
TcpClient tcpClient = new TcpClient("127.0.0.1", 77);
JObject jo = new JObject();
jo["MSG"] = "TRADE_HISTORY";
jo["MODE"] = "POSITIONS";
jo["FROM_DATE"] = "2023/08/20 00:00:00";
jo["TO_DATE"] = "2023/08/24 13:00:00";
Byte[] data = System.Text.Encoding.ASCII.GetBytes(jo.ToString(Newtonsoft.Json.Formatting.None) + "\r\n");
NetworkStream stream = tcpClient.GetStream();
stream.Write(data, 0, data.Length);
data = new Byte[bufferLen];
String responseData = String.Empty;
int bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
JObject jresult = JsonConvert.DeserializeObject<JObject>(responseData);
System.IO.File.AppendAllText("tradeHistory.csv", "OPEN_TIME,CLOSE_TIME,TICKET,SYMBOL,MAGIC,OPEN_PRICE,CLOSE_PRICE,TYPE,LOTS,STOP_LOSS,TAKE_PROFIT,SWAP,COMMISSION,COMMENT,PROFIT" + Environment.NewLine);
foreach (var item in jresult["POSITIONS"])
{
System.IO.File.AppendAllText("tradeHistory.csv",
item["OPEN_TIME"].ToString() + "," +
item["CLOSE_TIME"].ToString() + "," +
item["TICKET"].ToString() + "," +
item["SYMBOL"].ToString() + "," +
item["MAGIC"].ToString() + "," +
item["PRICE_CLOSE"].ToString() + "," +
item["PRICE_OPEN"].ToString() + "," +
item["TYPE"].ToString() + "," +
item["VOLUME"].ToString() + "," +
item["SL"].ToString() + "," +
item["TP"].ToString() + "," +
item["SWAP"].ToString() + "," +
item["COMMISSION"].ToString() + "," +
item["COMMENT"].ToString() + "," +
item["PROFIT"].ToString() +
Environment.NewLine);
}
Console.WriteLine("Finished!");
stream.Close();
tcpClient.Close();
}
}
}
Reply:
Finished!
If we open the tradeHistory.csv:
OPEN_TIME,CLOSE_TIME,TICKET,SYMBOL,MAGIC,PRICE_OPEN,PRICE_CLOSE,TYPE,LOTS,STOP_LOSS,TAKE_PROFIT,SWAP,COMMISSION,COMMENT,PROFIT
2023.08.20 12:30:25,2022.04.13 13:11:25,7103675,EURUSD,0,1.08424,1.08268,BUY,0.02,0,0,0,0,,-3.12
2023.08.20 09:14:18,2022.04.13 13:11:26,7103114,EURUSD,0,1.08342,1.0827,BUY,0.02,0,0,0,0,,-1.44
2023.08.20 07:52:48,2022.04.13 08:00:26,7102744,GBPUSD,0,1.29926,1.29862,SELL,0.02,0,0,0,0,,1.28
2023.08.20 13:26:59,2022.04.13 08:00:25,7099159,EURUSD,0,1.08522,1.08236,SELL,0.01,0,0,0,0,from #47099158,2.86
2023.08.20 13:26:59,2022.04.12 13:27:15,7099158,EURUSD,0,1.08522,1.08524,SELL,0.01,0,0,0,0,to #47099159,-0.02
2023.08.20 13:24:31,2022.04.12 13:26:58,7099144,EURUSD,0,1.08547,1.08523,SELL,0.01,0,0,0,0,from #47099143,0.24
2023.08.20 13:24:31,2022.04.12 13:24:55,7099143,EURUSD,0,1.08547,1.08559,SELL,0.01,0,0,0,0,to #47099144,-0.12
2023.08.20 13:23:10,2022.04.12 13:24:30,7099140,EURUSD,0,1.08556,1.08549,SELL,0.01,0,0,0,0,from #47099139,0.07
2023.08.20 13:23:10,2022.04.12 13:23:27,7099139,EURUSD,0,1.08556,1.08561,SELL,0.01,0,0,0,0,to #47099140,-0.05
2023.08.20 13:21:07,2022.04.12 13:21:21,7099135,EURUSD,0,1.0859,1.08582,BUY,0.02,0,0,0,0,,-0.16
2023.08.20 12:12:43,2022.04.12 19:38:00,7098889,EURUSD,0,1.07,1.08273,BUY LIMIT,0.02,1.0021,0,0,0,expiration [2022.04.12 19:38],0
2023.08.20 12:01:37,2022.04.12 13:18:42,7098870,EURUSD,0,1.08678,1.08562,BUY,0.01,0,0,0,0,,-1.16
Have you found any bug or error? Please notify us.
Basic Trading Application using MTsocketAPI5.dll
Example written in C# using our MTsocketAPI library:
MTsocketAPI C# Library source code: GitHub
Basic Trading Application source code: GitHub
PowerShell
WARNING: All these source codes are only examples used for testing. We don’t provide any guarantee or responsibility about it. Use these examples at your own risk.
Basic Examples for MT5 (for MT4 click here)
Example 1: Get actual EURUSD price to MT5 using PowerShell
$IP = [System.Net.Dns]::GetHostAddresses("127.0.0.1")
$Port = 77
$Address = [System.Net.IPAddress]::Parse($IP)
$Socket = New-Object System.Net.Sockets.TCPClient($Address,$Port)
$Stream = $Socket.GetStream()
$Writer = New-Object System.IO.StreamWriter($Stream)
$Reader = New-Object System.IO.StreamReader($Stream)
$Writer.WriteLine('{"MSG":"QUOTE","SYMBOL":"EURUSD"}')
$Writer.Flush()
$Response = $Reader.ReadLine()
Write-Host $Response
$Stream.Close()
$Socket.Close()
Reply:
{
"MSG":"QUOTE",
"SYMBOL":"EURUSD",
"ASK":1.08263,
"BID":1.08261,
"FLAGS":6,
"TIME":"2022.04.13 12:01:48.0",
"VOLUME":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Example 2: Send Order to MT5 using PowerShell
$IP = [System.Net.Dns]::GetHostAddresses("127.0.0.1")
$Port = 77
$Address = [System.Net.IPAddress]::Parse($IP)
$Socket = New-Object System.Net.Sockets.TCPClient($Address,$Port)
$Stream = $Socket.GetStream()
$Writer = New-Object System.IO.StreamWriter($Stream)
$Reader = New-Object System.IO.StreamReader($Stream)
$Writer.WriteLine('{"MSG":"ORDER_SEND","SYMBOL":"EURUSD","VOLUME":0.02,"TYPE":"ORDER_TYPE_BUY"}')
$Writer.Flush()
$Response = $Reader.ReadLine()
Write-Host $Response
$Stream.Close()
$Socket.Close()
Reply:
{"MSG":"ORDER_SEND","RETCODE":10009,"DEAL":2015119247,"ORDER":2020570871,"VOLUME":0.10,"PRICE":1.064860,"BID":1.064830,"ASK":1.064860,"REQUEST_ID":3136973155,"RETCODE_EXTERNAL":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Example 3: Stream actual EURUSD price from MT5 using PowerShell
$IP = [System.Net.Dns]::GetHostAddresses("127.0.0.1")
$Port_cmd = 77
$Port_data = 78
$Address = [System.Net.IPAddress]::Parse($IP)
$Socket_cmd = New-Object System.Net.Sockets.TCPClient($Address,$Port_cmd)
$Socket_data = New-Object System.Net.Sockets.TCPClient($Address,$Port_data)
$Stream_cmd = $Socket_cmd.GetStream()
$Stream_data = $Socket_data.GetStream()
$Writer_cmd = New-Object System.IO.StreamWriter($Stream_cmd)
$Reader_cmd = New-Object System.IO.StreamReader($Stream_cmd)
$Writer_data = New-Object System.IO.StreamWriter($Stream_data)
$Reader_data = New-Object System.IO.StreamReader($Stream_data)
$Writer_cmd.WriteLine('{"MSG":"TRACK_PRICES","SYMBOLS":["EURUSD"]}')
$Writer_cmd.Flush()
$Response_cmd = $Reader_cmd.ReadLine()
Write-Host $Response_cmd
while ($true)
{
$Response_data = $Reader_data.ReadLine()
Write-Host $Response_data
}
$Stream_cmd.Close()
$Socket_cmd.Close()
$Stream_data.Close()
$Socket_data.Close()
Reply:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
{"TIME":"2022.04.13 12:20:04","SYMBOL":"EURUSD","ASK":1.08373,"BID":1.08371,"VOLUME":19596}
{"TIME":"2022.04.13 12:20:13","SYMBOL":"EURUSD","ASK":1.08373,"BID":1.08370,"VOLUME":19596}
{"TIME":"2022.04.13 12:20:14","SYMBOL":"EURUSD","ASK":1.08373,"BID":1.08371,"VOLUME":26891}
{"TIME":"2022.04.13 12:20:14","SYMBOL":"EURUSD","ASK":1.08373,"BID":1.08370,"VOLUME":26892}
{"TIME":"2022.04.13 12:20:17","SYMBOL":"EURUSD","ASK":1.08373,"BID":1.08371,"VOLUME":26893}
Advanced Examples
Example 1: Get actual EURUSD price from MT5 using PowerShell (using JSON library)
$IP = [System.Net.Dns]::GetHostAddresses("127.0.0.1")
$Port = 77
$Address = [System.Net.IPAddress]::Parse($IP)
$Socket = New-Object System.Net.Sockets.TCPClient($Address,$Port)
$Stream = $Socket.GetStream()
$Writer = New-Object System.IO.StreamWriter($Stream)
$Reader = New-Object System.IO.StreamReader($Stream)
$Cmd = "" | Select MSG,SYMBOL
$Cmd.MSG = "QUOTE"
$Cmd.SYMBOL = "EURUSD"
$Json = ConvertTo-Json $Cmd -Compress
$Writer.WriteLine($Json)
$Writer.Flush()
$Response = $Reader.ReadLine()
Write-Host $Response
$Stream.Close()
$Socket.Close()
Reply:
{"MSG":"QUOTE","SYMBOL":"EURUSD"}
{"MSG":"QUOTE","SYMBOL":"EURUSD","ASK":1.07881,"BID":1.07880,"FLAGS":6,"TIME":"2022.04.18 09:34:36.0","VOLUME":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Example 2: Stream OHLC data from MT5 using PowerShell (using JSON library)
$IP = [System.Net.Dns]::GetHostAddresses("127.0.0.1")
$Port_cmd = 77
$Port_data = 78
$Address = [System.Net.IPAddress]::Parse($IP)
$Socket_cmd = New-Object System.Net.Sockets.TCPClient($Address,$Port_cmd)
$Socket_data = New-Object System.Net.Sockets.TCPClient($Address,$Port_data)
$Stream_cmd = $Socket_cmd.GetStream()
$Stream_data = $Socket_data.GetStream()
$Writer_cmd = New-Object System.IO.StreamWriter($Stream_cmd)
$Reader_cmd = New-Object System.IO.StreamReader($Stream_cmd)
$Writer_data = New-Object System.IO.StreamWriter($Stream_data)
$Reader_data = New-Object System.IO.StreamReader($Stream_data)
$Cmd = "" | Select MSG,OHLC
$cmd.MSG = "TRACK_OHLC"
$Items = "" | Select SYMBOL,TIMEFRAME,DEPTH
$Items.SYMBOL = "EURUSD"
$Items.TIMEFRAME = "PERIOD_M1"
$Items.DEPTH = 1
$Sub = @()
$Sub += $Items
$Cmd.OHLC = $Sub
$Json = ConvertTo-Json $Cmd -Compress
$Writer_cmd.WriteLine($Json)
$Writer_cmd.Flush()
$Response_cmd = $Reader_cmd.ReadLine()
Write-Host $Response_cmd
while ($true)
{
$Response_data = $Reader_data.ReadLine()
Write-Host $Response_data
}
$Stream_cmd.Close()
$Socket_cmd.Close()
$Stream_data.Close()
$Socket_data.Close()
Reply:
{"MSG":"TRACK_OHLC","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
{"SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2022.04.18 09:48:00","OPEN":1.07913,"HIGH":1.07924,"LOW":1.07911,"CLOSE":1.07924,"TICK_VOLUME":24}]}
{"SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2022.04.18 09:49:00","OPEN":1.07926,"HIGH":1.07927,"LOW":1.07911,"CLOSE":1.07920,"TICK_VOLUME":32}]}
{"SYMBOL":"EURUSD","PERIOD":"PERIOD_M1","OHLC":[{"TIME":"2022.04.18 09:50:00","OPEN":1.07920,"HIGH":1.07920,"LOW":1.07910,"CLOSE":1.07914,"TICK_VOLUME":26}]}
Example 3: Export Trade History from MT5 to CSV using PowerShell
$IP = "127.0.0.1"
$Port = 77
$Address = [System.Net.IPAddress]::Parse($IP)
$Socket = New-Object System.Net.Sockets.TCPClient($Address,$Port)
$Stream = $Socket.GetStream()
$Writer = New-Object System.IO.StreamWriter($Stream)
$Reader = New-Object System.IO.StreamReader($Stream)
$Cmd = "" | Select MSG,MODE,FROM_DATE,TO_DATE
$Cmd.MSG = "TRADE_HISTORY"
$Cmd.MODE = "POSITIONS"
$Cmd.FROM_DATE = "2022/09/29 00:00:00"
$Cmd.TO_DATE = "2022/09/30 00:00:00"
$Json = ConvertTo-Json $Cmd -Compress
$Writer.WriteLine($Json)
$Writer.Flush()
$Response = $Reader.ReadLine()
$DataObj = ConvertFrom-Json $Response
if ($DataObj.ERROR_ID -ge 0) {
$DataObj.POSITIONS | Export-Csv -Path "History.csv" -Delimiter "," -NoTypeInformation
Write-Host "Exported to CSV!"
}
else {
Write-Host $DataObj.ERROR_DESCRIPTION
}
$Stream.Close()
$Socket.Close()
Reply:
Exported to CSV!
Have you found any bug or error? Please notify us.
C++
WARNING: All these source codes are only examples used for testing. We don’t provide any guarantee or responsibility about it. Use these examples at your own risk.
Basic Examples for MT5 (for MT5 click here)
Example 1: Get actual EURUSD price from MT5 with C++
quote.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
/*
*
*
* gcc -o quote quote.c (Compile)
* ./quote 127.0.0.1 77 (Run)
*
*/
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char msg[]="{\"MSG\":\"QUOTE\",\"SYMBOL\":\"EURUSD\"}\r\n";
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
return 0;
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
printf("ERROR opening socket\r\n");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
printf("ERROR connecting\r\n");
return 0;
}
n = write(sockfd, msg, strlen(msg));
if (n < 0)
printf("ERROR writing to socket\r\n");
bzero(buffer,256);
n = read(sockfd, buffer, 255);
if (n < 0)
printf("ERROR reading from socket\r\n");
printf("%s\n", buffer);
close(sockfd);
return 0;
}
Reply:
./quote 127.0.0.1 77
{"MSG":"QUOTE","SYMBOL":"EURUSD","ASK":0.99914,"BID":0.99911,"FLAGS":6,"TIME":"2022.09.19 14:44:09.980","VOLUME":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Example 2: Send Order to MT5 with C++
sendorder.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
/*
*
*
* gcc -o sendorder sendorder.c (Compile)
* ./sendorder 127.0.0.1 77 (Run)
*
*/
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char msg[]="{\"MSG\":\"ORDER_SEND\",\"SYMBOL\":\"EURUSD\",\"VOLUME\":0.03,\"TYPE\":\"ORDER_TYPE_BUY\"}\r\n";
char buffer[512];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
return 0;
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
printf("ERROR opening socket\r\n");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
printf("ERROR connecting\r\n");
return 0;
}
n = write(sockfd, msg, strlen(msg));
if (n < 0)
printf("ERROR writing to socket\r\n");
bzero(buffer,512);
n = read(sockfd, buffer, 511);
if (n < 0)
printf("ERROR reading from socket\r\n");
printf("%s\n", buffer);
close(sockfd);
return 0;
}
Reply:
./sendorder 127.0.0.1 77
{"MSG":"ORDER_SEND","RETCODE":10009,"DEAL":2015119247,"ORDER":2020570871,"VOLUME":0.10,"PRICE":1.064860,"BID":1.064830,"ASK":1.064860,"REQUEST_ID":3136973155,"RETCODE_EXTERNAL":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Example 3: Stream actual EURUSD price from MT5 with C++
streamprices.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
/*
*
*
* gcc -o trackprices trackprices.c (Compile)
* ./trackprices 127.0.0.1 (Run)
*
*/
int main(int argc, char *argv[])
{
int sockfd_cmd, portno_cmd, n;
int sockfd_data, portno_data;
struct sockaddr_in serv_addr_cmd;
struct sockaddr_in serv_addr_data;
struct hostent *server_cmd;
struct hostent *server_data;
char msg[]="{\"MSG\":\"TRACK_PRICES\",\"SYMBOLS\":[\"EURUSD\"],\"TIMEFRAME\":\"PERIOD_M1\"}\r\n";
char buffer[256];
if (argc < 2) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
return 0;
}
portno_cmd = 77;
portno_data = 78;
sockfd_cmd = socket(AF_INET, SOCK_STREAM, 0);
sockfd_data = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd_cmd < 0)
printf("ERROR opening cmd socket\r\n");
if (sockfd_data < 0)
printf("ERROR opening data socket\r\n");
server_cmd = gethostbyname(argv[1]);
server_data = gethostbyname(argv[1]);
if (server_cmd == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr_cmd, sizeof(serv_addr_cmd));
bzero((char *) &serv_addr_data, sizeof(serv_addr_data));
serv_addr_cmd.sin_family = AF_INET;
serv_addr_data.sin_family = AF_INET;
bcopy((char *)server_cmd->h_addr,
(char *)&serv_addr_cmd.sin_addr.s_addr,
server_cmd->h_length);
bcopy((char *)server_data->h_addr,
(char *)&serv_addr_data.sin_addr.s_addr,
server_data->h_length);
serv_addr_cmd.sin_port = htons(portno_cmd);
serv_addr_data.sin_port = htons(portno_data);
if (connect(sockfd_cmd, (struct sockaddr *) &serv_addr_cmd, sizeof(serv_addr_cmd)) < 0)
{
printf("ERROR connecting to cmd port\r\n");
return 0;
}
if (connect(sockfd_data, (struct sockaddr *) &serv_addr_data, sizeof(serv_addr_data)) < 0)
{
printf("ERROR connecting to data port\r\n");
return 0;
}
n = write(sockfd_cmd, msg, strlen(msg));
if (n < 0)
printf("ERROR writing to socket\r\n");
bzero(buffer,256);
n = read(sockfd_cmd, buffer, 255);
if (n < 0)
printf("ERROR reading from socket\r\n");
printf("%s\n", buffer);
bzero(buffer,256);
while(1) {
n = read(sockfd_data, buffer, 255);
printf("%s", buffer);
}
close(sockfd_cmd);
close(sockfd_data);
return 0;
}
Reply:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
{"TIME":"2022.04.19 10:36:18","SYMBOL":"EURUSD","ASK":1.08011,"BID":1.08009,"VOLUME":29274}
{"TIME":"2022.04.19 10:36:19","SYMBOL":"EURUSD","ASK":1.08012,"BID":1.08009,"VOLUME":29276}
{"TIME":"2022.04.19 10:36:20","SYMBOL":"EURUSD","ASK":1.08011,"BID":1.08009,"VOLUME":29276}
{"TIME":"2022.04.19 10:36:21","SYMBOL":"EURUSD","ASK":1.08009,"BID":1.08008,"VOLUME":29278}
{"TIME":"2022.04.19 10:36:22","SYMBOL":"EURUSD","ASK":1.08009,"BID":1.08007,"VOLUME":29279}
{"TIME":"2022.04.19 10:36:28","SYMBOL":"EURUSD","ASK":1.08009,"BID":1.08006,"VOLUME":29280}
Advanced Examples
Example 1: Get actual EURUSD price from MT5 (using JSON library) with C++
In progress
Example 2: Stream OHLC data from MT5 (using JSON library) with C++
In progress
Example 3: Export MT5 Trade History from MT5 to a CSV file with C++
In progress
Have you found any bug or error? Please notify us.
NodeJS
WARNING: All these source codes are only examples used for testing. We don’t provide any guarantee or responsibility about it. Use these examples at your own risk.
Basic Examples for MT5 (for MT4 click here)
Example 1: Get actual EURUSD price from MT5 using NodeJS
// Include Nodejs' net module.
const Net = require('net');
// The port number and hostname of the server.
const port = 77;
const host = 'localhost';
// Create a new TCP client.
const client = new Net.Socket();
// Send a connection request to the server.
client.connect(port, host, function() {
// The client can now send data to the server by writing to its socket.
client.write('{"MSG":"QUOTE","SYMBOL":"EURUSD"}' + '\r\n');
});
// The client can also receive data from the server by reading from its socket.
client.on('data', function(chunk) {
console.log(`${chunk.toString()}`);
client.end();
});
Reply:
{
"MSG":"QUOTE",
"SYMBOL":"EURUSD",
"ASK":1.08263,
"BID":1.08261,
"FLAGS":6,
"TIME":"2022.04.13 12:01:48.0",
"VOLUME":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"The operation completed successfully"
}
Example 2: Send Order to MT5 using NodeJS
const Net = require('net');
const client_cmd = new Net.Socket();
client_cmd.connect(77, "localhost", function() {
client_cmd.write('{"MSG":"ORDER_SEND","SYMBOL":"EURUSD","VOLUME":0.02,"TYPE":"ORDER_TYPE_BUY"}' + '\r\n');
});
client_cmd.on('data', function(chunk) {
console.log(`${chunk.toString()}`);
client_cmd.end();
});
Reply:
{"MSG":"ORDER_SEND","RETCODE":10009,"DEAL":2015119247,"ORDER":2020570871,"VOLUME":0.10,"PRICE":1.064860,"BID":1.064830,"ASK":1.064860,"REQUEST_ID":3136973155,"RETCODE_EXTERNAL":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Example 3: Stream actual EURUSD price from MT5 using NodeJS
const Net = require('net');
const client_cmd = new Net.Socket();
const client_data = new Net.Socket();
client_cmd.connect(77, "localhost", function() {
client_cmd.write('{"MSG":"TRACK_PRICES","SYMBOLS":["EURUSD"]}' + '\r\n');
});
client_cmd.on('data', function(chunk) {
console.log(`${chunk.toString()}`);
client_cmd.end();
});
client_data.connect(78, "localhost");
client_data.on('data', function(chunk) {
console.log(`${chunk.toString()}`);
});
Reply:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Advanced Examples
Example 1: Get actual EURUSD price from MT5 (using JSON library) with NodeJS
const Net = require('net');
const client_cmd = new Net.Socket();
client_cmd.connect(77, "localhost", function() {
const JSONobj = {};
JSONobj["MSG"]="QUOTE";
JSONobj["SYMBOL"]="EURUSD";
client_cmd.write(JSON.stringify(JSONobj) + '\r\n');
});
client_cmd.on('data', function(chunk) {
//console.log(`${chunk.toString()}`);
const JSONresult = JSON.parse(chunk.toString());
console.log(`Time: ${JSONresult["TIME"]} Symbol: ${JSONresult["SYMBOL"]} Ask: ${JSONresult["ASK"]} Bid: ${JSONresult["BID"]}`);
client_cmd.end();
});
Reply:
Time: 2022.04.13 13:01:20.0 Symbol: EURUSD Ask: 1.08335 Bid: 1.08333
Example 2: Stream OHLC data from MT5 (using JSON library) with NodeJS
const Net = require('net');
const client_cmd = new Net.Socket();
const client_data = new Net.Socket();
client_cmd.connect(77, "localhost", function() {
const JSONobj = {};
const subJSONobj = {};
JSONobj["MSG"] = "TRACK_OHLC";
subJSONobj["SYMBOL"] = "EURUSD";
subJSONobj["TIMEFRAME"] = "PERIOD_M1";
subJSONobj["DEPTH"] = 1;
JSONobj["OHLC"] = [subJSONobj];
client_cmd.write(JSON.stringify(JSONobj) + '\r\n');
});
client_cmd.on('data', function(chunk) {
console.log(`${chunk.toString()}`);
client_cmd.end();
});
client_data.connect(78, "localhost");
client_data.on('data', function(chunk) {
//console.log(`${chunk.toString()}`);
var str = chunk.toString();
var lines = str.split("\n");
for (var i = 0; i < lines.length; i++) {
if (lines[i].search("OHLC")>0) {
const JSONresult = JSON.parse(lines[i]);
console.log(`Time: ${JSONresult["OHLC"][0]["TIME"]} Symbol: ${JSONresult["SYMBOL"]} Close Price: ${JSONresult["OHLC"][0]["CLOSE"]}`);
}
}
});
Reply:
{"MSG":"TRACK_OHLC","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully","DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"}
Time: 2022.09.20 11:23:00 Symbol: EURUSD Close Price: 1.00055
Time: 2022.09.20 11:24:00 Symbol: EURUSD Close Price: 1.00033
Time: 2022.09.20 11:25:00 Symbol: EURUSD Close Price: 1.00009
Time: 2022.09.20 11:26:00 Symbol: EURUSD Close Price: 1.00048
Time: 2022.09.20 11:27:00 Symbol: EURUSD Close Price: 1.00051
Time: 2022.09.20 11:28:00 Symbol: EURUSD Close Price: 1.00056
Example 3: Export Trade History from MT5 to a CSV file using NodeJS
const Net = require('net');
const fs = require('fs');
const delimiter = ',';
const client_cmd = new Net.Socket();
client_cmd.connect(77, "localhost", function() {
const JSONobj = {};
JSONobj["MSG"]="TRADE_HISTORY";
JSONobj["FROM_DATE"]="2022/09/19 13:00:00";
JSONobj["TO_DATE"]="2022/09/20 00:00:00";
JSONobj["MODE"]="POSITIONS";
client_cmd.write(JSON.stringify(JSONobj) + '\r\n');
});
client_cmd.on('data', function(chunk) {
const JSONresult = JSON.parse(chunk.toString());
console.log(chunk.toString());
console.log(`Number of trades: ${Object.keys(JSONresult['POSITIONS']).length}`);
fs.writeFileSync('tradeHistory.csv','OPEN_TIME,CLOSE_TIME,TICKET,SYMBOL,PRICE_OPEN,PRICE_CLOSE,PROFIT\r\n',{ flag: 'a+' });
for(let i = 0; i < Object.keys(JSONresult['POSITIONS']).length; i++) {
//console.log(JSONresult['TRADES'][i]['OPEN_TIME']);
const OPEN_TIME = JSONresult['POSITIONS'][i]['OPEN_TIME'];
const CLOSE_TIME = JSONresult['POSITIONS'][i]['CLOSE_TIME'];
const TICKET = JSONresult['POSITIONS'][i]['TICKET'];
const SYMBOL = JSONresult['POSITIONS'][i]['SYMBOL'];
const PRICE_OPEN = JSONresult['POSITIONS'][i]['PRICE_OPEN'];
const PRICE_CLOSE = JSONresult['POSITIONS'][i]['PRICE_CLOSE'];
const PROFIT = JSONresult['POSITIONS'][i]['PROFIT'];
fs.writeFileSync('tradeHistory.csv', OPEN_TIME + delimiter + CLOSE_TIME + delimiter + TICKET + delimiter + SYMBOL + delimiter + PRICE_OPEN + delimiter + PRICE_CLOSE + delimiter + PROFIT + '\r\n',{ flag: 'a+' });
}
console.log('Finished!');
client_cmd.end();
});
Reply:
{"MSG":"TRADE_HISTORY","POSITIONS":[{"OPEN_TIME":"2022.09.19 13:40:13.563","SYMBOL":"EURUSD","TICKET":2012142959,"TYPE":"BUY","VOLUME":0.06,"PRICE_OPEN":0.99776000,"MAGIC":0,"COMMENT":null,"CLOSE_TIME":"2022.09.19 13:40:55.999","PRICE_CLOSE":0.99769000,"PROFIT":-0.21,"COMMISSION":-0.23,"SWAP":0.00,"SL":0.00000,"TP":0.00000},{"OPEN_TIME":"2022.09.19 14:46:16.477","SYMBOL":"EURUSD","TICKET":2012143954,"TYPE":"BUY","VOLUME":0.03,"PRICE_OPEN":0.99925000,"MAGIC":0,"COMMENT":null,"CLOSE_TIME":"2022.09.19 14:46:16.477","PRICE_CLOSE":0.99925000,"PROFIT":0.00,"COMMISSION":-0.08,"SWAP":0.00,"SL":0.00000,"TP":0.00000},{"OPEN_TIME":"2022.09.19 14:47:43.642","SYMBOL":"EURUSD","TICKET":2012143985,"TYPE":"BUY","VOLUME":0.03,"PRICE_OPEN":0.99974000,"MAGIC":0,"COMMENT":null,"CLOSE_TIME":"2022.09.19 14:47:43.642","PRICE_CLOSE":0.99974000,"PROFIT":0.00,"COMMISSION":-0.08,"SWAP":0.00,"SL":0.00000,"TP":0.00000},{"OPEN_TIME":"2022.09.19 14:48:40.278","SYMBOL":"EURUSD","TICKET":2012144006,"TYPE":"BUY","VOLUME":0.03,"PRICE_OPEN":0.99974000,"MAGIC":0,"COMMENT":null,"CLOSE_TIME":"2022.09.19 14:48:40.278","PRICE_CLOSE":0.99974000,"PROFIT":0.00,"COMMISSION":-0.08,"SWAP":0.00,"SL":0.00000,"TP":0.00000},{"OPEN_TIME":"2022.09.19 14:57:32.452","SYMBOL":"EURUSD","TICKET":2012144150,"TYPE":"BUY","VOLUME":0.02,"PRICE_OPEN":0.99860000,"MAGIC":0,"COMMENT":null,"CLOSE_TIME":"2022.09.19 14:57:32.452","PRICE_CLOSE":0.99860000,"PROFIT":0.00,"COMMISSION":-0.05,"SWAP":0.00,"SL":0.00000,"TP":0.00000}],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Number of trades: 5
Finished!
Have you found any bug or error? Please notify us.
Go
WARNING: All these source codes are only examples used for testing. We don’t provide any guarantee or responsibility about it. Use these examples at your own risk.
Examples using Go version 1.13.8
Basic Examples for MT5 (for MT4 click here)
Example 1: Get actual EURUSD price from MT5 using Go
package main
import (
"fmt"
"net"
)
func main() {
con, err :=net.Dial("tcp", "localhost:77")
if err != nil { fmt.Println(err) }
defer con.Close()
msg := "{\"MSG\":\"QUOTE\",\"SYMBOL\":\"EURUSD\"}\r\n"
_, err = con.Write([]byte(msg))
if err != nil { fmt.Println(err) }
reply := make([]byte, 1024)
_, err = con.Read(reply)
if err != nil { fmt.Println(err) }
fmt.Println(string(reply))
}
Reply:
{"MSG":"QUOTE","SYMBOL":"EURUSD","ASK":0.99832,"BID":0.99828,"FLAGS":2,"TIME":"2022.09.19 14:56:33.108","VOLUME":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Example 2: Send Order to MT5 using Go
package main
import (
"fmt"
"net"
)
func main() {
con, err := net.Dial("tcp", "localhost:77")
if err != nil { fmt.Println(err) }
defer con.Close()
msg := "{\"MSG\":\"ORDER_SEND\",\"SYMBOL\":\"EURUSD\",\"TYPE\":\"ORDER_TYPE_BUY\",\"VOLUME\":0.02}\r\n"
_, err = con.Write([]byte(msg))
if err != nil { fmt.Println(err) }
reply := make([]byte, 1024)
_, err = con.Read(reply)
if err != nil { fmt.Println(err) }
fmt.Println(string(reply))
}
Reply:
{"MSG":"ORDER_SEND","RETCODE":10009,"DEAL":2015119247,"ORDER":2020570871,"VOLUME":0.10,"PRICE":1.064860,"BID":1.064830,"ASK":1.064860,"REQUEST_ID":3136973155,"RETCODE_EXTERNAL":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
Example 3: Stream actual EURUSD price from MT5 using Go
package main
import (
"fmt"
"net"
)
func main() {
con1, err := net.Dial("tcp", "localhost:77")
if err != nil { fmt.Println(err) }
con2, err := net.Dial("tcp", "localhost:78")
if err != nil { fmt.Println(err) }
defer con1.Close()
defer con2.Close()
msg := "{\"MSG\":\"TRACK_PRICES\",\"SYMBOLS\":[\"EURUSD\"]}\r\n"
_, err = con1.Write([]byte(msg))
if err != nil { fmt.Println(err) }
reply := make([]byte, 1024)
_, err = con1.Read(reply)
if err != nil { fmt.Println(err) }
fmt.Println(string(reply))
for{
reply = make([]byte, 1024)
_, err = con2.Read(reply)
if err != nil { fmt.Println(err) }
fmt.Println(string(reply))
}
}
Reply:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}
{"TIME":"2022.04.13 09:08:02","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08384,"VOLUME":18404}
{"TIME":"2022.04.13 09:08:03","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08385,"VOLUME":18405}
{"TIME":"2022.04.13 09:08:03","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08384,"VOLUME":18407}
{"TIME":"2022.04.13 09:08:04","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08380,"VOLUME":18408}
{"TIME":"2022.04.13 09:08:05","SYMBOL":"EURUSD","ASK":1.08384,"BID":1.08382,"VOLUME":18408}
{"TIME":"2022.04.13 09:08:05","SYMBOL":"EURUSD","ASK":1.08385,"BID":1.08382,"VOLUME":18410}
{"TIME":"2022.04.13 09:08:06","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08381,"VOLUME":18411}
{"TIME":"2022.04.13 09:08:06","SYMBOL":"EURUSD","ASK":1.08384,"BID":1.08381,"VOLUME":18411}
{"TIME":"2022.04.13 09:08:07","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08381,"VOLUME":18412}
...
Advanced Examples
Example 1: Get actual EURUSD price from MT5 (using JSON library) using Go
package main
import (
"encoding/json"
"fmt"
"net"
)
type quoteCommand struct {
MSG string
SYMBOL string
}
func main() {
cmd := quoteCommand{
MSG: "QUOTE",
SYMBOL: "EURUSD",
}
jsonData, err := json.Marshal(cmd)
con, err := net.Dial("tcp", "localhost:77")
if err != nil { fmt.Println(err) }
msg := string(jsonData) + "\r\n"
_, err = con.Write([]byte(msg))
if err != nil { fmt.Println(err) }
reply := make([]byte, 1024)
msgLen, err := con.Read(reply)
if err != nil { fmt.Println(err) }
con.Close()
bytes := []byte(string(reply[0:msgLen]))
var result map[string]interface{}
json.Unmarshal(bytes, &result)
fmt.Printf("Symbol: %s Ask: %f Bid: %f\n", result["SYMBOL"],result["ASK"],result["BID"])
}
Reply:
Symbol: EURUSD Ask: 1.022240 Bid: 1.022200
Example 2: Stream OHLC data from MT5 (using JSON library) using Go
In Progress
Example 3: Export Trade History from MT5 to a CSV file using Go
In Progress
Have you found any bug or error? Please notify us.
R
WARNING: All these source codes are only examples used for testing. We don’t provide any guarantee or responsibility about it. Use these examples at your own risk.
Basic Examples for MT5 (for MT4 click here)
Example 1: Get actual EURUSD price from MT5 using R
con <- socketConnection(host="localhost", port = 77, blocking = TRUE)
writeLines("{\"MSG\":\"QUOTE\",\"SYMBOL\":\"EURUSD\"}\r\n", con)
server_resp <- readLines(con, 1)
close(con)
print(server_resp)
Reply:
[1] "{\"MSG\":\"QUOTE\",\"SYMBOL\":\"EURUSD\",\"ASK\":1.00062,\"BID\":1.00058,\"FLAGS\":6,\"TIME\":\"2022.09.20 12:49:31.377\",\"VOLUME\":0,\"ERROR_ID\":0,\"ERROR_DESCRIPTION\":\"The operation completed successfully\",\"DEMO\":\"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)\"}"
Example 2: Send Order to MT5 using R
con <- socketConnection(host="localhost", port = 77, blocking = TRUE)
writeLines("{\"MSG\":\"ORDER_SEND\",\"SYMBOL\":\"EURUSD\",\"VOLUME\":0.03,\"TYPE\":\"ORDER_TYPE_BUY\"}\r\n", con)
server_resp <- readLines(con, 1)
close(con)
print(server_resp)
Reply:
[1] "{\"MSG\":\"ORDER_SEND\",\"RETCODE\":10009,\"DEAL\":2015119247,\"ORDER\":2020570871,\"VOLUME\":0.10,\"PRICE\":1.064860,\"BID\":1.064830,\"ASK\":1.064860,\"REQUEST_ID\":3136973155,\"RETCODE_EXTERNAL\":0,\"ERROR_ID\":0,\"ERROR_DESCRIPTION\":\"The operation completed successfully\"}"
Example 3: Stream actual EURUSD price from MT5 using R
conCMD <- socketConnection(host="localhost", port = 77, blocking = TRUE)
conDATA <- socketConnection(host="localhost", port = 78, blocking = TRUE)
writeLines("{\"MSG\":\"TRACK_PRICES\",\"SYMBOLS\":[\"EURUSD\"]}\r\n", conCMD)
server_resp <- readLines(conCMD, 1)
print(server_resp)
repeat {
print(readLines(conDATA, 1))
}
close(conCMD)
close(conDATA)
Reply:
[1] "{\"MSG\":\"TRACK_PRICES\",\"SUCCESS\":[\"EURUSD\"],\"ERROR_ID\":0,\"ERROR_DESCRIPTION\":\"The operation completed successfully\",\"DEMO\":\"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)\"}"
[1] "{\"TIME\":\"2022.09.20 13:12:41.288\",\"SYMBOL\":\"EURUSD\",\"ASK\":1.00013,\"BID\":1.00009,\"VOLUME\":49713"
[1] "{\"TIME\":\"2022.09.20 13:12:45.63\",\"SYMBOL\":\"EURUSD\",\"ASK\":1.00009,\"BID\":1.00006,\"VOLUME\":49714}"
[1] "{\"TIME\":\"2022.09.20 13:12:45.112\",\"SYMBOL\":\"EURUSD\",\"ASK\":1.00008,\"BID\":1.00005,\"VOLUME\":49715}"
[1] "{\"TIME\":\"2022.09.20 13:12:45.166\",\"SYMBOL\":\"EURUSD\",\"ASK\":1.00013,\"BID\":1.00009,\"VOLUME\":49716}"
[1] "{\"TIME\":\"2022.09.20 13:12:45.268\",\"SYMBOL\":\"EURUSD\",\"ASK\":1.00014,\"BID\":1.00011,\"VOLUME\":49717}"
[1] "{\"TIME\":\"2022.09.20 13:12:45.316\",\"SYMBOL\":\"EURUSD\",\"ASK\":1.00014,\"BID\":1.00010,\"VOLUME\":49718}"
Advanced Examples
Example 1: Get actual EURUSD price to MT5 (using JSON library) with R
library("rjson")
con <- socketConnection(host="localhost", port = 77, blocking = TRUE)
df <- data.frame(MSG = c("QUOTE"), SYMBOL = c("EURUSD"))
writeLines(paste0(toJSON(df),"\r\n"), con)
server_resp <- readLines(con, 1)
close(con)
print(server_resp)
Reply:
[1] "{\"MSG\":\"QUOTE\",\"SYMBOL\":\"EURUSD\",\"ASK\":1.00104,\"BID\":1.00100,\"FLAGS\":6,\"TIME\":\"2022.09.20 13:28:24.379\",\"VOLUME\":0,\"ERROR_ID\":0,\"ERROR_DESCRIPTION\":\"The operation completed successfully\"}"
Example 2: Stream OHLC data from MT5 (using JSON library) with R
library("rjson")
conCMD <- socketConnection(host="localhost", port = 77, blocking = TRUE)
conDATA <- socketConnection(host="localhost", port = 78, blocking = TRUE)
symbol <- list(SYMBOL = c("EURUSD"), TIMEFRAME = c("PERIOD_M1"))
array <- list(symbol)
result <- list(MSG = c("TRACK_OHLC"), "OHLC" = array)
writeLines(paste0(toJSON(result),"\r\n"), conCMD)
server_resp <- readLines(conCMD, 1)
print(server_resp)
jsonReply <- fromJSON(server_resp)
if (jsonReply["ERROR_ID"] == 0) {
print("Waiting for OHLC data. Please wait...")
repeat {
print(paste("OHLC Prices:",readLines(conDATA, 1)))
}
} else {
print(jsonReply["ERROR_DESCRIPTION"])
}
close(conCMD)
close(conDATA)
Reply:
[1] "{\"MSG\":\"TRACK_OHLC\",\"SUCCESS\":[\"EURUSD\"],\"ERROR_ID\":0,\"ERROR_DESCRIPTION\":\"The operation completed successfully\",\"DEMO\":\"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)\"}"
[1] "Waiting for OHLC data. Please wait..."
[1] "OHLC Prices: {\"SYMBOL\":\"EURUSD\",\"PERIOD\":\"PERIOD_M1\",\"OHLC\":[{\"TIME\":\"2022.09.20 15:16:00\",\"OPEN\":0.99830,\"HIGH\":0.99843,\"LOW\":0.99821,\"CLOSE\":0.99826,\"TICK_VOLUME\":163}]}"
[1] "OHLC Prices: {\"SYMBOL\":\"EURUSD\",\"PERIOD\":\"PERIOD_M1\",\"OHLC\":[{\"TIME\":\"2022.09.20 15:17:00\",\"OPEN\":0.99826,\"HIGH\":0.99844,\"LOW\":0.99812,\"CLOSE\":0.99827,\"TICK_VOLUME\":170}]}"
[1] "OHLC Prices: {\"SYMBOL\":\"EURUSD\",\"PERIOD\":\"PERIOD_M1\",\"OHLC\":[{\"TIME\":\"2022.09.20 15:18:00\",\"OPEN\":0.99828,\"HIGH\":0.99828,\"LOW\":0.99783,\"CLOSE\":0.99800,\"TICK_VOLUME\":176}]}"
Example 3: Export Trade History from MT5 to a CSV file using R
library("rjson")
con <- socketConnection(host="localhost", port = 77, blocking = TRUE)
df <- data.frame(MSG = c("TRADE_HISTORY"), FROM_DATE = c("2022.09.19 10:00:00"), TO_DATE = c("2022.09.20 23:59:59"), MODE = "POSITIONS")
writeLines(paste0(toJSON(df),"\r\n"), con)
server_resp <- readLines(con, 1)
json_resp <- fromJSON(server_resp)
if (json_resp["ERROR_ID"] == 0) {
#print(server_resp)
open_time <- c()
close_time <- c()
symbol <- c()
ticket <- c()
price_open <- c()
price_close <- c()
profit <- c()
for (row in json_resp[["POSITIONS"]]) {
open_time <- append(open_time,row[["OPEN_TIME"]])
close_time <- append(close_time,row[["CLOSE_TIME"]])
symbol <- append(symbol,row[["SYMBOL"]])
ticket <- append(ticket,row[["TICKET"]])
price_open <- append(price_open,row[["PRICE_OPEN"]])
price_close <- append(price_close,row[["PRICE_CLOSE"]])
profit <- append(profit,row[["PROFIT"]])
}
df <- data.frame(OPEN_TIME=open_time,CLOSE_TIME=close_time,SYMBOL=symbol,TICKET=ticket,PRICE_OPEN=price_open,PRICE_CLOSE=price_close,PROFIT=profit)
write.csv(df,file="tradeHistoryFinal.csv",row.names = FALSE)
print("CSV file created successfully!")
} else {
print(json_resp["ERROR_DESCRIPTION"])
}
close(con)
Reply:
[1] "CSV file created successfully!"
Have you found any bug or error? Please notify us.