diff --git a/sdk/js/authentication.mdx b/sdk/js/authentication.mdx new file mode 100644 index 0000000..10ade49 --- /dev/null +++ b/sdk/js/authentication.mdx @@ -0,0 +1,120 @@ +--- +title: Authentication +sidebar_position: 2 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +The Market Data API uses a **Bearer Token** for authentication. The token is required for each request you make to the API. Your token should have been e-mailed to you when you first signed up for an account. If you do not have a token or have lost your sign-up email, request a new token from the [Market Data Dashboard](https://www.marketdata.app/dashboard/). + +There are three ways to set your token when using the JavaScript SDK: + +1. Set it from an environment variable _(recommended for production)_ +2. Load it from a `.env` file _(recommended for local development)_ +3. Pass it directly when creating the [client](/sdk/js/client) + +On startup, the SDK will look for the `MARKETDATA_TOKEN` environment variable. If found, it will use the token for all requests. The SDK also loads a `.env` file automatically via `dotenv` if one is present in the working directory. + +:::tip +When your code is running in a production environment, we recommend using an environment variable to ensure your token is not stored with your code. This is the most secure way to set your token. +::: + +## How To Set-Up The Environment Variable + +Set the token in the environment variable `MARKETDATA_TOKEN`. Alternatively, you can pass it directly when creating the client, but please be aware that this is not secure and could pose a risk if your code is shared. + +### Set The Environment Variable In The Console + + + + +This command should be run in the terminal. It sets the environment variable for the current session only. If you open a new terminal window or restart your computer, the environment variable will not persist. + +```bash +export MARKETDATA_TOKEN="your_api_token" +``` + +#### Verify the Variable + +To verify that the `MARKETDATA_TOKEN` environment variable has been set properly, run `echo $MARKETDATA_TOKEN`. If set correctly, this prints the token value; if unset, the output is blank. + +#### Make The Variable Persistent + +Add the `export` line to your shell's profile script (`~/.bash_profile`, `~/.bashrc`, `~/.zshrc`, etc.), then either restart your terminal or run `source ~/.bashrc` (adjusting for your shell) to apply. + + + + +This command should be run in the Command Prompt. `setx` sets the variable permanently, but the new value is not available in the current Command Prompt session — you will need to open a new session. + +```bash +setx MARKETDATA_TOKEN "your_api_token" +``` + +#### Verify The Variable + +Open a new Command Prompt and run `echo %MARKETDATA_TOKEN%`. If the output prints the token, the variable is set correctly. If it prints `%MARKETDATA_TOKEN%` unchanged, the variable is not set. + + + + +### Using a .env File + +The SDK automatically loads a `.env` file from your working directory at import time (via [`dotenv`](https://github.com/motdotla/dotenv)). Create a file named `.env` in your project root: + +```env title=".env" +MARKETDATA_TOKEN=your_api_token +``` + +:::warning +Add `.env` to your `.gitignore` so the token is not committed to source control. +::: + +### Make A Test Request + +Use the following code to verify that your authentication is working by making a test request to `SPY` or any other symbol that requires authentication. Do not use `AAPL` to test your authentication because `AAPL` is a free test symbol and will return data even if you are not authenticated properly. + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +// No need to pass a token here — the SDK reads it from +// the MARKETDATA_TOKEN environment variable automatically. +const client = new MarketDataClient(); + +const result = await client.stocks.quotes("SPY"); + +result.match( + (quotes) => console.log(quotes), + (error) => console.error(`Error: ${error.message}`), +); +``` + +If your token is set correctly, you should see the output of the test request. If you see an error, double-check that you have set the token correctly. + +## How To Create a Client and Assign a Token Directly + +If you decide to pass the token directly when creating the client, you can do so by passing it as a property of the configuration object. This is not recommended for production code. + +### Example Code + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const token = "your_token_here"; + +const client = new MarketDataClient({ token }); + +const result = await client.stocks.quotes("SPY"); + +result.match( + (quotes) => console.log(quotes), + (error) => console.error(`Error: ${error.message}`), +); +``` + +## Next Steps + +After successful authentication, you will be able to begin making requests to the Market Data API. We recommend reading the brief overview of how the [client](/sdk/js/client) works, so you can get familiar with interacting with the SDK. + +You may also want to configure [Settings](/sdk/js/settings) to customize output format, date format, and other universal parameters. diff --git a/sdk/js/client.mdx b/sdk/js/client.mdx new file mode 100644 index 0000000..02a0f5d --- /dev/null +++ b/sdk/js/client.mdx @@ -0,0 +1,270 @@ +--- +title: Client +sidebar_position: 3 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +The Market Data JavaScript Client handles API requests, response parsing, rate-limit tracking, retries, and logging. The SDK supports stocks, options, funds, and market status data. + +### Get Started Quickly with the MarketDataClient + +1. Review the [documentation on authentication](/sdk/js/authentication) to learn how to set your API token. +2. Create a [`MarketDataClient`](#MarketDataClient) instance and use it to make requests to the Market Data API. +3. Make a test request and review the console output. The SDK includes logging capabilities to help you debug requests. +4. Check the [rate limit](#RateLimits) in the client to track credit usage and how many API credits remain. +5. Configure [Settings](/sdk/js/settings) to customize output format, date format, and other universal parameters. + + +## MarketDataClient + +```typescript +class MarketDataClient { + constructor(config?: MarketDataConfig); +} + +interface MarketDataConfig { + token?: string; + baseUrl?: string; + apiVersion?: string; + maxRetries?: number; + retryInitialWait?: number; + retryMaxWait?: number; + retryFactor?: number; + debug?: boolean; + logger?: Logger; +} +``` + +[MarketDataClient](#MarketDataClient) is the main client class for interacting with the Market Data API. It provides access to all resources (stocks, options, funds, markets) and handles authentication, rate limiting, and request management. + +#### Properties + +- `token` (string, optional): The authentication token for API requests. See [authentication documentation](/sdk/js/authentication) for details. +- `rateLimits` ([UserRateLimits](#RateLimits), optional): Current rate limit information. Populated after the first successful API request. +- `baseUrl` (string): The base URL for API requests (default: `https://api.marketdata.app`). +- `apiVersion` (string): The API version to use (default: `v1`). +- `headers` (Record<string, string>): HTTP headers including `Authorization` and `User-Agent`. +- `logger` ([Logger](#Logger)): The logger instance used for diagnostic output. +- `settings` ([MarketDataSettings](/sdk/js/settings)): Resolved configuration including env-var defaults. See [Settings](/sdk/js/settings) for details. + +#### Resources + +- `stocks` ([StocksResource](/sdk/js/stocks)): Access to stocks endpoints (prices, quotes, candles, earnings, news) +- `options` ([OptionsResource](/sdk/js/options)): Access to options endpoints (chain, expirations, quotes, lookup) +- `funds` ([FundsResource](/sdk/js/funds)): Access to funds endpoints (candles) +- `markets` ([MarketsResource](/sdk/js/markets)): Access to markets endpoints (status) + + +### constructor + +```typescript +new MarketDataClient(config?: MarketDataConfig) +``` + +Creates and configures a new `MarketDataClient` instance. This initializes the client with the provided token (or reads it from the `MARKETDATA_TOKEN` environment variable), sets up HTTP headers, and prepares the resource namespaces. + +#### Parameters + +- `config` ([MarketDataConfig](#MarketDataClient), optional) + + Configuration object. All properties are optional: + + - `token` (string): The authentication token. Falls back to `MARKETDATA_TOKEN` environment variable if not provided. + - `baseUrl` (string): Override the API base URL. Defaults to `https://api.marketdata.app`. + - `apiVersion` (string): Override the API version. Defaults to `v1`. + - `maxRetries` (number): Maximum retry attempts for retriable errors. Defaults to `3`. + - `retryInitialWait` (number): Initial wait in seconds before the first retry. Defaults to `0.5`. + - `retryMaxWait` (number): Maximum wait in seconds between retries. Defaults to `10`. + - `retryFactor` (number): Exponential backoff factor. Defaults to `2`. + - `debug` (boolean): If `true`, sets the default logger level to `DEBUG`. Defaults to `false`. + - `logger` ([Logger](#Logger)): A custom logger instance. If omitted, the SDK uses its built-in `DefaultLogger`. + +#### Returns + +- `MarketDataClient` + + A new `MarketDataClient` instance ready to make API requests. + +#### Notes + +- The client sets a `User-Agent` header of the form `marketdata-js-{version}` (e.g. `marketdata-js-0.0.1`). +- All authenticated requests include an `Authorization: Bearer {token}` header. +- The client reuses a single underlying `fetch` client, which benefits from Node's global connection pooling. +- Configuration properties can also be provided via environment variables — see [Settings](/sdk/js/settings) for the full list and their resolution order. + +#### Example + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +// 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" }); + +// Enable debug logging for troubleshooting +const debugClient = new MarketDataClient({ debug: true }); + +// Provide a custom logger +import { DefaultLogger, LogLevel } from "marketdata-sdk-js"; +const logger = new DefaultLogger(LogLevel.WARN); +const quietClient = new MarketDataClient({ logger }); +``` + + +## The Result Pattern + +Every resource method returns a [`MarketDataResult`](#MarketDataResult) — a `ResultAsync` from the [neverthrow](https://github.com/supermacro/neverthrow) library. Errors are **not thrown**; they are represented as failed results. + +This means your code never needs a `try`/`catch` around SDK calls. You handle success and failure explicitly. + +### Handling Results + + + + +The idiomatic way. Pattern-match on success and error with two callbacks. + +```typescript +const result = await client.stocks.prices("AAPL"); + +result.match( + (prices) => console.log("Success:", prices), + (error) => console.error("Failed:", error.message), +); +``` + + + + + +Branch on result state and access `.value` or `.error` directly. + +```typescript +const result = await client.stocks.prices("AAPL"); + +if (result.isOk()) { + console.log("Prices:", result.value); +} else { + console.error("Error:", result.error.message); +} +``` + + + + + +Convert to a thrown exception if you prefer `try`/`catch`. + +```typescript +try { + const result = await client.stocks.prices("AAPL"); + const prices = result._unsafeUnwrap(); + console.log(prices); +} catch (error) { + console.error("Failed:", error); +} +``` + + + + + +Chain operations on the success value without unwrapping. + +```typescript +const result = await client.stocks.prices("AAPL") + .map((prices) => prices.filter((p) => p.mid > 100)); + +if (result.isOk()) { + console.log("Filtered:", result.value); +} +``` + + + + + +### MarketDataResult + +```typescript +interface MarketDataResult extends ResultAsync { + save(filename?: string): Promise; + blob(): Promise; +} +``` + +Every resource method returns a `MarketDataResult`. In addition to the standard `ResultAsync` interface from neverthrow, it exposes two convenience methods: + +- `save(filename?: string)`: Write the response to a file. Returns a `Promise` resolving to the filename. Format is inferred from the extension when possible. +- `blob()`: Materialise the response as a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). Useful for downloading CSV responses. + + +## Accessing Rate Limits + +The client tracks rate limits from the API by reading the `X-Api-Ratelimit-*` headers on every response. The `client.rateLimits` property is populated after the first successful API call. + +```typescript +const client = new MarketDataClient(); + +// Make a request to populate rate limits +await client.stocks.prices("AAPL"); + +// Access current rate limits +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)}`); +} +``` + +#### UserRateLimits + +```typescript +interface UserRateLimits { + requestsLimit: number; // Total API credits allowed + requestsRemaining: number; // API credits remaining + requestsConsumed: number; // API credits consumed + requestsReset: number; // Unix timestamp when the limit resets +} +``` + +**Note:** Rate limits are tracked via the following response headers: + +- `x-api-ratelimit-limit`: Total API credits allowed +- `x-api-ratelimit-remaining`: Number of API credits remaining +- `x-api-ratelimit-consumed`: Number of API credits consumed +- `x-api-ratelimit-reset`: Unix timestamp when the rate limit resets + +If rate limits have been fetched and `requestsRemaining` is `0`, the next resource call will fail fast with a `RateLimitError` rather than hitting the API. + + +## Logging + +The SDK includes a built-in logger that outputs diagnostic information. You can pass a custom logger or use the default. + +```typescript +import { MarketDataClient, DefaultLogger, LogLevel } from "marketdata-sdk-js"; + +// 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 }); +``` + +**Log levels** (in order of verbosity): `DEBUG`, `INFO`, `WARN`, `ERROR`. + +The default logger obfuscates tokens in log output, showing only the last 4 characters. + +## Configuration + +The SDK supports flexible configuration of universal parameters through environment variables, constructor arguments, and per-method overrides. See the [Settings](/sdk/js/settings) documentation for complete details on all available configuration options and how they interact. diff --git a/sdk/js/funds/candles.mdx b/sdk/js/funds/candles.mdx new file mode 100644 index 0000000..d5407de --- /dev/null +++ b/sdk/js/funds/candles.mdx @@ -0,0 +1,184 @@ +--- +title: Candles +sidebar_position: 1 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Retrieve historical OHLC (open/high/low/close) candles for any supported mutual fund symbol. + +## Making Requests + +Use the `candles()` method on the `funds` resource to fetch fund candles. + +:::info +Mutual fund candles are daily-resolution only (unlike stock candles). They do not include a `volume` field. +::: + +| Output Format | Result Payload | Description | +|------------------------|-----------------------------------------|-------------------------------------------------| +| **internal** (default) | `FundsCandle[]` or `FundsCandleHuman[]` | Array of decoded candle records, one per bar. | +| **json** | Raw JSON object | The compressed, array-keyed response object. | +| **csv** | `Blob` | CSV payload. Use `.save(filename)` to write it. | + + +## candles + +```typescript +// Positional form +candles

( + symbol: string, + params?: P, +): MarketDataResult + +// Object form +candles

( + params: P & { symbol: string }, +): MarketDataResult +``` + +Fetches historical daily candles for a single fund symbol. + +#### Parameters + +- `symbol` (string) + + The fund symbol (e.g. `"VFINX"`). + +- `resolution` (string, optional, default `"D"`) + + The candle resolution. Funds support daily-and-up only: `"D"`, `"daily"`, `"1D"`, `"W"`, `"weekly"`, `"1W"`, `"M"`, `"monthly"`, `"1M"`, `"Y"`, `"yearly"`, `"1Y"`, or any integer prefix of those units. + +- `from` (string | Date, optional) + + Start of the date range. + +- `to` (string | Date, optional) + + End of the date range. + +- `countback` (number, optional) + + Fetch `N` candles before `to` (mutually exclusive with `from`). + +- [`outputFormat`](/sdk/js/settings#output-format) (optional): The format of the returned data. Alias: `format`. +- [`dateFormat`](/sdk/js/settings#date-format) (optional): Date format. Alias: `dateformat`. +- [`columns`](/sdk/js/settings#columns) (optional): Columns to include. +- [`addHeaders`](/sdk/js/settings#headers) (optional): Whether to include headers in CSV output. Alias: `headers`. +- [`useHumanReadable`](/sdk/js/settings#human-readable) (optional): Use human-readable field names. Alias: `human`. +- [`mode`](/sdk/js/settings#data-mode) (optional): The data mode to use. + +#### Returns + +- [`MarketDataResult`](/sdk/js/client#MarketDataResult) + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +// VFINX is available without authentication (free test symbol). +const result = await client.funds.candles("VFINX", { countback: 30 }); + +result.match( + (candles) => { + for (const c of candles) { + console.log(`t=${c.t} o=${c.o} h=${c.h} l=${c.l} c=${c.c}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.funds.candles("VFINX", { + resolution: "M", + from: "2020-01-01", + to: "2024-12-31", +}); + +result.match( + (candles) => console.log(`${candles.length} monthly bars`), + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.funds.candles("VFINX", { + countback: 10, + human: true, +}); + +result.match( + (candles) => { + for (const c of candles) { + console.log(`Date=${c.Date} Open=${c.Open} Close=${c.Close}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +## FundsCandle + +```typescript +interface FundsCandle { + s?: string; + t: number; // timestamp + o: number; // open + h: number; // high + l: number; // low + c: number; // close +} +``` + +`FundsCandle` uses the API's short, machine-readable field names. + +#### Properties + +- `s` (string, optional): Status indicator. +- `t` (number): Unix timestamp of the bar. +- `o` (number): Opening NAV. +- `h` (number): High NAV. +- `l` (number): Low NAV. +- `c` (number): Closing NAV. + + +## FundsCandleHuman + +```typescript +interface FundsCandleHuman { + s?: string; + Date: number; + Open: number; + High: number; + Low: number; + Close: number; +} +``` + +`FundsCandleHuman` is returned when `human: true` is set. diff --git a/sdk/js/funds/index.mdx b/sdk/js/funds/index.mdx new file mode 100644 index 0000000..0e22372 --- /dev/null +++ b/sdk/js/funds/index.mdx @@ -0,0 +1,14 @@ +--- +title: Funds +slug: /js/funds +sidebar_position: 30 +--- + +The JavaScript SDK from Market Data provides methods designed to streamline your use of the following Funds endpoints. These intuitive methods provide a seamless interface for accessing mutual fund data. + +## Funds Endpoints + +import DocCardList from "@theme/DocCardList"; +import { useCurrentSidebarCategory } from "@docusaurus/theme-common"; + + diff --git a/sdk/js/index.mdx b/sdk/js/index.mdx new file mode 100644 index 0000000..e8e32e6 --- /dev/null +++ b/sdk/js/index.mdx @@ -0,0 +1,40 @@ +--- +title: JavaScript SDK +sidebar_position: 4 +slug: /js +sidebar_custom_props: + badge: n +--- + +Welcome to the Market Data JavaScript SDK documentation. This SDK allows you to integrate Market Data services into your Node.js and TypeScript applications. It ships typed responses, runtime schema validation, and a functional error-handling pattern. + +:::info +The JavaScript SDK is in early development (version `0.0.1`). The API surface and return types may change before 1.0. +::: + +## Open Source + +The SDK is open source and available on GitHub. Feel free to contribute to the project, report bugs, or request new features. + +- [JavaScript SDK GitHub](https://github.com/MarketDataApp/sdk-js/) + +## Documentation + +The best source for documentation on the SDK is right here. This documentation is the most up-to-date and accurate source of information on the SDK. + +## Using the SDK + +This SDK is designed to help you get up and running with Market Data's APIs as quickly as possible, providing you with all the tools you need to access real-time stock and options prices, historical data, and much more. + +### Getting Started + +1. [Install the SDK](/sdk/js/installation) into a Node.js or TypeScript project. +2. Set up your [authentication token](/sdk/js/authentication) to access the API. +3. Learn about the [client](/sdk/js/client) and how to make your first API requests. +4. Configure [Settings](/sdk/js/settings) to customize output format, date format, and other universal parameters. +5. Explore the available endpoints for [stocks](/sdk/js/stocks), [options](/sdk/js/options), [funds](/sdk/js/funds), and [markets](/sdk/js/markets). + +### Support + +- If you have any questions or need further assistance, please don't hesitate to open a ticket at our [helpdesk](https://www.marketdata.app/dashboard/). +- If you find a bug you may also [open an issue in our GitHub repository](https://github.com/MarketDataApp/sdk-js/issues). Please only open issues if you find a bug. Use our helpdesk for general questions or implementation assistance. diff --git a/sdk/js/installation.mdx b/sdk/js/installation.mdx new file mode 100644 index 0000000..be3aaaa --- /dev/null +++ b/sdk/js/installation.mdx @@ -0,0 +1,98 @@ +--- +title: Installation +sidebar_position: 1 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +This guide will help you install the Market Data JavaScript SDK and configure it for your needs. + +## Prerequisites + +- Node.js >= 20 +- A package manager: [pnpm](https://pnpm.io/) (used by the SDK itself), [npm](https://npmjs.com), or [yarn](https://yarnpkg.com) + +## Basic Installation + + + + +```bash +pnpm add marketdata-sdk-js +``` + + + + +```bash +npm install marketdata-sdk-js +``` + + + + +```bash +yarn add marketdata-sdk-js +``` + + + + +:::info +The SDK is in early development (version `0.0.1`) and has not yet been published to npm. Until it is, install directly from GitHub: + +```bash +pnpm add github:MarketDataApp/sdk-js +``` +::: + +## TypeScript Support + +The SDK is written in TypeScript and ships first-class type definitions. No `@types/*` package is needed. The SDK builds to both ESM and CommonJS, so it works with either module system. + +- **ESM**: `import { MarketDataClient } from "marketdata-sdk-js";` +- **CommonJS**: `const { MarketDataClient } = require("marketdata-sdk-js");` + +## Local Development Installation + +For local development, clone the repository and install from the project directory: + +```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 +``` + +The project uses [Corepack](https://nodejs.org/api/corepack.html) to pin the pnpm version. If `pnpm` is not available, enable Corepack first: + +```bash +corepack enable +``` + +## Core Dependencies + +The SDK includes the following core dependencies (installed automatically): + +- `dotenv`: Loads environment variables from a `.env` file +- `neverthrow`: Functional `Result` type for error handling +- `p-limit`: Concurrency pool for fan-out requests +- `p-retry`: Retry logic with exponential backoff +- `zod`: Runtime schema validation and type inference + +## Next Steps + +After installation, you'll need to: + +1. Set up your [authentication token](/sdk/js/authentication) +2. Learn about the [client](/sdk/js/client) and how to make your first API requests +3. Configure [settings](/sdk/js/settings) to customize output format, date format, and other universal parameters diff --git a/sdk/js/markets/index.mdx b/sdk/js/markets/index.mdx new file mode 100644 index 0000000..c3d6a40 --- /dev/null +++ b/sdk/js/markets/index.mdx @@ -0,0 +1,14 @@ +--- +title: Markets +slug: /js/markets +sidebar_position: 40 +--- + +The JavaScript SDK from Market Data provides methods designed to streamline your use of the following Markets endpoints. These intuitive methods provide a seamless interface for accessing market status information. + +## Markets Endpoints + +import DocCardList from "@theme/DocCardList"; +import { useCurrentSidebarCategory } from "@docusaurus/theme-common"; + + diff --git a/sdk/js/markets/status.mdx b/sdk/js/markets/status.mdx new file mode 100644 index 0000000..97dc204 --- /dev/null +++ b/sdk/js/markets/status.mdx @@ -0,0 +1,176 @@ +--- +title: Status +sidebar_position: 1 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Retrieve market status information (open/closed) for dates and countries. + +## Making Requests + +Use the `status()` method on the `markets` resource to fetch market status information. + +| Output Format | Result Payload | Description | +|------------------------|-------------------------------------------|-------------------------------------------------| +| **internal** (default) | `MarketStatus[]` or `MarketStatusHuman[]` | Array of decoded market-status records. | +| **json** | Raw JSON object | The compressed, array-keyed response object. | +| **csv** | `Blob` | CSV payload. Use `.save(filename)` to write it. | + + +## status + +```typescript +status

( + params?: P, +): MarketDataResult +``` + +Fetches market status information. All parameters are optional. + +#### 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`](/sdk/js/settings#output-format) (optional): The format of the returned data. Alias: `format`. +- [`dateFormat`](/sdk/js/settings#date-format) (optional): Date format. Alias: `dateformat`. +- [`columns`](/sdk/js/settings#columns) (optional): Columns to include. +- [`addHeaders`](/sdk/js/settings#headers) (optional): Whether to include headers in CSV output. Alias: `headers`. +- [`useHumanReadable`](/sdk/js/settings#human-readable) (optional): Use human-readable field names. Alias: `human`. +- [`mode`](/sdk/js/settings#data-mode) (optional): The data mode to use. + +#### Returns + +- [`MarketDataResult`](/sdk/js/client#MarketDataResult) + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.markets.status(); + +result.match( + (days) => { + for (const d of days) { + console.log(`date=${d.date} status=${d.status}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.markets.status({ + from: "2024-01-01", + to: "2024-01-31", + country: "US", +}); + +result.match( + (days) => console.log(days), + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +// Last 7 trading-status days +const result = await client.markets.status({ countback: 7 }); + +result.match( + (days) => console.log(days), + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.markets.status({ countback: 7, human: true }); + +result.match( + (days) => { + for (const d of days) { + console.log(`Date=${d.Date} Status=${d.Status}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +## MarketStatus + +```typescript +interface MarketStatus { + s?: string; + date: number; + status: string; +} +``` + +#### Properties + +- `s` (string, optional): Status indicator. +- `date` (number): Unix timestamp of the trading day. +- `status` (string): Market status (e.g. `"open"`, `"closed"`). + + +## MarketStatusHuman + +```typescript +interface MarketStatusHuman { + s?: string; + Date: number; + Status: string; +} +``` + +`MarketStatusHuman` is returned when `human: true` is set. diff --git a/sdk/js/options/chain.mdx b/sdk/js/options/chain.mdx new file mode 100644 index 0000000..dbd99f5 --- /dev/null +++ b/sdk/js/options/chain.mdx @@ -0,0 +1,269 @@ +--- +title: Chain +sidebar_position: 1 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Retrieve the full option chain — every call and put contract — for any supported underlying symbol, with extensive filtering options. + +## Making Requests + +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. + +| Output Format | Result Payload | Description | +|------------------------|-------------------------------------------|-------------------------------------------------| +| **internal** (default) | `OptionsChain[]` or `OptionsChainHuman[]` | Array of decoded option-contract records. | +| **json** | Raw JSON object | The compressed, array-keyed response object. | +| **csv** | `Blob` | CSV payload. Use `.save(filename)` to write it. | + + +## chain + +```typescript +// Positional form +chain

( + symbol: string, + params?: P, +): MarketDataResult + +// Object form +chain

( + params: P & { symbol: string }, +): MarketDataResult +``` + +Fetches the option chain for a single underlying symbol. + +#### Parameters + +- `symbol` (string) + + 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. + +- `days_to_expiration` (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. + +- `strike_limit` (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"`). + +- `min_bid` / `max_bid` / `min_ask` / `max_ask` (number, optional) + + Filter by quote price thresholds. + +- `max_bid_ask_spread` (number, optional), `max_bid_ask_spread_pct` (number, optional) + + Filter by spread thresholds. + +- `min_open_interest` (number, optional), `min_volume` (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`](/sdk/js/settings#output-format) (optional): The format of the returned data. Alias: `format`. +- [`dateFormat`](/sdk/js/settings#date-format) (optional): Date format. Alias: `dateformat`. +- [`columns`](/sdk/js/settings#columns) (optional): Columns to include. +- [`addHeaders`](/sdk/js/settings#headers) (optional): Whether to include headers in CSV output. Alias: `headers`. +- [`useHumanReadable`](/sdk/js/settings#human-readable) (optional): Use human-readable field names. Alias: `human`. +- [`mode`](/sdk/js/settings#data-mode) (optional): The data mode to use. + +#### Returns + +- [`MarketDataResult`](/sdk/js/client#MarketDataResult) + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.options.chain("AAPL"); + +result.match( + (contracts) => console.log(`Got ${contracts.length} contracts`), + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +// Calls only, narrow strike window, high open interest +const result = await client.options.chain("AAPL", { + side: "call", + strike_limit: 10, + min_open_interest: 100, +}); + +result.match( + (contracts) => { + for (const c of contracts) { + console.log( + `${c.optionSymbol} strike=${c.strike} mid=${c.mid} delta=${c.delta} oi=${c.openInterest}` + ); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.options.chain("AAPL", { + date: "2024-01-15", + expiration: "2024-02-16", + side: "call", +}); + +result.match( + (contracts) => console.log(contracts), + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.options.chain("AAPL", { + side: "put", + human: true, +}); + +result.match( + (contracts) => { + for (const c of contracts) { + console.log( + `${c.Symbol} Strike=${c.Strike} Mid=${c.Mid} Delta=${c.Delta}` + ); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +## OptionsChain + +```typescript +interface OptionsChain { + s?: string; + optionSymbol: string; + underlying: string; + expiration: number; + side: string; + strike: number; + firstTraded: number; + dte: number; + updated: number; + bid: number | null; + bidSize: number | null; + mid: number | null; + ask: number | null; + askSize: number | null; + last: number | null; + openInterest: number | null; + volume: number | null; + inTheMoney: boolean; + intrinsicValue: number; + extrinsicValue: number; + underlyingPrice: number; + iv: number | null; + delta: number | null; + gamma: number | null; + theta: number | null; + vega: number | null; +} +``` + +#### Properties + +- `optionSymbol` (string): OCC-format option symbol (e.g. `"AAPL271217C00250000"`). +- `underlying` (string): The underlying stock symbol. +- `expiration` (number): Unix timestamp of the expiration date. +- `side` (string): `"call"` or `"put"`. +- `strike` (number): The strike price. +- `firstTraded` (number): Unix timestamp when the contract first traded. +- `dte` (number): Days to expiration. +- `updated` (number): Unix timestamp when the quote was last updated. +- `bid`, `ask`, `mid`, `last` (number | null): Quote prices. +- `bidSize`, `askSize` (number | null): Quote sizes. +- `openInterest`, `volume` (number | null): Liquidity metrics. +- `inTheMoney` (boolean): Whether the contract is currently in the money. +- `intrinsicValue`, `extrinsicValue` (number): Value decomposition. +- `underlyingPrice` (number): Price of the underlying at quote time. +- `iv`, `delta`, `gamma`, `theta`, `vega` (number | null): Implied volatility and Greeks. + + +## OptionsChainHuman + +When `human: true` is set, field names are returned in `Title_Case`: `Symbol`, `Underlying`, `Expiration_Date`, `Option_Side`, `Strike`, `Days_To_Expiration`, `Bid`, `Ask`, `Mid`, `Open_Interest`, `Volume`, `In_The_Money`, `IV`, `Delta`, `Gamma`, `Theta`, `Vega`, etc. diff --git a/sdk/js/options/expirations.mdx b/sdk/js/options/expirations.mdx new file mode 100644 index 0000000..7606878 --- /dev/null +++ b/sdk/js/options/expirations.mdx @@ -0,0 +1,148 @@ +--- +title: Expirations +sidebar_position: 3 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Retrieve the list of current or historical option expiration dates for a given underlying symbol. + +## Making Requests + +Use the `expirations()` method on the `options` resource to fetch available expiration dates. + +| Output Format | Result Payload | Description | +|------------------------|-------------------------------------------------------------------|------------------------------------------| +| **internal** (default) | `OptionsExpirationsResponse` or `OptionsExpirationsHumanResponse` | Object with the list of expirations. | +| **json** | Raw JSON object | The raw response as returned by the API. | + + +## expirations + +```typescript +// Positional form +expirations

( + symbol: string, + params?: P, +): MarketDataResult + +// Object form +expirations

( + params: P & { symbol: string }, +): MarketDataResult +``` + +Fetches the list of expirations for a single underlying symbol. + +#### Parameters + +- `symbol` (string) + + The underlying stock symbol. + +- `strike` (number, optional) + + Filter to expirations that have at least one contract at the given strike. + +- `date` (string | Date, optional) + + Fetch expirations as-of a specific historical date. + +- [`outputFormat`](/sdk/js/settings#output-format) (optional): The format of the returned data. Alias: `format`. +- [`dateFormat`](/sdk/js/settings#date-format) (optional): Date format. Alias: `dateformat`. +- [`columns`](/sdk/js/settings#columns) (optional): Columns to include. +- [`useHumanReadable`](/sdk/js/settings#human-readable) (optional): Use human-readable field names. Alias: `human`. + +#### Returns + +- [`MarketDataResult`](/sdk/js/client#MarketDataResult) + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.options.expirations("AAPL"); + +result.match( + (data) => { + console.log(`Updated: ${data.updated}`); + for (const exp of data.expirations) { + console.log(exp); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +// Only expirations that trade the $250 strike +const result = await client.options.expirations("AAPL", { strike: 250 }); + +result.match( + (data) => console.log(data.expirations), + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.options.expirations("AAPL", { human: true }); + +result.match( + (data) => console.log(data.Expirations), + (error) => console.error(error.message), +); +``` + + + + + +## OptionsExpirationsResponse + +```typescript +interface OptionsExpirationsResponse { + s: string; + expirations: string[]; + updated: number; +} +``` + +#### Properties + +- `s` (string): Status indicator. +- `expirations` (string[]): List of expiration dates in `YYYY-MM-DD` format. +- `updated` (number): Unix timestamp when the data was last updated. + + +## OptionsExpirationsHumanResponse + +```typescript +interface OptionsExpirationsHumanResponse { + s?: string; + Expirations: string[]; + Date: number; +} +``` + +`OptionsExpirationsHumanResponse` is returned when `human: true` is set. diff --git a/sdk/js/options/index.mdx b/sdk/js/options/index.mdx new file mode 100644 index 0000000..6169c7e --- /dev/null +++ b/sdk/js/options/index.mdx @@ -0,0 +1,14 @@ +--- +title: Options +slug: /js/options +sidebar_position: 20 +--- + +The JavaScript SDK from Market Data provides methods designed to streamline your use of the following Options endpoints. These intuitive methods provide a seamless interface for accessing options data including chains, expirations, quotes, and lookup functionality. + +## Options Endpoints + +import DocCardList from "@theme/DocCardList"; +import { useCurrentSidebarCategory } from "@docusaurus/theme-common"; + + diff --git a/sdk/js/options/lookup.mdx b/sdk/js/options/lookup.mdx new file mode 100644 index 0000000..a5cddaa --- /dev/null +++ b/sdk/js/options/lookup.mdx @@ -0,0 +1,111 @@ +--- +title: Lookup +sidebar_position: 4 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Convert a human-readable option description (e.g. `"AAPL 7/28/2023 200 Call"`) into its standard OCC option symbol. + +## Making Requests + +Use the `lookup()` method on the `options` resource to resolve an OCC symbol from a natural-language description. The URL-encoded lookup string is handled for you by the SDK. + + +## lookup + +```typescript +// Positional form +lookup

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

( + params: P & { lookup: string }, +): MarketDataResult +``` + +Resolves a human-readable option description to its OCC symbol. + +#### Parameters + +- `lookupStr` (string) + + A natural-language description of the option contract (e.g. `"AAPL 7/28/2023 200 Call"`, `"TSLA Jan 2025 300 Put"`). + +- [`outputFormat`](/sdk/js/settings#output-format) (optional): The format of the returned data. Alias: `format`. +- [`useHumanReadable`](/sdk/js/settings#human-readable) (optional): Use human-readable field names. Alias: `human`. + +#### Returns + +- [`MarketDataResult`](/sdk/js/client#MarketDataResult) + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.options.lookup("AAPL 7/28/2023 200 Call"); + +result.match( + (data) => console.log(data.optionSymbol), // "AAPL230728C00200000" + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.options.lookup("AAPL 7/28/2023 200 Call", { + human: true, +}); + +result.match( + (data) => console.log(data.Symbol), + (error) => console.error(error.message), +); +``` + + + + + +## OptionsLookupResponse + +```typescript +interface OptionsLookupResponse { + s: string; + optionSymbol: string; + updated?: number; +} +``` + +#### Properties + +- `s` (string): Status indicator. +- `optionSymbol` (string): The OCC-format option symbol. +- `updated` (number, optional): Unix timestamp when the lookup resolved. + + +## OptionsLookupHumanResponse + +```typescript +interface OptionsLookupHumanResponse { + s?: string; + Symbol: string; +} +``` + +`OptionsLookupHumanResponse` is returned when `human: true` is set. diff --git a/sdk/js/options/quotes.mdx b/sdk/js/options/quotes.mdx new file mode 100644 index 0000000..61ae8bb --- /dev/null +++ b/sdk/js/options/quotes.mdx @@ -0,0 +1,136 @@ +--- +title: Quotes +sidebar_position: 2 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Retrieve quotes for one or more specific option contracts, including full Greeks. + +## Making Requests + +Use the `quotes()` method on the `options` resource to fetch quotes for individual option contracts identified by their OCC symbol. When multiple symbols are provided, the SDK fans out concurrently and merges the results. + +| Output Format | Result Payload | Description | +|------------------------|---------------------------------------------|---------------------------------------------------| +| **internal** (default) | `OptionsQuotes[]` or `OptionsQuotesHuman[]` | Array of decoded quote records, one per contract. | +| **json** | Raw JSON object | The compressed, array-keyed response object. | +| **csv** | `Blob` | CSV payload. Use `.save(filename)` to write it. | + + +## quotes + +```typescript +// Positional form +quotes

( + symbols: string | string[], + params?: P, +): MarketDataResult + +// Object form +quotes

( + params: P & { symbols: string | string[] }, +): MarketDataResult +``` + +Fetches quotes for one or more option contracts. + +#### Parameters + +- `symbols` (string | string[]) + + A single OCC-format option symbol (e.g. `"AAPL271217C00250000"`) or an array of symbols. When you pass an array, the SDK fetches each contract concurrently and merges the results. + +- [`outputFormat`](/sdk/js/settings#output-format) (optional): The format of the returned data. Alias: `format`. +- [`dateFormat`](/sdk/js/settings#date-format) (optional): Date format. Alias: `dateformat`. +- [`columns`](/sdk/js/settings#columns) (optional): Columns to include. +- [`addHeaders`](/sdk/js/settings#headers) (optional): Whether to include headers in CSV output. Alias: `headers`. +- [`useHumanReadable`](/sdk/js/settings#human-readable) (optional): Use human-readable field names. Alias: `human`. +- [`mode`](/sdk/js/settings#data-mode) (optional): The data mode to use. + +Additional endpoint-specific parameters like `from`, `to`, and `date` are passed through to the REST API. See [REST API Options Quotes](/api/options/quotes) for the full list. + +#### Returns + +- [`MarketDataResult`](/sdk/js/client#MarketDataResult) + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.options.quotes("AAPL271217C00250000"); + +result.match( + (quotes) => { + const q = quotes[0]; + console.log( + `${q.optionSymbol}: bid=${q.bid} ask=${q.ask} delta=${q.delta}` + ); + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.options.quotes([ + "AAPL271217C00250000", + "AAPL271217P00250000", + "AAPL271217C00300000", +]); + +result.match( + (quotes) => { + for (const q of quotes) { + console.log(`${q.optionSymbol}: mid=${q.mid}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.options.quotes("AAPL271217C00250000", { + human: true, +}); + +result.match( + (quotes) => console.log(quotes[0]), + (error) => console.error(error.message), +); +``` + + + + + +## OptionsQuotes + +`OptionsQuotes` uses the same field shape as [`OptionsChain`](/sdk/js/options/chain#OptionsChain): `optionSymbol`, `underlying`, `expiration`, `side`, `strike`, `bid`, `ask`, `mid`, `last`, `openInterest`, `volume`, `inTheMoney`, `intrinsicValue`, `extrinsicValue`, `iv`, `delta`, `gamma`, `theta`, `vega`, and so on. + +See [OptionsChain](/sdk/js/options/chain#OptionsChain) for the complete list of fields. + + +## OptionsQuotesHuman + +`OptionsQuotesHuman` is returned when `human: true` is set. Field shape mirrors [`OptionsChainHuman`](/sdk/js/options/chain#OptionsChainHuman) — same columns, `Title_Case` names. diff --git a/sdk/js/settings.mdx b/sdk/js/settings.mdx new file mode 100644 index 0000000..7840097 --- /dev/null +++ b/sdk/js/settings.mdx @@ -0,0 +1,326 @@ +--- +title: Settings +sidebar_position: 4 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +The Market Data JavaScript SDK provides flexible configuration for customizing API requests. You can configure universal parameters like output format, date format, data mode, and more through multiple methods with different priority levels. + +## Configuration Priority + +The SDK supports three ways to configure universal parameters, with a clear priority hierarchy. + +### Priority Order (Lowest to Highest) + +1. **Environment Variables** (lowest priority) + - Read from variables like `MARKETDATA_OUTPUT_FORMAT`, `MARKETDATA_DATE_FORMAT`, etc. + - A `.env` file in your working directory is loaded automatically via [`dotenv`](https://github.com/motdotla/dotenv). + - Applied globally to all API calls unless overridden. + +2. **Client Constructor Arguments** (medium priority) + - Set via the `MarketDataConfig` object passed to `new MarketDataClient({ ... })`. + - Applied to all API calls made with that client instance unless overridden. + - Only applies to config-level settings (`token`, `baseUrl`, `apiVersion`, retry options). + +3. **Direct Method Parameters** (highest priority) + - Passed directly as parameters to resource methods. + - Applied only to that specific API call. + +### How It Works + +When making an API call, the SDK merges parameters in this order: + +1. **Start with environment variables** (lowest priority) + - Values are read from `MARKETDATA_*` variables on startup. + +2. **Override with constructor arguments** (medium priority) + - Values passed to `new MarketDataClient({ ... })` replace env values for config-level settings. + +3. **Override with direct method parameters** (highest priority) + - Parameters passed directly to resource methods like `client.stocks.prices("AAPL", { human: true })` take final priority. + +### Examples + + + + +Set universal parameters via environment variables: + +```bash +export MARKETDATA_OUTPUT_FORMAT=json +export MARKETDATA_DATE_FORMAT=timestamp +export MARKETDATA_USE_HUMAN_READABLE=true +``` + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +// All calls will use the env-var defaults unless overridden. +const result = await client.stocks.prices("AAPL"); +``` + + + + + +Set client-level configuration via the constructor: + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +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, +}); +``` + +Constructor arguments override environment variables for the settings they cover. + + + + + +Pass parameters directly to resource methods: + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +// Override per call — these parameters apply to this request only. +const result = await client.stocks.prices("AAPL", { + human: true, + dateformat: "timestamp", + columns: ["ask", "bid", "mid"], +}); +``` + +Direct method parameters override both environment variables and constructor arguments. + + + + +## Available Configuration Options + +### Output Format + +Controls the format of the API response data. + +**Available Values:** +- `"internal"` (default): Returns decoded plain JavaScript objects (the array-keyed wire format is unpacked into one record per row). +- `"json"`: Returns the raw JSON response from the API, without unpacking. +- `"csv"`: Returns a `Blob` containing CSV data. Use `.save(filename)` on the result to write it to disk. + +The SDK also exposes an `OutputFormat` enum you can import for type safety: + +```typescript +import { OutputFormat } from "marketdata-sdk-js"; +// OutputFormat.INTERNAL, OutputFormat.JSON, OutputFormat.CSV +``` + +**Configuration Methods:** + +1. **Environment Variable:** `MARKETDATA_OUTPUT_FORMAT` (values: `internal`, `json`, `csv`) +2. **Per-call parameter:** `format: "csv"` or `outputFormat: "csv"` + +**Example:** + +```typescript +import { MarketDataClient, OutputFormat } from "marketdata-sdk-js"; + +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 +``` + +For more details, see the [API Format documentation](/api/universal-parameters/format). + +### Date Format + +Specifies the format for date and time information in responses. + +**Available Values:** +- `"timestamp"`: ISO 8601 timestamp format (e.g., `2020-12-30 16:00:00 -05:00`) +- `"unix"`: Unix timestamp in seconds (e.g., `1609362000`) +- `"spreadsheet"`: Excel spreadsheet format (e.g., `44195.66667`) + +The SDK also exposes a `DateFormat` enum: + +```typescript +import { DateFormat } from "marketdata-sdk-js"; +// DateFormat.TIMESTAMP, DateFormat.UNIX, DateFormat.SPREADSHEET +``` + +**Configuration Methods:** + +1. **Environment Variable:** `MARKETDATA_DATE_FORMAT` (values: `timestamp`, `unix`, `spreadsheet`) +2. **Per-call parameter:** `dateformat: "unix"` or `dateFormat: "unix"` + +**Example:** + +```typescript +import { MarketDataClient, DateFormat } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const candles = await client.stocks.candles("AAPL", { dateFormat: DateFormat.TIMESTAMP }); +``` + +For more details, see the [API Date Format documentation](/api/universal-parameters/date-format). + +### Columns + +Limits the response to only the columns you need, reducing data transfer and processing time. + +**Type:** `string[]` + +**Configuration Methods:** + +1. **Environment Variable:** `MARKETDATA_COLUMNS` (comma-separated list, e.g., `ask,bid`) +2. **Per-call parameter:** `columns: ["ask", "bid"]` + +**Example:** + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const quotes = await client.stocks.quotes("AAPL", { columns: ["ask", "bid"] }); +``` + +For more details, see the [API Columns documentation](/api/universal-parameters/columns). + +### Headers + +Controls whether headers are included in CSV output. + +**Type:** `boolean` + +**Default:** `true` + +**Configuration Methods:** + +1. **Environment Variable:** `MARKETDATA_ADD_HEADERS` (values: `true`, `false`) +2. **Per-call parameter:** `headers: false` or `addHeaders: false` + +**Example:** + +```typescript +import { MarketDataClient, OutputFormat } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const csv = await client.stocks.candles("AAPL", { + outputFormat: OutputFormat.CSV, + addHeaders: false, +}); +``` + +For more details, see the [API Headers documentation](/api/universal-parameters/headers). + +### Human Readable + +Uses human-readable field names in responses instead of short, machine-friendly ones. Field names are returned in `Title_Case` (e.g. `Symbol`, `Change_Price`) rather than `camelCase`. + +**Type:** `boolean` + +**Default:** `false` + +**Configuration Methods:** + +1. **Environment Variable:** `MARKETDATA_USE_HUMAN_READABLE` (values: `true`, `false`) +2. **Per-call parameter:** `human: true` or `useHumanReadable: true` + +**Example:** + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const quotes = await client.stocks.quotes("AAPL", { human: true }); + +quotes.match( + (data) => console.log(data[0].Symbol, data[0].Mid), + (err) => console.error(err.message), +); +``` + +For more details, see the [API Human Readable documentation](/api/universal-parameters/human-readable). + +### Data Mode + +Controls whether the API returns live, cached, or delayed data. + +**Available Values:** +- `"live"`: Real-time data (paid plans). +- `"cached"`: Cached data. Lower cost per request; honours an optional `maxage` freshness window. +- `"delayed"`: 15+ minute delayed data. + +The SDK also exposes a `Mode` enum: + +```typescript +import { Mode } from "marketdata-sdk-js"; +// Mode.LIVE, Mode.CACHED, Mode.DELAYED +``` + +**Configuration Methods:** + +1. **Environment Variable:** `MARKETDATA_MODE` (values: `live`, `cached`, `delayed`) +2. **Per-call parameter:** `mode: "cached"` + +**Example:** + +```typescript +import { MarketDataClient, Mode } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const quotes = await client.stocks.quotes("AAPL", { mode: Mode.CACHED }); +``` + +For more details, see the [API Data Mode documentation](/api/universal-parameters/mode). + +## Environment Variables Reference + +| Variable | Purpose | Default | +|---------------------------------|-------------------------------------------|------------------------------| +| `MARKETDATA_TOKEN` | API authentication token | _(none)_ | +| `MARKETDATA_BASE_URL` | API base URL | `https://api.marketdata.app` | +| `MARKETDATA_API_VERSION` | API version | `v1` | +| `MARKETDATA_OUTPUT_FORMAT` | Default output format | `internal` | +| `MARKETDATA_DATE_FORMAT` | Default date format | _(API default)_ | +| `MARKETDATA_USE_HUMAN_READABLE` | Use human-readable field names by default | `false` | +| `MARKETDATA_ADD_HEADERS` | Include headers in CSV output | `true` | +| `MARKETDATA_MODE` | Default data mode | _(API default)_ | +| `MARKETDATA_MAX_RETRIES` | Maximum retry attempts | `3` | +| `MARKETDATA_RETRY_INITIAL_WAIT` | Initial retry wait (seconds) | `0.5` | +| `MARKETDATA_RETRY_MAX_WAIT` | Maximum retry wait (seconds) | `10` | +| `MARKETDATA_RETRY_FACTOR` | Exponential backoff factor | `2` | + +## Parameter Aliases + +For convenience, the SDK accepts both the short form used by the REST API and the camelCase TypeScript form. Both resolve to the same underlying parameter: + +| Short (REST style) | Long (camelCase) | +|--------------------|--------------------| +| `dateformat` | `dateFormat` | +| `format` | `outputFormat` | +| `headers` | `addHeaders` | +| `human` | `useHumanReadable` | diff --git a/sdk/js/stocks/candles.mdx b/sdk/js/stocks/candles.mdx new file mode 100644 index 0000000..0f18db5 --- /dev/null +++ b/sdk/js/stocks/candles.mdx @@ -0,0 +1,222 @@ +--- +title: Candles +sidebar_position: 3 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Retrieve historical OHLCV (open/high/low/close/volume) candles for any supported stock symbol. + +## Making Requests + +Use the `candles()` method on the `stocks` resource to fetch candles. The method handles large intraday date ranges automatically by splitting them into year-sized chunks and fetching them concurrently (up to 50 in-flight at once), then merging the results. + +| Output Format | Result Payload | Description | +|------------------------|-----------------------------------------|-------------------------------------------------| +| **internal** (default) | `StockCandle[]` or `StockCandleHuman[]` | Array of decoded candle records, one per bar. | +| **json** | Raw JSON object | The compressed, array-keyed response object. | +| **csv** | `Blob` | CSV payload. Use `.save(filename)` to write it. | + + +## candles + +```typescript +// Positional form +candles

( + symbol: string, + params?: P, +): MarketDataResult + +// Object form +candles

( + params: P & { symbol: string }, +): MarketDataResult +``` + +Fetches historical candles for a single symbol. + +#### Parameters + +- `symbol` (string) + + The stock symbol to fetch candles for. + +- `resolution` (string, optional, default `"D"`) + + The candle resolution. Common values: + - Minute-based: `"1"`, `"5"`, `"15"`, `"30"`, `"45"`, `"minutely"` + - Hour-based: `"H"`, `"1H"`, `"2H"`, `"hourly"` + - Day-and-up: `"D"`, `"daily"`, `"W"`, `"weekly"`, `"M"`, `"monthly"`, `"Y"`, `"yearly"` + +- `from` (string | Date, optional) + + Start of the date range. Accepts ISO strings, Unix seconds as a string, or a `Date`. + +- `to` (string | Date, optional) + + End of the date range. Accepts ISO strings, Unix seconds as a string, or a `Date`. + +- `countback` (number, optional) + + Fetch `N` candles before `to` (mutually exclusive with `from`). + +- `extended` (boolean, optional) + + Include extended-hours data for intraday resolutions. + +- `adjustsplits` (boolean, optional) + + Adjust historical prices for splits. + +- [`outputFormat`](/sdk/js/settings#output-format) (optional): The format of the returned data. Alias: `format`. +- [`dateFormat`](/sdk/js/settings#date-format) (optional): Date format for response timestamps. Alias: `dateformat`. +- [`columns`](/sdk/js/settings#columns) (optional): Columns to include. +- [`addHeaders`](/sdk/js/settings#headers) (optional): Whether to include headers in CSV output. Alias: `headers`. +- [`useHumanReadable`](/sdk/js/settings#human-readable) (optional): Use human-readable field names. Alias: `human`. +- [`mode`](/sdk/js/settings#data-mode) (optional): The data mode to use. + +#### Returns + +- [`MarketDataResult`](/sdk/js/client#MarketDataResult) + +#### Notes + +- For intraday resolutions (minute- or hour-based), date ranges longer than 365 days are split into yearly chunks and fetched concurrently. The individual responses are merged back into a single chronologically ordered result. +- Up to 50 chunks can be in flight simultaneously (sliding window, not batching). + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +// Default resolution is "D" (daily) +const result = await client.stocks.candles("AAPL", { countback: 30 }); + +result.match( + (candles) => { + for (const c of candles) { + console.log(`t=${c.t} o=${c.o} h=${c.h} l=${c.l} c=${c.c} v=${c.v}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +// Hourly candles over a multi-year range. +// The SDK automatically splits into year-sized chunks +// and fetches them concurrently. +const result = await client.stocks.candles("AAPL", { + resolution: "1H", + from: new Date("2023-01-01"), + to: new Date("2024-12-31"), +}); + +result.match( + (candles) => console.log(`Got ${candles.length} bars`), + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.candles("AAPL", { + resolution: "D", + countback: 10, + human: true, +}); + +result.match( + (candles) => { + for (const c of candles) { + console.log(`Date=${c.Date} Open=${c.Open} Close=${c.Close}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient, OutputFormat } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.candles("AAPL", { + resolution: "D", + countback: 100, + outputFormat: OutputFormat.CSV, +}); + +const filename = await result.save("aapl_daily.csv"); +console.log(`CSV saved to: ${filename}`); +``` + + + + + +## StockCandle + +```typescript +interface StockCandle { + s?: string; + t: number; // timestamp + o: number; // open + h: number; // high + l: number; // low + c: number; // close + v: number; // volume +} +``` + +`StockCandle` uses the API's short, machine-readable field names. + +#### Properties + +- `s` (string, optional): Status indicator. +- `t` (number): Unix timestamp of the bar. +- `o` (number): Opening price. +- `h` (number): High price. +- `l` (number): Low price. +- `c` (number): Closing price. +- `v` (number): Volume. + + +## StockCandleHuman + +```typescript +interface StockCandleHuman { + s?: string; + Date: number; + Open: number; + High: number; + Low: number; + Close: number; + Volume: number; +} +``` + +`StockCandleHuman` is returned when `human: true` is set. diff --git a/sdk/js/stocks/earnings.mdx b/sdk/js/stocks/earnings.mdx new file mode 100644 index 0000000..6a146c0 --- /dev/null +++ b/sdk/js/stocks/earnings.mdx @@ -0,0 +1,166 @@ +--- +title: Earnings +sidebar_position: 4 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Retrieve historical and upcoming earnings information for any supported stock symbol. + +## Making Requests + +Use the `earnings()` method on the `stocks` resource to fetch earnings data. + +| Output Format | Result Payload | Description | +|------------------------|---------------------------------------------|-------------------------------------------------| +| **internal** (default) | `StockEarnings[]` or `StockEarningsHuman[]` | Array of decoded earnings records. | +| **json** | Raw JSON object | The compressed, array-keyed response object. | +| **csv** | `Blob` | CSV payload. Use `.save(filename)` to write it. | + + +## earnings + +```typescript +// Positional form +earnings

( + symbol: string, + params?: P, +): MarketDataResult + +// Object form +earnings

( + params: P & { symbol: string }, +): MarketDataResult +``` + +Fetches earnings data for a single symbol. + +#### Parameters + +- `symbol` (string) + + The stock symbol to fetch earnings for. + +- [`outputFormat`](/sdk/js/settings#output-format) (optional): The format of the returned data. Alias: `format`. +- [`dateFormat`](/sdk/js/settings#date-format) (optional): Date format for response timestamps. Alias: `dateformat`. +- [`columns`](/sdk/js/settings#columns) (optional): Columns to include. +- [`addHeaders`](/sdk/js/settings#headers) (optional): Whether to include headers in CSV output. Alias: `headers`. +- [`useHumanReadable`](/sdk/js/settings#human-readable) (optional): Use human-readable field names. Alias: `human`. +- [`mode`](/sdk/js/settings#data-mode) (optional): The data mode to use. + +Additional endpoint-specific parameters (e.g. `from`, `to`, `date`) are passed through to the REST API as-is. See the [REST API Earnings documentation](/api/stocks/earnings) for the complete list. + +#### Returns + +- [`MarketDataResult`](/sdk/js/client#MarketDataResult) + +:::info +Earnings data is a premium endpoint on the Market Data API. Your plan must include earnings access for this method to return data. +::: + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.earnings("AAPL"); + +result.match( + (earnings) => { + for (const e of earnings) { + console.log( + `FY${e.fiscalYear} Q${e.fiscalQuarter}: ` + + `reported=${e.reportedEPS} estimated=${e.estimatedEPS}` + ); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.earnings("AAPL", { human: true }); + +result.match( + (earnings) => { + for (const e of earnings) { + console.log(`${e.Symbol} FY${e.Fiscal_Year} Q${e.Fiscal_Quarter}: ${e.Reported_EPS}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +## StockEarnings + +```typescript +interface StockEarnings { + s?: string; + symbol: string; + fiscalYear: number; + fiscalQuarter: number; + date: number; + reportDate: number; + reportTime: string | null; + currency: string | null; + reportedEPS: number | null; + estimatedEPS: number | null; + surpriseEPS: number | null; + surpriseEPSpct: number | null; + updated: number; +} +``` + +#### Properties + +- `symbol` (string): The stock symbol. +- `fiscalYear` (number): The fiscal year of the earnings report. +- `fiscalQuarter` (number): The fiscal quarter (1–4). +- `date` (number): Unix timestamp of the earnings event. +- `reportDate` (number): Unix timestamp when the earnings were reported. +- `reportTime` (string | null): Time of day the earnings were reported (e.g. `"bmo"`, `"amc"`). +- `currency` (string | null): Currency of the EPS figures. +- `reportedEPS` (number | null): The actual reported earnings per share. +- `estimatedEPS` (number | null): The analyst consensus estimate. +- `surpriseEPS` (number | null): The difference between reported and estimated EPS. +- `surpriseEPSpct` (number | null): The surprise as a fraction of the estimate. +- `updated` (number): Unix timestamp when the record was last updated. + + +## StockEarningsHuman + +```typescript +interface StockEarningsHuman { + s?: string; + Symbol: string; + Fiscal_Year: number; + Fiscal_Quarter: number; + Date: number; + Report_Date: number; + Report_Time: string | null; + Currency: string | null; + Reported_EPS: number | null; + Estimated_EPS: number | null; + Surprise_EPS: number | null; + Surprise_EPS_Percent: number | null; + Updated: number; +} +``` + +`StockEarningsHuman` is returned when `human: true` is set. Field names use `Title_Case`. diff --git a/sdk/js/stocks/index.mdx b/sdk/js/stocks/index.mdx new file mode 100644 index 0000000..dfd8ca8 --- /dev/null +++ b/sdk/js/stocks/index.mdx @@ -0,0 +1,14 @@ +--- +title: Stocks +slug: /js/stocks +sidebar_position: 10 +--- + +The JavaScript SDK from Market Data provides methods designed to streamline your use of the following Stocks endpoints. These intuitive methods provide a seamless interface, effectively masking the intricacies involved in managing HTTP requests and responses. + +## Stocks Endpoints + +import DocCardList from "@theme/DocCardList"; +import { useCurrentSidebarCategory } from "@docusaurus/theme-common"; + + diff --git a/sdk/js/stocks/news.mdx b/sdk/js/stocks/news.mdx new file mode 100644 index 0000000..bf58680 --- /dev/null +++ b/sdk/js/stocks/news.mdx @@ -0,0 +1,140 @@ +--- +title: News +sidebar_position: 5 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Retrieve news articles for any supported stock symbol. + +## Making Requests + +Use the `news()` method on the `stocks` resource to fetch news. + +| Output Format | Result Payload | Description | +|------------------------|-------------------------------------|-------------------------------------------------| +| **internal** (default) | `StockNews[]` or `StockNewsHuman[]` | Array of decoded news articles. | +| **json** | Raw JSON object | The compressed, array-keyed response object. | +| **csv** | `Blob` | CSV payload. Use `.save(filename)` to write it. | + + +## news + +```typescript +// Positional form +news

( + symbol: string, + params?: P, +): MarketDataResult + +// Object form +news

( + params: P & { symbol: string }, +): MarketDataResult +``` + +Fetches news articles for a single symbol. + +#### Parameters + +- `symbol` (string) + + The stock symbol to fetch news for. + +- `from` (string | Date, optional) + + Start of the date range for news articles. + +- `to` (string | Date, optional) + + End of the date range for news articles. + +- `date` (string | Date, optional) + + Fetch news for a specific date. + +- `countback` (number, optional) + + Number of articles to return, counting backwards from `to`. + +- [`outputFormat`](/sdk/js/settings#output-format) (optional): The format of the returned data. Alias: `format`. +- [`dateFormat`](/sdk/js/settings#date-format) (optional): Date format. Alias: `dateformat`. +- [`columns`](/sdk/js/settings#columns) (optional): Columns to include. +- [`addHeaders`](/sdk/js/settings#headers) (optional): Whether to include headers in CSV output. Alias: `headers`. +- [`useHumanReadable`](/sdk/js/settings#human-readable) (optional): Use human-readable field names. Alias: `human`. +- [`mode`](/sdk/js/settings#data-mode) (optional): The data mode to use. + +#### Returns + +- [`MarketDataResult`](/sdk/js/client#MarketDataResult) + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.news("AAPL"); + +result.match( + (articles) => { + for (const a of articles) { + console.log(`${a.source}: ${a.headline}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.news("AAPL", { + from: "2024-01-01", + to: "2024-01-31", +}); + +result.match( + (articles) => console.log(`Got ${articles.length} articles`), + (error) => console.error(error.message), +); +``` + + + + + +## StockNews + +```typescript +interface StockNews { + s?: string; + symbol: string; + headline: string; + content: string; + source: string; + publicationDate: number; +} +``` + +#### Properties + +- `symbol` (string): The stock symbol. +- `headline` (string): The news headline. +- `content` (string): The article content or summary. +- `source` (string): The news source publisher. +- `publicationDate` (number): Unix timestamp when the article was published. + + +## StockNewsHuman + +`StockNewsHuman` is returned when `human: true` is set. It uses the same field names as `StockNews` for most columns, but with `Symbol` capitalized. diff --git a/sdk/js/stocks/prices.mdx b/sdk/js/stocks/prices.mdx new file mode 100644 index 0000000..4580aaf --- /dev/null +++ b/sdk/js/stocks/prices.mdx @@ -0,0 +1,224 @@ +--- +title: Prices +sidebar_position: 1 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Retrieve stock prices for any supported stock symbol. + +## Making Requests + +Use the `prices()` method on the `stocks` resource to fetch stock prices. The method returns a [`MarketDataResult`](/sdk/js/client#MarketDataResult) which resolves to decoded records by default. The output format is controlled by the `outputFormat` parameter (or `MARKETDATA_OUTPUT_FORMAT` env var): + +| Output Format | Result Payload | Description | +|------------------------|---------------------------------------|-----------------------------------------------------------------------| +| **internal** (default) | `StockPrice[]` or `StockPriceHuman[]` | Array of decoded price records, one per symbol. | +| **json** | Raw JSON object | The compressed, array-keyed response object as returned by the API. | +| **csv** | `Blob` | CSV payload. Use `.save(filename)` on the result to write it to disk. | + + +## prices + +```typescript +// Positional form +prices

( + symbols: string | string[], + params?: P, +): MarketDataResult + +// Object form +prices

( + params: P & { symbols: string | string[] }, +): MarketDataResult +``` + +Fetches stock prices for one or more symbols. The return type is narrowed automatically: + +- If `human: true` (or `useHumanReadable: true`) → payload is `StockPriceHuman[]` +- If `outputFormat: "csv"` → payload is `Blob` +- Otherwise → payload is `StockPrice[]` + +#### Parameters + +- `symbols` (string | string[]) + + A single symbol string or an array of symbol strings for which to fetch prices. + +- [`outputFormat`](/sdk/js/settings#output-format) (optional) + + The format of the returned data. See [Settings](/sdk/js/settings#output-format) for details. Also accepts the alias `format`. + +- [`dateFormat`](/sdk/js/settings#date-format) (optional) + + The date format to use in the response. Also accepts the alias `dateformat`. See [Settings](/sdk/js/settings#date-format) for details. + +- [`columns`](/sdk/js/settings#columns) (optional) + + Specify which columns to include in the response. See [Settings](/sdk/js/settings#columns) for details. + +- [`addHeaders`](/sdk/js/settings#headers) (optional) + + Whether to include headers in CSV output. Also accepts the alias `headers`. See [Settings](/sdk/js/settings#headers) for details. + +- [`useHumanReadable`](/sdk/js/settings#human-readable) (optional) + + Whether to use human-readable field names. Also accepts the alias `human`. See [Settings](/sdk/js/settings#human-readable) for details. + +- [`mode`](/sdk/js/settings#data-mode) (optional) + + The data mode to use (`"live"`, `"cached"`, `"delayed"`). See [Settings](/sdk/js/settings#data-mode) for details. + +#### Returns + +- [`MarketDataResult`](/sdk/js/client#MarketDataResult) + + A Result wrapping the prices data in the requested format. Handle success and failure with `.match()`, `.isOk()` / `.isErr()`, or any other neverthrow method. + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.prices("AAPL"); + +result.match( + (prices) => console.log(prices[0].mid), + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.prices(["AAPL", "MSFT", "GOOGL"]); + +result.match( + (prices) => { + for (const p of prices) { + console.log(`${p.symbol}: ${p.mid}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.prices("AAPL", { human: true }); + +result.match( + (prices) => { + for (const p of prices) { + console.log(`${p.Symbol}: mid=${p.Mid}, change=${p.Change_Percent}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient, OutputFormat } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.prices(["AAPL", "MSFT"], { + outputFormat: OutputFormat.JSON, +}); + +result.match( + (json) => console.log(json), + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient, OutputFormat } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.prices(["AAPL", "MSFT"], { + outputFormat: OutputFormat.CSV, +}); + +// Save the Blob to disk (Node.js) +const filename = await result.save("prices.csv"); +console.log(`CSV saved to: ${filename}`); +``` + + + + + +## StockPrice + +```typescript +interface StockPrice { + s?: string; + symbol: string; + mid: number; + change: number; + changepct: number; + updated: number; +} +``` + +`StockPrice` represents a single stock price, with short machine-readable field names. + +#### Properties + +- `s` (string, optional): Status indicator (`"ok"` for successful responses). +- `symbol` (string): The stock symbol. +- `mid` (number): The mid price calculated between the ask and bid. +- `change` (number): The price change. +- `changepct` (number): The fractional price change (e.g. `0.0124` for +1.24%). +- `updated` (number): Unix timestamp when the price was last updated. + + +## StockPriceHuman + +```typescript +interface StockPriceHuman { + s?: string; + Symbol: string; + Mid: number; + Change_Price: number; + Change_Percent: number; + Date: number; +} +``` + +`StockPriceHuman` represents a stock price in human-readable format with capitalized, snake-case field names. Returned when `human: true` (or `useHumanReadable: true`) is set. + +#### Properties + +- `Symbol` (string): The stock symbol. +- `Mid` (number): The mid price. +- `Change_Price` (number): The price change. +- `Change_Percent` (number): The percent change. +- `Date` (number): Unix timestamp of the update. diff --git a/sdk/js/stocks/quotes.mdx b/sdk/js/stocks/quotes.mdx new file mode 100644 index 0000000..04ae5cd --- /dev/null +++ b/sdk/js/stocks/quotes.mdx @@ -0,0 +1,198 @@ +--- +title: Quotes +sidebar_position: 2 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Retrieve stock quotes (bid, ask, mid, last, volume, etc.) for one or more supported stock symbols. + +## Making Requests + +Use the `quotes()` method on the `stocks` resource to fetch stock quotes. The method returns a [`MarketDataResult`](/sdk/js/client#MarketDataResult) which resolves to decoded records by default. + +| Output Format | Result Payload | Description | +|------------------------|---------------------------------------|-------------------------------------------------| +| **internal** (default) | `StockQuote[]` or `StockQuoteHuman[]` | Array of decoded quote records, one per symbol. | +| **json** | Raw JSON object | The compressed, array-keyed response object. | +| **csv** | `Blob` | CSV payload. Use `.save(filename)` to write it. | + + +## quotes + +```typescript +// Positional form +quotes

( + symbols: string | string[], + params?: P, +): MarketDataResult + +// Object form +quotes

( + params: P & { symbols: string | string[] }, +): MarketDataResult +``` + +Fetches stock quotes for one or more symbols. + +#### Parameters + +- `symbols` (string | string[]) + + A single symbol string or an array of symbol strings for which to fetch quotes. + +- `52week` (boolean, optional) + + Include the 52-week high and low in the response. + +- `extended` (boolean, optional) + + Include extended-hours quote data. + +- [`outputFormat`](/sdk/js/settings#output-format) (optional): The format of the returned data. Alias: `format`. +- [`dateFormat`](/sdk/js/settings#date-format) (optional): The date format to use. Alias: `dateformat`. +- [`columns`](/sdk/js/settings#columns) (optional): Columns to include. +- [`addHeaders`](/sdk/js/settings#headers) (optional): Whether to include headers in CSV output. Alias: `headers`. +- [`useHumanReadable`](/sdk/js/settings#human-readable) (optional): Use human-readable field names. Alias: `human`. +- [`mode`](/sdk/js/settings#data-mode) (optional): The data mode to use. + +#### Returns + +- [`MarketDataResult`](/sdk/js/client#MarketDataResult) + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.quotes("AAPL"); + +result.match( + (quotes) => console.log(quotes[0]), + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.quotes(["AAPL", "MSFT", "GOOGL"]); + +result.match( + (quotes) => { + for (const q of quotes) { + console.log(`${q.symbol}: bid=${q.bid}, ask=${q.ask}, last=${q.last}`); + } + }, + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.quotes("AAPL", { "52week": true }); + +result.match( + (quotes) => console.log(quotes[0]), + (error) => console.error(error.message), +); +``` + + + + + +```typescript +import { MarketDataClient } from "marketdata-sdk-js"; + +const client = new MarketDataClient(); + +const result = await client.stocks.quotes("AAPL", { human: true }); + +result.match( + (quotes) => { + const q = quotes[0]; + console.log(`${q.Symbol}: Bid=${q.Bid} / Ask=${q.Ask}, Volume=${q.Volume}`); + }, + (error) => console.error(error.message), +); +``` + + + + + +## StockQuote + +```typescript +interface StockQuote { + s?: string; + symbol: string; + ask: number; + askSize: number; + bid: number; + bidSize: number; + mid: number; + last: number; + change: number; + changepct: number; + volume: number; + updated: number; +} +``` + +`StockQuote` represents a single stock quote with short, machine-readable field names. + +#### Properties + +- `s` (string, optional): Status indicator (`"ok"` for successful responses). +- `symbol` (string): The stock symbol. +- `ask` (number): The ask price. +- `askSize` (number): The ask size. +- `bid` (number): The bid price. +- `bidSize` (number): The bid size. +- `mid` (number): The mid price. +- `last` (number): The last traded price. +- `change` (number): The price change. +- `changepct` (number): The fractional price change. +- `volume` (number): The trading volume. +- `updated` (number): Unix timestamp when the quote was last updated. + + +## StockQuoteHuman + +```typescript +interface StockQuoteHuman { + s?: string; + Symbol: string; + Ask: number; + Ask_Size: number; + Bid: number; + Bid_Size: number; + Mid: number; + Last: number; + Change_Price: number; + Change_Percent: number; + Volume: number; + Date: number; +} +``` + +`StockQuoteHuman` is returned when `human: true` is set. Field names are in `Title_Case` rather than `camelCase`.