Skip to content

An MT5 API for Node.js and TypeScript

Updated 2026-11-23

MetaTrader 5 has no official Node.js package, and its own API is Windows-only. FiveSocket gives you MT5 over HTTPS instead, so you call https://api.fivesocket.com/v1 with plain fetch and an API key from Node.js 18 or later, Bun or Deno. You link the account once, then read balances, positions and candles and place orders from TypeScript, with no Windows machine and no MetaTrader5 Python package.

7-day free trial. Paid plans start at $9.99 a month. See pricing

What you need

  • Node.js 18 or later, Bun or Deno. All three have fetch built in, so there is nothing to install.
  • A FiveSocket API key from the control panel. It is shown once, so keep it in an environment variable such as FIVESOCKET_KEY.
  • An MT5 account linked to FiveSocket. Link it with POST /v1/accounts and the accounts:write scope, or in the control panel. Use the investor password if the program should only read.

FiveSocket has no official npm package. The examples below use plain fetch and write their types inline, so you copy a few lines instead of adding a dependency. The OpenAPI document at https://api.fivesocket.com/v1/openapi.json describes every request if you would rather generate a client.

Each key carries scopes. Listing accounts needs accounts:read, balance, positions and candles need data:read, and orders need trading:execute. Give each program its own key with only the scopes it uses. Read about the MT5 REST API

A small typed client

Start with one helper that sends the Bearer key, throws a typed error when a call fails, and waits and retries when the API says to. Save it as fivesocket.ts and import it from the other examples.

const base = "https://api.fivesocket.com/v1"

type ApiErrorBody = {
    error: { code: string, message: string, requestId: string, details?: Record<string, unknown> }
}

export class FiveSocketError extends Error {
    constructor(
        readonly status: number,
        readonly code: string,
        readonly requestId: string,
        message: string,
    ) {
        super(message)
    }
}

type Options = { method?: "GET" | "POST" | "PUT", body?: unknown, idempotencyKey?: string }

export async function api<T>(path: string, options: Options = {}): Promise<T> {
    const method = options.method ?? "GET"
    for (let attempt = 0; ; attempt++) {
        const response = await fetch(`${base}${path}`, {
            method,
            headers: {
                Authorization: `Bearer ${process.env.FIVESOCKET_KEY}`,
                ...(options.body === undefined ? {} : { "Content-Type": "application/json" }),
                ...(options.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}),
            },
            body: options.body === undefined ? undefined : JSON.stringify(options.body),
        })
        const retryable = response.status === 429 || response.status === 503 || (response.status === 202 && method === "GET")
        if (retryable && attempt < 5) {
            const header = Number(response.headers.get("retry-after"))
            const seconds = Number.isFinite(header) && header > 0 ? header : 2 ** attempt
            await new Promise((resolve) => setTimeout(resolve, seconds * 1000))
            continue
        }
        if (!response.ok) {
            const { error } = (await response.json()) as ApiErrorBody
            throw new FiveSocketError(response.status, error.code, error.requestId, error.message)
        }
        return (await response.json()) as T
    }
}

Errors from the API are JSON with an error object holding a stable code, a message and a requestId. Quote the requestId if you contact support.

List accounts, read the balance and open positions

GET /v1/accounts lists your linked accounts and their status. Use an account's id in the path of every other call. Balance and positions come from the live MT5 session when you ask. Money, prices and volumes are decimal strings, so keep them as strings or parse them with a decimal library rather than doing float maths on them.

import { api } from "./fivesocket"

type Account = { id: string, login: string, server: string, status: "pending" | "active" | "invalid" | "disabled", createdAt: string }
type Balance = { balance: string, equity: string, margin: string, marginFree: string, currency: string, leverage: string }
type Position = { id: string, symbol: string, side: "buy" | "sell", volume: string, openPrice: string, currentPrice: string }

const { data: accounts } = await api<{ data: Account[] }>("/accounts")
const accountId = accounts[0].id

const balance = await api<Balance>(`/accounts/${accountId}/balance`)
console.log(balance.balance, balance.equity, balance.currency)

const { positions } = await api<{ positions: Position[] }>(`/accounts/${accountId}/positions`)
for (const position of positions) {
    console.log(position.symbol, position.side, position.volume, position.openPrice)
}

The first read after a session has gone idle logs in to your broker and can take several seconds. If it runs long, the API answers 202 with the code account_warming and a Retry-After header, and the helper repeats the request for you.

Read candles

The candles endpoint takes a symbol spelled exactly as your broker spells it, a timeframe of M1, M5, M15, H1, H4 or D1, and either a count of recent completed bars from 1 to 1,000, or an ordered from and to range with an optional limit. Count cannot be combined with from, to or limit, and a range needs both from and to with from earlier than to. Range pages run backward: keep everything else the same, replace to with nextTo, and stop when it is null.

import { api } from "./fivesocket"

const accountId = process.env.FIVESOCKET_ACCOUNT_ID

type Candle = { openTime: string, open: string, high: string, low: string, close: string, tickVolume: string, spread: number }
type CandlePage = { symbol: string, timeframe: string, data: Candle[], nextTo: string | null }

const recent = await api<CandlePage>(`/accounts/${accountId}/candles?symbol=EURUSD&timeframe=H1&count=200`)

