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

@revolut/revolut-x-api

v1.0.53

Published

Typed HTTP client for the Revolut X Exchange REST API

Readme

revolutx-api

Typed HTTP client for the Revolut X Public Trading API REST API. Zero runtime dependencies — uses only Node.js built-ins (crypto, fetch).

npm Release License: MIT


Table of Contents


Installation

Download revolutx-api-*.tgz from the latest release, then:

npm install ./revolutx-api-*.tgz

Or from source:

git clone https://github.com/revolut-engineering/revolut-x-api.git
cd revolut-x-api/api && npm install
npm run build

Requires Node.js 20+.


Quick Start

import { RevolutXClient } from "@revolut/revolut-x-api";

const client = new RevolutXClient({
  apiKey: "your-api-key",
  privateKeyPath: "~/.config/revolut-x/private.pem",
});

const balances = await client.getBalances();
console.log(balances);

Configuration

Client Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | apiKey | string | — | Revolut X API key | | privateKey | KeyObject | — | Ed25519 private key object | | privateKeyPath | string | — | Path to PEM-encoded private key file | | baseUrl | string | https://revx.revolut.com | API base URL. It must use https:// (plain http:// only for localhost, 127.x.x.x or [::1]) and must not end with /api, since the client adds /api/1.0 | | timeout | number | 30000 | Request timeout in milliseconds | | maxRetries | number | 3 | Max retry attempts for failed requests | | autoLoadCredentials | boolean | true | Auto-load credentials from config directory | | logger | LogCallback | — | Custom log handler — receives structured log entries |

Credential Auto-loading

When neither apiKey nor privateKey is provided, the client loads credentials from the platform config directory:

| Platform | Path | |----------|------| | macOS | ~/.config/revolut-x/ | | Linux | ~/.config/revolut-x/ | | Windows | %APPDATA%\revolut-x\ |

Override with REVOLUTX_CONFIG_DIR environment variable.

Expected files: config.json (contains apiKey) and private.pem (Ed25519 key).

Set autoLoadCredentials: false to disable.


API Reference

Client State

// Check if the client has credentials configured
client.isAuthenticated; // → boolean

Account

// Get all balances
const balances = await client.getBalances();
// → AccountBalance[] — { currency, available, reserved, total, staked? }

// List sub-accounts with total balances converted to a currency
const subAccounts = await client.getSubAccounts({ convertTo: "EUR" }); // convertTo optional, default "USD"
// → { data: { sub_accounts: SubAccount[] }, metadata: { timestamp, convert_to } }
// SubAccount — { name, total_balance: { amount, currency }, created_date, updated_date }
// total_balance is available + reserved converted at mid-market rates

Configuration

// Get supported currencies
const currencies = await client.getCurrencies();
// → CurrencyMap — { [symbol]: { symbol, name, scale, asset_type, status } }

// Get trading pairs
const pairs = await client.getCurrencyPairs();
// → CurrencyPairMap — { [pair]: { base, quote, base_step, quote_step, min/max_order_size, status } }

// Get your fee tiers by trading volume (spot and futures)
const feeTiers = await client.getFeeTiers();
// → { data: FeeTierGroup[], metadata: { timestamp } }
// FeeTierGroup — { type: "spot" | "futures", current_tier: number | null, currency, tiers: FeeTier[] }
// FeeTier — { tier, volume_from, volume_to? (absent on the top tier), maker_fee, taker_fee }
// current_tier reflects your 30-day trading volume; null when no volume is on record

Market Data

// Tickers (all or filtered)
const tickers = await client.getTickers();
const btc = await client.getTickers({ symbols: ["BTC-USD"] });
// → { data: Ticker[], metadata: { timestamp } }
// Ticker includes bid, ask, mid, index_price, last_price, and 24h statistics.

// OHLCV candles
const candles = await client.getCandles("BTC-USD", {
  interval: "1h",      // "1m","5m","15m","30m","1h","4h","1d","2d","4d","1w","2w","4w" or minutes as number
  startDate: 1700000000000,
  endDate: 1700086400000,
});
// → { data: Candle[] }

// Order book (authenticated)
const book = await client.getOrderBook("BTC-USD", { limit: 10 }); // depth per side, 1-192, default 50
// → { data: { asks, bids }, metadata: { timestamp } }
// asks ascending (asks[0] = best/lowest ask), bids descending (bids[0] = best/highest bid)

Orders

