TypeScript SDK

fundedops is the official JavaScript and TypeScript SDK for the FundedOps API. It ships one typed FundedOps client with the same method surface as the Python SDK, written in camelCase, plus typed responses, a typed error hierarchy, a live stream you read with for await and a helper that verifies webhook signatures.

The SDK supports both MT4 and MT5 accounts. The same client, methods, and types work identically against either platform, so there are no MT4-specific calls to learn.

Install

Requires Node 22 or newer. The SDK uses the built-in fetch, WebSocket and AbortSignal, and it works with both import and require. Bun and Deno are not tested.

npm install fundedops

Use it on a server only. An API key is a secret, so do not ship it to a browser or a mobile app.

Account methods live under the client.accounts namespace. waitUntilConnected, stream, searchServers, getBilling and the trading methods are on the client itself. Amounts (volume, prices, stops) accept a number or a decimal string.

Use it from JavaScript

The package works from plain JavaScript on Node 22 or newer. You do not need TypeScript or a build step.

With ES modules:

import { FundedOps } from "fundedops";
 
const client = new FundedOps({ apiKey: process.env.FUNDEDOPS_API_KEY });
const accounts = await client.accounts.list();

With CommonJS:

const { FundedOps } = require("fundedops");
 
const client = new FundedOps({ apiKey: process.env.FUNDEDOPS_API_KEY });
 
async function main() {
  const accounts = await client.accounts.list();
  console.log(accounts.length);
}
 
main();

Usage

Construct a FundedOps client with your API key. The constructor also takes baseUrl, timeoutMs and fetch.

import { FundedOps } from "fundedops";
 
const client = new FundedOps({ apiKey: "fo_live_..." });
 
// List your accounts.
const accounts = await client.accounts.list();
for (const account of accounts) {
  console.log(account.id, account.state, account.connectionStatus);
}
 
// Read last-known figures.
const info = await client.accounts.accountInformation(accounts[0].id);
console.log(info.balance, info.equity, info.currency);
 
// Deploy an account and wait until it connects (timeoutMs is mandatory).
await client.accounts.deploy(accounts[0].id);
const account = await client.waitUntilConnected(accounts[0].id, { timeoutMs: 180_000 });
console.log(account.connectionStatus); // "connected"

The account lifecycle and read surface is on client.accounts:

GroupMethods
Lifecyclecreate, get, list, update, delete, deploy, undeploy, redeploy
Account stateaccountInformation, positions, pendingOrders
HistoryhistoryDeals, historyPositions, historyOrders, balanceOperations, balanceHistory
Symbols and pricessymbols, symbol, quote, quotes, candles
Calculations and checkscalculateMargin, calculateProfit, checkOrder
StatisticstradeStats, equityHistory
const open = await client.accounts.positions(accountId);
const pending = await client.accounts.pendingOrders(accountId);
const deals = await client.accounts.historyDeals(accountId, { limit: 100 });
const closed = await client.accounts.historyPositions(accountId, { limit: 100 });

client.searchServers("ic markets demo", { platform: "mt5" }) finds broker server names, best match first. client.getBilling() returns your prepaid balance and every billed account with its next charge.

waitUntilConnected throws DeployFailedError as soon as the account cannot connect, and WaitTimeoutError when timeoutMs runs out. The error's code, retryable and message come from the account's error.

import { DeployFailedError } from "fundedops";
 
try {
  await client.waitUntilConnected(accountId, { timeoutMs: 180_000 });
} catch (error) {
  if (error instanceof DeployFailedError) console.log(error.code, error.retryable, error.message);
  else throw error;
}

Streaming

client.stream([accountId, ...]) opens a WebSocket, subscribes each account, answers server pings for you and yields typed events. Read it with for await.

import { isStreamEvent } from "fundedops";
 
for await (const event of client.stream([accountId])) {
  if (isStreamEvent(event, "positions_updated")) {
    console.log("open:", event.updated.length, "closed:", event.removed_ids);
  } else if (isStreamEvent(event, "account_information_updated")) {
    console.log("equity", event.account_information?.equity);
  }
}

Event field names follow the wire format, so they stay in snake_case. Compare with isStreamEvent(event, type), not event.type ===: it narrows the event to that frame, and fields that can be missing are null or undefined. There is no auto-reconnect: a clean server close ends the loop, and an abnormal close throws StreamClosedError. To resume, reconnect and resubscribe, and the server sends a fresh snapshot. stream.close() ends one stream and client.close() ends every stream the client opened. See WebSockets for the frame vocabulary.

