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 🙏

© 2024 – Pkg Stats / Ryan Hefner

ftx-api

v1.1.14

Published

Node.js/typescript connector for FTX's REST APIs and WebSockets

Downloads

395

Readme

ftx-api

Tests npm version npm size npm downloads last commit CodeFactor

Node.js connector for the FTX APIs and WebSockets, with TypeScript & browser support.

Installation

npm install --save ftx-api

Issues & Discussion

Related projects

Check out my related projects:

Documentation

Most methods accept JS objects, except for methods with only one parameter. These can be populated using parameters specified by FTX's API documentation.

Structure

This project uses typescript. Resources are stored in 3 key structures:

  • src - the whole connector written in typescript
  • lib - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release.
  • dist - the packed bundle of the project for use in browser environments.
  • examples - demonstrations on various workflows using this library

Usage

Create API credentials at FTX

REST API Clients

Import and instance the RestClient to access all REST API methods.

  • All methods return promises.
  • Supports subaccounts.

Example

const { RestClient } = require('ftx-api');

const restClientOptions = {
  // override the max size of the request window (in ms)
  recv_window?: number;

  // how often to sync time drift with FTX servers
  sync_interval_ms?: number | string;

  // Default: false. Disable above sync mechanism if true.
  disable_time_sync?: boolean;

  // Default: false. If true, we'll throw errors if any params are undefined
  strict_param_validation?: boolean;

  // Optionally override API protocol + domain
  // e.g 'https://ftx.us/api'
  baseUrl?: string;

  // Default: true. whether to try and post-process request exceptions.
  parse_exceptions?: boolean;

  // Subaccount nickname URI-encoded
  subAccountName?: string;
};

const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';

const client = new RestClient(
  API_KEY,
  PRIVATE_KEY,

  // restClientOptions,
  // requestLibraryOptions
);

client.getMarkets()
  .then(result => {
    console.log("getMarkets result: ", result);
  })
  .catch(err => {
    console.error("getMarkets error: ", err);
  });

client.setAccountLeverage(5)
  .then(result => {
    console.log("setAccountLeverage result: ", result);
  })
  .catch(err => {
    console.error("setAccountLeverage error: ", err);
  });

See rest-client.ts for further information.

WebSockets

  • Automatically connect to FTX websockets
  • Automatically authenticate, if key & secret are provided.
  • Automatically checks connection integrity. If connection stale (no response to pings), automatically reconnects, re-authenticates and resubscribes to previous topics.
  • Supports subaccounts.
const { WebsocketClient } = require('ftx-api');

const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';

const wsConfig = {
  key: API_KEY,
  secret: PRIVATE_KEY,

  /*
    The following parameters are optional:
  */

  // Subaccount nickname
  // subAccountName: 'sub1',

  // how long to wait (in ms) before deciding the connection should be terminated & reconnected
  // pongTimeout: 1000,

  // how often to check (in ms) that WS connection is still alive
  // pingInterval: 10000,

  // how long to wait before attempting to reconnect (in ms) after connection is closed
  // reconnectTimeout: 500,

  // config options sent to RestClient (used for time sync). See RestClient docs.
  // restOptions: { },

  // config for axios used for HTTP requests. E.g for proxy support
  // requestOptions: { }

  // override which URL to use for websocket connections
  // wsUrl: 'wss://example.ftx.com/ws'
};

const ws = new WebsocketClient(wsConfig);

// subscribe to multiple topics at once
ws.subscribe(['fills', 'orders']);

// and/or subscribe to individual topics on demand
ws.subscribe('fills');

// and/or subscribe to complex topics on demand, one at a time
ws.subscribe({
  channel: 'trades',
  market: 'BTC-PERP'
});

// or as a list of complex topics
ws.subscribe([
  {
    channel: 'trades',
    market: 'BTC-PERP'
  },
  {
    channel: 'orderbookGrouped',
    market: 'BTC-PERP',
    grouping: 500
  }
]);

// Listen to events coming from websockets. This is the primary data source
ws.on('update', data => {
  console.log('update', data);
});

// Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics)
ws.on('open', ({ event }) => {
  console.log('connection opened');
});

// Optional: Listen to responses to websocket queries (e.g. the response after subscribing to a topic)
ws.on('response', response => {
  console.log('response', response);
});

// Optional: Listen to connection close event. Unexpected connection closes are automatically reconnected.
ws.on('close', () => {
  console.log('connection closed');
});

// Optional: Listen to raw error events.
// Note: responses to invalid topics are currently only sent in the "response" event.
ws.on('error', err => {
  console.error('ERR', err);
});

See websocket-client.ts for further information.

Examples

More demonstrations can be found in the examples folder.


Customise Logging

Pass a custom logger which supports the log methods silly, debug, notice, info, warning and error, or override methods from the default logger as desired.

const { WebsocketClient, DefaultLogger } = require('ftx-api');

// Disable all logging on the silly level
DefaultLogger.silly = () => {};

const ws = new WebsocketClient(
  { key: 'xxx', secret: 'yyy' },
  DefaultLogger
);

Browser Usage

Build a bundle using webpack:

  • npm install
  • npm build
  • npm pack

The bundle can be found in dist/. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO.


FTX.US

This client also supports the US FTX exchange. Simply set the "domain" to "ftxus" in both the RestClient and the WebsocketClient. See examples/ftxus.ts for a demonstration.

Contributions & Thanks

Donations

tiagosiebler

If you found this project interesting or useful, create accounts with my referral links:

Or buy me a coffee using any of these:

  • BTC: 1C6GWZL1XW3jrjpPTS863XtZiXL1aTK7Jk
  • ETH (ERC20): 0xd773d8e6a50758e1ada699bb6c4f98bb4abf82da

Contributions & Pull Requests

Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.