// Place limit buy
const result = await client.placeOrder({
  symbol: "BTC-USD",
  side: "buy",
  limit: {
    price: "95000",
    baseSize: "0.001",          // baseSize or quoteSize required
    executionInstructions: ["post_only"],  // optional: "allow_taker" | "post_only"
  },
  clientOrderId: "my-order-1", // optional, auto-generated if omitted
});
// → { data: { venue_order_id, client_order_id, state } }
// Pass your own clientOrderId to find the order after a lost reply.

// Place market sell
await client.placeOrder({
  symbol: "BTC-USD",
  side: "sell",
  market: { baseSize: "0.001" },
});

// Place conditional (stop) order — activates at the trigger price, then sells at market
await client.placeOrder({
  symbol: "BTC-USD",
  side: "sell",
  conditional: {
    triggerPrice: "100000",
    baseSize: "0.001",             // baseSize or quoteSize required
    // limitPrice: "100500",       // optional: limit order on trigger instead of market
  },
});

// Place take-profit / stop-loss order (trigger directions are derived from side)
await client.placeOrder({
  symbol: "BTC-USD",
  side: "sell",
  tpsl: {
    baseSize: "0.001",            // base size only
    takeProfit: { triggerPrice: "110000" },   // optional, at least one leg required
    stopLoss: { triggerPrice: "90000" },      // optional
    // legs accept optional limitPrice for a limit order on trigger
  },
});

// Active orders (with filters)
const active = await client.getActiveOrders({
  symbols: ["BTC-USD"],
  side: "buy",                                          // "buy" | "sell"
  orderStates: ["new", "partially_filled"],             // "pending_new" | "new" | "partially_filled"
  orderTypes: ["limit", "conditional", "tpsl"],         // "limit" | "conditional" | "tpsl"
  limit: 50,
  cursor: "...",                                        // pagination cursor
});

// Historical orders
const history = await client.getHistoricalOrders({
  symbols: ["BTC-USD"],
  orderStates: ["filled", "cancelled", "partially_filled"], // "filled" | "cancelled" | "rejected" | "replaced" | "partially_filled"
  orderTypes: ["market", "limit"],                      // "market" | "limit"
  startDate: 1700000000000,
  endDate: 1700086400000,
  limit: 100,
  cursor: "...",                                        // pagination cursor
});

// Get specific order
const order = await client.getOrder("venue-order-id");

// Replace an open order — only the fields you pass change, the rest stay as-is
await client.replaceOrder("venue-order-id", {
  clientOrderId: "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  price: "96000",
});

// Replace a conditional order's trigger (the whole trigger is replaced;
// omitting limitPrice switches to market execution on trigger)
await client.replaceOrder("venue-order-id", {
  clientOrderId: "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  conditional: { triggerPrice: "100000", limitPrice: "99500" },
});

// Replace TP/SL triggers on a take-profit/stop-loss order —
// explicit null removes a leg, omitted fields stay unchanged
await client.replaceOrder("venue-order-id", {
  clientOrderId: "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  baseSize: "0.002",
  takeProfit: { triggerPrice: "115000", limitPrice: "114900" },
  stopLoss: null,
});

// Cancel single order
await client.cancelOrder("venue-order-id");

// Cancel all active orders
await client.cancelAllOrders();

Trades

// Order fills
const fills = await client.getOrderFills("venue-order-id");

// All trades for a pair
const trades = await client.getAllTrades("BTC-USD", {
  startDate: 1700000000000,
  endDate: 1700086400000,
});

// My private trades
const myTrades = await client.getPrivateTrades("BTC-USD");

// My trading volume (quote-currency volume contributed)
const volume = await client.getTradingVolume({ intervalDays: 30 }); // intervalDays optional, 1-180, default 30
// → { data: TradingVolumeEntry[], metadata: { timestamp } }
// TradingVolumeEntry — { type: "spot" | "futures", amount, currency, start_date, end_date }
// "futures" is omitted when there is no active derivatives account

Transactions

const transactions = await client.getTransactions({
  startDate: 1700000000000,
  endDate: 1700086400000,
  types: ["buy", "sell", "receive", "send", "stake", "un_stake", "reward"],
  currencies: ["BTC", "USD"],
});
// → { data: Transaction[], metadata: { timestamp, next_cursor? } }
// A transaction may have source fields, destination fields, or both:
// buys and sells have both legs, sends and stakes only a source,
// receives, rewards, and un_stakes only a destination.
// Each leg includes account: { type } — revolut, revolut_x,
// external_fiat, or external_crypto.

