# Quickstart

Node.js `tardis-dev` library provides convenient access to tick-level historical and real-time cryptocurrency market data both in [exchange-native and normalized formats](https://docs.tardis.dev/faq/data#what-is-a-difference-between-exchange-native-and-normalized-data-format). Instead of callbacks it relies on [async iteration (for await ...of)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) enabling composability features like [seamless switching between real-time data streaming and historical data replay](https://docs.tardis.dev/normalization#seamless-switching-between-real-time-streaming-and-historical-market-data-replay) or [computing derived data locally](https://docs.tardis.dev/normalization#computing-derived-data-locally).

## Features

* [historical](https://docs.tardis.dev/historical-data-details/overview) tick-level [market data replay](https://docs.tardis.dev/node-client/replaying-historical-data) backed by Tardis.dev [HTTP API](https://docs.tardis.dev/api/http-api-reference#data-feeds-exchange) — includes full order book depth snapshots plus incremental updates, trades, historical open interest, funding, index, mark prices, liquidations and more
* consolidated [real-time data streaming API](https://docs.tardis.dev/node-client/streaming-real-time-data) connecting directly to exchanges' public WebSocket APIs
* support for both [exchange-native](https://docs.tardis.dev/faq/data#what-is-a-difference-between-exchange-native-and-normalized-data-format) and [normalized market data](https://docs.tardis.dev/node-client/normalization) formats (unified format for accessing market data across all supported exchanges — normalized trades, order book and ticker data)
* [seamless switching between real-time streaming and historical market data replay](https://docs.tardis.dev/normalization#seamless-switching-between-real-time-streaming-and-historical-market-data-replay) thanks to [`async iterables`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) providing unified way of consuming data messages
* transparent historical local data caching (cached data is stored on disk in compressed format and decompressed on demand when reading the data)
* support for top cryptocurrency exchanges: [BitMEX](https://docs.tardis.dev/historical-data-details/bitmex), [Deribit](https://docs.tardis.dev/historical-data-details/deribit), [Binance Spot](https://docs.tardis.dev/historical-data-details/binance), [Binance USDS-M Futures](https://docs.tardis.dev/historical-data-details/binance-futures), [OKX Spot](https://docs.tardis.dev/historical-data-details/okex), [HTX Spot](https://docs.tardis.dev/historical-data-details/huobi), [bitFlyer](https://docs.tardis.dev/historical-data-details/bitflyer), [Bitstamp](https://docs.tardis.dev/historical-data-details/bitstamp), [Coinbase Exchange](https://docs.tardis.dev/historical-data-details/coinbase), [Kraken Futures (Crypto Facilities)](https://docs.tardis.dev/historical-data-details/cryptofacilities), [Gemini](https://docs.tardis.dev/historical-data-details/gemini), [Kraken](https://docs.tardis.dev/historical-data-details/kraken), [Bitfinex](https://docs.tardis.dev/historical-data-details/bitfinex), [Bybit Derivatives](https://docs.tardis.dev/historical-data-details/bybit) and more
* automatic closed connections and stale connections reconnection logic for real-time streams
* [combining multiple exchanges feeds into single one](https://docs.tardis.dev/normalization#combining-data-streams) via [`combine`](https://docs.tardis.dev/normalization#combining-data-streams) helper function — synchronized historical market data replay and consolidated real-time data streaming from multiple exchanges
* [computing derived data locally](https://docs.tardis.dev/normalization#computing-derived-data-locally) like order book imbalance, customizable trade bars, book snapshots and more via [`compute`](https://docs.tardis.dev/normalization#computing-derived-data-locally) helper function and `computables`, e.g., volume based bars, top 20 levels order book snapshots taken every 10 ms etc
* [full limit order book reconstruction](https://docs.tardis.dev/normalization#limit-order-book-reconstruction) both for real-time and historical data via `OrderBook` object
* fast and lightweight architecture — low memory footprint and no heavy in-memory buffering
* [extensible mapping logic](https://docs.tardis.dev/normalization#modifying-built-in-and-adding-custom-normalizers) that allows adjusting normalized formats for specific needs
* built-in TypeScript support
* [Open Source](https://github.com/tardis-dev/tardis-node)

{% embed url="<https://github.com/tardis-dev/tardis-node?1>" %}
Tardis-dev GitHub repository
{% endembed %}

## Installation

Requires Node.js v24+ installed.

```bash
npm install tardis-dev --save
```

{% hint style="info" %}
Node.js examples on this page use ES modules and top-level await. Save snippets as `.mjs` or set `"type": "module"` in your `package.json`.
{% endhint %}

## Historical Replay

{% tabs %}
{% tab title="Exchange-native" %}

```javascript
import { replay } from 'tardis-dev'

const messages = replay({
  exchange: 'binance',
  filters: [
    { channel: 'trade', symbols: ['btcusdt'] },
    { channel: 'depth', symbols: ['btcusdt'] }
  ],
  from: '2024-03-01',
  to: '2024-03-02'
})

for await (const { localTimestamp, message } of messages) {
  console.log(localTimestamp, message)
}
```

{% endtab %}

{% tab title="Normalized" %}

```javascript
import { replayNormalized, normalizeTrades, normalizeBookChanges } from 'tardis-dev'

const messages = replayNormalized(
  {
    exchange: 'binance',
    symbols: ['btcusdt'],
    from: '2024-03-01',
    to: '2024-03-02'
  },
  normalizeTrades,
  normalizeBookChanges
)

for await (const message of messages) {
  console.log(message)
}
```

{% endtab %}
{% endtabs %}

{% content-ref url="replaying-historical-data" %}
[replaying-historical-data](https://docs.tardis.dev/node-client/replaying-historical-data)
{% endcontent-ref %}

## Real-Time Streaming

{% tabs %}
{% tab title="Exchange-native" %}

```javascript
import { stream } from 'tardis-dev'

const messages = stream({
  exchange: 'binance',
  filters: [
    { channel: 'trade', symbols: ['btcusdt'] },
    { channel: 'depth', symbols: ['btcusdt'] }
  ]
})

for await (const { localTimestamp, message } of messages) {
  console.log(localTimestamp, message)
}
```

{% endtab %}

{% tab title="Normalized" %}

```javascript
import { streamNormalized, normalizeTrades, normalizeBookChanges } from 'tardis-dev'

const messages = streamNormalized(
  {
    exchange: 'binance',
    symbols: ['btcusdt']
  },
  normalizeTrades,
  normalizeBookChanges
)

for await (const message of messages) {
  console.log(message)
}
```

{% endtab %}
{% endtabs %}

{% content-ref url="streaming-real-time-data" %}
[streaming-real-time-data](https://docs.tardis.dev/node-client/streaming-real-time-data)
{% endcontent-ref %}

## Debugging and logging

`tardis-dev` lib uses [debug](https://github.com/visionmedia/debug) package for verbose logging and debugging purposes that can be enabled via `DEBUG` environment variable set to `tardis-dev*`.

## ES Modules and TypeScript

Examples in this page use standard ES module imports and top-level await:

```typescript
import { replay, stream } from 'tardis-dev'

const messages = replay({ exchange: 'binance', from: '2024-03-01', to: '2024-03-02' })

for await (const { localTimestamp, message } of messages) {
  console.log(localTimestamp, message)
}
```

This works in modern Node.js and gives you first class TypeScript typings.

## Historical market data helpers

### `init(options)`

{% hint style="info" %}
This function doesn't affect real-time streaming functionality in any way, it's useful only for historical data replay.
{% endhint %}

When working with market data via [`replay`](https://docs.tardis.dev/replaying-historical-data#replay-options) and [`replayNormalized`](https://docs.tardis.dev/replaying-historical-data#replaynormalized-options-...normalizers), by default only the first day of each month of historical data is available for replay, and locally cached historical data is stored in the default location on disk (OS temp dir).

`Init` function allows providing an `apiKey` received via email after ordering historical market data access via [Tardis.dev website](https://tardis.dev), a custom `cacheDir`, and the preferred compression for historical replay requests. `apiKey` can also be provided directly via options of [`replay`](https://docs.tardis.dev/replaying-historical-data#replay-options) and [`replayNormalized`](https://docs.tardis.dev/replaying-historical-data#replaynormalized-options-...normalizers) functions - that overrides anything that was provided via `init`.

```javascript
import { init } from 'tardis-dev'

init({
  apiKey: 'YOUR API KEY',
  cacheDir: 'CUSTOM CACHE DIR PATH',
  dataFeedCompression: 'gzip'
})
```

#### init options

| name                    | type                          | default                    | description                                                                                                                                                                           |
| ----------------------- | ----------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **apiKey**              | string (optional)             | undefined                  | API key for Tardis.dev[ HTTP API](https://docs.tardis.dev/api/http-api-reference#data-feeds-exchange) - if not provided only first day of each month of historical data is accessible |
| **cacheDir**            | string                        | \<os.tmpdir>/.tardis-cache | path to local dir that will be used as cache location - if not provided default `temp` dir for given OS will be used                                                                  |
| **dataFeedCompression** | `'zstd' \| 'gzip'` (optional) | `'zstd'`                   | preferred compression for historical replay requests; set to `'gzip'` when you need the client to request gzip-compressed slices                                                      |

### `getExchangeDetails(exchange)`

Given exchange id provides exchange details (available symbols, availability dates, available channels, pricing info etc) provided by [exchanges/:exchange](https://docs.tardis.dev/api/http-api-reference#exchanges-exchange) API endpoint.

```javascript
import { getExchangeDetails } from 'tardis-dev'

const binanceExchangeDetails = await getExchangeDetails('binance')
console.log(binanceExchangeDetails.id)
```

#### type of response returned by awaiting on `getExchangeDetails`

```typescript
{
  id: string
  name: string
  enabled: boolean
  delisted?: boolean
  availableSince: string
  availableTo?: string

  availableChannels: string[]

  availableSymbols: {
    id: string
    type: 'spot' | 'future' | 'perpetual' | 'option' | 'combo'
    availableSince: string
    availableTo?: string
    name?: string
  }[]

  incidentReports: {
    from: string
    to: string
    status: 'resolved' | 'wontfix' | 'unresolved'
    details: string
  }[]

  channelDetails: {
    name: string
    description: string
    frequency: string
    frequencySource: string
    exchangeDocsUrl?: string
    sourceFor?: string[]
    availableSince: string
    availableTo?: string
    apiVersion?: string
    additionalInfo?: string
    generated?: true
  }[]

  apiDocsUrl?: string

  dataCollectionDetails?: {
    recorderDataCenter: {
      host: string
      regionId: string
      location: string
    }
    recorderDataCenterChanges?: {
      until: string
      dataCenter: { host: string; regionId: string; location: string }
    }[]
    wssConnection?: {
      url: string
      apiVersion?: string
      proxiedViaCloudflare?: boolean
    }
    wssConnectionChanges?: {
      until: string
      url?: string
      apiVersion?: string
      proxiedViaCloudflare?: boolean
    }[]
    exchangeDataCenter?: {
      host: string
      regionId: string
      location: string
    }
    exchangeDataCenterChanges?: {
      until: string
      dataCenter: { host: string; regionId: string; location: string }
    }[]
  }

  datasets: {
    formats: ['csv']
    exportedFrom: string
    exportedUntil: string
    stats: {
      trades: number
      bookChanges: number
    }
    symbols: {
      id: string
      type: 'spot' | 'future' | 'perpetual' | 'option' | 'combo'
      availableSince: string
      availableTo?: string
      dataTypes: DatasetType[]
    }[]
  }
}

// where DatasetType is one of:
type DatasetType =
  | 'trades'
  | 'incremental_book_L2'
  | 'quotes'
  | 'derivative_ticker'
  | 'options_chain'
  | 'book_snapshot_25'
  | 'book_snapshot_5'
  | 'liquidations'
  | 'book_ticker'
```

### `getApiKeyAccessInfo(apiKey?)`

Given `apiKey` provided as optional parameter or provided in [`init`](#init-options) function provides information about what historical data access is available for it: exchanges, access type, data plan, date ranges, and symbol restrictions.

```javascript
import { getApiKeyAccessInfo } from 'tardis-dev'

const details = await getApiKeyAccessInfo('YOUR_API_KEY')
console.log(details)
```

#### type of response returned by awaiting on `getApiKeyAccessInfo()`

```typescript
{
  exchange: string
  accessType: string
  from: string
  to: string
  symbols: string[]
  dataPlan: string
}[]
```

### `clearCache()`

Clears local data cache dir.

```javascript
import { clearCache } from 'tardis-dev'

await clearCache()
```

### `downloadDatasets(options)`

Downloads CSV datasets for specified exchange, data types, symbols and date range. Handles day-by-day downloads, retries and skipping already-downloaded files automatically.

```javascript
import { downloadDatasets } from 'tardis-dev'

await downloadDatasets({
  exchange: 'binance',
  dataTypes: ['trades', 'incremental_book_L2'],
  from: '2024-03-01',
  to: '2024-03-02',
  symbols: ['BTCUSDT'],
  apiKey: 'YOUR_API_KEY'
})
```

{% content-ref url="../../downloadable-csv-files/api#download-via-client-libraries" %}
[#download-via-client-libraries](https://docs.tardis.dev/downloadable-csv-files/api#download-via-client-libraries)
{% endcontent-ref %}

### `getInstrumentInfo(exchange, symbol)`

Returns instrument metadata (tick sizes, contract multipliers, base/quote currencies) for a given exchange and symbol.

```javascript
import { getInstrumentInfo, init } from 'tardis-dev'

init({ apiKey: 'YOUR_API_KEY' }) // set API key globally for instrument info requests

const info = await getInstrumentInfo('binance', 'btcusdt')
console.log(info)
```
