npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

pipsocket

v0.1.0

Published

TypeScript client for the Pipsocket API: REST and WebSocket access to MetaTrader 5 accounts hosted by Pipsocket.

Readme

pipsocket

TypeScript client for the Pipsocket API: REST and WebSocket access to MetaTrader 5 accounts hosted by Pipsocket.

Versions are 0.x for now: until 1.0, a minor release may change this package's API. CHANGELOG.md says what each one changes.

Why

Pipsocket runs each MT5 terminal for you and gives it an API, so your code runs anywhere Node runs.

| | MetaQuotes' MetaTrader5 package (Python) | pipsocket | | ------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | Runs on | Windows only (its wheels on PyPI are all win_amd64, version 5.0.6231, checked 9 Nov 2026) | Linux, macOS, Windows, any server runtime | | Needs | An MT5 terminal running on the same machine | A Pipsocket account ($15 per account per month); the terminal is hosted |

  • One install, no runtime dependencies for REST (it uses the built-in fetch).
  • Typed answers, generated from the API's own OpenAPI document.
  • Retries that are safe: the client knows which answers are worth another try.

Install

npm install pipsocket

Node 22 or later. ESM only, with type declarations.

Quickstart

Make your workspace's key on the dashboard's API key page, and keep it on your server:

export PIPSOCKET_KEY=psk_...

Then read the account, place an order on a demo account, handle its outcome, and close what it opened. A symbol allows only some filling modes and volumes, and MT5 rejects an order with any other (10030, 10014), so the order takes them from the symbol. It also carries a magic number of your own, so the script closes only its own positions:

import { Pipsocket } from "pipsocket";

const ps = new Pipsocket(); // reads PIPSOCKET_KEY
const acct = ps.account("acc_01m6tx3k9f2qw8r7bznd5yvh4c");

const account = await acct.get();
console.log(account.status, account.balance, account.currency);

// A filling mode and a volume this symbol allows. A market order can use fok or ioc (boc is for
// limit orders only).
const eurusd = await acct.symbols.get("EURUSD");
const filling = (["fok", "ioc"] as const).find((mode) => eurusd.filling_modes.includes(mode));
if (!filling) throw new Error("EURUSD allows neither fok nor ioc, the filling modes a market order can use");

const MAGIC = 4021; // this script's own number, kept by MT5 on its orders, deals and positions

let order = await acct.orders.place({
  symbol: "EURUSD",
  type: "buy",
  volume: eurusd.volume_min,
  type_filling: filling,
  magic: MAGIC,
});
if (order.kind === "pending" || order.kind === "unknown") order = await acct.requests.wait(order.id);

switch (order.kind) {
  case "completed":
  case "partial":
  case "placed":
    // MT5 took the request. That alone doesn't mean filled: a fill has a deal (result.deal isn't 0);
    // a pending order placed has its order and deal 0, whether the state is placed or completed.
    if (order.result.deal === 0) {
      console.log("placed, not filled: order", order.result.order);
      break;
    }
    console.log("filled: deal", order.result.deal);
    // Close the position this order opened: on this symbol, with this script's magic number.
    for (const position of await acct.positions.list()) {
      if (position.symbol !== "EURUSD" || position.magic !== MAGIC) continue;
      const close = await acct.positions.close(position.ticket, { volume: position.volume, type_filling: filling });
      console.log("close", position.ticket, close.state);
    }
    break;
  case "rejected":
    console.log("rejected:", order.result.retcode_name);
    break;
  case "not_sent":
  case "not_executed":
    console.log("not executed:", order.message);
    break;
  case "executed":
    console.log("executed, as settled by an owner or admin:", order.message);
    break;
  default:
    // Still pending or unknown after the wait, or a state this version doesn't know: it may have
    // executed, so read positions and history before trading again.
    console.log("outcome not known yet:", order.state);
}

Every call is for one account, so the client gives you a handle per account. Field names are the API's own (type_filling, price_open), as in the API reference.

Streaming

The stream pushes what happens on the account as it happens: fills, deals, prices, the account every second. On Node it needs the ws package:

npm install pipsocket ws
import { isEvent, Pipsocket } from "pipsocket";

const acct = new Pipsocket().account("acc_01m6tx3k9f2qw8r7bznd5yvh4c");
const stream = acct.stream({ ticks: ["EURUSD"] });