// Single transaction by ID (includes fees, account details, description)
const transaction = await client.getTransaction("a1b2c3d4-e5f6-7890-abcd-ef0123456789");
// → TransactionDetails
// Detail legs may include fee, fee_currency, and account
// (type, optional display_name, optional crypto_address).
// Receives and sends show both legs in details (only one in the list);
// stakes show only a source and un_stakes and rewards only a destination.
// Fees appear on at most one leg — the leg paid in the fee's currency
// (the source leg for same-currency sends/receives). Stake, un_stake, reward,
// and external top-ups never show fees.
// May also include order_id, crypto_transaction_hash, network, and description.

Authentication

Revolut X uses Ed25519 request signing. Each request includes three headers:

  • X-Revx-API-Key — your API key
  • X-Revx-Timestamp — epoch milliseconds
  • X-Revx-Signature — Ed25519 signature of {timestamp}{METHOD}{path}{query}{body}

Generating a Keypair

import { generateKeypair } from "@revolut/revolut-x-api";

const publicKeyPem = generateKeypair(
  "/path/to/private.pem",
  "/path/to/public.pem",
);
console.log("Register this public key with Revolut X:");
console.log(publicKeyPem);

Auth Utilities

import {
  signRequest,
  buildAuthHeaders,
  loadPrivateKey,
  getPublicKeyPem,
  createTimestamp,
} from "@revolut/revolut-x-api";

const key = loadPrivateKey("/path/to/private.pem");
const headers = buildAuthHeaders("api-key", key, "GET", "/api/1.0/balances");

// Derive public key PEM from an existing private key object
const publicKeyPem = getPublicKeyPem(key);

// Get a current epoch-milliseconds timestamp string
const ts = createTimestamp();

Logging

Pass a logger callback to receive structured log entries from the client (requests, retries, errors, etc.):

import { LogCallback, LogLevel } from "@revolut/revolut-x-api";

const client = new RevolutXClient({
  apiKey: "your-api-key",
  privateKeyPath: "~/.config/revolut-x/private.pem",
  logger: (entry) => {
    console.log(`[${entry.level}] ${entry.message}`, entry.data ?? "");
  },
});

Each LogEntry has:

| Field | Type | Description | |-------|------|-------------| | level | LogLevel | "debug" | "info" | "warn" | "error" | | message | string | Human-readable description | | data | unknown | Optional structured payload |


Error Handling

All errors extend RevolutXError:

| Error | HTTP Status | When | |-------|-------------|------| | AuthNotConfiguredError | — | No API key or private key configured | | InvalidCredentialsError | — | The saved credentials can't be used, for example a damaged config file or a missing or damaged key. issue says which file, what is wrong (missing, unreadable, not_a_file or malformed) and where. A subclass of AuthNotConfiguredError | | ConfigurationError | — | A client setting is wrong, such as the base URL | | AuthenticationError | 401 | Invalid API key or signature | | ForbiddenError | 403 | Access denied | | RateLimitError | 429 | Rate limit exceeded — check retryAfter (ms) | | ValidationError | 400 | Request failed schema validation | | BadRequestError | 400 | The exchange refused the request, for example invalid order parameters or a client order id that was already used | | NotFoundError | 404 | Resource not found | | ConflictError | 409 | Conflicting request (e.g. timestamp skew) | | ServerError | 5xx | Server-side error — check statusCode. A POST, PUT or DELETE that got a 5xx and then an error answer on the automatic retry also throws it, with that answer as cause, since the first attempt may have taken effect. A duplicate client order id on that retry stays a BadRequestError, with the ServerError as cause. A retry that gets no answer throws NetworkError | | NetworkError | — | Connection, timeout, unreadable reply, or an order reply without the order's details. mayHaveReachedServer is false only when the request surely never left, so an order may exist when it is true |

import { RateLimitError, BadRequestError } from "@revolut/revolut-x-api";

try {
  await client.placeOrder({ ... });
} catch (err) {
  if (err instanceof RateLimitError) {
    const waitMs = err.retryAfter ?? 1000;
    console.log(`Rate limited. Retry after ${waitMs}ms`);
  } else if (err instanceof BadRequestError) {
    console.error("Order rejected:", err.message);
  }
}

Rate Limiting

The client does not throttle requests proactively. When the server responds with 429, a RateLimitError is thrown immediately. Check the retryAfter property for the server-indicated wait time in milliseconds before retrying.


Symbol Format

Use dashes in requests: BTC-USD, ETH-USD.

The API returns symbols with slashes in responses: BTC/USD.


Support

License

MIT