Introduction
MTsocketAPI is a full-featured expert advisor for Metatrader 4 platform (Metatrader 5 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, MT4 accounts, MT4 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 for MT4 in your Metatrader application (for MT5 please click here).
First, you must download the Expert Advisor for MT4 from here: MTsocketAPI
Open you Metatrader application and go to File > Open Data Folder:
You will see something like this:
Then go to MQL4 > Experts folder and paste here the file MTsocketAPI.ex4 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 copy the MTsocketAPI.ex4 file to the Experts folder (detailed instuctions here).
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:
Now, click on the Common tab and check “Allow DLL imports”:
Note: MTsocketAPI needs ws2_32.dll windows library to manage sockets.
And finally, click OK to start MTsocketAPI.
Important: If you see a “sad” face like this:
You must click the “Auto Trading” button to enable it:
Now you must see the happy face:
Note: To make sure that MTsocketAPI started successfully, you can check the Metatrader 4 Experts tab:
Basic Usage with TELNET
MTsocketAPI opens two TCP ports by default:
- TCP 77 (Commands): This port can be used for send commands and receive MTsocketAPI replies.
- TCP 78 (Data): This port can be used to stream tick 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)
First steps:
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","OPENED_POSITIONS","TRADE_HISTORY","EXIT"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
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 and example:
Example 1: Get Price
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":1.09047,
"BID":1.09045,
"FLAGS":6,
"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 or OHLC data over the port TCP78 (data). To stream tick data use TRACK_PRICES command and to stream OHLC data use TRACK_OHLC command. See the following examples.
Example 2: Send 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",
"TICKET":47094374,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
As you can see you received the ticket number assigned to your order.
Example 3: Close Order
Now if we want to close our newly created order:
{"MSG": "ORDER_CLOSE", "TICKET": 47094374}
And this is the reply:
{
"MSG":"ORDER_CLOSE",
"TICKET":47094374,
"TYPE":"FULLY_CLOSED",
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
Example 4: Get Order History
Finally, let’s check the closed price and profit for this order:
{
"MSG": "TRADE_HISTORY",
"FROM_DATE": "2022/04/11 12:26:00",
"TO_DATE": "2022/04/11 12:31:00"
}
Note: You can use any date format accepted by MT4. More info.
Result:
{
"MSG":"TRADE_HISTORY",
"TRADES":[
{
"SYMBOL":"EURUSD",
"MAGIC":0,
"TICKET":47094374,
"OPEN_TIME":"2022.04.11 12:26:56",
"CLOSE_TIME":"2022.04.11 12:30:07",
"OPEN_PRICE":1.09026,
"CLOSE_PRICE":1.09006,
"TYPE":0,
"LOTS":0.01,
"STOP_LOSS":0.00000,
"TAKE_PROFIT":0.00000,
"SWAP":0.00,
"COMMISSION":0.00,
"COMMENT":null,
"PROFIT":-0.20
}
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
Now we disconnect softly:
{
"MSG": "EXIT",
}
Result:
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:
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 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 MQL4 -> Files and paste here the file License.txt
Finally, restart the Metratrader application.
MTsocketAPI Commands
MTsocketAPI accepts commands in the 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 beauty format applied to easily see 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
- CUSTOM_INDICATOR
- EXIT
- MA_INDICATOR
- ORDER_SEND
- ORDER_MODIFY
- ORDER_CLOSE
- ORDER_LIST
- PRICE_HISTORY
- QUOTE
- SYMBOL_INFO
- SYMBOL_LIST
- TERMINAL_INFO
- TRACK_PRICES
- TRACK_OHLC
- 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":"XXXXXX",
"CURRENCY":"USD",
"NAME":"Test User",
"SERVER":"Forex-Demo",
"LOGIN":6549871,
"TRADE_MODE":0,
"LEVERAGE":100,
"LIMIT_ORDERS":0,
"MARGIN_SO_MODE":0,
"TRADE_ALLOWED":1,
"TRADE_EXPERT":1,
"BALANCE":105820.62,
"CREDIT":0.00,
"PROFIT":0.00,
"EQUITY":105820.62,
"MARGIN":0.00,
"MARGIN_FREE":105820.62,
"MARGIN_LEVEL":0.00,
"MARGIN_SO_CAL":100.00,
"MARGIN_SO_SO":100.00,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
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_H1", "PERIOD":0,"SHIFT":0}
Same command in Beauty Format:
{
"MSG":"ATR_INDICATOR",
"SYMBOL":"EURUSD",
"TIMEFRAME":"PERIOD_H1",
"PERIOD":0, "SHIFT":0
}
MTsocketAPI reply:
{
"MSG":"ATR_INDICATOR",
"DATA_VALUE":0.00105000,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
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)", "MODE (Integer)", "SHIFT (Integer)" ], "OPTIONAL_TAGS":[ "PARAM1", "PARAM2", "PARAM3", "PARAM4" ] }
Example:
Single Line command (necessary for MTsocketAPI):
{"MSG":"CUSTOM_INDICATOR", "INDICATOR_NAME":"Momentum", "SYMBOL":"EURUSD", "TIMEFRAME":"PERIOD_H1", "MODE":0, "SHIFT":0, "PARAM1":14, "PARAM2":0}
Same command in Beauty Format:
{
"MSG":"CUSTOM_INDICATOR",
"INDICATOR_NAME":"Momentum",
"SYMBOL":"EURUSD",
"TIMEFRAME":"PERIOD_H1",
"MODE":0,
"SHIFT":0,
"PARAM1":14,
"PARAM2":0
}
MTsocketAPI reply:
{
"MSG":"CUSTOM_INDICATOR",
"DATA_VALUE":100.14402760,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
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 (Integer)", "APPLIED_PRICE (Integer)", "SHIFT (Integer)" ], "OPTIONAL_TAGS":[null] }
Example:
Single Line command (necessary for MTsocketAPI):
{"MSG":"MA_INDICATOR", "SYMBOL":"EURUSD", "TIMEFRAME":"PERIOD_H1", "MA_PERIOD":14, "MA_SHIFT":0, "MA_METHOD":0, "APPLIED_PRICE":0, "SHIFT":0}
Same command in Beauty Format:
{
"MSG":"MA_INDICATOR",
"SYMBOL":"EURUSD",
"TIMEFRAME":"PERIOD_H1",
"MA_PERIOD":14,
"MA_SHIFT":0,
"MA_METHOD":0,
"APPLIED_PRICE":0,
"SHIFT":0
}
MTsocketAPI reply:
{
"MSG":"MA_INDICATOR",
"DATA_VALUE":0.69516286,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
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":1383989469}
Same command in Beauty Format:
{
"MSG":"ORDER_INFO",
"TICKET":1383989469
}
MTsocketAPI reply:
{
"MSG":"ORDER_INFO",
"TRADES":{
"TICKET":1383989469,
"MAGIC":0,
"SYMBOL":"EURUSD",
"LOTS":0.01,
"TYPE":"sell",
"PRICE_OPEN":1.03009,
"OPEN_TIME":"2025.01.09 22:26:41",
"STOP_LOSS":0.00000,
"SWAP":0.00,
"COMMISSION":0.00,
"TAKE_PROFIT":0.00000,
"PROFIT":-0.05,
"COMMENT":null,
"EXPIRATION":"1970.01.01 00:00:00"
},
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
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)", "MAGICNR (Integer)", "EXPIRATION (String)" ], "MANDATORY_TAGS_PENDING":[ "SYMBOL (String)", "VOLUME (Double)", "TYPE (String)", "PRICE (Double)" ], "OPTIONAL_TAGS_PENDING":[ "SLIPPAGE (Integer)", "SL (Double)", "TP (Double)", "COMMENT (String)", "MAGICNR (Integer)", "EXPIRATION (String)" ] }
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
MTsocketAPI reply:
{
"MSG":"ORDER_SEND",
"TICKET":47098870,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
Limit Order Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"ORDER_SEND", "SYMBOL":"EURUSD", "VOLUME":0.02, "SL":1.06, "TYPE":"ORDER_TYPE_BUY_LIMIT", "PRICE":1.07, "EXPIRATION":"2022.04.12 19:38"}
Same command in Beauty Format:
{
"MSG":"ORDER_SEND",
"SYMBOL":"EURUSD",
"VOLUME":0.02,
"SL":1.06,
"TYPE":"ORDER_TYPE_BUY_LIMIT",
"PRICE":1.07,
"EXPIRATION":"2022.04.12 19:38"
}
Important: EXPIRATION tag value must be at least 10 minutes over the actual broker time.
MTsocketAPI reply:
{
"MSG":"ORDER_SEND",
"TICKET":6549871,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
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)" ] }
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":6549871,
"SL":1.002,
"TP":0
}
MTsocketAPI reply:
{
"MSG":"ORDER_MODIFY",
"TICKET":6549871,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
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.
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)" ] }
Example:
Fully close
Single Line command (necessary for MTsocketAPI):
{"MSG":"ORDER_CLOSE", "TICKET":6549871}
Same command in Beauty Format:
{
"MSG":"ORDER_CLOSE",
"TICKET":6549871
}
MTsocketAPI reply:
{
"MSG":"ORDER_CLOSE",
"TICKET":47099135,
"TYPE":"FULLY_CLOSED",
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error",
}
Partially close
Single Line command (necessary for MTsocketAPI):
{"MSG":"ORDER_CLOSE", "TICKET":6549871, "VOLUME": 0.01}
Same command in Beauty Format:
{
"MSG":"ORDER_CLOSE",
"TICKET":6549871,
"VOLUME": 0.01
}
MTsocketAPI reply:
{
"MSG":"ORDER_CLOSE",
"TICKET":47099143,
"TYPE":"PARTIALLY_CLOSED",
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
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",
"TRADES":[
{
"TICKET":65432145,
"MAGIC":0,
"SYMBOL":"GBPUSD",
"LOTS":0.02,
"TYPE":"BUY",
"OPEN_PRICE":1.29926,
"OPEN_TIME":"2022.04.13 07:52:48",
"STOP_LOSS":0.00000,
"SWAP":0.00,
"COMMISSION":0.00,
"TAKE_PROFIT":0.00000,
"PROFIT":0.16,
"COMMENT":null,
"EXPIRATION":"1970.01.01 00:00:00"
},
{
"TICKET":65321464,
"MAGIC":0,
"SYMBOL":"EURUSD",
"LOTS":0.01,
"TYPE":"SELL",
"OPEN_PRICE":1.08522,
"OPEN_TIME":"2022.04.12 13:26:59",
"STOP_LOSS":0.00000,
"SWAP":0.00,
"COMMISSION":0.00,
"TAKE_PROFIT":0.00000,
"PROFIT":2.59,
"COMMENT":"from #65432164",
"EXPIRATION":"1970.01.01 00:00:00"
}
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
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 MT4 the performance may worsen visibly while processing a big amount of data.
Important: If you haven’t downloaded that symbol/timeframe data before, MT4 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] }
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":6,
"TIME":"2022.09.06 08:20:39.0",
"VOLUME":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
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] }
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 18:11:34",
"DIGITS":5,
"SPREAD_FLOAT":1,
"SPREAD":9,
"TRADE_CALC_MODE":0,
"TRADE_MODE":2,
"START_TIME":0,
"EXPIRATION_TIME":0,
"TRADE_STOPS_LEVEL":20,
"TRADE_FREEZE_LEVEL":0,
"TRADE_EXEMODE":2,
"SWAP_MODE":2,
"SWAP_ROLLOVER3DAYS":3,
"POINT":0.00001000,
"TRADE_TICK_SIZE":0.00001000,
"TRADE_CONTRACT_SIZE":0.00001000,
"VOLUME_MIN":0.01000000,
"VOLUME_MAX":14100654.08000000,
"VOLUME_STEP":0.01000000,
"SWAP_LONG":-2.53000000,
"SWAP_SHORT":0.20000000,
"MARGIN_INITIAL":0.00000000,
"MARGIN_MAINTENANCE":0.00000000,
"CURRENCY_BASE":"EUR",
"CURRENCY_PROFIT":"USD",
"CURRENCY_MARGIN":"EUR",
"DESCRIPTION":"1 Lot= 100,000 EUR",
"PATH":"Forex -Majors1\\EURUSD",
"SESSION_QUOTE":[
{
"SUNDAY":"21:05-24:00"
},
{
"MONDAY":"00:00-20:58, 21:05-24:00"
},
{
"TUESDAY":"00:00-20:58, 21:05-24:00"
},
{
"WEDNESDAY":"00:00-20:58, 21:05-24:00"
},
{
"THURSDAY":"00:00-20:58, 21:05-24:00"
},
{
"FRIDAY":"00:00-20:58"
}
],
"SESSION_TRADE":[
{
"SUNDAY":"21:05-24:00"
},
{
"MONDAY":"00:00-20:58, 21:05-24:00"
},
{
"TUESDAY":"00:00-20:58, 21:05-24:00"
},
{
"WEDNESDAY":"00:00-20:58, 21:05-24:00"
},
{
"THURSDAY":"00:00-20:58, 21:05-24:00"
},
{
"FRIDAY":"00:00-20:58"
}
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error",
"DEMO":"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)"
}
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":2,
"TIME":"2022.04.12 10:21:22",
"DIGITS":5,
"SPREAD_FLOAT":1,
"SPREAD":13,
"TRADE_CALC_MODE":0,
"START_TIME":0,
"EXPIRATION_TIME":0,
"TRADE_STOPS_LEVEL":0,
"TRADE_FREEZE_LEVEL":0,
"TRADE_EXEMODE":2,
"SWAP_MODE":0,
"SWAP_ROLLOVER3DAYS":3,
"POINT":0.00001000,
"TRADE_TICK_SIZE":0.00001000,
"TRADE_CONTRACT_SIZE":0.00001000,
"VOLUME_MIN":0.01000000,
"VOLUME_MAX":1000.00000000,
"VOLUME_STEP":0.01000000,
"SWAP_LONG":-19.00000000,
"SWAP_SHORT":1.50000000,
"MARGIN_INITIAL":0.00000000,
"MARGIN_MAINTENANCE":0.00000000,
"CURRENCY_BASE":"AUD",
"CURRENCY_PROFIT":"CAD",
"CURRENCY_MARGIN":"AUD",
"DESCRIPTION":"Australian Dollar vs Canadian Dollar",
"PATH":"Forex\\AUDCAD"
},
{
"NAME":"AUDCHF",
"TRADE_MODE":2,
"TIME":"2022.04.12 10:21:24",
"DIGITS":5,
"SPREAD_FLOAT":1,
"SPREAD":8,
"TRADE_CALC_MODE":0,
"START_TIME":0,
"EXPIRATION_TIME":0,
"TRADE_STOPS_LEVEL":0,
"TRADE_FREEZE_LEVEL":0,
"TRADE_EXEMODE":2,
"SWAP_MODE":0,
"SWAP_ROLLOVER3DAYS":3,
"POINT":0.00001000,
"TRADE_TICK_SIZE":0.00001000,
"TRADE_CONTRACT_SIZE":0.00001000,
"VOLUME_MIN":0.01000000,
"VOLUME_MAX":1000.00000000,
"VOLUME_STEP":0.01000000,
"SWAP_LONG":2.00000000,
"SWAP_SHORT":-21.00000000,
"MARGIN_INITIAL":0.00000000,
"MARGIN_MAINTENANCE":0.00000000,
"CURRENCY_BASE":"AUD",
"CURRENCY_PROFIT":"CHF",
"CURRENCY_MARGIN":"AUD",
"DESCRIPTION":"Australian Dollar vs Swiss Franc",
"PATH":"Forex\\AUDCHF"
},
{
... all the symbols here
}
]
}
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":"XXXXXXXXXXX",
"NAME":"YYYYYYYYYYYY",
"PATH":"C:\\Program Files (x86)\\Metatrader",
"DATA_PATH":"C:\\Users\\example1\\AppData\\Roaming\\MetaQuotes\\Terminal\\B18F210DB0E0855A96EB7E49C5C0EE25",
"COMMONDATA_PATH":"C:\\Users\\example1\\AppData\\Roaming\\MetaQuotes\\Terminal\\Common",
"BUILD":1353,
"COMMUNITY_ACCOUNT":0,
"COMMUNITY_CONNECTION":0,
"CONNECTED":1,
"DLLS_ALLOWED":1,
"TRADE_ALLOWED":1,
"EMAIL_ENABLED":0,
"FTP_ENABLED":0,
"NOTIFICATIONS_ENABLED":0,
"MAXBARS":65000,
"MQID":0,
"CODEPAGE":0,
"CPU_CORES":8,
"DISK_SPACE":21695,
"MEMORY_PHYSICAL":8060,
"MEMORY_TOTAL":4095,
"MEMORY_AVAILABLE":3867,
"MEMORY_USED":228,
"SCREEN_DPI":96,
"PING_LAST":37199,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
Note: Information about each field can be read here.
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":"no error"
}
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 '^]'.
{"TIME":"2022.04.12 08:16:35","SYMBOL":"EURUSD","ASK":1.08594,"BID":1.08592,"VOLUME":16246}
{"TIME":"2022.04.12 08:16:35","SYMBOL":"EURUSD","ASK":1.08595,"BID":1.08592,"VOLUME":16247}
{"TIME":"2022.04.12 08:16:36","SYMBOL":"EURUSD","ASK":1.08594,"BID":1.08592,"VOLUME":16248}
{"TIME":"2022.04.12 08:16:37","SYMBOL":"EURUSD","ASK":1.08595,"BID":1.08592,"VOLUME":16249}
{"TIME":"2022.04.12 08:16:40","SYMBOL":"EURUSD","ASK":1.08598,"BID":1.08596,"VOLUME":16249}
{"TIME":"2022.04.12 08:16:41","SYMBOL":"EURUSD","ASK":1.08599,"BID":1.08596,"VOLUME":16251}
{"TIME":"2022.04.12 08:16:42","SYMBOL":"EURUSD","ASK":1.08597,"BID":1.08595,"VOLUME":16252}
{"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_M5
- PERIOD_M15
- PERIOD_M30
- PERIOD_H1
- PERIOD_H4
- 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":"no error"
}
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":[]
}
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)" ], "OPTIONAL_TAGS":[null] }
Example
Single Line command (necessary for MTsocketAPI):
{"MSG":"TRADE_HISTORY", "FROM_DATE":"2022/04/12 13:00:00", "TO_DATE": "2022/04/12 13:35:00"}
Same command in Beauty Format:
{
"MSG":"TRADE_HISTORY",
"FROM_DATE":"2022/04/12 13:00:00",
"TO_DATE": "2022/04/12 13:35:00"
}
MTsocketAPI reply:
{
"MSG":"TRADE_HISTORY",
"TRADES":[
{
"SYMBOL":"EURUSD",
"MAGIC":0,
"TICKET":47099158,
"OPEN_TIME":"2022.04.12 13:26:59",
"CLOSE_TIME":"2022.04.12 13:27:15",
"OPEN_PRICE":1.08522,
"CLOSE_PRICE":1.08524,
"TYPE":"SELL",
"LOTS":0.01,
"STOP_LOSS":0.00000,
"TAKE_PROFIT":0.00000,
"SWAP":0.00,
"COMMISSION":0.00,
"COMMENT":"to #47099159",
"PROFIT":-0.02
},
{
"SYMBOL":"EURUSD",
"MAGIC":0,"TICKET":47099144,
"OPEN_TIME":"2022.04.12 13:24:31",
"CLOSE_TIME":"2022.04.12 13:26:58",
"OPEN_PRICE":1.08547,
"CLOSE_PRICE":1.08523,
"TYPE":"BUY",
"LOTS":0.01,
"STOP_LOSS":0.00000,
"TAKE_PROFIT":0.00000,
"SWAP":0.00,
"COMMISSION":0.00,
"COMMENT":"from #47099143",
"PROFIT":0.24
}
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
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 MT4 (for MT5 click here)
Example 1: Get actual EURUSD price from MT4 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'))
Result:
{
"MSG":"QUOTE",
"SYMBOL":"EURUSD",
"ASK":1.08293,
"BID":1.08291,
"FLAGS":6,
"TIME":"2023.08.23 08:33:48.0",
"VOLUME":0,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
Example 2: Send Order to MT4 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'))
Result:
{
"MSG":"ORDER_SEND",
"TICKET":47103114,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
Example 3: Stream actual EURUSD price from MT4 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'))
Result:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
{"TIME":"2023.08.23 09:08:02","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08384,"VOLUME":18404}
{"TIME":"2023.08.23 09:08:03","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08385,"VOLUME":18405}
{"TIME":"2023.08.23 09:08:03","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08384,"VOLUME":18407}
{"TIME":"2023.08.23 09:08:04","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08380,"VOLUME":18408}
{"TIME":"2023.08.23 09:08:05","SYMBOL":"EURUSD","ASK":1.08384,"BID":1.08382,"VOLUME":18408}
{"TIME":"2023.08.23 09:08:05","SYMBOL":"EURUSD","ASK":1.08385,"BID":1.08382,"VOLUME":18410}
{"TIME":"2023.08.23 09:08:06","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08381,"VOLUME":18411}
{"TIME":"2023.08.23 09:08:06","SYMBOL":"EURUSD","ASK":1.08384,"BID":1.08381,"VOLUME":18411}
{"TIME":"2023.08.23 09:08:07","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08381,"VOLUME":18412}
...
Advanced Examples
Example 1: Get actual EURUSD price from MT4 (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'])
Result:
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': 'no error'}
Symbol: EURUSD
Ask: 1.08308
Bid: 1.08306
Example 2: Stream OHLC data from MT4 (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')
JSONprice = json.loads(dataReceived)
if JSONprice["MSG"] == "TRACK_OHLC":
#print('RAW data received:',dataReceived)
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'])
Result:
RAW JSON message received: {'MSG': 'TRACK_OHLC', 'SUCCESS': ['EURUSD'], 'ERROR_ID': 0, 'ERROR_DESCRIPTION': 'no error'}
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 MT4 to a CSV file using Python
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['FROM_DATE'] = '2023/08/23 00:00:00'
JSONobject['TO_DATE'] = '2023/08/24 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['TRADES']:
#print('row:',item['TICKET'])
row = [item['SYMBOL'],item['MAGIC'],item['TICKET'],item['OPEN_TIME'],item['CLOSE_TIME'],item['PRICE_OPEN'],item['PRICE_CLOSE'],item['TYPE'],item['LOTS'],item['STOP_LOSS'],item['TAKE_PROFIT'],item['SWAP'],item['COMMISSION'],item['COMMENT'],item['PROFIT']]
writer.writerow(row)
f.close()
print('Exported successfully!')
Result:
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 MT4 (for MT5 click here)
Example 1: Get actual EURUSD price from MT4 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());
}
}
}
Result:
{
"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":"no error"
}
Example 2: Send Order to MT4 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());
}
}
}
Result:
{"MSG":"ORDER_SEND","TICKET":65432164,"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
Example 3: Stream actual EURUSD price from MT4 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());
}
}
}
Result:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
{"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 MT4 (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());
}
}
}
Result:
Time: 2022.04.18 12:45:03.0 Symbol: EURUSD Ask: 1.08068
Example 2: Stream OHLC data from MT4 (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 (Compile)
* $ java -cp .:json-simple-1.1.1.jar getStreamJSON (Run)
* */
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 json = (JSONObject) parser.parse(jsonString);
JSONArray jarr= (JSONArray)json.get("OHLC");
JSONObject jelem= (JSONObject)jarr.get(0);
System.out.println("Time: " + jelem.get("TIME") + " Symbol: " + json.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());
}
}
}
Result:
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 MT4 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 (Compile)
* $ java -cp .:json-simple-1.1.1.jar getHistory (Run)
* */
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/04/13 07:00:00");
jo.put("TO_DATE","2022/04/15 00:00:00");
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("TRADES");
FileWriter myFile = new FileWriter("tradeHistory.csv");
myFile.write("OPEN_TIME,CLOSE_TIME,TICKET,SYMBOL,MAGIC,OPEN_PRICE,CLOSE_PRICE,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);
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("OPEN_PRICE").toString() + "," +
item.get("CLOSE_PRICE").toString() + "," +
item.get("TYPE").toString() + "," +
item.get("LOTS").toString() + "," +
item.get("STOP_LOSS").toString() + "," +
item.get("TAKE_PROFIT").toString() + "," +
item.get("SWAP").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());
}
}
}
Result:
{
"MSG":"TRADE_HISTORY",
"TRADES":[
{
"SYMBOL":"EURUSD",
"MAGIC":0,
"TICKET":47103675,
"OPEN_TIME":"2022.04.13 12:30:25",
"CLOSE_TIME":"2022.04.13 13:11:25",
"OPEN_PRICE":1.08424,
"CLOSE_PRICE":1.08268,
"TYPE":"BUY",
"LOTS":0.02,
"STOP_LOSS":0.00000,
"TAKE_PROFIT":0.00000,
"SWAP":0.00,
"COMMISSION":0.00,
"COMMENT":null,
"PROFIT":-3.12
},
{
"SYMBOL":"EURUSD",
"MAGIC":0,
"TICKET":47103114,
"OPEN_TIME":"2022.04.13 09:14:18",
"CLOSE_TIME":"2022.04.13 13:11:26",
"OPEN_PRICE":1.08342,
"CLOSE_PRICE":1.08270,
"TYPE":"BUY",
"LOTS":0.02,
"STOP_LOSS":0.00000,
"TAKE_PROFIT":0.00000,
"SWAP":0.00,
"COMMISSION":0.00,
"COMMENT":null,
"PROFIT":-1.44
},
{
"SYMBOL":"GBPUSD",
"MAGIC":0,
"TICKET":47102744,
"OPEN_TIME":"2022.04.13 07:52:48",
"CLOSE_TIME":"2022.04.13 08:00:26",
"OPEN_PRICE":1.29926,
"CLOSE_PRICE":1.29862,
"TYPE":"SELL",
"LOTS":0.02,
"STOP_LOSS":0.00000,
"TAKE_PROFIT":0.00000,
"SWAP":0.00,
"COMMISSION":0.00,
"COMMENT":null,
"PROFIT":1.28
},
{
"SYMBOL":"EURUSD",
"MAGIC":0,
"TICKET":47099159,
"OPEN_TIME":"2022.04.12 13:26:59",
"CLOSE_TIME":"2022.04.13 08:00:25",
"OPEN_PRICE":1.08522,
"CLOSE_PRICE":1.08236,
"TYPE":"SELL",
"LOTS":0.01,
"STOP_LOSS":0.00000,
"TAKE_PROFIT":0.00000,
"SWAP":0.00,
"COMMISSION":0.00,
"COMMENT":"from #47099158",
"PROFIT":2.86
}
],
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
tradeHistory.csv created!
If we open the tradeHistory.csv:
OPEN_TIME,CLOSE_TIME,TICKET,SYMBOL,MAGIC,OPEN_PRICE,CLOSE_PRICE,TYPE,LOTS,STOP_LOSS,TAKE_PROFIT,SWAP,COMMISSION,COMMENT,PROFIT
2022.04.13 12:30:25,2022.04.13 13:11:25,47103675,EURUSD,0,1.08424,1.08268,BUY,0.02,0.0,0.0,0.0,0.0,null,-3.12
2022.04.13 09:14:18,2022.04.13 13:11:26,47103114,EURUSD,0,1.08342,1.0827,BUY,0.02,0.0,0.0,0.0,0.0,null,-1.44
2022.04.13 07:52:48,2022.04.13 08:00:26,47102744,GBPUSD,0,1.29926,1.29862,SELL,0.02,0.0,0.0,0.0,0.0,null,1.28
2022.04.12 13:26:59,2022.04.13 08:00:25,47099159,EURUSD,0,1.08522,1.08236,SELL,0.01,0.0,0.0,0.0,0.0,from #47099158,2.86
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.
Basic Examples for MT4 (for MT5 click here)
Example 1: Get actual EURUSD price from MT4 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();
}
}
}
Result:
{
"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":"no error"
}
Example 2: Send Order to MT4 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();
}
}
}
Result:
{"MSG":"ORDER_SEND","TICKET":6543215,"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
Example 3: Stream actual EURUSD price from MT4 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();
}
}
}
Result:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
{"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 MT4 (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();
}
}
}
Result:
Symbol: EURUSD Ask: 1.07934 Bid: 1.07931 Time: 2022.04.19 12:02:28.0
Example 2: Stream OHLC data from MT4 (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(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);
JObject jresult = JsonConvert.DeserializeObject<JObject>(responseData);
Console.WriteLine("Time: {0} Symbol: {1} Open: {2} Close: {3} High: {4} Low: {5}", jresult["OHLC"][0]["TIME"], jresult["SYMBOL"], jresult["OHLC"][0]["OPEN"], jresult["OHLC"][0]["CLOSE"], jresult["OHLC"][0]["HIGH"], jresult["OHLC"][0]["LOW"]);
} while (true);
stream_cmd.Close();
stream_data.Close();
tcpClient_cmd.Close();
tcpClient_data.Close();
}
}
}
Result:
{"MSG":"TRACK_OHLC","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
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 MT4 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["FROM_DATE"] = "2022/04/12 13:00:00";
jo["TO_DATE"] = "2022/04/15 13:00:00";
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);
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["TRADES"])
{
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_OPEN"].ToString() + "," +
item["PRICE_CLOSE"].ToString() + "," +
item["TYPE"].ToString() + "," +
item["LOTS"].ToString() + "," +
item["STOP_LOSS"].ToString() + "," +
item["TAKE_PROFIT"].ToString() + "," +
item["SWAP"].ToString() + "," +
item["COMMISSION"].ToString() + "," +
item["COMMENT"].ToString() + "," +
item["PROFIT"].ToString() +
Environment.NewLine);
}
Console.WriteLine("Finished!");
stream.Close();
tcpClient.Close();
}
}
}
Result:
Finished!
If we open the tradeHistory.csv:
OPEN_TIME,CLOSE_TIME,TICKET,SYMBOL,MAGIC,OPEN_PRICE,CLOSE_PRICE,TYPE,LOTS,STOP_LOSS,TAKE_PROFIT,SWAP,COMMISSION,COMMENT,PROFIT
2022.04.13 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
2022.04.13 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
2022.04.13 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
2022.04.12 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
2022.04.12 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
2022.04.12 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
2022.04.12 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
2022.04.12 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
2022.04.12 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
2022.04.12 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
2022.04.12 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
2022.04.12 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.
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 MT4 (for MT5 click here)
Example 1: Get actual EURUSD price from MT4 with 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()
Result:
{
"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":"no error"
}
Example 2: Send Order to MT4 with 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()
Result:
{
"MSG":"ORDER_SEND",
"TICKET":6543216,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
Example 3: Stream actual EURUSD price from MT4 with 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()
Result:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
{"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 (using JSON library) from MT4 with 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)
$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()
Result:
{"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":"no error"}
Example 2: Stream OHLC data (using JSON library) from MT4 with 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)
$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()
Result:
{"MSG":"TRACK_OHLC","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
{"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 MT4 to CSV with 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)
$Cmd = "" | Select MSG,FROM_DATE,TO_DATE
$Cmd.MSG = "TRADE_HISTORY"
$Cmd.FROM_DATE = "2022/04/12 13:00:00"
$Cmd.TO_DATE = "2022/04/15 00:00:00"
$Json = ConvertTo-Json $Cmd -Compress
$Writer.WriteLine($Json)
$Writer.Flush()
$Response = $Reader.ReadLine()
$DataObj = ConvertFrom-Json $Response
$DataObj.TRADES | Export-Csv -Path "History.csv" -Delimiter "," -NoTypeInformation
Write-Host "Exported to CSV!"
$Stream.Close()
$Socket.Close()
Result:
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 MT4 (for MT5 click here)
Example 1: Get actual EURUSD price from MT4 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;
}
Result:
./quote 127.0.0.1 77
{
"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":"no error"
}
Example 2: Send Order to MT4 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[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;
}
Result:
./sendorder 127.0.0.1 77
{"MSG":"ORDER_SEND","TICKET":65432145,"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
Example 3: Stream actual EURUSD price from MT4 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;
}
Result:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
{"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 MT4 (using JSON library) with C++
In progress
Example 2: Stream OHLC data from MT4 (using JSON library) with C++
In progress
Example 3: Export MT4 Trade History from MT4 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 MT4 (for MT5 click here)
Example 1: Get actual EURUSD price from MT4 using NodeJS
const Net = require('net');
const client = new Net.Socket();
client.connect(77, "localhost", function() {
client.write('{"MSG":"QUOTE","SYMBOL":"EURUSD"}' + '\r\n');
});
client.on('data', function(chunk) {
console.log(`${chunk.toString()}`);
client.end();
});
Result:
{
"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":"no error"
}
Example 2: Send Order to MT4 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();
});
Result:
{
"MSG":"ORDER_SEND",
"TICKET":6543216,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
Example 3: Stream actual EURUSD price from MT4 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()}`);
});
Result:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
{"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 MT4 (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();
});
Result:
Time: 2022.04.13 13:01:20.0 Symbol: EURUSD Ask: 1.08335 Bid: 1.08333
Example 2: Stream OHLC data from MT4 (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) {
const JSONresult = JSON.parse(chunk.toString());
console.log(`Time: ${JSONresult["OHLC"][0]["TIME"]} Symbol: ${JSONresult["SYMBOL"]} Close Price: ${JSONresult["OHLC"][0]["CLOSE"]}`);
});
Result:
{"MSG":"TRACK_OHLC","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
Time: 2022.04.13 13:05:00 Symbol: EURUSD Close Price: 1.08264
Time: 2022.04.13 13:06:00 Symbol: EURUSD Close Price: 1.08271
Time: 2022.04.13 13:07:00 Symbol: EURUSD Close Price: 1.08287
Example 3: Export Trade History from MT4 to a CSV file using NodeJS
const Net = require('net');
const fs = require('fs');
const delimiter = ',';
const exportedFile = 'tradeHistory.csv';
const fromDate = "2022/04/12 13:00:00";
const toDate = "2022/04/15 00:00:00";
const client_cmd = new Net.Socket();
client_cmd.connect(77, "localhost", function() {
const JSONobj = {};
JSONobj["MSG"]="TRADE_HISTORY";
JSONobj["FROM_DATE"]=fromDate;
JSONobj["TO_DATE"]=toDate;
client_cmd.write(JSON.stringify(JSONobj) + '\r\n');
});
client_cmd.on('data', function(chunk) {
const JSONresult = JSON.parse(chunk.toString());
const numTrades = Object.keys(JSONresult['TRADES']).length;
console.log(`Number of trades: ${numTrades}`);
//First we must write the CSV HEADER
fs.writeFileSync('tradeHistory.csv','OPEN_TIME,CLOSE_TIME,TICKET,SYMBOL,LOTS,OPEN_PRICE,CLOSE_PRICE,PROFIT\r\n',{ flag: 'a+' });
//Loop JSON array
for(let i = 0; i < numTrades; i++) {
//You can add more files like COMMENT, SWAP, COMMISSION...
const OPEN_TIME = JSONresult['TRADES'][i]['OPEN_TIME'];
const CLOSE_TIME = JSONresult['TRADES'][i]['CLOSE_TIME'];
const TICKET = JSONresult['TRADES'][i]['TICKET'];
const SYMBOL = JSONresult['TRADES'][i]['SYMBOL'];
const LOTS = JSONresult['TRADES'][i]['LOTS'];
const OPEN_PRICE = JSONresult['TRADES'][i]['OPEN_PRICE'];
const CLOSE_PRICE = JSONresult['TRADES'][i]['CLOSE_PRICE'];
const PROFIT = JSONresult['TRADES'][i]['PROFIT'];
fs.writeFileSync(exportedFile, OPEN_TIME + delimiter + CLOSE_TIME + delimiter + TICKET + delimiter + SYMBOL + delimiter + LOTS + delimiter + OPEN_PRICE + delimiter + CLOSE_PRICE + delimiter + PROFIT + '\r\n',{ flag: 'a+' });
}
console.log(`Created the file ${exportedFile}!`);
client_cmd.end();
});
Result:
Number of trades: 12
Created the file tradeHistory.csv!
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 MT4 (for MT5 click here)
Example 1: Get actual EURUSD price from MT4 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))
}
Result:
{
"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":"no error"
}
Example 2: Send Order to MT4 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))
}
Result:
{
"MSG":"ORDER_SEND",
"TICKET":47103114,
"ERROR_ID":0,
"ERROR_DESCRIPTION":"no error"
}
Example 3: Stream actual EURUSD price from MT4 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{
_, err = con2.Read(reply)
if err != nil { fmt.Println(err) }
fmt.Println(string(reply))
}
}
Result:
{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"no error"}
{"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 MT4 (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"])
}
Result:
Symbol: EURUSD Ask: 1.022240 Bid: 1.022200
Example 2: Stream OHLC data from MT4 (using JSON library) using Go
In Progress
Example 3: Export Trade History from MT4 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 MT4 (for MT5 click here)
Example 1: Get actual EURUSD price from MT4 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\":0.99080,\"BID\":0.99074,\"FLAGS\":6,\"TIME\":\"2022.09.21 08:22:28.0\",\"VOLUME\":0,\"ERROR_ID\":0,\"ERROR_DESCRIPTION\":\"no error\"}"
Example 2: Send Order to MT4 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\",\"TICKET\":47587709,\"ERROR_ID\":0,\"ERROR_DESCRIPTION\":\"no error\",\"DEMO\":\"MTsocketAPI running in DEMO mode (www.mtsocketapi.com)\"}"
Example 3: Stream actual EURUSD price from MT4 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\":\"no error\"}"
[1] "{\"TIME\":\"2022.09.21 08:26:13\",\"SYMBOL\":\"EURUSD\",\"ASK\":0.99092,\"BID\":0.99087,\"VOLUME\":63164}"
[1] "{\"TIME\":\"2022.09.21 08:26:15\",\"SYMBOL\":\"EURUSD\",\"ASK\":0.99094,\"BID\":0.99089,\"VOLUME\":63164}"
[1] "{\"TIME\":\"2022.09.21 08:26:15\",\"SYMBOL\":\"EURUSD\",\"ASK\":0.99094,\"BID\":0.99090,\"VOLUME\":63164}"
[1] "{\"TIME\":\"2022.09.21 08:26:15\",\"SYMBOL\":\"EURUSD\",\"ASK\":0.99096,\"BID\":0.99091,\"VOLUME\":63164}"
Advanced Examples
Example 1: Get actual EURUSD price to MT4 (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\":0.99155,\"BID\":0.99155,\"FLAGS\":6,\"TIME\":\"2022.09.21 08:28:59.0\",\"VOLUME\":0,\"ERROR_ID\":0,\"ERROR_DESCRIPTION\":\"no error\"}"
Example 2: Stream OHLC data from MT4 (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 {
JSONdata <- fromJSON(readLines(conDATA, 1))
if (is.null(JSONdata[["OHLC"]]) == FALSE) {
print(paste("OHLC Prices:",readLines(conDATA, 1)))
}
}
} else {
print(jsonReply["ERROR_DESCRIPTION"])
}
close(conCMD)
close(conDATA)
Reply:
[1] "Waiting for OHLC data. Please wait..."
[1] "OHLC Prices: {\"TIME\":\"2022.09.21 08:58:02\",\"SYMBOL\":\"EURUSD.pro\",\"ASK\":0.99112,\"BID\":0.99112,\"VOLUME\":39595}"
[1] "OHLC Prices: {\"TIME\":\"2022.09.21 08:59:01\",\"SYMBOL\":\"EURUSD.pro\",\"ASK\":0.99103,\"BID\":0.99101,\"VOLUME\":39684}"
[1] "OHLC Prices: {\"TIME\":\"2022.09.21 09:00:03\",\"SYMBOL\":\"EURUSD.pro\",\"ASK\":0.99122,\"BID\":0.99119,\"VOLUME\":39726}"
Example 3: Export Trade History from MT4 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.09 10:00:00"), TO_DATE = c("2022.09.20 23:59:59"))
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[["TRADES"]]) {
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("File created successfully!")
} else {
print(json_resp["ERROR_DESCRIPTION"])
}
close(con)
Reply:
[1] "File created successfully!"
Have you found any bug or error? Please notify us.