### Run Example Scripts Source: https://github.com/marketdataapp/sdk-js/blob/main/README.md Install dependencies and run a specific chart example script from the examples directory. ```bash cd examples pnpm install pnpm chart:lightweight # or any other script above ``` -------------------------------- ### Local Development Setup Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/installation.md Commands to clone the SDK repository, install dependencies, run tests, and build the project for local development. ```bash # Clone the repository git clone https://github.com/MarketDataApp/sdk-js.git cd sdk-js # Install dependencies pnpm install # Run the test suite (all mocked, no API calls) pnpm test # Build the dual CJS+ESM bundle pnpm build ``` -------------------------------- ### Install MarketData SDK Source: https://github.com/marketdataapp/sdk-js/blob/main/README.md Install the SDK using npm, yarn, or pnpm. Ensure Node.js v20 or higher is installed. ```bash npm install @marketdata/sdk ``` ```bash yarn add @marketdata/sdk ``` ```bash pnpm add @marketdata/sdk ``` -------------------------------- ### Install SDK with npm Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/installation.md Use this command to add the Market Data SDK to your project when using npm as your package manager. ```bash npm install @marketdata/sdk ``` -------------------------------- ### Install SDK with pnpm Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/installation.md Use this command to add the Market Data SDK to your project when using pnpm as your package manager. ```bash pnpm add @marketdata/sdk ``` -------------------------------- ### Install SDK with yarn Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/installation.md Use this command to add the Market Data SDK to your project when using yarn as your package manager. ```bash yarn add @marketdata/sdk ``` -------------------------------- ### Quick Start with MarketData SDK Source: https://github.com/marketdataapp/sdk-js/blob/main/README.md Initialize the MarketDataClient and fetch stock prices, historical candles, or market status. An API token is optional and enables demo mode. ```typescript import { MarketDataClient } from '@marketdata/sdk'; // Initialize client const client = new MarketDataClient({ token: 'YOUR_API_TOKEN' // Optional - runs in demo mode without token }); // Get stock prices const prices = await client.stocks.prices('AAPL'); console.log(prices[0].mid); // 150.25 // Get historical candles const candles = await client.stocks.candles('AAPL', { resolution: '1H', from: new Date('2024-01-01'), to: new Date('2024-01-31') }); // Get market status const status = await client.markets.status(); ``` -------------------------------- ### Create Client and Assign Token Directly Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/authentication.md This TypeScript example shows how to create a MarketDataClient instance and pass the API token directly in the configuration object. This method is not recommended for production environments. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const token = "your_token_here"; const client = new MarketDataClient({ token }); try { const quotes = await client.stocks.quotes("SPY"); console.log(quotes); } catch (error) { console.error(`Error: ${error.message}`); } ``` -------------------------------- ### Fetch Request Headers with Market Data SDK Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/utilities/headers.md Use the `headers()` method on the `utilities` resource to fetch the request-header echo. This method takes no parameters. Use this to confirm what gets through when you wire the SDK behind a corporate proxy or add custom headers via your runtime's fetch interception. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const h = await client.utilities.headers(); console.log(h["user-agent"]); // "marketdata-sdk-js/1.0.0" console.log(h["accept-encoding"]); } catch (error) { console.error(error); } ``` -------------------------------- ### Make Test Request Using Environment Variable Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/authentication.md This TypeScript example demonstrates making a stock quotes request after setting the API token via the MARKETDATA_TOKEN environment variable. The SDK automatically detects and uses the token. ```typescript import { MarketDataClient } from "@marketdata/sdk"; // No need to pass a token here — the SDK reads it from // the MARKETDATA_TOKEN environment variable automatically. const client = new MarketDataClient(); try { const quotes = await client.stocks.quotes("SPY"); console.log(quotes); } catch (error) { console.error(`Error: ${error.message}`); } ``` -------------------------------- ### Get Daily Stock Candles Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Fetches daily OHLCV data for a given stock symbol. Requires importing the MarketDataClient. ```typescript import { MarketDataClient } from '@marketdata/sdk'; const client = new MarketDataClient(); const candles = await client.stocks.candles('AAPL'); console.log(candles); ``` -------------------------------- ### Handle Errors with try/catch Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/client.md Use standard JavaScript `try/catch` blocks to handle potential errors when making requests. This example demonstrates catching specific error types like `AuthenticationError`, `RateLimitError`, and general errors. ```typescript import { MarketDataClient, AuthenticationError, RateLimitError, NotFoundError, } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const prices = await client.stocks.prices("AAPL"); console.log("Success:", prices); } catch (error) { if (error instanceof AuthenticationError) { console.error("Bad token:", error.message); } else if (error instanceof RateLimitError) { console.error("Rate limit exceeded"); } else { console.error("Failed:", error); } } ``` -------------------------------- ### Get Prices in Human-Readable Format Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Fetch stock prices with human-readable field names and values by setting the `human` option to `true`. This is useful for display purposes. ```typescript const prices = await client.stocks.prices('AAPL', { human: true }); console.log(prices.Symbol); console.log(prices.Mid); console.log(prices['Change $']); console.log(prices['Change %']); ``` -------------------------------- ### Fetch Service Status with Uptime Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/utilities/status.md Retrieves the current service status payload and logs each service's name along with its 30-day and 90-day uptime percentages. This example demonstrates accessing optional uptime properties from the response. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const s = await client.utilities.status(); for (let i = 0; i < s.service.length; i++) { const u30 = s.uptimePct30d?.[i] ?? null; const u90 = s.uptimePct90d?.[i] ?? null; console.log(`${s.service[i]} — 30d=${u30}% 90d=${u90}%`); } } catch (error) { console.error(error); } ``` -------------------------------- ### Initialize MarketDataClient Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/client.md Instantiate the MarketDataClient. The token can be provided directly or will be read from the MARKETDATA_TOKEN environment variable. Use `await client.ready` to ensure the client is ready for requests, especially if startup validation is enabled. The `skipStartupValidation` option can be set to true to bypass the initial token validation, which is useful for serverless environments. ```typescript import { MarketDataClient } from "@marketdata/sdk"; // Token will be read from MARKETDATA_TOKEN environment variable const client = new MarketDataClient(); // Or provide the token explicitly const clientWithToken = new MarketDataClient({ token: "your_token_here" }); // Fail fast on invalid tokens (default) — await readiness: await client.ready; // Skip the startup /user/ call (e.g. on Lambda cold starts) const fast = new MarketDataClient({ token: "your_token_here", skipStartupValidation: true, }); // Enable debug logging for troubleshooting const debugClient = new MarketDataClient({ debug: true }); // Provide a custom logger import { DefaultLogger, LogLevel } from "@marketdata/sdk"; const logger = new DefaultLogger(LogLevel.WARN); const quietClient = new MarketDataClient({ logger }); ``` -------------------------------- ### Initializing MarketDataClient with Logging Options Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/client.md Demonstrates how to initialize the MarketDataClient with different logging configurations. This includes using the default logger, enabling debug logging, and providing a custom logger with a specific log level. ```typescript import { MarketDataClient, DefaultLogger, LogLevel } from "@marketdata/sdk"; // Default logger (INFO level) const client1 = new MarketDataClient(); // Debug logging (more verbose — shows request URLs, response timings, token suffix) const client2 = new MarketDataClient({ debug: true }); // Custom log level const logger = new DefaultLogger(LogLevel.WARN); const client3 = new MarketDataClient({ logger }); ``` -------------------------------- ### Get Stock Candles Using Countback Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Retrieves a specified number of recent candles using the 'countback' parameter as an alternative to a date range. ```typescript const candles = await client.stocks.candles('AAPL', { countback: 100 }); console.log(candles); ``` -------------------------------- ### Initialize Client with Default Environment Variables Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/settings.md Instantiate the MarketDataClient without explicit configuration. The client will automatically pick up settings from environment variables. This is useful for applying global configurations. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); // All calls will use the env-var defaults unless overridden. const result = await client.stocks.prices("AAPL"); ``` -------------------------------- ### Initialize MarketDataClient Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/markets.md Instantiate the MarketDataClient to interact with market data services. Ensure you have the necessary authentication token. ```typescript import { MarketDataClient } from '@marketdata/sdk'; const client = new MarketDataClient(); ``` -------------------------------- ### Fetch Market Status (Human-Readable) Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/markets.md Get market status with human-readable field names. Access properties like 'Date' and 'Status' directly. ```typescript const status = await client.markets.status({ human: true }); console.log(status.Date); console.log(status.Status); ``` -------------------------------- ### Get Extended Hours Candles with Split Adjustment Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Retrieves extended trading hours data and adjusts for stock splits. Use the 'extended' and 'adjustsplits' parameters. ```typescript const candles = await client.stocks.candles('AAPL', { resolution: 'D', from: new Date('2023-01-01'), to: new Date('2023-12-31'), extended: true, adjustsplits: true }); ``` -------------------------------- ### Get Prices for a Single Stock Symbol Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Fetch the current price for a single stock symbol using the `prices` method. The response is in the default machine-readable format. ```typescript import { MarketDataClient } from '@marketdata/sdk'; const client = new MarketDataClient(); const prices = await client.stocks.prices('AAPL'); console.log(prices); ``` -------------------------------- ### Initialize MarketDataClient Source: https://github.com/marketdataapp/sdk-js/blob/main/README.md Configure and instantiate the MarketDataClient with API token, base URL, retry settings, and optional logger. ```typescript const client = new MarketDataClient({ token: 'YOUR_API_TOKEN', // Optional baseUrl: 'https://api.marketdata.app', // Optional apiVersion: 'v1', // Optional maxRetries: 3, // Optional, default: 3 retryInitialWait: 0.5, // Optional, default: 0.5 seconds retryMaxWait: 5, // Optional, default: 5 seconds retryFactor: 2, // Optional, default: 2 logger: customLogger, // Optional, custom logger debug: false // Optional, enable debug logging }); ``` -------------------------------- ### Get Stock Candles with Specific Resolution Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Retrieves stock candles for different timeframes like hourly, 15-minute, or weekly. The resolution parameter controls the data granularity. ```typescript const hourly = await client.stocks.candles('AAPL', { resolution: '1H' }); const minute15 = await client.stocks.candles('AAPL', { resolution: '15' }); const weekly = await client.stocks.candles('AAPL', { resolution: 'W' }); ``` -------------------------------- ### Configure .env File for Authentication Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/authentication.md Create a .env file in your project root to store your API token. The SDK automatically loads this file using dotenv. Remember to add .env to your .gitignore. ```env MARKETDATA_TOKEN=your_api_token ``` -------------------------------- ### Initialize MarketDataClient and Fetch Data Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/README.md Demonstrates initializing the MarketDataClient and fetching stock prices, historical candles, and market status. An API token is optional for demo mode. ```typescript import { MarketDataClient } from "@marketdata/sdk"; // Initialize client const client = new MarketDataClient({ token: "YOUR_API_TOKEN", // Optional - runs in demo mode without token }); // Get stock prices const prices = await client.stocks.prices("AAPL"); console.log(prices[0].mid); // 150.25 // Get historical candles const candles = await client.stocks.candles("AAPL", { resolution: "1H", from: new Date("2024-01-01"), to: new Date("2024-01-31"), }); // Get market status const status = await client.markets.status(); ``` -------------------------------- ### Get Raw JSON Response for Prices Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Obtain the raw JSON response from the API by specifying `format: 'json'`. This bypasses SDK transformations and provides the direct API output. ```typescript const json = await client.stocks.prices('AAPL', { format: 'json' }); console.log(json); ``` -------------------------------- ### Get Prices for Multiple Stock Symbols Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Retrieve current prices for multiple stock symbols by passing an array of symbols to the `prices` method. The response is in the default machine-readable format. ```typescript const prices = await client.stocks.prices(['AAPL', 'GOOGL', 'MSFT']); console.log(prices); ``` -------------------------------- ### Configure Client with Constructor Arguments Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/settings.md Set client-specific configuration options, including authentication token, base URL, API version, and retry parameters, when creating a new MarketDataClient instance. These arguments override environment variables for the settings they cover. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient({ token: "your_token_here", baseUrl: "https://api.marketdata.app", apiVersion: "v1", maxRetries: 5, retryInitialWait: 1, retryMaxWait: 15, retryFactor: 2, debug: true, }); ``` -------------------------------- ### MarketDataClient Constructor Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/client.md Initializes a new instance of the MarketDataClient. Configuration options can be provided to customize authentication, base URL, retry behavior, and logging. ```APIDOC ## MarketDataClient Constructor ### Description Initializes a new instance of the `MarketDataClient`. Configuration options can be provided to customize authentication, base URL, retry behavior, and logging. ### Signature ```typescript constructor(config?: MarketDataConfig); ``` ### Parameters #### Configuration (`MarketDataConfig`) - `token` (string, optional): The authentication token for API requests. - `baseUrl` (string, optional): The base URL for API requests (default: `https://api.marketdata.app`). - `apiVersion` (string, optional): The API version to use (default: `v1`). - `maxRetries` (number, optional): Maximum number of retries for failed requests. - `retryInitialWait` (number, optional): Initial wait time in milliseconds before retrying. - `retryMaxWait` (number, optional): Maximum wait time in milliseconds between retries. - `retryFactor` (number, optional): Factor by which the wait time increases with each retry. - `skipStartupValidation` (boolean, optional): If true, skips the initial validation call on startup. - `debug` (boolean, optional): Enables debug logging. - `logger` ([Logger](#Logger), optional): A custom logger instance. ``` -------------------------------- ### Save or Get Blob from API Response Source: https://github.com/marketdataapp/sdk-js/blob/main/README.md Utilize chained .save() or .blob() methods on API responses for direct file saving or obtaining a Blob object without intermediate awaits. ```typescript // Save directly to disk const path = await client.stocks.prices('AAPL', { format: 'csv' }).save('aapl.csv'); ``` ```typescript // Or get a Blob const blob = await client.stocks.prices('AAPL', { format: 'csv' }).blob(); ``` -------------------------------- ### Handle Authentication Errors with Market Data SDK Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Demonstrates how to catch and handle specific authentication errors when using the Market Data SDK. Ensure the SDK is imported and initialized before use. ```typescript import { MarketDataClient, AuthenticationError } from '@marketdata/sdk'; const client = new MarketDataClient(); try { const prices = await client.stocks.prices('AAPL'); console.log(prices); } catch (err) { if (err instanceof AuthenticationError) console.error('Bad token'); else throw err; } ``` -------------------------------- ### Get Stock Candles in Human-Readable Format Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Fetches candle data formatted for human readability, providing separate arrays for Date, Open, High, Low, Close, and Volume. Set the 'human' parameter to true. ```typescript const candles = await client.stocks.candles('AAPL', { human: true }); console.log(candles.Date); console.log(candles.Open); console.log(candles.Close); console.log(candles.Volume); ``` -------------------------------- ### Set Universal Parameters via Environment Variables Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/settings.md Configure global API request settings like output format, date format, and human-readable mode using environment variables. A .env file is automatically loaded. These settings are applied to all API calls unless overridden. ```bash export MARKETDATA_OUTPUT_FORMAT=json export MARKETDATA_DATE_FORMAT=timestamp export MARKETDATA_USE_HUMAN_READABLE=true ``` -------------------------------- ### Accessing Rate Limit Information Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Instantiate the client and await its ready state to access rate limit details. This is useful for monitoring and managing API usage. ```typescript const client = new MarketDataClient({ token: 'YOUR_TOKEN' }); await client.ready; // populates rateLimits on construction if (client.rateLimits) { console.log(`Limit: ${client.rateLimits.requestsLimit}`); console.log(`Remaining: ${client.rateLimits.requestsRemaining}`); console.log(`Consumed: ${client.rateLimits.requestsConsumed}`); console.log(`Reset at: ${new Date(client.rateLimits.requestsReset * 1000)}`); } ``` -------------------------------- ### Fluent .catch() for Error Handling Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/client.md Illustrates how to handle errors using fluent chaining with the .catch() method, providing an alternative to try/catch blocks for simpler error handling scenarios. ```APIDOC ## .catch() Fluent chaining without `try`/`catch`. ```typescript const prices = await client.stocks .prices("AAPL") .catch((error) => { console.error("Failed:", error.message); return []; }); ``` ``` -------------------------------- ### Get Stock Candles for a Date Range Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks.md Fetches stock candles within a specified date range using 'from' and 'to' parameters. Supports intraday resolutions with automatic date range splitting for concurrent fetching. ```typescript const candles = await client.stocks.candles('AAPL', { resolution: '1H', from: new Date('2023-01-01'), to: new Date('2024-12-31') }); console.log(candles); ``` -------------------------------- ### Configure Output Format with SDK Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/settings.md Set the desired output format for API responses. Use `OutputFormat.CSV` to receive a Blob that can be saved to disk. ```typescript import { MarketDataClient, OutputFormat } from "@marketdata/sdk"; const client = new MarketDataClient(); // Default (internal) — returns plain JS objects const defaultResult = await client.stocks.prices("AAPL"); // CSV — returns a Blob const csvResult = await client.stocks.prices("AAPL", { outputFormat: OutputFormat.CSV }); await csvResult.save("prices.csv"); // writes to disk ``` -------------------------------- ### Verify npm Package Signatures Source: https://github.com/marketdataapp/sdk-js/blob/main/README.md Use this command to audit the signatures of the @marketdata/sdk package to ensure its integrity and authenticity. ```bash npm audit signatures @marketdata/sdk ``` -------------------------------- ### Fetch and Save Daily Candles as CSV Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks/candles.md Fetches daily candles for a symbol and saves them to a CSV file. Requires importing `MarketDataClient` and `OutputFormat`. The `save()` method returns the filename where the CSV was saved. ```typescript import { MarketDataClient, OutputFormat } from "@marketdata/sdk"; const client = new MarketDataClient(); const csv = await client.stocks.candles("AAPL", { resolution: "D", countback: 100, outputFormat: OutputFormat.CSV, }); const filename = await csv.save("aapl_daily.csv"); console.log(`CSV saved to: ${filename}`); ``` -------------------------------- ### Fetch Default News Articles Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks/news.md Fetches news articles for a given stock symbol using the default output format. Ensure the MarketDataClient is initialized and imported. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const articles = await client.stocks.news("AAPL"); for (const a of articles) { console.log(`${a.source}: ${a.headline}`); } } catch (error) { console.error(error); } ``` -------------------------------- ### Configure Date Format with SDK Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/settings.md Specify the format for date and time information in responses. Use `DateFormat.TIMESTAMP` for ISO 8601 format. ```typescript import { MarketDataClient, DateFormat } from "@marketdata/sdk"; const client = new MarketDataClient(); const candles = await client.stocks.candles("AAPL", { dateFormat: DateFormat.TIMESTAMP }); ``` -------------------------------- ### Fetch Option Chain Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/options/chain.md Use the `chain()` method on the `options` resource to fetch an option chain. The response includes Greeks (delta, gamma, theta, vega, IV), intrinsic/extrinsic value, and underlying price alongside the quote fields. ```APIDOC ## GET /options/chain ### Description Retrieves the full option chain for a given underlying symbol, including all call and put contracts, Greeks, intrinsic/extrinsic value, and underlying price. ### Method GET ### Endpoint /options/chain ### Query Parameters - **symbol** (string) - Required - The underlying symbol for which to fetch the option chain. - **output** (string) - Optional - The desired output format. Options: `internal` (default), `json`, `csv`. ### Response #### Success Response (200) - **data** (OptionsChain[] or OptionsChainHuman[] or object or Blob) - The option chain data in the requested format. ### Response Example ```json { "data": [ { "contract_symbol": "SPY230616C00400000", "strike_price": 400.0, "expiration_date": "2023-06-16", "calls": [ { "contract_type": "call", "delta": 0.5, "gamma": 0.1, "theta": -0.05, "vega": 0.02, "iv": 0.15, "intrinsic_value": 10.0, "extrinsic_value": 5.0, "underlying_price": 410.0, "bid_price": 15.0, "ask_price": 16.0, "volume": 1000, "open_interest": 5000 } ], "puts": [ { "contract_type": "put", "delta": -0.5, "gamma": -0.1, "theta": -0.05, "vega": 0.02, "iv": 0.15, "intrinsic_value": 0.0, "extrinsic_value": 10.0, "underlying_price": 410.0, "bid_price": 5.0, "ask_price": 6.0, "volume": 800, "open_interest": 4000 } ] } ] } ``` ``` -------------------------------- ### Fetch Full Options Chain Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/options/chain.md Retrieves all available option contracts for a given stock symbol. Ensure the MarketDataClient is initialized. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const contracts = await client.options.chain("AAPL"); console.log(`Got ${contracts.length} contracts`); } catch (error) { console.error(error); } ``` -------------------------------- ### Standard try/catch for Error Handling Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/client.md Demonstrates the idiomatic approach to handling errors using a try/catch block. It shows how to catch specific error types like AuthenticationError, RateLimitError, and NotFoundError. ```APIDOC ## try / catch The idiomatic approach. ```typescript import { MarketDataClient, AuthenticationError, RateLimitError, NotFoundError, } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const prices = await client.stocks.prices("AAPL"); console.log("Success:", prices); } catch (error) { if (error instanceof AuthenticationError) { console.error("Bad token:", error.message); } else if (error instanceof RateLimitError) { console.error("Rate limit exceeded"); } else { console.error("Failed:", error); } } ``` ``` -------------------------------- ### Configure Columns with SDK Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/settings.md Limit the response data to specific columns by providing an array of column names. This reduces data transfer and processing time. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); const quotes = await client.stocks.quotes("AAPL", { columns: ["ask", "bid"] }); ``` -------------------------------- ### Fetch Stock Prices as CSV and Save to File Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks/prices.md Retrieve stock prices in CSV format and save the resulting Blob to a file using the `.save()` method. This is suitable for data analysis or import into other tools. ```typescript import { MarketDataClient, OutputFormat } from "@marketdata/sdk"; const client = new MarketDataClient(); const csv = await client.stocks.prices(["AAPL", "MSFT"], { outputFormat: OutputFormat.CSV, }); // Save the Blob to disk (Node.js) const filename = await csv.save("prices.csv"); console.log(`CSV saved to: ${filename}`); ``` -------------------------------- ### headers() Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/utilities/headers.md Fetches the request-header echo. This method is part of the utilities resource and takes no parameters. It returns a MarketDataPromise that resolves to a HeadersResponse, which is a map of header names to their values as seen by the API. The 'Authorization' header is redacted server-side. ```APIDOC ## headers() ### Description Fetches the request-header echo. Takes no parameters. ### Method `headers()` ### Returns - [`MarketDataPromise`](../client.md#MarketDataPromise) ### Default Example ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const h = await client.utilities.headers(); console.log(h["user-agent"]); // "marketdata-sdk-js/1.0.0" console.log(h["accept-encoding"]); } catch (error) { console.error(error); } ``` ``` -------------------------------- ### Fetch Human-Readable Daily Candles Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/stocks/candles.md Fetches daily candles for a symbol and returns them in a human-readable format. Requires importing `MarketDataClient` and initializing it. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const candles = await client.stocks.candles("AAPL", { resolution: "D", countback: 10, human: true, }); for (const c of candles) { console.log(`Date=${c.Date} Open=${c.Open} Close=${c.Close}`); } } catch (error) { console.error(error); } ``` -------------------------------- ### Set Environment Variable (Windows) Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/authentication.md Sets the MARKETDATA_TOKEN environment variable permanently on Windows systems. A new Command Prompt session is required for the change to take effect. ```bash setx MARKETDATA_TOKEN "your_api_token" ``` -------------------------------- ### Fetch Fund Candles (Default) Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/funds/candles.md Fetches the last 30 daily candles for a fund symbol using the default output format. Ensure the MarketDataClient is initialized. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { // VFINX is available without authentication (free test symbol). const candles = await client.funds.candles("VFINX", { countback: 30 }); for (const c of candles) { console.log(`t=${c.t} o=${c.o} h=${c.h} l=${c.l} c=${c.c}`); } } catch (error) { console.error(error); } ``` -------------------------------- ### Error Handling Source: https://github.com/marketdataapp/sdk-js/blob/main/README.md Details on how to handle errors returned by the SDK, including specific error classes and general exception handling. ```APIDOC ## Error Handling Every method returns a `Promise` that resolves with the response or rejects with a `MarketDataClientError`. Use ordinary `try`/`catch` with `await`. ### Error Classes All SDK errors extend `MarketDataClientError`: - `ValidationError`: Request parameters failed validation, or the server response failed schema validation. - `RateLimitError`: Pre-flight credit check or 429 from the server. - `RequestError`: Transport / HTTP failure (e.g., 5xx after retries exhausted). ### Example Usage with `try`/`catch` ```typescript import { MarketDataClientError, RateLimitError, ValidationError, RequestError } from '@marketdata/sdk'; try { const prices = await client.stocks.prices('AAPL'); console.log(prices[0].mid); } catch (error) { if (error instanceof RateLimitError) { console.error('Rate limit exceeded'); } else if (error instanceof ValidationError) { console.error('Invalid parameters:', error.message); } else if (error instanceof RequestError) { console.error('Request failed after retries:', error.message); } else if (error instanceof MarketDataClientError) { console.error('SDK error:', error.message); } else { throw error; } } ``` ``` -------------------------------- ### Fetch Full Options Chain Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/options/chain.md Retrieves the complete options chain for a specified stock symbol. ```APIDOC ## chain Fetches the option chain for a single underlying symbol. ### Method `chain(symbol: string, params?: P): MarketDataPromise chain(params: P & { symbol: string }): MarketDataPromise ``` ```APIDOC ### Parameters - `symbol` (string) - Required - The underlying stock symbol (e.g. "AAPL"). - `date` (string | Date, optional) - Fetch the chain as-of a specific historical date (end-of-day snapshot). - `expiration` (string | Date, optional) - Filter by specific expiration date. - `dte` (number, optional) - Filter by number of days to expiration. - `from` / `to` (string | Date, optional) - Range filter for expiration dates. - `month` (number, optional, 1–12), `year` (number, optional) - Filter by expiration month and/or year. - `weekly` / `monthly` / `quarterly` (boolean, optional) - Filter by expiration cycle type. - `strike` (number | string, optional) - Filter by specific strike price. - `delta` (number, optional) - Filter by target delta value. - `strikeLimit` (number, optional) - Limit the response to the N strikes nearest the underlying price. - `range` (string, optional) - Filter by in-the-money / out-of-the-money range (e.g. "itm", "otm"). - `minBid` / `maxBid` / `minAsk` / `maxAsk` (number, optional) - Filter by quote price thresholds. - `maxBidAskSpread` (number, optional), `maxBidAskSpreadPct` (number, optional) - Filter by spread thresholds. - `minOpenInterest` (number, optional), `minVolume` (number, optional) - Filter by liquidity thresholds. - `nonstandard` (boolean, optional) - Include or exclude non-standard contracts. - `side` ("call" | "put" | "both", optional) - Filter by option side. - `am` / `pm` (boolean, optional) - Filter by AM-settled or PM-settled contracts. - `outputFormat` (optional): The format of the returned data. Alias: `format`. - `dateFormat` (optional): Date format. Alias: `dateformat`. - `columns` (optional): Columns to include. - `addHeaders` (optional): Whether to include headers in CSV output. Alias: `headers`. - `useHumanReadable` (optional): Use human-readable field names. Alias: `human`. - `mode` (optional): The data mode to use. ``` ```APIDOC ### Returns - `MarketDataPromise` ``` ```APIDOC ### Example ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const contracts = await client.options.chain("AAPL"); console.log(`Got ${contracts.length} contracts`); } catch (error) { console.error(error); } ``` ``` -------------------------------- ### status() - Fetch Market Status Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/markets/status.md Fetches market status information. All parameters are optional. The `outputFormat` parameter can be used to specify the desired output format (e.g., 'json', 'csv'). ```APIDOC ## status() ### Description Fetches market status information. All parameters are optional. ### Method `status