for await (const event of stream) {
  if (isEvent(event, "resync")) console.log("baseline", event.reason, event.positions?.length, "positions");
  else if (isEvent(event, "tick")) console.log(event.symbol, event.bid, event.ask);
  else if (isEvent(event, "request")) console.log("request", event.request, event.state);
  else console.log(event.type);
}

The events are the API's messages as they are (see the WebSocket stream), plus one the helper adds: resync. A message of a type added later is passed on too, so isEvent(event, "tick") is how to narrow one to its known shape. The helper reconnects by itself, with backoff, sends your tick set again, pings the socket every 20 seconds, and after every connect and every gap yields a resync event. stream.setTicks(symbols) changes the tick set; stream.close(), or leaving the loop, stops it.

What a resync gives, and what it doesn't:

  • A new baseline for state. account, positions and orders as REST showed them after the subscription was live: replace your own state with them. positions and orders are null when the terminal isn't running, which is not the same as empty.
  • Every deal, request, transaction and status event the socket carried from the subscription on, delivered after the resync when it finishes without another gap. account and tick events are thinned during a resync: the next account event comes within a second, and only the newest tick per symbol is kept.
  • Not one moment in time. The reads happen one after another, so a position can change between them.
  • Not an order between events and the snapshot. An event delivered after a resync can describe something older than the snapshot. Events are notices, not deltas: never add them to or subtract them from the snapshot. Deduplicate deals and orders by ticket and requests by id, and read again when exact state matters.
  • Not a replay of the gap. Events from a gap are not sent again, request events included. What happened in it comes from the resync: history holds the deals and past orders read back from history since the last checkpoint, best effort, and requests.wait(id) tells you how a request you sent settled. Ticks and transaction events from a gap are gone. When there is no history, history_reason says why (no_checkpoint, account_changed, range_too_large or unavailable).
  • History from a little before the gap. A resync's history starts 5 minutes before its checkpoint, so it can include deals from before you opened the stream. The helper leaves out deals it has already delivered to you as deal events or in an earlier resync, and orders from an earlier resync's history, as far as it remembers them (the last 10,000 of each). That is best effort: an order you saw only in a transaction event, or an old ticket, can come again, so deduplicate deals and orders by ticket yourself.

reason is connected, reconnected, lagged (the server dropped events), host_back (the account's host or terminal came back) or overflow (your loop fell behind and the helper's own queue filled). Pass snapshot: false to get the resync event without the reads. queueSize (1000 by default) is how many events the helper holds for you before it treats a backlog as a gap.

A refused key or account (401, 404) ends the stream with that error, as does a key rolled while it was open, at the stream's next read (or a requests.wait lookup's). A network failure never ends it on Node: it keeps reconnecting, with backoff, until you close it. On Bun, and on Deno without ws, the WebSocket can't say why an upgrade failed, so the stream checks with a REST read: a 401 or 404 there ends it at once, and if the API answers but the upgrade keeps failing five times running, it ends with StreamHandshakeError (see Runtimes). An open stream also helps requests.wait: a request event ends the wait as soon as it arrives, and a trade call never reports a request as pending once the stream has shown it final.

Every call

| Call | Method | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | The account | acct.get() | | Positions | acct.positions.list() | | Close a position, close by, set stops | acct.positions.close(ticket, { volume, type_filling }), acct.positions.closeBy(ticket, { position_by }), acct.positions.setLevels(ticket, { sl, tp }) | | Pending orders | acct.orders.list() | | Place, check, modify or cancel an order | acct.orders.place(order), acct.orders.check(order), acct.orders.modify(ticket, changes), acct.orders.cancel(ticket) | | Look up a request | acct.requests.get(id), and acct.requests.wait(id) until it is final | | Deal and order history | acct.history.deals({ from, to }), acct.history.orders({ from, to }) | | Symbols and prices | acct.symbols.list(), acct.symbols.get(name), acct.symbols.tick(name) | | Kill switch | acct.killSwitch.get(), acct.killSwitch.engage({ deviation }), acct.killSwitch.lift() |

History ranges are the broker's server time in whole seconds, both ends included, not UTC: build them from the account's server_time, never from your own clock:

import { Pipsocket } from "pipsocket";

const acct = new Pipsocket().account("acc_01m6tx3k9f2qw8r7bznd5yvh4c");

const { server_time } = await acct.get(); // the broker's server time, in seconds
if (typeof server_time !== "number") throw new Error("The terminal hasn't reported its server time yet");
const deals = await acct.history.deals({ from: server_time - 86_400, to: server_time });
console.log(deals.length, "deals in the last day");

