Examples

This section provides practical examples of how to use the FMP Node Wrapper for common use cases.

Basic Setup

First, set up your client:

1import { FMP } from 'fmp-node-api';
2
3// Option 1: Use environment variable (recommended)
4const fmp = new FMP(); // Automatically uses FMP_API_KEY from environment
5
6// Option 2: Provide API key directly
7const fmp = new FMP({
8apiKey: 'your-api-key-here',
9timeout: 15000,
10});
11
12// Option 3: Mixed configuration
13const fmp = new FMP({
14timeout: 15000, // custom timeout, apiKey from FMP_API_KEY env var
15});

Example 1: Stock Price Monitor

Create a simple stock price monitoring script:

1async function monitorStockPrice(symbol: string) {
2  try {
3    const quote = await fmp.stock.getQuote({ symbol });
4
5    if (quote.success && quote.data?.[0]) {
6      const stock = quote.data[0];
7      console.log(`\n${stock.name} (${stock.symbol})`);
8      console.log(`Price: $${stock.price}`);
9      console.log(`Change: ${stock.change > 0 ? '+' : ''}${stock.change} (${stock.changePercent}%)`);
10      console.log(`Market Cap: $${(stock.marketCap / 1e9).toFixed(2)}B`);
11      console.log(`Volume: ${stock.volume.toLocaleString()}`);
12    } else {
13      console.error('Failed to get quote:', quote.error);
14    }
15
16  } catch (error) {
17    console.error('Error monitoring stock:', error);
18  }
19
20}
21
22// Monitor multiple stocks
23const symbols = ['AAPL', 'MSFT', 'GOOGL', 'TSLA'];
24for (const symbol of symbols) {
25await monitorStockPrice(symbol);
26}

Example 2: Financial Analysis Dashboard

Build a comprehensive financial analysis dashboard:

1async function analyzeCompany(symbol: string) {
2  console.log(`\n=== Financial Analysis: ${symbol} ===\n`);
3
4// Get company profile
5const profile = await fmp.stock.getCompanyProfile({ symbol });
6if (profile.success && profile.data?.[0]) {
7const company = profile.data[0];
8console.log('Company: ' + company.companyName);
9console.log('Industry: ' + company.industry);
10console.log('Sector: ' + company.sector);
11console.log('Market Cap: $' + (company.marketCap / 1e9).toFixed(2) + 'B');
12console.log('Beta: ' + company.beta);
13}
14
15// Get financial ratios
16const ratios = await fmp.financial.getFinancialRatios({ symbol });
17if (ratios.success && ratios.data?.[0]) {
18const ratio = ratios.data[0];
19console.log('\n--- Key Ratios ---');
20console.log('P/E Ratio: ' + ratio.priceEarningsRatio);
21console.log('P/B Ratio: ' + ratio.priceToBookRatio);
22console.log('ROE: ' + (ratio.returnOnEquity _ 100).toFixed(2) + '%');
23console.log('ROA: ' + (ratio.returnOnAssets _ 100).toFixed(2) + '%');
24console.log('Debt/Equity: ' + ratio.debtEquityRatio);
25console.log('Current Ratio: ' + ratio.currentRatio);
26}
27
28// Get recent financial statements
29const incomeStatement = await fmp.financial.getIncomeStatement({
30symbol,
31period: 'annual',
32limit: 3,
33});
34
35if (incomeStatement.success && incomeStatement.data) {
36console.log('\n--- Recent Performance ---');
37incomeStatement.data.forEach((year) => {
38console.log(`${year.calendarYear}:`);
39console.log(' Revenue: $' + (year.revenue / 1e9).toFixed(2) + 'B');
40console.log(' Net Income: $' + (year.netIncome / 1e9).toFixed(2) + 'B');
41console.log(' Profit Margin: ' + (year.netIncomeRatio * 100).toFixed(2) + '%');
42});
43}
44}
45
46// Analyze multiple companies
47const companies = ['AAPL', 'MSFT', 'GOOGL'];
48for (const company of companies) {
49await analyzeCompany(company);
50}

Example 3: Historical Data Analysis

Analyze historical price data and calculate returns:

1async function analyzeHistoricalData(symbol: string, years: number = 5) {
2  const endDate = new Date();
3  const startDate = new Date();
4  startDate.setFullYear(endDate.getFullYear() - years);
5
6  const historicalData = await fmp.stock.getHistoricalPrice({
7    symbol,
8    from: startDate.toISOString().split('T')[0],
9    to: endDate.toISOString().split('T')[0],
10  });
11
12  if (historicalData.success && historicalData.data?.historical) {
13    const prices = historicalData.data.historical;
14
15    // Calculate total return
16    const firstPrice = prices[prices.length - 1].close;
17    const lastPrice = prices[0].close;
18    const totalReturn = ((lastPrice - firstPrice) / firstPrice) * 100;
19
20    // Calculate volatility (standard deviation of daily returns)
21    const dailyReturns = [];
22    for (let i = 1; i < prices.length; i++) {
23      const dailyReturn =
24        (prices[i - 1].close - prices[i].close) / prices[i].close;
25      dailyReturns.push(dailyReturn);
26    }
27
28    const avgReturn =
29      dailyReturns.reduce((sum, ret) => sum + ret, 0) / dailyReturns.length;
30    const variance =
31      dailyReturns.reduce((sum, ret) => sum + Math.pow(ret - avgReturn, 2), 0) /
32      dailyReturns.length;
33    const volatility = Math.sqrt(variance) * Math.sqrt(252) * 100; // Annualized
34
35    console.log(`\n=== Historical Analysis: ${symbol} ===`);
36    console.log(`Period: ${years} years`);
37    console.log(`Total Return: ${totalReturn.toFixed(2)}%`);
38    console.log(`Annualized Volatility: ${volatility.toFixed(2)}%`);
39    console.log(`Starting Price: $${firstPrice.toFixed(2)}`);
40    console.log(`Ending Price: $${lastPrice.toFixed(2)}`);
41
42    // Find best and worst days
43    const bestDay = prices.reduce((best, day) =>
44      day.changePercent > best.changePercent ? day : best
45    );
46    const worstDay = prices.reduce((worst, day) =>
47      day.changePercent < worst.changePercent ? day : worst
48    );
49
50     console.log(
51      `\nBest Day: ${bestDay.date} (+${bestDay.changePercent.toFixed(2)}%)`
52    );
53    console.log(
54      `Worst Day: ${worstDay.date} (${worstDay.changePercent.toFixed(2)}%)`
55    );
56
57  }
58
59}
60
61// Analyze historical data for multiple stocks
62const symbols = ['AAPL', 'MSFT', 'GOOGL'];
63for (const symbol of symbols) {
64await analyzeHistoricalData(symbol, 3);
65}

Example 4: Portfolio Tracker

Create a simple portfolio tracking system:

1interface PortfolioPosition {
2  symbol: string;
3  shares: number;
4  costBasis: number;
5}
6
7async function trackPortfolio(portfolio: PortfolioPosition[]) {
8console.log('\n=== Portfolio Tracker ===\n');
9
10let totalValue = 0;
11let totalCost = 0;
12
13for (const position of portfolio) {
14const quote = await fmp.stock.getQuote({ symbol: position.symbol });
15
16  if (quote.success && quote.data?.[0]) {
17    const stock = quote.data[0];
18    const currentValue = stock.price * position.shares;
19    const costValue = position.costBasis * position.shares;
20    const gainLoss = currentValue - costValue;
21    const gainLossPercent = (gainLoss / costValue) * 100;
22
23    console.log(`${position.symbol}:`);
24    console.log(`  Shares: ${position.shares}`);
25    console.log(`  Current Price: $${stock.price.toFixed(2)}`);
26    console.log(`  Cost Basis: $${position.costBasis.toFixed(2)}`);
27    console.log(`  Current Value: $${currentValue.toFixed(2)}`);
28    console.log(
29      `  Gain/Loss: $${gainLoss.toFixed(2)} (${gainLossPercent.toFixed(2)}%)`
30    );
31    console.log('');
32
33    totalValue += currentValue;
34    totalCost += costValue;
35  }
36
37}
38
39const portfolioGainLoss = totalValue - totalCost;
40const portfolioGainLossPercent = (portfolioGainLoss / totalCost) * 100;
41
42console.log('=== Portfolio Summary ===');
43console.log(`Total Cost: $${totalCost.toFixed(2)}`);
44console.log(`Total Value: $${totalValue.toFixed(2)}`);
45console.log(
46`Total Gain/Loss: $${portfolioGainLoss.toFixed(2)} (${portfolioGainLossPercent.toFixed(2)}%)`
47);
48}
49
50// Example portfolio
51const portfolio: PortfolioPosition[] = [
52{ symbol: 'AAPL', shares: 10, costBasis: 150.0 },
53{ symbol: 'MSFT', shares: 5, costBasis: 300.0 },
54{ symbol: 'GOOGL', shares: 3, costBasis: 2500.0 },
55];
56
57await trackPortfolio(portfolio);

Example 5: Market Scanner

Create a market scanner to find stocks meeting specific criteria:

1async function marketScanner() {
2const symbols = [
3  'AAPL',
4  'MSFT',
5  'GOOGL',
6  'TSLA',
7  'AMZN',
8  'META',
9  'NVDA',
10  'NFLX',
11];
12const results = [];
13
14console.log('Scanning market for value stocks...\n');
15
16for (const symbol of symbols) {
17try {
18const [quote, ratios] = await Promise.all([
19fmp.stock.getQuote({ symbol }),
20fmp.financial.getFinancialRatios({ symbol }),
21]);
22
23    if (
24      quote.success &&
25      ratios.success &&
26      quote.data?.[0] &&
27      ratios.data?.[0]
28    ) {
29      const stock = quote.data[0];
30      const ratio = ratios.data[0];
31
32      // Define criteria for "value" stocks
33      const isValueStock =
34        ratio.priceEarningsRatio < 20 &&
35        ratio.priceToBookRatio < 5 &&
36        ratio.returnOnEquity > 0.15 &&
37        stock.price > 10;
38
39      if (isValueStock) {
40        results.push({
41          symbol,
42          name: stock.name,
43          price: stock.price,
44          pe: ratio.priceEarningsRatio,
45          pb: ratio.priceToBookRatio,
46          roe: ratio.returnOnEquity,
47        });
48      }
49    }
50  } catch (error) {
51    console.error(`Error scanning ${symbol}:`, error);
52  }
53
54}
55
56console.log('=== Value Stocks Found ===\n');
57results.forEach(stock => {
58console.log(`${stock.name} (${stock.symbol})`);
59console.log(` Price: $${stock.price.toFixed(2)}`);
60console.log(` P/E: ${stock.pe.toFixed(2)}`);
61console.log(` P/B: ${stock.pb.toFixed(2)}`);
62console.log(` ROE: ${(stock.roe * 100).toFixed(2)}%`);
63console.log('');
64});
65}
66
67await marketScanner();

Example 6: Multi-Asset Dashboard

Create a comprehensive dashboard covering multiple asset classes:

1async function multiAssetDashboard() {
2console.log('=== Multi-Asset Market Dashboard ===\n');
3
4// Stock market data
5const [stockQuote, marketPerformance] = await Promise.all([
6fmp.stock.getQuote({ symbol: 'SPY' }),
7fmp.market.getMarketPerformance()
8]);
9
10if (stockQuote.success && marketPerformance.success) {
11console.log('šŸ“Š Stock Market:');
12console.log(` S&P 500: $${stockQuote.data[0].price} (${stockQuote.data[0].changesPercentage.toFixed(2)}%)`);
13console.log(` Top Performer: ${marketPerformance.data[0]?.name} (${marketPerformance.data[0]?.changesPercentage.toFixed(2)}%)`);
14}
15
16// Forex data
17const forexQuote = await fmp.forex.getQuote({ symbol: 'EURUSD' });
18if (forexQuote.success) {
19console.log('\nšŸ’± Forex:');
20console.log(` EUR/USD: ${forexQuote.data[0].price} (${forexQuote.data[0].changesPercentage.toFixed(2)}%)`);
21}
22
23// Crypto data
24const cryptoQuote = await fmp.crypto.getQuote({ symbol: 'BTCUSD' });
25if (cryptoQuote.success) {
26console.log('\nšŸŖ™ Cryptocurrency:');
27console.log(` Bitcoin: $${cryptoQuote.data[0].price.toLocaleString()} (${cryptoQuote.data[0].changesPercentage.toFixed(2)}%)`);
28}
29
30// ETF data
31const etfQuote = await fmp.etf.getQuote({ symbol: 'QQQ' });
32if (etfQuote.success) {
33console.log('\nšŸ“ˆ ETF:');
34console.log(` QQQ: $${etfQuote.data[0].price} (${etfQuote.data[0].changesPercentage.toFixed(2)}%)`);
35}
36
37// Market hours
38const marketHours = await fmp.market.getMarketHours();
39if (marketHours.success) {
40console.log('\nšŸ• Market Status:');
41console.log(` Stock Market: ${marketHours.data.stockMarket}`);
42console.log(` Forex: ${marketHours.data.forex}`);
43console.log(` Crypto: ${marketHours.data.crypto}`);
44}
45}
46
47await multiAssetDashboard();

Example 7: Economic Analysis

Analyze economic indicators and their market impact:

1async function economicAnalysis() {
2console.log('=== Economic Analysis ===\n');
3
4// Get treasury rates
5const rates = await fmp.economic.getTreasuryRates();
6if (rates.success) {
7const current = rates.data[0];
8console.log('šŸ“ˆ Treasury Rates:');
9console.log(` 3-Month: ${current.month3.toFixed(2)}%`);
10console.log(` 2-Year: ${current.year2.toFixed(2)}%`);
11console.log(` 10-Year: ${current.year10.toFixed(2)}%`);
12console.log(` 30-Year: ${current.year30.toFixed(2)}%`);
13
14  // Analyze yield curve
15  const yieldCurve = current.year10 - current.month3;
16  console.log(`\nYield Curve Spread (10Y - 3M): ${yieldCurve.toFixed(2)}%`);
17
18  if (yieldCurve < 0) {
19    console.log('āš ļø  Inverted Yield Curve - Recession indicator');
20  } else if (yieldCurve < 0.5) {
21    console.log('āš ļø  Flat Yield Curve - Economic uncertainty');
22  } else {
23    console.log('āœ… Normal Yield Curve - Healthy economy');
24  }
25
26}
27
28// Get economic calendar
29const calendar = await fmp.economic.getEconomicCalendar();
30if (calendar.success) {
31const highImpact = calendar.data.filter(event => event.impact === 'High');
32console.log(`\nšŸ“… High-Impact Economic Events: ${highImpact.length}`);
33highImpact.slice(0, 3).forEach(event => {
34console.log(` - ${event.event} (${event.date})`);
35});
36}
37}
38
39await economicAnalysis();

Example 8: Fund Comparison Tool

Compare different investment funds:

1async function fundComparison() {
2console.log('=== Fund Comparison ===\n');
3
4const funds = [
5{ symbol: 'SPY', name: 'SPDR S&P 500 ETF' },
6{ symbol: 'VFINX', name: 'Vanguard 500 Index Fund' },
7{ symbol: 'QQQ', name: 'Invesco QQQ Trust' }
8];
9
10const results = [];
11
12for (const fund of funds) {
13try {
14const [quote, profile] = await Promise.all([
15fmp.etf.getQuote({ symbol: fund.symbol }).catch(() =>
16fmp.mutualFund.getQuote({ symbol: fund.symbol })
17),
18fmp.etf.getProfile({ symbol: fund.symbol }).catch(() =>
19fmp.mutualFund.getProfile({ symbol: fund.symbol })
20)
21]);
22
23    if (quote.success && profile.success) {
24      results.push({
25        name: fund.name,
26        symbol: fund.symbol,
27        price: quote.data[0].price,
28        change: quote.data[0].changesPercentage,
29        volume: quote.data[0].volume,
30        marketCap: quote.data[0].marketCap
31      });
32    }
33  } catch (error) {
34    console.error(`Error getting data for ${fund.symbol}:`, error);
35  }
36
37}
38
39console.log('Fund Comparison Results:');
40results.forEach(fund => {
41console.log(`\n${fund.name} (${fund.symbol})`);
42console.log(` Price: $${fund.price.toFixed(2)} (${fund.change > 0 ? '+' : ''}${fund.change.toFixed(2)}%)`);
43console.log(` Volume: ${fund.volume.toLocaleString()}`);
44console.log(` Market Cap: $${(fund.marketCap / 1e9).toFixed(2)}B`);
45});
46}
47
48await fundComparison();

Error Handling Best Practices

Always implement proper error handling:

1async function robustApiCall<T>(
2apiCall: () => Promise<{ success: boolean; data?: T; error?: string }>,
3retries: number = 3
4): Promise<T | null> {
5for (let attempt = 1; attempt <= retries; attempt++) {
6  try {
7    const response = await apiCall();
8
9    if (response.success && response.data) {
10      return response.data;
11    } else {
12      console.warn(`Attempt ${attempt} failed:`, response.error);
13    }
14  } catch (error) {
15    console.error(`Attempt ${attempt} error:`, error);
16  }
17
18  if (attempt < retries) {
19    // Wait before retrying (exponential backoff)
20    await new Promise(resolve =>
21      setTimeout(resolve, Math.pow(2, attempt) * 1000)
22    );
23  }
24
25}
26
27return null;
28}
29
30// Usage
31const quote = await robustApiCall(() => fmp.stock.getQuote({ symbol: 'AAPL' }));
32if (quote) {
33console.log('Stock price:', quote[0].price);
34}

Performance Optimization

For better performance when making multiple API calls:

1async function batchApiCalls(symbols: string[]) {
2// Make concurrent API calls
3const promises = symbols.map(symbol => fmp.stock.getQuote({ symbol }));
4const results = await Promise.allSettled(promises);
5
6const successful = results
7.filter(
8(result): result is PromiseFulfilledResult<any> =>
9result.status === 'fulfilled' && result.value.success
10)
11.map(result => result.value.data[0]);
12
13  return successful;
14
15}
16
17// Usage
18const symbols = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'AMZN'];
19const quotes = await batchApiCalls(symbols);
20console.log(`Retrieved ${quotes.length} quotes successfully`);

Code Block Features

Copy Button

All code blocks automatically include a copy button that appears on hover. You can also disable it if needed:

1// This code block has the copy button disabled
2const example = "Copy button is hidden for this block";

Filename Display

You can also display a filename for better context:

example.ts
1// This shows a filename in the header
2export function example() {
3  return "Hello World";
4}

Need more examples? Check out the API Reference for detailed endpoint documentation.