Skip to content

NodeJS

Important

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.

Generate source code instantly

Select your desired programming language via our web interface to automatically retrieve code:

MTsocketAPI source code

Example 1: Get EURUSD price

getprice.js
const http = require('http');

const options = {
  method: 'GET',
  hostname: '127.0.0.1',
  port: '81',
  path: '/v1/quote?symbol=EURUSD',
  headers: {
    Accept: 'application/json'
  }
};

const req = http.request(options, function (res) {
  const chunks = [];

  res.on('data', function (chunk) {
    chunks.push(chunk);
  });

  res.on('end', function () {
    const body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.end();
  1. Run the code:
node getprice.js

Example 2: Send buy order

sendorder.js
const http = require('http');

const options = {
  method: 'POST',
  hostname: '127.0.0.1',
  port: '81',
  path: '/v1/order?symbol=EURUSD&volume=0.01&type=ORDER_TYPE_BUY',
  headers: {
    'Content-Type': 'application/json',
    Accept: 'application/json'
  }
};

const req = http.request(options, function (res) {
  const chunks = [];

  res.on('data', function (chunk) {
    chunks.push(chunk);
  });

  res.on('end', function () {
    const body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.end();
  1. Run the code:
node sendorder.js

Example 3: Stream EURUSD price using websockets

streamprices.js
const http = require('http');
const WebSocket = require('ws');

const options = {
  method: 'POST',
  hostname: '127.0.0.1',
  port: '81',
  path: '/v1/track/prices?symbols=EURUSD',
  headers: {
    'Content-Type': 'application/json',
    Accept: 'application/json'
  }
};

const req = http.request(options, function (res) {
  const chunks = [];

  res.on('data', function (chunk) {
    chunks.push(chunk);
  });

  res.on('end', function () {
    const body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.end();

// WebSocket configuration
const wsUrl = "ws://127.0.0.1:81";
const ws = new WebSocket(wsUrl);

// Event handlers
ws.on('open', () => {
console.log("Connected to WebSocket");
});

ws.on('message', (data) => {
console.log("Received data:", data.toString());
});

ws.on('error', (error) => {
console.error("WebSocket error:", error);
});

ws.on('close', () => {
console.log("WebSocket connection closed");
});

// Graceful shutdown
process.on('SIGINT', () => {
console.log("\nClosing connection...");
ws.close();
process.exit();
});
  1. Fist install ws packet:
npm install ws
  1. Run the code:
node streamprices.js