Every call takes an options object last: { signal, timeoutMs, maxRetries }, and the six trade calls also idempotencyKey.

Order outcomes

A trade call returns a TradeRequest for every answer that is a recorded request, whatever its state, rejections included. kind is the state, closed so that a switch on it narrows result; state is the API's own string. See request ids and errors.

| kind | Meaning | result | | -------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------- | | completed | MT5 completed the request: an order filled, a pending order placed, or a change or cancel made | MT5's answer: retcode, order, deal | | placed | MT5 placed it, such as a pending order. Not filled | MT5's answer, with order set and deal 0 | | partial | MT5 filled part of it. Final for that request | MT5's answer, with the deal | | rejected | MT5 rejected it. Final: change it and send it again (a new call, a new key) | MT5's answer: retcode_name says why | | pending | No answer from the trade server within 5 s. Never sent again: requests.wait(id) | null | | unknown | No answer within 130 s. It may have executed: check positions and history | null | | not_sent | The terminal didn't send it. Call again to send it | { error, message } | | not_executed | Was unknown, settled as never executed (settlement says by whom) | { error, message }, or who settled it | | executed | Was unknown, settled as executed by an owner or admin | Who settled it, and why | | unrecognised | A state this version doesn't know yet: read state | as sent |

completed doesn't mean filled. To tell a fill, read result.deal: it isn't 0 when an order filled (and its sent.action is "deal"). A pending order that MT5 accepted has result.order set and deal 0, whether it comes back placed or completed; so does a modify or a cancel.

isAccepted(request), isFinal(request) and isOutstanding(request) answer the common questions, and throwForState(request) throws TradeNotAccepted for rejected, not_sent and not_executed, if you would rather have exceptions.

requests.wait(id, { timeoutMs }) looks the request up until it is final or the timeout passes (30 s by default), then returns it as it stands. It never throws for "still pending", and it sends nothing but lookups.

Retries and idempotency keys

Every trade call sends an Idempotency-Key, and every retry inside the call sends the same one, so a trade is never sent twice. Calling the method again is a new trade, with a new key.

When an attempt may have reached the account's host and no recorded request comes back (the connection dropped, 503 engine_unavailable, 504 engine_timeout), the call retries with the same key: that returns the request if the host recorded it, and sends it if it never arrived. If the retries run out, it throws OutcomeUnknown, with the key on it. The trade may or may not have been sent: call again with idempotencyKey: error.idempotencyKey (it returns the request, or sends the trade), or read positions and history first. Once an attempt may have been sent, the call never reports that nothing was sent.

To survive a crash or a cancelled call, make the key yourself and save it before sending:

import { newKey, OutcomeUnknown, Pipsocket } from "pipsocket";

const acct = new Pipsocket().account("acc_01m6tx3k9f2qw8r7bznd5yvh4c");

// A filling mode and a volume the symbol allows (MT5 rejects any other): fok or ioc for a market order.
const eurusd = await acct.symbols.get("EURUSD");
const filling = (["fok", "ioc"] as const).find((mode) => eurusd.filling_modes.includes(mode));
if (!filling) throw new Error("EURUSD allows neither fok nor ioc, the filling modes a market order can use");
const buy = { symbol: "EURUSD", type: "buy", volume: eurusd.volume_min, type_filling: filling } as const;

const key = newKey();
// Save the key, with the order it is for, before sending (a database row, a file).
try {
  const order = await acct.orders.place(buy, { idempotencyKey: key });
  console.log(order.state);
} catch (error) {
  if (!(error instanceof OutcomeUnknown)) throw error;
  // Later, or after a restart: the same call with the same key returns the recorded request.
  const order = await acct.orders.place(buy, { idempotencyKey: key });
  console.log(order.state);
}

A key matches the first request made with it, whatever the body: never build keys from the order (such as "buy-eurusd"), and never reuse one for a different trade. A key protects its request for 7 days after the outcome is known.

Errors and retries

When a call can't give you its answer, it throws a PipsocketError. Every PipsocketError a trade call throws carries the idempotencyKey it sent. Two things a trade call can throw are not PipsocketErrors: a TypeError for a bad argument (a malformed key or ticket), raised before anything is sent, which has no key; and your own AbortSignal's reason, passed through as it is, which isn't guaranteed to carry it (a string or a frozen object can't). A cancelled trade may still have been sent, so for a call you may cancel, make the key with newKey() and save it first.