(params?: P): MarketDataPromise` ### Parameters #### Query Parameters - `country` (string, optional): Filter by country code (e.g. "US", "CA", "GB"). - `date` (string | Date, optional): Specific date to fetch status for. - `from` (string | Date, optional): Start of the date range. - `to` (string | Date, optional): End of the date range. - `countback` (number, optional): Number of days to return, counting backwards from `to` (or the current date if `to` is not provided). - `outputFormat` (string, optional): The format of the returned data. Alias: `format`. - `dateFormat` (string, optional): Date format. Alias: `dateformat`. - `columns` (string, optional): Columns to include. - `addHeaders` (boolean, optional): Whether to include headers in CSV output. Alias: `headers`. - `useHumanReadable` (boolean, optional): Use human-readable field names. Alias: `human`. - `mode` (string, optional): The data mode to use. ### Returns - `MarketDataPromise` ### Example: Today ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const days = await client.markets.status(); for (const d of days) { console.log(`date=${d.date} status=${d.status}`); } } catch (error) { console.error(error); } ``` ### Example: Date Range ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const days = await client.markets.status({ from: "2024-01-01", to: "2024-01-31", country: "US", }); console.log(days); } catch (error) { console.error(error); } ``` ### Example: Countback ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { // Last 7 trading-status days const days = await client.markets.status({ countback: 7 }); console.log(days); } catch (error) { console.error(error); } ``` ### Example: Human Readable ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const days = await client.markets.status({ countback: 7, human: true }); for (const d of days) { console.log(`Date=${d.Date} Status=${d.Status}`); } } catch (error) { console.error(error); } ``` ``` -------------------------------- ### Handle No-Data Responses with MarketDataPromise Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/client.md When a server returns a 404, the SDK resolves the Promise with an empty array and flags it with `no_data: true`. Use `hasData()` to conditionally process the response. ```typescript const pending = client.stocks.prices("UNKNOWN"); const prices = await pending; if (!(await pending.hasData())) { console.log("No data for that symbol"); } else { console.log(prices); } ``` -------------------------------- ### Chained Save Operations with MarketDataPromise Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/client.md Demonstrates chaining `saveToFile` operations on a MarketDataPromise without intermediate awaits. The format is inferred from the file extension. ```typescript const path = await client.stocks .candles("AAPL", { resolution: "D", countback: 90 }) .saveToFile("aapl-90d.csv"); ``` -------------------------------- ### lookup() Method Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/options/lookup.md Resolves a human-readable option description to its OCC symbol. It can be called using a positional string argument or an object with a 'lookup' property. Optional parameters include 'outputFormat' and 'useHumanReadable'. ```APIDOC ## lookup ### Description Resolves a human-readable option description to its OCC symbol. ### Method Signature ```typescript // Positional form lookup

