JavaScript & Node.js Integration Guide

Learn how to integrate Smart Money API into JavaScript and Node.js applications. This comprehensive guide covers HTTP clients (fetch, axios), async patterns, error handling, TypeScript support, and browser-based implementations for real-time dashboards.

Node.js Setup and Dependencies

Start with Node.js 14+ for modern async/await support. Initialize your project with npm and install necessary dependencies.

BASH
# Create project mkdir smart-money-js cd smart-money-js # Initialize npm project npm init -y # Install dependencies npm install axios dotenv node-cache pino npm install --save-dev typescript ts-node @types/node # Create directory structure mkdir src mkdir tests

Fetch vs Axios Comparison

Both fetch (native to modern JavaScript) and axios (third-party library) work well with Smart Money API. Here's a comparison to help you choose:

Fetch API (Built-in)

  • No dependencies (native to modern browsers and Node.js 18+)
  • Lightweight and fast
  • Requires manual error handling for HTTP errors
  • Better for simple requests
JAVASCRIPT
// Simple fetch example const API_KEY = process.env.SMARTMONEY_PUBLIC_KEY; async function getWhales() { try { const response = await fetch( 'https://api.smartmoneyapi.com/v1/whales/top-positions', { method: 'GET', headers: { 'X-API-Key': API_KEY, 'Content-Type': 'application/json' } } ); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error('Fetch error:', error); throw error; } } // Usage getWhales().then(data => { console.log(`Fetched ${data.data.length} whale positions`); });

Axios (Third-party)

  • Automatic error handling for HTTP errors
  • Request/response interceptors
  • Built-in timeout handling
  • Better for complex applications
JAVASCRIPT
// Axios example const axios = require('axios'); const api = axios.create({ baseURL: 'https://api.smartmoneyapi.com/v1', headers: { 'X-API-Key': process.env.SMARTMONEY_PUBLIC_KEY, 'Content-Type': 'application/json' }, timeout: 30000 }); async function getWhales() { try { const response = await api.get('/whales/top-positions'); return response.data; } catch (error) { console.error('API error:', error.message); throw error; } } // Usage getWhales().then(data => { console.log(`Fetched ${data.data.length} whale positions`); });

Creating a Reusable Client

Build a reusable Smart Money API client class for consistent behavior across your application.