Prices

client.accounts.quote(accountId, symbol) returns the latest bid and ask. client.accounts.candles(accountId, symbol, timeframe, { startTime, endTime, limit }) returns up to 1,000 bars, oldest first (limit defaults to 100). A call waits up to about 10 seconds for the account. It throws ServiceUnavailableError with code E_PRICES_UNAVAILABLE when the account cannot read prices right now or did not answer within about 10 seconds; retry shortly.

const quote = await client.accounts.quote(accountId, "EURUSD");
console.log(quote.bid, quote.ask, quote.time);
 
const bars = await client.accounts.candles(accountId, "EURUSD", "H1", { limit: 200 });
for (const bar of bars.candles) {
  console.log(bar.time, bar.open, bar.high, bar.low, bar.close, bar.tickVolume);
}

client.accounts.quotes(accountId, symbols) takes a list of names and returns the latest prices of 1 to 50 distinct symbols in one call. Every symbol ends up in quotes or in errors, so one unknown symbol never fails the call. An error's status is the HTTP status quote would answer for that symbol alone (404 or 503), with code when that answer carries one. Only symbols subscribed on a WebSocket stream are answered from the cache. Every other symbol is one request to the account, which answers about 40 a second and shares a queue of 100 waiting requests with Get Quote and the calculations, so polling many unstreamed symbols quickly can return 503 E_PRICES_UNAVAILABLE. Stream the symbols you poll often.

const result = await client.accounts.quotes(accountId, ["EURUSD", "GBPUSD", "XAUUSD"]);
for (const quote of result.quotes) console.log(quote.symbol, quote.bid, quote.ask);
for (const error of result.errors ?? []) console.log(error.symbol, error.status, error.code);

Calculations

Three read-only calls ask the account what a trade would cost, without trading. They work with a Read Only key. The Trading guide has the rules.

MethodWhat it does
client.accounts.calculateMargin(accountId, symbol, type, volume, { price })The margin the order needs.
client.accounts.calculateProfit(accountId, symbol, type, volume, openPrice, closePrice)The profit of a trade between two prices.
client.accounts.checkOrder(accountId, type, symbol, volume, { price, stopLimitPrice, stopLoss, takeProfit })Whether the account could place the order now.
const margin = await client.accounts.calculateMargin(accountId, "EURUSD", "buy", 0.1);
const profit = await client.accounts.calculateProfit(accountId, "EURUSD", "buy", 0.1, 1.08, 1.09);
const check = await client.accounts.checkOrder(accountId, "buy_limit", "EURUSD", 0.1, { price: 1.08 });
if (!check.canPlace) console.log(check.code, check.message);

A refusal is a normal answer, not an error: canPlace is false with a code such as E_INVALID_VOLUME or E_ACCOUNT_CANNOT_TRADE.

For live prices, call the subscribe methods on the stream, before the loop or while you iterate. Frames sent before iteration wait and go out once, right after the accounts subscribe. A stream holds up to 50 price subscriptions, quote symbols and candle streams together.

const stream = client.stream([accountId]);
stream.subscribeQuotes(accountId, ["EURUSD", "GBPUSD"]);
stream.subscribeCandles(accountId, "EURUSD", "M5");
for await (const event of stream) {
  if (isStreamEvent(event, "quotes")) {
    for (const quote of event.quotes) console.log(quote.symbol, quote.bid, quote.ask);
  } else if (isStreamEvent(event, "candle") && event.closed && event.candle) {
    console.log("closed", event.symbol, event.timeframe, event.candle.time, event.candle.close);
  }
}

unsubscribeQuotes and unsubscribeCandles take the same arguments. Each call is answered with a price_subscriptions event. Closed bars arrive at least once, so de-duplicate them on symbol, timeframe and candle.time. WebSockets has the frames, caps and the coalescing rules.

Trading

The trading methods need a Full Access API key and an account connected with its master password (account.tradeAllowed is true). The Trading guide explains the rules behind them. Every method takes its options as the last argument.

