Example Usage
Example: Get EURUSD price quote
The example code below processes QUOTE command sent to the \quote
endpoint. Codes are presented in NodeJS.
Important
Code examples are for reference only and is not guaranteed to work for your requirements. You are responsible for your own application performance and security.
server.js
const http = require('http');
const net = require('net');
const MT5_PORT = 8777;
const SERVER_PORT = 3000;
const server = http.createServer((req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
if (req.method === 'POST' && req.url === '/quote') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const { SYMBOL } = JSON.parse(body);
if (!SYMBOL) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'SYMBOL required' }));
return;
}
const client = new net.Socket();
const command = JSON.stringify({ MSG: 'QUOTE', SYMBOL });
let responseData = '';
const timeout = setTimeout(() => {
client.destroy();
res.writeHead(504);
res.end(JSON.stringify({ error: 'Timeout' }));
}, 10000);
client.connect(MT5_PORT, '127.0.0.1', () => {
client.write(command + '\r\n');
});
client.on('data', data => {
responseData += data.toString();
try {
const jsonResponse = JSON.parse(responseData);
if (jsonResponse.MSG) {
clearTimeout(timeout);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(responseData);
client.destroy();
}
} catch (e) {
console.log(e)
}
});
client.on('error', () => {
clearTimeout(timeout);
res.writeHead(500);
res.end(JSON.stringify({ error: 'MT5 connection failed' }));
});
} catch (e) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(SERVER_PORT, () => {
console.log(`Server running on port ${SERVER_PORT}`);
});
Start server.js
node server.js
Send command using Curl
curl -X POST http://localhost:3000/quote \
-H "Content-Type: application/json" \
-d '{"SYMBOL": "EURUSD"}'
Send command using Powershell
Invoke-RestMethod -Uri "http://localhost:3000/quote" -Method POST -ContentType "application/json" -Body '{"SYMBOL": "EURUSD"}'