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

@twelvedata/twelvedata-node

v1.2.7

Published

Twelve Data API client for Node.js

Downloads

934

Readme

Twelve Data API client for Node.js

npm npm downloads license issues

Twelve Data official library. This package supports all main features of the service:

  • Real-time and historical market data: time series, quotes, end-of-day prices, exchange rates, and market movers.
  • Fundamentals: financial statements, earnings, dividends, splits, company profiles, and key statistics.
  • 100+ technical indicators: SMA, EMA, RSI, MACD, Bollinger Bands, Ichimoku, and many more.
  • Analysis & estimates: analyst ratings, price targets, EPS trends, revenue and growth estimates.
  • ETFs and mutual funds: summaries, composition, performance, risk, and ratings.

🔑 API key is required. If you don't have it yet, get it by signing up here.

Requirements

Ensure you have Node.js v18.0.0 or later. We recommend the latest LTS version. Use nvm (macOS/Linux) or nvm-windows for Node version management across projects.

Installation

npm install @twelvedata/twelvedata-node
# or
yarn add @twelvedata/twelvedata-node

🔗 View the package on npm.

Quick start

1. Set up a new project

mkdir my-node-app && cd my-node-app
npm init -y && npm pkg set type=module
npm i @twelvedata/twelvedata-node

2. Create time-series.ts script

import { MarketDataApi, CreateConfig, TwelvedataApiError } from "@twelvedata/twelvedata-node";

const config = CreateConfig("YOUR_API_KEY_HERE"); // defaults to process.env.TWELVEDATA_API_KEY
const api = new MarketDataApi(config);

async function main() {
    try {
        const response = await api.getTimeSeries({
            interval: "1day",
            symbol: "AAPL",
            outputsize: 5,
        });
        console.log(response);
    } catch (error) {
        if (error instanceof TwelvedataApiError) {
            console.error("API error:", error);
        } else {
            console.error("Unexpected error:", error);
        }
    }
}

main().catch(console.error);

3. Run the script

Node.js >= 22:

npx ts-node time-series.ts

Node.js < 22:

npx tsx time-series.ts

👀 Check the full example and other examples here.

WebSocket

The library ships with a WebSocket client for streaming real-time prices from Twelve Data. It handles authorization, sends both application-level heartbeats and protocol-level pings, detects dead connections, and automatically reconnects with exponential backoff — re-subscribing to your active symbols on the way back up.

WebSocket streaming is available on the Pro (individual) and Venture (business) plans and above. Basic and Grow plans are limited to one connection and up to 8 simultaneous subscriptions from the trial symbol list. See the WebSocket FAQ for more details.

Usage

import {
    TwelvedataWebSocketClient,
    TwelvedataWebSocketError,
    WebSocketAuthError,
} from "@twelvedata/twelvedata-node";

const client = new TwelvedataWebSocketClient({ apiKey: "YOUR_API_KEY_HERE" }); // defaults to process.env.TWELVEDATA_API_KEY

client.on("price", (event) => {
    console.log(`${event.symbol} @ ${event.price} (${event.timestamp})`);
});

client.on("subscribe-status", (event) => {
    console.log("Subscribed:", event.success.map((s) => s.symbol));
    if (event.fails.length) {
        console.warn("Failed:", event.fails);
    }
});

client.on("reconnecting", ({ attempt, delayMs }) => {
    console.log(`Reconnecting (attempt ${attempt}) in ${delayMs}ms…`);
});

client.on("error", (error) => {
    if (error instanceof TwelvedataWebSocketError) {
        console.error("WebSocket error:", error.name, error.message);
    } else {
        console.error("Unexpected error:", error);
    }
});

async function main() {
    try {
        await client.connect();
    } catch (error) {
        if (error instanceof WebSocketAuthError) {
            // Invalid / missing API key — not retried.
            process.exit(1);
        }
        throw error;
    }

    client.subscribe("AAPL,EUR/USD,BTC/USD");

    // Later, if you want to stop:
    // client.unsubscribe("BTC/USD");
    // client.disconnect();
}

main().catch(console.error);

For the full list of WebSocket error types and recommended handling, see WebSocket errors.

WebSocket client configuration

All timing and retry knobs are exported as constants and can be overridden via constructor options:

import {
    TwelvedataWebSocketClient,
    DEFAULT_HEARTBEAT_INTERVAL_MS,
} from "@twelvedata/twelvedata-node";

const client = new TwelvedataWebSocketClient({
    apiKey: process.env.TWELVEDATA_API_KEY, // optional; falls back to env var
    heartbeatIntervalMs: DEFAULT_HEARTBEAT_INTERVAL_MS, // 10_000 by default
    pingIntervalMs: 30_000,
    pingTimeoutMs: 10_000,
    reconnect: {
        initialDelayMs: 1_000,
        maxDelayMs: 30_000,
        maxAttempts: 10,
        backoffFactor: 2,
    },
    // Pass `reconnect: false` to disable automatic reconnection entirely.
});

👀 Check the full example and other examples here.

Error Handling

See error_handling.md for error types, properties, and usage examples.

For the complete list of API error codes and their meanings, see the Twelve Data Errors documentation.

API Reference

See api_reference.md for the complete list of API endpoints and models.

Documentation

Delve deeper with our official documentation.

Examples

Explore practical scenarios in the examples directory.

Support

Stay updated

Contributing

  1. Fork and clone: $ git clone https://github.com/twelvedata/twelvedata-node ..
  2. Branch out: $ git checkout -b my-feature.
  3. Commit changes and test.
  4. Push your branch and open a pull request with a comprehensive description.

For more guidance on contributing, see the GitHub Docs on GitHub.

License

This project is licensed under the MIT. See the LICENSE file in this repository for more details.

Migrating from 1.0.x to 1.1.0

Version 1.1.0 replaces axios with the native fetch API. This removes the axios dependency but introduces a breaking change in response handling:

Before (1.0.x with axios):

const response = await api.getTimeSeries({ symbol: "AAPL", interval: "1day" });
console.log(response.data); // axios wrapped the body in response.data

After (1.1.0 with fetch):

const response = await api.getTimeSeries({ symbol: "AAPL", interval: "1day" });
console.log(response); // response is the parsed body directly

In short: replace response.data with response everywhere you call the API.