|

|  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 Dev Kit 2

Endless customization

OMI DEV KIT 2

$69.99

Speak, Transcribe, Summarize conversations with an omi AI necklace. It gives you action items, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

  • Real-time conversation transcription and processing.
  • Action items, summaries and memories
  • Thousands of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

thought to action.

team@basedhardware.com

Company

Careers

Invest

Privacy

Events

Vision

Trust

Products

Omi

Omi Apps

Omi Dev Kit 2

omiGPT

Personas

Resources

Apps

Bounties

Affiliate

Docs

GitHub

Help Center

Feedback

Enterprise

© 2025 Based Hardware. All rights reserved.