MethodWhat it does
placeOrder(accountId, type, symbol, volume, { price, stopLimitPrice, stopLoss, takeProfit, slippage, comment, magic, expirationType, expirationTime, fillingMode, expiresInSeconds, idempotencyKey })Opens a position at the market price or places a pending order.
modifyOrder(accountId, ticket, { price, stopLimitPrice, stopLoss, takeProfit, expirationType, expirationTime, expiresInSeconds, idempotencyKey })Changes a pending order.
cancelOrder(accountId, ticket, { idempotencyKey })Cancels a pending order.
modifyPosition(accountId, ticket, { stopLoss, takeProfit, expiresInSeconds, idempotencyKey })Changes a position's stop loss or take profit.
closePosition(accountId, ticket, { volume, slippage, expiresInSeconds, idempotencyKey })Closes a position, or part of it with volume.
closePositions(accountId, { symbol, slippage, expiresInSeconds, idempotencyKey })Closes every open position, or those on symbol.
closePositionBy(accountId, ticket, oppositeTicket, { expiresInSeconds, idempotencyKey })Closes a position against an opposite position on the same symbol. E_INVALID_CLOSE_BY means the two positions cannot be closed by each other (the same ticket, different symbols or the same direction).
getTradeRequest(accountId, tradeRequestId)One trade request.
listTradeRequests(accountId, { offset, limit })The account's trade requests, newest first.
waitForTradeRequest(accountId, tradeRequestId, { timeoutMs, intervalMs, signal })Polls a queued or sent request until its status is done, rejected, expired or unknown and returns the trade request. Throws WaitTimeoutError once timeoutMs passes.

Each trading write resolves with a trade request: done when the broker carried it out, or queued, sent or unknown when it had not answered within about 10 seconds. Then call waitForTradeRequest. A write that is rejected or expires throws an error; waitForTradeRequest returns such a request with its status instead.

import { FundedOps, TradeOutcomeUnknownError, TradeRejectedError } from "fundedops";
 
const client = new FundedOps({ apiKey: "fo_live_..." }); // a Full Access key
const idempotencyKey = crypto.randomUUID();
const order = { stopLoss: 1.079, idempotencyKey };
 
let trade;
try {
  trade = await client.placeOrder(accountId, "buy", "EURUSD", 0.1, order);
} catch (error) {
  if (error instanceof TradeOutcomeUnknownError) {
    // The connection failed before an answer arrived. Send the same call with the
    // same key: you get the first request's outcome, never a second trade.
    trade = await client.placeOrder(accountId, "buy", "EURUSD", 0.1, order);
  } else if (error instanceof TradeRejectedError) {
    console.log(error.code, error.brokerCode, error.retryable);
    throw error;
  } else {
    throw error;
  }
}
 
if (trade.status === "queued" || trade.status === "sent") {
  trade = await client.waitForTradeRequest(accountId, trade.id, { timeoutMs: 60_000 });
}
console.log(trade.status, trade.result);
 
// Move the stop loss. An omitted takeProfit keeps the take profit as it is.
await client.modifyPosition(accountId, "1834920571", { stopLoss: 1.0815 });
// Remove the take profit.
await client.modifyPosition(accountId, "1834920571", { takeProfit: null });
  • Idempotency keys. Every trading write sends an Idempotency-Key. Pass idempotencyKey to choose it; otherwise the SDK generates one per call. The key it sent is on trade.idempotencyKey and on .idempotencyKey of any error the call throws. Sending a key again never trades twice: it returns the first request's outcome. When the connection fails before any answer arrives (a timeout, a reset, an abort), the call throws TradeOutcomeUnknownError with the key. The SDK never retries on its own.
  • Omitted and null. In modifyOrder and modifyPosition, an omitted field keeps its value and null removes it (stop loss, take profit, expiration).
  • Numbers. Prices and volumes accept a number or a decimal string. A string is sent exactly as given, so use one when a float would lose precision.
  • Times. expirationTime takes a Date or an ISO string.
  • Account fields. Account.tradeAllowed and Account.marginMode (hedging, netting or exchange) say whether the account can trade. client.accounts.update(accountId, { password: "..." }) switches it to another password.

Webhooks

webhooks.verify checks the signature and age of a delivery and returns the parsed event. Pass the raw request body (a Buffer or the exact string), before any JSON parsing, and the FundedOps-Signature header. It throws WebhookSignatureError when the check fails. A delivery more than 300 seconds old is refused. Change the window with { tolerance }; 0 skips the age check. The Webhooks guide lists the events.

import express from "express";
import { webhooks, WebhookSignatureError } from "fundedops";
 
const app = express();
 
app.post("/fundedops", express.raw({ type: "application/json" }), (req, res) => {
  try {
    const signature = req.header("FundedOps-Signature") ?? "";
    const event = webhooks.verify(req.body, signature, process.env.WEBHOOK_SECRET!);
    console.log(event.type, event.accountId);
    res.sendStatus(200);
  } catch (error) {
    if (error instanceof WebhookSignatureError) return res.sendStatus(400);
    throw error;
  }
});