JAVASCRIPT
const axios = require('axios'); const crypto = require('crypto'); class SmartMoneyClient { constructor(publicKey, secretKey, options = {}) { this.publicKey = publicKey || process.env.SMARTMONEY_PUBLIC_KEY; this.secretKey = secretKey || process.env.SMARTMONEY_SECRET_KEY; this.baseURL = 'https://api.smartmoneyapi.com/v1'; this.timeout = options.timeout || 30000; this.client = axios.create({ baseURL: this.baseURL, timeout: this.timeout }); // Add request interceptor for authentication this.client.interceptors.request.use(config => { config.headers['X-API-Key'] = this.publicKey; if (this.secretKey) { const timestamp = Date.now().toString(); const signature = this._createSignature( config.method.toUpperCase(), config.url, timestamp, config.params ); config.headers['X-Timestamp'] = timestamp; config.headers['X-Signature'] = signature; } return config; }); // Add response interceptor for error handling this.client.interceptors.response.use( response => response, error => { if (error.response) { switch (error.response.status) { case 429: throw new Error('Rate limit exceeded'); case 401: throw new Error('Invalid API key'); case 403: throw new Error('Insufficient permissions'); default: throw error; } } throw error; } ); } _createSignature(method, path, timestamp, params) { let message = `${method}${path}${timestamp}`; if (params) { const queryString = Object.entries(params) .sort(([a], [b]) => a.localeCompare(b)) .map(([k, v]) => `${k}=${v}`) .join('&'); message += `?${queryString}`; } return crypto .createHmac('sha256', this.secretKey) .update(message) .digest('hex'); } async getWhales(limit = 50) { const response = await this.client.get('/whales/top-positions', { params: { limit } }); return response.data; } async getDerivatives(symbol) { const response = await this.client.get('/derivatives/funding-rates', { params: { symbol } }); return response.data; } async getOnchainFlows() { const response = await this.client.get('/onchain/exchange-flows'); return response.data; } async getSignals() { const response = await this.client.get('/signals/confirmation-scores'); return response.data; } } module.exports = SmartMoneyClient;

Async/Await Patterns

Master async/await for clean, readable asynchronous code. JavaScript's async/await makes handling API calls intuitive.

JAVASCRIPT
const SmartMoneyClient = require('./SmartMoneyClient'); const client = new SmartMoneyClient(); // Basic async/await async function monitorWhales() { try { const whales = await client.getWhales(10); console.log(`Found ${whales.data.length} whale positions`); return whales; } catch (error) { console.error('Error monitoring whales:', error); } } // Parallel requests with Promise.all async function fetchAllData() { try { const [whales, derivatives, flows] = await Promise.all([ client.getWhales(), client.getDerivatives('BTC'), client.getOnchainFlows() ]); return { whales, derivatives, flows }; } catch (error) { console.error('Error fetching data:', error); } } // Sequential requests with dependency async function analyzeMarket() { try { // First fetch whales const whales = await client.getWhales(); console.log(`Analyzed ${whales.data.length} whales`); // Then fetch derivatives for those whales const derivatives = await client.getDerivatives('BTC'); console.log(`Checked derivatives: ${derivatives.data.length} records`); return { whales, derivatives }; } catch (error) { console.error('Market analysis failed:', error); } } // Error handling with async/await async function safeFetch() { try { const data = await client.getWhales(); return data; } catch (error) { if (error.message.includes('Rate limit')) { console.log('Rate limit hit, backing off...'); await new Promise(resolve => setTimeout(resolve, 60000)); // Wait 1 minute return await client.getWhales(); // Retry } else if (error.response?.status === 404) { console.log('Resource not found'); return null; } else { throw error; } } } // Usage (async () => { await monitorWhales(); const data = await fetchAllData(); console.log('All data fetched:', data); })();

Error Handling and Retries

Implement robust error handling with automatic retries for transient failures and exponential backoff.

JAVASCRIPT
class RobustSmartMoneyClient extends SmartMoneyClient { constructor(publicKey, secretKey, options = {}) { super(publicKey, secretKey, options); this.maxRetries = options.maxRetries || 3; this.retryDelay = options.retryDelay || 1000; } async _retryRequest(fn, retries = 0) { try { return await fn(); } catch (error) { // Don't retry on client errors if (error.response?.status >= 400 && error.response?.status < 500) { throw error; } // Retry on transient errors if (retries < this.maxRetries) { const delay = this.retryDelay * Math.pow(2, retries); // Exponential backoff console.log(`Retrying after ${delay}ms (attempt ${retries + 1})`); await new Promise(resolve => setTimeout(resolve, delay)); return this._retryRequest(fn, retries + 1); } throw error; } } async getWhalesWithRetry(limit = 50) { return this._retryRequest(async () => { return this.getWhales(limit); }); } async fetchWithFallback(primaryFn, fallbackFn) { try { return await primaryFn(); } catch (error) { console.warn('Primary request failed, trying fallback:', error.message); try { return await fallbackFn(); } catch (fallbackError) { console.error('Fallback also failed:', fallbackError.message); throw fallbackError; } } } } // Usage const client = new RobustSmartMoneyClient(); // With retries const whales = await client.getWhalesWithRetry(); // With fallback const data = await client.fetchWithFallback( () => client.getWhales(), () => client.getSignals() // Use signals if whales endpoint fails );

TypeScript Integration

Use TypeScript for type-safe Smart Money API integration with IntelliSense and compile-time error checking.

TYPESCRIPT
// types.ts export interface WhalePosition { address: string; balance_usd: number; primary_asset: string; leverage: number; } export interface DerivativesData { symbol: string; funding_rate: number; open_interest_usd: number; timestamp: string; } export interface SignalResponse { symbol: string; confirmation_score: number; signal_type: 'bullish' | 'bearish' | 'neutral'; } // client.ts import axios, { AxiosInstance } from 'axios'; import * as crypto from 'crypto'; class TypedSmartMoneyClient { private client: AxiosInstance; private publicKey: string; private secretKey?: string; constructor(publicKey: string, secretKey?: string) { this.publicKey = publicKey; this.secretKey = secretKey; this.client = axios.create({ baseURL: 'https://api.smartmoneyapi.com/v1', timeout: 30000 }); this.setupInterceptors(); } private setupInterceptors(): void { this.client.interceptors.request.use(config => { config.headers['X-API-Key'] = this.publicKey; if (this.secretKey && config.url) { const timestamp = Date.now().toString(); const signature = this._createSignature( config.method?.toUpperCase() || 'GET', config.url, timestamp, config.params as Record ); config.headers['X-Timestamp'] = timestamp; config.headers['X-Signature'] = signature; } return config; }); } private _createSignature( method: string, path: string, timestamp: string, params?: Record ): string { let message = `${method}${path}${timestamp}`; if (params) { const queryString = Object.entries(params) .sort(([a], [b]) => a.localeCompare(b)) .map(([k, v]) => `${k}=${v}`) .join('&'); message += `?${queryString}`; } return crypto .createHmac('sha256', this.secretKey || '') .update(message) .digest('hex'); } async getWhales(limit: number = 50): Promise { const response = await this.client.get<{ data: WhalePosition[] }>( '/whales/top-positions', { params: { limit } } ); return response.data.data; } async getDerivatives(symbol: string): Promise { const response = await this.client.get( '/derivatives/funding-rates', { params: { symbol } } ); return response.data; } async getSignals(): Promise { const response = await this.client.get<{ data: SignalResponse[] }>( '/signals/confirmation-scores' ); return response.data.data; } } export default TypedSmartMoneyClient; // main.ts import TypedSmartMoneyClient from './client'; import { WhalePosition, SignalResponse } from './types'; const client = new TypedSmartMoneyClient( process.env.SMARTMONEY_PUBLIC_KEY!, process.env.SMARTMONEY_SECRET_KEY ); async function monitorMarket(): Promise { try { const whales: WhalePosition[] = await client.getWhales(); const signals: SignalResponse[] = await client.getSignals(); console.log(`Monitoring ${whales.length} whales and ${signals.length} signals`); signals.forEach(signal => { const confidence = (signal.confirmation_score * 100).toFixed(1); console.log( `${signal.symbol}: ${signal.signal_type.toUpperCase()} ` + `(${confidence}% confidence)` ); }); } catch (error) { console.error('Market monitoring failed:', error); } } monitorMarket();

Browser Integration

Use Smart Money API in browser-based applications with proper CORS handling and client-side caching.

HTML
Smart Money Dashboard

Smart Money Tracker

Best Practices and Optimization

Follow these best practices for production-ready Smart Money API integration in JavaScript.

Key Recommendations

  • Environment Variables: Use .env files with dotenv for secrets, never hardcode API keys
  • Rate Limiting: Monitor X-RateLimit headers and implement backoff logic
  • Caching: Cache responses appropriately (5-10 minutes for most data)
  • Error Handling: Always handle promise rejections and network errors
  • Timeouts: Set reasonable timeouts (30-60 seconds) for API calls
  • Logging: Log all API errors for debugging and monitoring
  • TypeScript: Use TypeScript for type safety in production applications
  • Testing: Mock API responses in unit tests using libraries like jest

For advanced topics, explore our guides on WebSocket streaming, data visualization, and building trading bots.

Ready to Build with JavaScript?

Start building real-time dashboards and trading applications with Smart Money API. Get full access to whale tracking and derivatives intelligence.

View JavaScript Plans