|

|  How to Fetch Stock Market Data Using Twelve Data API in Node.js

How to Fetch Stock Market Data Using Twelve Data API in Node.js

October 31, 2024

Discover how to efficiently fetch stock market data with the Twelve Data API using Node.js. Follow this guide for a seamless integration process.

How to Fetch Stock Market Data Using Twelve Data API in Node.js

 

Introduction to Twelve Data API in Node.js

 

  • The Twelve Data API is a popular choice for fetching real-time and historical stock market data. It's easy to use and integrate with applications using Node.js. Below, we explore how to set up Node.js to work with Twelve Data for stock data retrieval, ensuring you can leverage its features efficiently.

 

Install Required Packages

 

  • To interact with the Twelve Data API in Node.js, start by installing the necessary npm packages. You'll require axios for HTTP requests. If you haven't already, initialize a Node.js project with npm init and install axios using the following command:

 

npm install axios

 

Set Up Environment Variables

 

  • Using environment variables to store your API key is a good practice. Create a .env file in the root of your project containing your Twelve Data API key as follows:

 

TWELVE_DATA_API_KEY=your_api_key_here

 

  • Add the dotenv package to manage environment variables in your application:

 

npm install dotenv

 

Service to Fetch Stock Data

 

  • Create a service file that encapsulates the logic for fetching stock data. Let's name this file stockService.js. The service will use the axios library to make HTTP GET requests to the Twelve Data API.

 

require('dotenv').config();
const axios = require('axios');

const BASE_URL = 'https://api.twelvedata.com';
const API_KEY = process.env.TWELVE_DATA_API_KEY;

async function fetchStockData(symbol) {
  try {
    const response = await axios.get(`${BASE_URL}/quote`, {
      params: {
        symbol,
        apikey: API_KEY
      }
    });
    return response.data;
  } catch (error) {
    console.error('Error fetching stock data:', error);
    throw error;
  }
}

// Example usage
fetchStockData('AAPL')
  .then(data => console.log(data))
  .catch(error => console.error(error));

module.exports = { fetchStockData };

 

Include Error Handling

 

  • Good error handling practices help ensure that your application remains robust and can gracefully handle failures such as network issues or invalid API responses. The error handling in the service above logs any issues and rethrows them for upstream handling.

 

Utilize the Stock Data in Your Application

 

  • You can now import and use the fetchStockData function in your main application file or other modules. Here’s a simple example of how it might be used to get data for another stock:

 

const { fetchStockData } = require('./stockService');

fetchStockData('GOOGL')
  .then(data => console.log('Google stock data:', data))
  .catch(error => console.error('Failed to fetch Google stock data:', error));

 

Advanced Fetching: Using Multiple Endpoints

 

  • The Twelve Data API offers many endpoints apart from just stock quotes, including time series, fundamental data, and more. You can extend your service by adding functions that fetch data from these endpoints. Modify your stockService.js to include calls to other API endpoints as needed.

 

async function fetchTimeSeries(symbol, interval) {
  try {
    const response = await axios.get(`${BASE_URL}/time_series`, {
      params: {
        symbol,
        interval,
        apikey: API_KEY
      }
    });
    return response.data;
  } catch (error) {
    console.error('Error fetching time series data:', error);
    throw error;
  }
}

// Usage Example
fetchTimeSeries('AAPL', '1day')
  .then(data => console.log('AAPL Time Series:', data))
  .catch(error => console.error(error));

 

Conclusion

 

  • Fetching stock market data using the Twelve Data API in Node.js is straightforward with the help of libraries like axios. By structuring your application effectively, keeping environment variables secret, and handling errors properly, you can create a robust system for stock data retrieval.
  • Remember to refer to the official Twelve Data API documentation for more information on endpoints and customization options to further enhance your application's capabilities.

 

Limited Beta: Claim Your Dev Kit and Start Building Today

Instant transcription

Access hundreds of community apps

Sync seamlessly on iOS & Android

Order Now

Turn Ideas Into Apps & Earn Big

Build apps for the AI wearable revolution, tap into a $100K+ bounty pool, and get noticed by top companies. Whether for fun or productivity, create unique use cases, integrate with real-time transcription, and join a thriving dev community.

Get Developer Kit Now

OMI AI PLATFORM
Remember Every Moment,
Talk to AI and Get Feedback

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi 開発キット 2

無限のカスタマイズ

OMI 開発キット 2

$69.99

Omi AIネックレスで会話を音声化、文字起こし、要約。アクションリストやパーソナライズされたフィードバックを提供し、あなたの第二の脳となって考えや感情を語り合います。iOSとAndroidでご利用いただけます。

  • リアルタイムの会話の書き起こしと処理。
  • 行動項目、要約、思い出
  • Omi ペルソナと会話を活用できる何千ものコミュニティ アプリ

もっと詳しく知る

Omi Dev Kit 2: 新しいレベルのビルド

主な仕様

OMI 開発キット

OMI 開発キット 2

マイクロフォン

はい

はい

バッテリー

4日間(250mAH)

2日間(250mAH)

オンボードメモリ(携帯電話なしで動作)

いいえ

はい

スピーカー

いいえ

はい

プログラム可能なボタン

いいえ

はい

配送予定日

-

1週間

人々が言うこと

「記憶を助ける、

コミュニケーション

ビジネス/人生のパートナーと、

アイデアを捉え、解決する

聴覚チャレンジ」

ネイサン・サッズ

「このデバイスがあればいいのに

去年の夏

記録する

「会話」

クリスY.

「ADHDを治して

私を助けてくれた

整頓された。"

デビッド・ナイ

OMIネックレス:開発キット
脳を次のレベルへ

最新ニュース
フォローして最新情報をいち早く入手しましょう

最新ニュース
フォローして最新情報をいち早く入手しましょう

thought to action.

Based Hardware Inc.
81 Lafayette St, San Francisco, CA 94103
team@basedhardware.com / help@omi.me

Company

Careers

Invest

Privacy

Events

Manifesto

Compliance

Products

Omi

Wrist Band

Omi Apps

omi Dev Kit

omiGPT

Personas

Omi Glass

Resources

Apps

Bounties

Affiliate

Docs

GitHub

Help Center

Feedback

Enterprise

Ambassadors

Resellers

© 2025 Based Hardware. All rights reserved.