Error handling

Every non-2xx response throws a typed error derived from FundedOpsError. Each carries status, error, message, requestId, and optional details / metadata.

ErrorStatusMeaning
ValidationError400The request failed validation.
CredentialsBlockedError400The broker rejected this login recently; retry after blockedUntil (rejectedAt, blockedUntil).
UnauthorizedError401Missing or invalid API key.
PaymentRequiredError402Insufficient credit balance.
ForbiddenError403The API key is read-only, or limited to chosen accounts and the endpoint covers your whole developer account. On trading calls code is E_ACCOUNT_CANNOT_TRADE or E_TRADING_NOT_SUPPORTED when the account cannot trade.
NotFoundError404The resource does not exist, is not yours, or your API key is limited to other accounts.
ConflictError409The request conflicts with current state.
RateLimitedError429Rate limit exceeded (retryAfter, in seconds), or 50 trade requests are already waiting for the account (E_QUEUE_FULL). Nothing was stored.
InternalError500Server-side error, or a non-envelope error body.
TradeRejectedError422The broker rejected a trade (code, brokerCode, retryable, tradeRequestId). Send it again only with a new key, and only when retryable.
IdempotencyKeyReusedError422The idempotency key was already used for a different request.
ServiceUnavailableError503The account job could not be queued, or the account is not connected for trading (E_ACCOUNT_NOT_CONNECTED); nothing was stored, so retry shortly with the same key.
TradeExpiredError503A subclass of ServiceUnavailableError: the trade expired before it was sent, so nothing happened at the broker (code, tradeRequestId). Send it again with a new key.
TradeOutcomeUnknownErrornoneA trading write failed on the way (timeout, connection reset, abort) before any answer arrived, so the outcome is unknown. Send the same call again with idempotencyKey: error.idempotencyKey, or find it with listTradeRequests.
DeployFailedErrornoneThrown by waitUntilConnected when the account cannot connect (code, retryable, account).
WaitTimeoutErrornonewaitUntilConnected or waitForTradeRequest ran past timeoutMs.

Catch a specific class, or FundedOpsError to handle everything. RateLimitedError exposes the Retry-After value as retryAfter:

import { NotFoundError, RateLimitedError } from "fundedops";
 
try {
  await client.accounts.get(accountId);
} catch (error) {
  if (error instanceof RateLimitedError) {
    await new Promise((resolve) => setTimeout(resolve, (error.retryAfter ?? 1) * 1000));
    await client.accounts.get(accountId);
  } else if (!(error instanceof NotFoundError)) {
    throw error;
  }
}

Timeouts and rate limits

Every request times out after 30 seconds. Change it with timeoutMs in the constructor. Every method also takes a signal option; aborting it cancels the call. A trading write that is aborted or times out throws TradeOutcomeUnknownError, because the broker may have received it. waitUntilConnected and waitForTradeRequest take timeoutMs, an optional intervalMs and an optional signal.

const client = new FundedOps({ apiKey: "fo_live_...", timeoutMs: 10_000 });
const controller = new AbortController();
setTimeout(() => controller.abort(), 5_000);
const accounts = await client.accounts.list({ signal: controller.signal });

The constructor also takes fetch, which replaces the global fetch for every REST call (a proxy, a custom agent, a test double). The live stream always uses the global WebSocket. The key travels in the WebSocket URL's query string, so never log stream URLs.

client.rateLimit holds the request budget from the latest response's X-RateLimit-* headers: limit (bucket size), remaining (requests left) and reset (seconds until the bucket is full again). It is null until a response carries the headers, and a response without them keeps the last value.

await client.accounts.list();
console.log(client.rateLimit?.remaining, client.rateLimit?.reset);

Differences from the Python SDK

The two SDKs cover the same API. The names differ where TypeScript habits differ:

Python SDKTypeScript SDK
*Page and *List types*Response types
OrderCheckOrderCheckResult
StreamClosedStreamClosedError
__version__VERSION
parse_eventparseEvent
raise_for_envelopeerrorFromResponse

In modify_order and modify_position (modifyOrder and modifyPosition in TypeScript), Python keeps a field with KEEP and removes it with None; TypeScript keeps it by leaving it out and removes it with null. Stream event fields keep the wire names.

For the complete list of endpoints and their request and response shapes, see the API reference.