const bars: Candle[] = []
let to: string | null = "2026-11-01T00:00:00Z"
while (to) {
    const query = new URLSearchParams({ symbol: "EURUSD", timeframe: "H1", from: "2026-10-01T00:00:00Z", to, limit: "1000" })
    const page = await api<CandlePage>(`/accounts/${accountId}/candles?${query}`)
    bars.unshift(...page.data)
    to = page.nextTo
}
console.log(recent.data.length, bars.length, bars.at(-1)?.close)

A symbol the account does not have returns 404 with the code symbol_not_found and up to five suggested names. A 503 with candle_history_unavailable and Retry-After means the terminal is still loading history, and the helper waits and retries. Read the historical data guide

Place an order

Trading is off until you turn it on for an account with a policy of exact symbols and the largest order size for each. The key needs the trading:execute scope. Every write needs an Idempotency-Key header, and an order also carries a clientOrderId that is unique for the account. Repeating the same key with the same order never sends it to the broker twice.

import { api, FiveSocketError } from "./fivesocket"

const accountId = process.env.FIVESOCKET_ACCOUNT_ID

await api(`/accounts/${accountId}/execution`, {
    method: "PUT",
    idempotencyKey: "enable-1",
    body: { symbols: [{ symbol: "EURUSD", maxVolume: "0.10" }] },
})

try {
    const command = await api<{ commandId: string, outcome: string }>(`/accounts/${accountId}/execution/orders`, {
        method: "POST",
        idempotencyKey: "order-1",
        body: { clientOrderId: "order-1", symbol: "EURUSD", side: "buy", type: "market", volume: "0.10" },
    })
    console.log(command.outcome, command.commandId)
} catch (error) {
    if (error instanceof FiveSocketError) {
        console.error(error.status, error.code, error.requestId)
    }
    throw error
}
  • The response is a command with a commandId and an outcome. A rejection by the gateway or the broker comes back as a 200 with the outcome rejected, so check the outcome and not only the status.
  • If the broker's reply is lost, the outcome can be commit_unknown. Do not send a new order. Poll the original command at /v1/accounts/{accountId}/execution/commands/{commandId}.

Test against a demo account first, and keep the policy's symbols and sizes narrow. Code that places real orders can lose real money when it misbehaves.

Handle errors and rate limits

  • 400 invalid_request: the request is wrong, such as mixing count with from and to. Fix it and do not retry.
  • 401 invalid_api_key, 402 subscription_required and 403 insufficient_scope: the key, the subscription or the key's scopes need attention.
  • 429 rate_limit_exceeded: you passed the per-key, per-workspace or per-account limit for the minute. The response carries Retry-After and RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers. Wait the number of seconds given.
  • 503 with Retry-After, such as capacity_exhausted or candle_history_unavailable: a transient condition. Wait and send the same request again.
  • 504 request_timeout: the read ran past its deadline. Retry reads after a pause. For a trade, look up its command before trying again.

The helper above retries 429 and 503 up to five times, using Retry-After and falling back to exponential backoff, and repeats a GET after a 202. It does not retry anything else. Requests per minute depend on your plan, and headers on each successful response show how many you have left.

There is no streaming feed and no webhooks, so your code polls. Poll at a pace that stays under your limit. Use MT5 from code without Windows

Frequently asked questions

Is there an official MetaTrader 5 package for Node.js?
No. MetaQuotes publishes the MetaTrader5 package for Python on Windows, and nothing for Node.js. FiveSocket is an HTTPS API, so Node.js, Bun and Deno call it with plain fetch.
Does FiveSocket have an npm SDK?
No. There is no FiveSocket npm package. The API is plain HTTPS with an OpenAPI document, so you can use fetch directly or generate a client from the document.
Which Node.js version do I need?
Node.js 18 or later, because it includes fetch. Bun and Deno work the same way. The examples are TypeScript and read the key from the FIVESOCKET_KEY environment variable.
Do I need Windows or the MetaTrader5 Python package?
No. FiveSocket hosts the MT5 terminal session for you, so your code runs on macOS, Linux, Windows or a serverless function, and you run no MT5 terminal.
How do I handle a 429 rate limit?
Wait the number of seconds in the Retry-After header, then send the same request again. Cap the number of retries and back off if the header is missing. Requests per minute depend on your plan.
Can I stream prices over a WebSocket?
No. FiveSocket has no streaming feed and no webhooks. Your code polls the REST endpoints for balances, positions and candles.
Can I place trades from Node.js?
Yes, after you turn trading on for the account with a policy of exact symbols and maximum order sizes, using a key with the trading:execute scope. Send an Idempotency-Key with every write, and test on a demo account first.
How much does it cost?
Plans start at $9.99 a month for one MT5 account. Link your MT5 account and try it free, no card: 24 hours or 100 calls, whichever comes first. Then a 7-day free trial, card required. Cancel anytime. The trial includes one connected MT5 account.

Try it on your own account.

Link your MT5 account and try it free, no card: 24 hours or 100 calls, whichever comes first. Then a 7-day free trial, card required. Cancel anytime. The trial includes one connected MT5 account. Cancel before the trial ends and you are not charged. A demo account is the safest place to start.

7-day free trial. Paid plans start at $9.99 a month. See pricing