(lookupStr: string, params?: P): MarketDataPromise // Object form lookup

(params: P & { lookup: string }): MarketDataPromise ``` ### Parameters - `lookupStr` (string) - Required - A natural-language description of the option contract (e.g. "AAPL 7/28/2023 200 Call", "TSLA Jan 2025 300 Put"). - `params` (object) - Optional - An object containing additional parameters. - `lookup` (string) - Required (when using object form) - A natural-language description of the option contract. - `outputFormat` (string) - Optional - The format of the returned data. Alias: `format`. - `useHumanReadable` (boolean) - Optional - Use human-readable field names. Alias: `human`. ### Returns - `MarketDataPromise` - A promise that resolves to either an `OptionsLookupResponse` or `OptionsLookupHumanResponse` object. ### Default Usage Example ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const data = await client.options.lookup("AAPL 7/28/2023 200 Call"); console.log(data.optionSymbol); // "AAPL230728C00200000" } catch (error) { console.error(error); } ``` ### Human Readable Output Example ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const data = await client.options.lookup("AAPL 7/28/2023 200 Call", { human: true, }); console.log(data.Symbol); } catch (error) { console.error(error); } ``` ``` -------------------------------- ### Chained Save Operations Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/client.md Illustrates how to chain save operations without intermediate `await` calls, allowing for sequential saving of data to files. ```APIDOC ## Chained Saves Chained saves work without an intermediate `await`: ```typescript const path = await client.stocks .candles("AAPL", { resolution: "D", countback: 90 }) .saveToFile("aapl-90d.csv"); ``` ``` -------------------------------- ### Chainable Helpers (.save() / .blob()) Source: https://github.com/marketdataapp/sdk-js/blob/main/README.md Provides chainable methods to directly save API responses to disk or retrieve them as a Blob object. ```APIDOC ## Chainable Helpers (`.save()` / `.blob()`) Every returned Promise also supports chained CSV/JSON helpers. No intermediate `await` is required. ### `.save(filePath)` Saves the API response directly to a file on disk. - **filePath** (string) - Required - The path to the file where the response will be saved. ### `.blob()` Retrieves the API response as a Blob object. ### Example Usage ```typescript // Save directly to disk const path = await client.stocks.prices('AAPL', { format: 'csv' }).save('aapl.csv'); // Or get a Blob const blob = await client.stocks.prices('AAPL', { format: 'csv' }).blob(); ``` Both helpers throw `MarketDataClientError` on request failure, same as a plain `await`. ``` -------------------------------- ### Fetch Human-Readable Options Chain Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/options/chain.md Retrieves an options chain with human-readable field names. ```APIDOC ### Example ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const contracts = await client.options.chain("AAPL", { side: "put", human: true, }); for (const c of contracts) { console.log( `${c.Symbol} Strike=${c.Strike} Mid=${c.Mid} Delta=${c.Delta}` ); } } catch (error) { console.error(error); } ``` ``` -------------------------------- ### Fetch Fund Candles by Date Range Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/funds/candles.md Fetches monthly candles for a specific date range. Requires setting the resolution to 'M' (monthly) and providing 'from' and 'to' dates. Ensure the MarketDataClient is initialized. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const candles = await client.funds.candles("VFINX", { resolution: "M", from: "2020-01-01", to: "2024-12-31", }); console.log(`${candles.length} monthly bars`); } catch (error) { console.error(error); } ``` -------------------------------- ### Fetch Fund Candles in Human-Readable Format Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/funds/candles.md Fetches the last 10 daily candles using human-readable field names by setting the 'human' option to true. Ensure the MarketDataClient is initialized. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { const candles = await client.funds.candles("VFINX", { countback: 10, human: true, }); for (const c of candles) { console.log(`Date=${c.Date} Open=${c.Open} Close=${c.Close}`); } } catch (error) { console.error(error); } ``` -------------------------------- ### MarketDataClient Class Definition Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/client.md Defines the MarketDataClient class and its configuration interface. Use this class to instantiate the client for API interactions. ```typescript class MarketDataClient { constructor(config?: MarketDataConfig); readonly ready: Promise; } interface MarketDataConfig { token?: string; baseUrl?: string; apiVersion?: string; maxRetries?: number; retryInitialWait?: number; retryMaxWait?: number; retryFactor?: number; skipStartupValidation?: boolean; debug?: boolean; logger?: Logger; } ``` -------------------------------- ### Fetch Market Status using Countback Source: https://github.com/marketdataapp/sdk-js/blob/main/docs/markets/status.md Retrieves the market status for a specified number of days counting backwards from the current date. Logs the result. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { // Last 7 trading-status days const days = await client.markets.status({ countback: 7 }); console.log(days); } catch (error) { console.error(error); } ```