| Error | When | | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | OutcomeUnknown | A trade may have been sent and no recorded request came back: see retries and idempotency keys | | APIConnectionError, APITimeoutError | The network failed, or an attempt took longer than timeoutMs. If an answer broke off part way, status and raw keep what arrived | | AuthenticationError | 401: the key is missing, wrong, or was rolled | | NotFound | 404: no such account, order, position, request or symbol | | InvalidRequest, RangeTooLarge | 400 or 422: fix the call. Nothing was sent | | SymbolBusy | 409: an earlier request on the symbol has no outcome yet. blocking lists them; retryAfter is null when one is unknown. Nothing was sent | | KillSwitchEngaged, BillingHold | 423: new exposure is refused. Nothing was sent | | AccountUnavailable | 503: the account's terminal isn't connected, is restarting, or needs a restart. On engaging the kill switch, killSwitch shows it engaged all the same | | Unavailable | 503 engine_unavailable or 504 engine_timeout on a call that is safe to repeat, after the retries | | EngineBusy, TerminalTimeout, TerminalError, NoPrice | The host or the terminal couldn't answer | | APIError | Any other refusal: status, code, body and raw say what came back | | TradeNotAccepted | Only from throwForState(request), for a request that was rejected, not sent or not executed |

import { AccountUnavailable, Pipsocket } from "pipsocket";

const acct = new Pipsocket().account("acc_01m6tx3k9f2qw8r7bznd5yvh4c");

try {
  console.log(await acct.positions.list());
} catch (error) {
  if (error instanceof AccountUnavailable) console.log("The terminal isn't running:", error.code);
  else throw error;
}

The client retries what is worth retrying, twice by default, and starts no new attempt 60 seconds after the first: a lost connection, 503 engine_unavailable, 504 engine_timeout, 503 engine_busy, 504 terminal_timeout, and 409 symbol_busy with a Retry-After, waiting 0.5 s and then 1 s (with jitter) between attempts, or what Retry-After says. It never retries a refusal that won't change, such as a 401 or a 404, and never retries a recorded request: a rejected or not_sent one is returned. See Errors and retcodes for every code.

| Option | Default | | | ----------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | apiKey | PIPSOCKET_KEY | Never logged and never in an error message | | timeoutMs | 40000 | Per attempt. The API itself waits up to 30 s for the account's host | | maxRetries | 2 | 0 turns retries off | | retryDeadlineMs | 60000 | No new attempt starts this long after the first | | baseUrl | https://api.pipsocket.com | For a mock server in your own tests | | fetch | the runtime's fetch | A custom one must make one attempt per call and follow no redirects. Its failures count as possibly sent unless it marks them with markNotSent(error) |

Cancel a call with an AbortSignal: the call throws the signal's reason as it is, and sends nothing more. A trade that was already written may still execute, so for a call you may cancel, make and save the key first, as above.

Runtimes

| Runtime | REST | Stream | | ------------------ | ------------- | -------------------------------------------------------------- | | Node 22 and later | yes | yes, with the ws package | | Bun | yes | yes, with its own WebSocket | | Deno 2.5 and later | yes | yes, with the ws package (recommended), or its own WebSocket | | Cloudflare Workers | yes | no | | Browsers | no, by design | no |

With ws, the stream sees why an upgrade was refused: a 401 or 404 ends it at once, and close() drops the connection at once. Bun's WebSocket, and Deno's own without ws, can't say why an upgrade was refused, so after a failed upgrade the stream makes one REST read with the same key: a 401 or 404 there ends the stream, and if the API answers and the upgrade still fails five times running, the stream ends with StreamHandshakeError. Deno's own WebSocket also waits for the server to answer its close, so a stream closed while the network is dead can keep the process up until the connection times out. A runtime that needs another WebSocket client can pass its own adapter as socket.

The client refuses to start in a browser: the API doesn't answer browsers' cross-origin requests, and an API key in a web page would leak. Call the API from your server.

Links

Versioning

Versions follow semver and stay below 1.0 for now, so a minor version may change the API. CHANGELOG.md lists every change and the API document each release was built from.

Support

Report SDK bugs in this repository's issues. For your account, billing or a trade, write to [email protected]. Security issues: see SECURITY.md.

Licence

MIT. See LICENSE.

MetaTrader is a trademark of MetaQuotes Ltd. Pipsocket is not affiliated with MetaQuotes.