### Local Development Setup Source: https://www.marketdata.app/docs/sdk/js/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 SDK with npm Source: https://www.marketdata.app/docs/sdk/js/installation.md Use this command to add the Market Data SDK to your project when using npm. ```bash npm install @marketdata/sdk ``` -------------------------------- ### Install SDK with pnpm Source: https://www.marketdata.app/docs/sdk/js/installation.md Use this command to add the Market Data SDK to your project when using pnpm. ```bash pnpm add @marketdata/sdk ``` -------------------------------- ### Install SDK with yarn Source: https://www.marketdata.app/docs/sdk/js/installation.md Use this command to add the Market Data SDK to your project when using yarn. ```bash yarn add @marketdata/sdk ``` -------------------------------- ### Java Quick Start: Get Stock Quote Source: https://www.marketdata.app/docs/sdk/java/index.md Demonstrates how to initialize the MarketDataClient and fetch a stock quote for a given symbol using Java. The client is AutoCloseable and reads the token from the environment. ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.stocks.StockQuoteRequest; // The no-arg constructor reads MARKETDATA_TOKEN from the environment (or a .env file) // and validates it on startup. The client is AutoCloseable. try (MarketDataClient client = new MarketDataClient()) { // A single quote — quote(...) returns a list; a single symbol is row 0. var quote = client.stocks().quote(StockQuoteRequest.of("AAPL")).values().get(0); System.out.println(quote.symbol() + " last=" + quote.last()); } ``` -------------------------------- ### Instantiate MarketDataClient in Kotlin Source: https://www.marketdata.app/docs/sdk/java/client.md Shows how to create a MarketDataClient instance in Kotlin using the 'use' extension function for automatic resource management, with examples for both default and explicit configurations. ```kotlin import com.marketdata.sdk.MarketDataClient MarketDataClient().use { client -> // ... } MarketDataClient("your_token", null, null, false).use { client -> // ... } ``` -------------------------------- ### Kotlin Quick Start: Get Stock Quote Source: https://www.marketdata.app/docs/sdk/java/index.md Shows how to use the MarketDataClient in Kotlin to retrieve a stock quote. It utilizes the `use {}` block for automatic client closure, similar to Java's try-with-resources. ```kotlin import com.marketdata.sdk.MarketDataClient import com.marketdata.sdk.stocks.StockQuoteRequest // `use {}` closes the client when the block ends — the Kotlin equivalent of try-with-resources. MarketDataClient().use { client -> val quote = client.stocks().quote(StockQuoteRequest.of("AAPL")).values()[0] println("${quote.symbol()} last=${quote.last()}") } ``` -------------------------------- ### Kotlin Error Handling Source: https://www.marketdata.app/docs/sdk/java/client.md Example of handling `MarketDataException` and its subtypes in Kotlin. ```APIDOC ### Kotlin ```kotlin import com.marketdata.sdk.exception.* try { val quote = client.stocks().quote(StockQuoteRequest.of("AAPL")) } catch (e: AuthenticationError) { println("Check your token") } catch (e: RateLimitError) { println("Rate limited") } catch (e: MarketDataException) { println(e.supportInfo) } ``` ``` -------------------------------- ### Kotlin Example: Single Option Quote Source: https://www.marketdata.app/docs/sdk/java/options/quotes.md Shows how to fetch a single option quote using the MarketDataClient in Kotlin. Ensure the MarketDataClient is properly closed. ```kotlin import com.marketdata.sdk.MarketDataClient import com.marketdata.sdk.options.OptionsQuoteRequest MarketDataClient().use { client -> val q = client.options() .quote(OptionsQuoteRequest.of("AAPL260116C00200000")) .values()[0] println("last=${q.last()} iv=${q.iv()} delta=${q.delta()}") } ``` -------------------------------- ### Java Example: Fetching Stock Quotes Source: https://www.marketdata.app/docs/sdk/java/stocks/quotes.md Demonstrates how to use the MarketDataClient to fetch real-time quotes for a single stock (AAPL) and multiple stocks (AAPL, MSFT, GOOGL). ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.stocks.StockQuote; import com.marketdata.sdk.stocks.StockQuoteRequest; import com.marketdata.sdk.stocks.StockQuotesRequest; try (MarketDataClient client = new MarketDataClient()) { // A single symbol — row 0 of the list. StockQuote q = client.stocks().quote(StockQuoteRequest.of("AAPL")).values().get(0); System.out.printf("%s last=%.2f bid/ask=%.2f/%.2f%n", q.symbol(), q.last(), q.bid(), q.ask()); // Several symbols in one request. var quotes = client.stocks().quotes( StockQuotesRequest.of("AAPL", "MSFT", "GOOGL")); for (StockQuote row : quotes.values()) { System.out.printf("% -6s last=%.2f%n", row.symbol(), row.last()); } } ``` -------------------------------- ### Quick Start: Market Data JavaScript SDK Source: https://www.marketdata.app/docs/sdk/js/index.md Initialize the MarketDataClient and make initial API requests for 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(); ``` -------------------------------- ### Java Error Handling (JDK 17) Source: https://www.marketdata.app/docs/sdk/java/client.md Example of how to handle `MarketDataException` and its subtypes using a traditional try-catch block in Java 17. ```APIDOC ### Java (JDK 17) ```java import com.marketdata.sdk.exception.*; try { var quote = client.stocks().quote(StockQuoteRequest.of("AAPL")); } catch (AuthenticationError e) { System.out.println("Check your token"); } catch (RateLimitError e) { System.out.println("Rate limited — retry after " + e.getRetryAfter().map(d -> d.toSeconds() + "s").orElse("a moment")); } catch (MarketDataException e) { // Any other case. Attach getSupportInfo() to a bug report. System.out.println(e.getSupportInfo()); } ``` ``` -------------------------------- ### Kotlin Example: Fetching Stock Quotes Source: https://www.marketdata.app/docs/sdk/java/stocks/quotes.md Shows how to retrieve real-time quotes for a single stock (AAPL) and multiple stocks (AAPL, MSFT, GOOGL) using the MarketDataClient in Kotlin. ```kotlin import com.marketdata.sdk.MarketDataClient import com.marketdata.sdk.stocks.StockQuoteRequest import com.marketdata.sdk.stocks.StockQuotesRequest MarketDataClient().use { client -> val q = client.stocks().quote(StockQuoteRequest.of("AAPL")).values()[0] println("${q.symbol()} last=${q.last()}") val quotes = client.stocks().quotes( StockQuotesRequest.of("AAPL", "MSFT", "GOOGL")) for (row in quotes.values()) { println("${row.symbol()} last=${row.last()}") } } ``` -------------------------------- ### Java Example: Single and Multiple Option Quotes Source: https://www.marketdata.app/docs/sdk/java/options/quotes.md Demonstrates fetching a single option quote and multiple option quotes using the MarketDataClient. The multiple quote request fans out concurrently. ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.options.OptionQuote; import com.marketdata.sdk.options.OptionsQuoteRequest; import com.marketdata.sdk.options.OptionsQuotesRequest; try (MarketDataClient client = new MarketDataClient()) { // Single contract. OptionQuote q = client.options() .quote(OptionsQuoteRequest.of("AAPL260116C00200000")) .values().get(0); System.out.println("last=" + q.last() + " iv=" + q.iv() + " delta=" + q.delta()); // Multiple contracts — one request each, keyed by symbol. var quotes = client.options().quotes( OptionsQuotesRequest.of("AAPL260116C00200000", "AAPL260116C00210000")); quotes.forEach((sym, resp) -> System.out.println(sym + " → " + resp.values().size() + " row(s)")); } ``` -------------------------------- ### Get Stock Prices (Java) Source: https://www.marketdata.app/docs/sdk/java/stocks/prices.md Fetches and prints the mid and change for AAPL and MSFT stock symbols. Ensure MarketDataClient is properly closed. ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.stocks.StockPrice; import com.marketdata.sdk.stocks.StockPricesRequest; try (MarketDataClient client = new MarketDataClient()) { var prices = client.stocks().prices(StockPricesRequest.of("AAPL", "MSFT")); for (StockPrice p : prices.values()) { System.out.printf("% -6s mid=%.2f change=%.2f%n", p.symbol(), p.mid(), p.change()); } } ``` -------------------------------- ### Get Stock Prices (Kotlin) Source: https://www.marketdata.app/docs/sdk/java/stocks/prices.md Fetches and prints the mid and change for AAPL and MSFT stock symbols using Kotlin's `use` for resource management. ```kotlin import com.marketdata.sdk.MarketDataClient import com.marketdata.sdk.stocks.StockPricesRequest MarketDataClient().use { client -> val prices = client.stocks().prices(StockPricesRequest.of("AAPL", "MSFT")) for (p in prices.values()) { println("${p.symbol()} mid=${p.mid()} change=${p.change()}") } } ``` -------------------------------- ### Accessing Market Data Response Source: https://www.marketdata.app/docs/sdk/java/client.md Example of how to call a client method and access various parts of the typed response object, including values, status, and rate limits. ```java var response = client.stocks().quote(StockQuoteRequest.of("AAPL")); response.values(); // List — the part you usually want response.statusCode(); // 200 response.requestId(); // e.g. for a support ticket response.rateLimit(); // this request's rate-limit snapshot (may be null) response.saveToFile(Path.of("aapl.json")); // cache the raw body ``` -------------------------------- ### Kotlin: Composing Async Calls with thenApply and thenCompose Source: https://www.marketdata.app/docs/sdk/java/client.md Provides examples of composing asynchronous operations in Kotlin using CompletableFuture. It illustrates transforming results with `thenApply`, chaining dependent calls with `thenCompose`, and executing multiple independent calls concurrently. ```kotlin import com.marketdata.sdk.options.OptionsLookupRequest import com.marketdata.sdk.options.OptionsQuoteRequest import com.marketdata.sdk.stocks.StockQuoteRequest import java.util.concurrent.CompletableFuture // thenApply — transform the result without blocking. val lastPrice = client.stocks() .quoteAsync(StockQuoteRequest.of("AAPL")) .thenApply { resp -> resp.values()[0].last() } // thenCompose — chain a dependent async call. val optionQuote = client.options() .lookupAsync(OptionsLookupRequest.of("AAPL 1/16/2026 \$200 Call")) .thenCompose { sym -> client.options().quoteAsync(OptionsQuoteRequest.of(sym.values())) } // Independent calls in parallel, then use every result. val aapl = client.stocks().quoteAsync(StockQuoteRequest.of("AAPL")) val msft = client.stocks().quoteAsync(StockQuoteRequest.of("MSFT")) CompletableFuture.allOf(aapl, msft).join() val spread = aapl.join().values()[0].last()!! - msft.join().values()[0].last()!! ``` -------------------------------- ### Instantiate MarketDataClient in Java Source: https://www.marketdata.app/docs/sdk/java/client.md Demonstrates how to create a MarketDataClient instance using the no-argument constructor for production or a parameterized constructor for explicit configuration and disabling startup validation. ```java import com.marketdata.sdk.MarketDataClient; // Production: token from the cascade, validated on startup. try (MarketDataClient client = new MarketDataClient()) { // ... } // Explicit, no startup validation (e.g. on a Lambda cold start): try (MarketDataClient client = new MarketDataClient("your_token", null, null, false)) { // ... } ``` -------------------------------- ### Get Single Stock Quote Source: https://www.marketdata.app/docs/sdk/java/stocks/quotes.md Retrieves real-time quote data for a single stock symbol. ```APIDOC ## Get Single Stock Quote ### Description Retrieves real-time quote data for a single stock symbol. ### Method Signature ```java StockQuotesResponse quote(StockQuoteRequest request) CompletableFuture quoteAsync(StockQuoteRequest request) ``` ### Request Type `StockQuoteRequest.of(String symbol)` `StockQuoteRequest.builder(String symbol)` `.extended(boolean extended)` // include extended-session prices `.candle(boolean candle)` // add OHLC columns `.week52(boolean week52)` // add 52-week high/low `.build()` ### Response Returns a `StockQuotesResponse` object containing a list with a single `StockQuote`. #### StockQuote Fields - `symbol` (String) - `ask` (Double) - `askSize` (Long) - `bid` (Double) - `bidSize` (Long) - `mid` (Double) - `last` (Double) - `change` (Double) - `changepct` (Double) - `volume` (Long) - `updated` (ZonedDateTime) - `open` (Double) - Optional, requires `.candle(true)` - `high` (Double) - Optional, requires `.candle(true)` - `low` (Double) - Optional, requires `.candle(true)` - `close` (Double) - Optional, requires `.candle(true)` - `week52High` (Double) - Optional, requires `.week52(true)` - `week52Low` (Double) - Optional, requires `.week52(true)` ``` -------------------------------- ### MarketDataClient Constructors Source: https://www.marketdata.app/docs/sdk/java/client.md Demonstrates how to create a MarketDataClient instance using either the no-arg constructor for production or the four-arg constructor for explicit configuration. ```APIDOC ## MarketDataClient Constructors ### Description Instantiate the `MarketDataClient` for interacting with the MarketData API. The no-arg constructor is suitable for production, automatically resolving configuration and validating the token on startup. The four-argument constructor offers explicit control over `apiKey`, `baseUrl`, `apiVersion`, and `validateOnStartup`, which is useful for testing or specific runtime environments. ### Constructors 1. **`MarketDataClient()`** * **Description**: Production constructor. Resolves API key and settings from the configuration cascade. Validates the token by making a `GET /user/` request on startup. * **Usage**: `try (MarketDataClient client = new MarketDataClient()) { ... }` 2. **`MarketDataClient(@Nullable String apiKey, @Nullable String baseUrl, @Nullable String apiVersion, boolean validateOnStartup)`** * **Description**: Full control constructor. Allows explicit setting of API key, base URL, API version, and whether to validate the token on startup. Null values for `apiKey`, `baseUrl`, or `apiVersion` will fall back to the configuration cascade or default values. * **Parameters**: * `apiKey` (String) - The API key for authentication. Can be null to use the cascade. * `baseUrl` (String) - The base URL for API requests. Defaults to `https://api.marketdata.app`. Can be null to use the default. * `apiVersion` (String) - The API version to use. Defaults to `v1`. Can be null to use the default. * `validateOnStartup` (boolean) - If true, validates the token on construction. Set to `false` to skip this validation. * **Usage**: `try (MarketDataClient client = new MarketDataClient("your_token", null, null, false)) { ... }` ### Note on Configuration * Misconfigurations in `baseUrl` or `apiVersion` will result in an `IllegalArgumentException` during construction. * API keys are redacted in the client's `toString()` output for security. ``` -------------------------------- ### MarketData Client Initialization with Logging Options Source: https://www.marketdata.app/docs/sdk/js/client.md Demonstrates different ways to initialize the MarketDataClient with logging configurations. This includes using the default logger, enabling debug logging for more verbose output, 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 }); ``` -------------------------------- ### Initialize Market Data Client with Default Settings Source: https://www.marketdata.app/docs/sdk/js/settings.md Instantiate the MarketDataClient without specific arguments. It will automatically pick up settings from environment variables. ```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"); ``` -------------------------------- ### Get Multiple Stock Quotes Source: https://www.marketdata.app/docs/sdk/java/stocks/quotes.md Retrieves real-time quote data for multiple stock symbols in a single request. ```APIDOC ## Get Multiple Stock Quotes ### Description Retrieves real-time quote data for multiple stock symbols in a single request. The backend batches symbols into a comma-separated list. ### Method Signature ```java StockQuotesResponse quotes(StockQuotesRequest request) CompletableFuture quotesAsync(StockQuotesRequest request) ``` ### Request Type `StockQuotesRequest.of(String first, String... rest)` // shortcut: symbols only `StockQuotesRequest.builder(String first, String... rest)` `.addSymbol(String symbol)` `.extended(boolean extended)` `.candle(boolean candle)` `.week52(boolean week52)` `.build()` ### Response Returns a `StockQuotesResponse` object containing a list of `StockQuote` objects, one for each requested symbol. #### StockQuote Fields - `symbol` (String) - `ask` (Double) - `askSize` (Long) - `bid` (Double) - `bidSize` (Long) - `mid` (Double) - `last` (Double) - `change` (Double) - `changepct` (Double) - `volume` (Long) - `updated` (ZonedDateTime) - `open` (Double) - Optional, requires `.candle(true)` - `high` (Double) - Optional, requires `.candle(true)` - `low` (Double) - Optional, requires `.candle(true)` - `close` (Double) - Optional, requires `.candle(true)` - `week52High` (Double) - Optional, requires `.week52(true)` - `week52Low` (Double) - Optional, requires `.week52(true)` ``` -------------------------------- ### Client Configuration Cascade Source: https://www.marketdata.app/docs/sdk/java/settings.md Demonstrates how explicit constructor arguments take precedence over environment variables for client configuration. Null values fall through to the cascade. ```java new MarketDataClient("explicit-token", null, null, true); ``` -------------------------------- ### MarketDataClient Initialization Source: https://www.marketdata.app/docs/sdk/js/client.md Instantiate the MarketDataClient to begin making API requests. You can provide a configuration object to customize its behavior, such as setting an API token or base URL. ```APIDOC ## MarketDataClient Constructor ### Description Initializes a new instance of the MarketDataClient. ### Parameters #### Constructor Parameters - **config** (MarketDataConfig, optional) - Configuration object for the client. - **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 to increase wait time between retries. - **skipStartupValidation** (boolean, optional) - Skips the initial validation call on startup. - **debug** (boolean, optional) - Enables debug logging. - **logger** (Logger, optional) - A custom logger instance. ### Properties - **ready** (Promise<void>) - Resolves when the client is ready for use after initial validation. Rejects on authentication errors. ### Example ```javascript import { MarketDataClient } from 'marketdata-client'; const client = new MarketDataClient({ token: 'YOUR_API_TOKEN', apiVersion: 'v2' }); // Await client.ready if you need to ensure validation has completed before making requests await client.ready; ``` ``` -------------------------------- ### Limit and Offset Rows in API Response Source: https://www.marketdata.app/docs/sdk/java/settings.md Applies limits to the number of rows returned and allows skipping rows from the start of the result set. ```java client.stocks().limit(100).offset(0); ``` -------------------------------- ### Instantiate MarketDataClient Source: https://www.marketdata.app/docs/sdk/js/client.md Create a new MarketDataClient instance. The token can be provided directly or will be read from the MARKETDATA_TOKEN environment variable. The client's readiness can be awaited to ensure startup validation is complete. ```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 }); ``` -------------------------------- ### MarketDataClient Constructor Source: https://www.marketdata.app/docs/sdk/js/client.md Creates and configures a new MarketDataClient instance. Initializes the client with authentication, sets up HTTP headers, and prepares resource namespaces. ```APIDOC ## constructor MarketDataClient ### Description 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, prepares the resource namespaces, and kicks off eager `/user/` validation (unless `skipStartupValidation: true`). ### 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`. - `skipStartupValidation` (boolean): If `true`, skips the eager `/user/` call the constructor makes to validate the token. Defaults to `false`. Use on serverless platforms where cold-start latency matters. - `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-sdk-js/{version}` (e.g. `marketdata-sdk-js/1.0.0`). - 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, and enforces a global 50-request concurrency pool across every endpoint. - Every request has a 99-second timeout; a timed-out fetch rejects with `NetworkError`. - Configuration properties can also be provided via environment variables — see [Settings](https://www.marketdata.app/docs/sdk/js/settings) for the full list and their resolution order. ### Example ```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 }); ``` ``` -------------------------------- ### Get User Details Source: https://www.marketdata.app/docs/sdk/java/utilities/user.md Retrieve your account details, including your daily request quota. This method is also used by the SDK on startup to validate your token. ```APIDOC ## Get User Details ### Description Retrieve your account details — including how much of your daily request quota remains. This is the same endpoint the SDK calls on startup to validate your token. ### Method Signature ```java UtilitiesUserResponse user() CompletableFuture userAsync() ``` ### Returns `UtilitiesUserResponse` wrapping a `User`, which exposes your plan and quota — for example `requestsRemaining()` and `requestsLimit()`. ``` -------------------------------- ### Java Error Handling (JDK 21+) Source: https://www.marketdata.app/docs/sdk/java/client.md Example of exhaustive error handling using a `switch` statement on `MarketDataException` in Java 21+, leveraging sealed classes. ```APIDOC ### Java (JDK 21+) ```java import com.marketdata.sdk.exception.*; // On JDK 21+ the sealed hierarchy enables an exhaustive switch — the compiler // rejects the code if any subtype is left unhandled. try { var quote = client.stocks().quote(StockQuoteRequest.of("AAPL")); } catch (MarketDataException e) { String message = switch (e) { case AuthenticationError a -> "Authentication failed — check your token"; case BadRequestError b -> "Bad request — check your parameters"; case NotFoundError n -> "Not found"; case RateLimitError r -> "Rate limited"; case ServerError s -> "Server error (HTTP " + s.getStatusCode() + ")"; case NetworkError n -> "Network problem — is the API reachable?"; case ParseError p -> "Could not parse the response"; }; System.out.println(message); } ``` ``` -------------------------------- ### Set Environment Variables for Market Data SDK Source: https://www.marketdata.app/docs/sdk/js/settings.md Configure universal parameters like output format, date format, and human-readable mode using environment variables. These settings are applied globally unless overridden. ```bash export MARKETDATA_OUTPUT_FORMAT=json export MARKETDATA_DATE_FORMAT=timestamp export MARKETDATA_USE_HUMAN_READABLE=true ``` -------------------------------- ### Get Options Expirations Source: https://www.marketdata.app/docs/sdk/java/options/expirations.md Fetches a list of available expiration dates for a given stock symbol. You can optionally filter by strike price or a specific historical date. ```APIDOC ## Get Options Expirations ### Description Retrieves a list of available expiration dates for a given underlying symbol. This method can be used to find all possible expiration dates for options contracts associated with a specific stock. ### Method Signature ```java OptionsExpirationsResponse expirations(OptionsExpirationsRequest request) CompletableFuture expirationsAsync(OptionsExpirationsRequest request) ``` ### Request Object: OptionsExpirationsRequest Used to specify the parameters for fetching expiration dates. #### Static Factory Methods - `OptionsExpirationsRequest.of(String symbol)`: Creates a request for the given symbol. - `OptionsExpirationsRequest.builder(String symbol)`: Creates a builder to construct a request. #### Builder Methods - `.strike(double strike)`: (Optional) Filters expirations to only include those that list this specific strike price. - `.date(LocalDate date)`: (Optional) For historical data, specifies the calendar date as it stood when the request is made. This allows retrieving expirations as they were known on a past date. - `.build()`: Constructs the `OptionsExpirationsRequest` object. ### Response - `OptionsExpirationsResponse`: An object that wraps a `List` containing the expiration dates. ### Example Usage (Java) ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.options.OptionsExpirationsRequest; import java.time.ZonedDateTime; try (MarketDataClient client = new MarketDataClient()) { var expirations = client.options().expirations(OptionsExpirationsRequest.of("AAPL")); System.out.println("AAPL has " + expirations.values().size() + " expirations"); for (ZonedDateTime exp : expirations.values()) { System.out.println(" " + exp.toLocalDate()); } } ``` ``` -------------------------------- ### Get Options Expirations - Kotlin Source: https://www.marketdata.app/docs/sdk/java/options/expirations.md Retrieve expiration dates for a symbol using the `expirations` method. The `use` extension function ensures the client is closed automatically. ```kotlin import com.marketdata.sdk.MarketDataClient import com.marketdata.sdk.options.OptionsExpirationsRequest MarketDataClient().use { client -> val expirations = client.options().expirations(OptionsExpirationsRequest.of("AAPL")) println("AAPL has ${expirations.values().size} expirations") } ``` -------------------------------- ### Java: Basic Sync and Async Client Usage Source: https://www.marketdata.app/docs/sdk/java/client.md Demonstrates synchronous and asynchronous calls to the client's utilities status endpoint. The sync method blocks until a response is received, while the async method returns a CompletableFuture. It also shows how to fan out multiple async calls and wait for all of them to complete. ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.UtilitiesStatusResponse; import java.util.concurrent.CompletableFuture; try (MarketDataClient client = new MarketDataClient()) { // Sync — blocks and returns the typed response. var sync = client.utilities().status(); System.out.println(sync.values().size() + " services"); // Async — returns immediately with a future. Attach a callback, or join(). CompletableFuture future = client.utilities().statusAsync(); future.thenAccept(resp -> System.out.println(resp.values().size() + " services")); // Fan out several calls in parallel and wait for all of them. var a = client.utilities().statusAsync(); var b = client.utilities().statusAsync(); CompletableFuture.allOf(a, b).join(); } ``` -------------------------------- ### Get Options Expirations - Java Source: https://www.marketdata.app/docs/sdk/java/options/expirations.md Fetch and print expiration dates for a given symbol using the synchronous `expirations` method. Ensure to close the client after use. ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.options.OptionsExpirationsRequest; import java.time.ZonedDateTime; try (MarketDataClient client = new MarketDataClient()) { var expirations = client.options().expirations(OptionsExpirationsRequest.of("AAPL")); System.out.println("AAPL has " + expirations.values().size() + " expirations"); for (ZonedDateTime exp : expirations.values()) { System.out.println(" " + exp.toLocalDate()); } } ``` -------------------------------- ### Configure Market Data Client with Constructor Arguments Source: https://www.marketdata.app/docs/sdk/js/settings.md Set client-level configuration, including API token, base URL, API version, and retry options, by passing a MarketDataConfig object to the constructor. These settings override environment variables. ```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, }); ``` -------------------------------- ### Configure .env File for Authentication Source: https://www.marketdata.app/docs/sdk/java/authentication.md The SDK automatically loads the MARKETDATA_TOKEN from a .env file in the project root. Ensure this file is added to your .gitignore. ```env MARKETDATA_TOKEN=your_api_token ``` -------------------------------- ### Get Market Status for a Date Range - Kotlin Source: https://www.marketdata.app/docs/sdk/java/markets/status.md Fetch market status for the past week using the MarketDataClient. Iterates through the results to print the date and status. ```kotlin import com.marketdata.sdk.MarketDataClient import com.marketdata.sdk.markets.MarketStatusRequest import java.time.LocalDate MarketDataClient().use { client -> val status = client.markets().status( MarketStatusRequest.builder() .from(LocalDate.now().minusDays(7)) .to(LocalDate.now()) .build()) for (day in status.values()) { println("${day.date().toLocalDate()} ${day.status()}") } } ``` -------------------------------- ### Access Stocks Endpoint Source: https://www.marketdata.app/docs/sdk/java/stocks/index.md Demonstrates how to access the main Stocks endpoint using the Java SDK. ```java client.stocks() ``` -------------------------------- ### Get User Details (Kotlin) Source: https://www.marketdata.app/docs/sdk/java/utilities/user.md Retrieves user account details, including request quota, using the synchronous `user()` method. Ensure a valid token is provided. ```kotlin import com.marketdata.sdk.MarketDataClient MarketDataClient().use { client -> val me = client.utilities().user().values() println("Quota: ${me.requestsRemaining()} of ${me.requestsLimit()} left today") } ``` -------------------------------- ### Accessing Resources Source: https://www.marketdata.app/docs/sdk/java/client.md Demonstrates how to access different market data resources (stocks, options, funds, markets, utilities) through the MarketDataClient. ```APIDOC ## Accessing Resources ### Description Once a `MarketDataClient` is instantiated, you can access various market data resources through dedicated methods. Each method returns a resource-specific client object that allows you to perform operations related to that data type. ### Methods - **`stocks()`**: Returns a `StocksResource` client for stock-related data. - **`options()`**: Returns an `OptionsResource` client for options data. - **`funds()`**: Returns a `FundsResource` client for fund data. - **`markets()`**: Returns a `MarketsResource` client for market data. - **`utilities()`**: Returns a `UtilitiesResource` client for utility functions. ### Usage Example ```java import com.marketdata.sdk.MarketDataClient; try (MarketDataClient client = new MarketDataClient()) { // Access stocks resource client.stocks().someStockMethod(); // Access options resource client.options().someOptionsMethod(); // Access funds resource client.funds().someFundsMethod(); // Access markets resource client.markets().someMarketsMethod(); // Access utilities resource client.utilities().someUtilitiesMethod(); } ``` ``` -------------------------------- ### Get User Details (Java) Source: https://www.marketdata.app/docs/sdk/java/utilities/user.md Retrieves user account details, including request quota, using the synchronous `user()` method. Ensure a valid token is provided. ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.utilities.User; try (MarketDataClient client = new MarketDataClient()) { User me = client.utilities().user().values(); System.out.println("Quota: " + me.requestsRemaining() + " of " + me.requestsLimit() + " requests left today"); } ``` -------------------------------- ### Retrieve Stock Candles Source: https://www.marketdata.app/docs/sdk/java/stocks/candles.md Use the `candles()` method on the `stocks` resource to get historical OHLCV data. You can specify the resolution, symbol, and date range using `StockCandlesRequest`. ```APIDOC ## Retrieve Stock Candles ### Description Retrieves historical OHLCV (open/high/low/close/volume) candles for a stock symbol. ### Method Signature ```java StockCandlesResponse candles(StockCandlesRequest request) CompletableFuture candlesAsync(StockCandlesRequest request) ``` ### Parameters #### `StockCandlesRequest` - `resolution` (StockResolution) - Required - The desired candle interval. - `symbol` (String) - Required - The stock symbol. - `date` (LocalDate) - Optional - A single trading day. - `from` (LocalDate) - Optional - Window start date (inclusive). - `to` (LocalDate) - Optional - Window end date (exclusive). - `countback` (int) - Optional - Number of candles before `to`. - `exchange` (String) - Optional - Disambiguate the exchange. - `extended` (boolean) - Optional - Include extended-hours bars (intraday). - `country` (String) - Optional - Exchange country (ISO 3166, 2-letter). - `adjustSplits` (boolean) - Optional - Adjust for stock splits (default: true for daily). - `adjustDividends` (boolean) - Optional - Adjust for dividends (default: true for daily). #### `StockResolution` Options - `StockResolution.DAILY`, `StockResolution.WEEKLY`, `StockResolution.MONTHLY`, `StockResolution.YEARLY` - `StockResolution.minutes(int)` - `StockResolution.hours(int)` - `StockResolution.days(int)` - `StockResolution.of(String rawWireToken)` ### Response `StockCandlesResponse` wrapping `List`: #### `StockCandle` Fields - `time` (ZonedDateTime) - Bar opening moment (America/New_York). - `open` (Double) - Opening price. - `high` (Double) - Highest price. - `low` (Double) - Lowest price. - `close` (Double) - Closing price. - `volume` (Long) - Trading volume. ### Example Usage (Java) ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.stocks.StockCandlesRequest; import com.marketdata.sdk.stocks.StockResolution; import java.time.LocalDate; try (MarketDataClient client = new MarketDataClient()) { var candles = client.stocks().candles( StockCandlesRequest.builder(StockResolution.DAILY, "AAPL") .from(LocalDate.now().minusWeeks(1)) .to(LocalDate.now()) .build()); } ``` ``` -------------------------------- ### Accessing Options Endpoints Source: https://www.marketdata.app/docs/sdk/java/options/index.md Demonstrates how to access the main Options resource using the Market Data Java SDK. ```APIDOC ## Accessing Options To access the Options resource, use the `client.options()` method. ### Method Signature ```java client.options() ``` ### Description This method returns an object that allows interaction with the Options API. ### Usage Example ```java OptionsApi optionsApi = client.options(); ``` ``` -------------------------------- ### Filter Expirations by Strike Source: https://www.marketdata.app/docs/sdk/js/options/expirations.md To retrieve only expirations that trade a specific strike price, provide the `strike` parameter in the options object. This example filters for expirations trading the $250 strike. ```typescript import { MarketDataClient } from "@marketdata/sdk"; const client = new MarketDataClient(); try { // Only expirations that trade the $250 strike const data = await client.options.expirations("AAPL", { strike: 250 }); console.log(data.expirations); } catch (error) { console.error(error); } ``` -------------------------------- ### Kotlin: Basic Sync and Async Client Usage Source: https://www.marketdata.app/docs/sdk/java/client.md Illustrates synchronous and asynchronous client calls in Kotlin. Similar to Java, it shows basic usage of sync and async methods for retrieving utility status and handling the CompletableFuture returned by async operations. ```kotlin import com.marketdata.sdk.MarketDataClient import java.util.concurrent.CompletableFuture MarketDataClient().use { client -> // Sync val sync = client.utilities().status() println("${sync.values().size} services") // Async — returns a CompletableFuture (coroutine users can await() it // via kotlinx-coroutines-jdk8). client.utilities().statusAsync() .thenAccept { resp -> println("${resp.values().size} services") } .join() } ``` -------------------------------- ### Get HTTP Headers (Java) Source: https://www.marketdata.app/docs/sdk/java/utilities/headers.md Retrieves the HTTP headers the server received for the current request. Ensure you have a valid token and the `MarketDataClient` is properly initialized. The response values are lower-cased. ```java import com.marketdata.sdk.MarketDataClient; try (MarketDataClient client = new MarketDataClient()) { var headers = client.utilities().headers().values(); System.out.println("Server saw " + headers.size() + " request headers"); } ``` -------------------------------- ### Get Market Status for a Date Range - Java Source: https://www.marketdata.app/docs/sdk/java/markets/status.md Fetch market status for the past week using the MarketDataClient. Iterates through the results to print the date, status, and trading indicator. ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.markets.MarketStatus; import com.marketdata.sdk.markets.MarketStatusRequest; import java.time.LocalDate; try (MarketDataClient client = new MarketDataClient()) { var status = client.markets().status( MarketStatusRequest.builder() .from(LocalDate.now().minusDays(7)) .to(LocalDate.now()) .build()); for (MarketStatus day : status.values()) { System.out.println(day.date().toLocalDate() + " " + day.status() + (day.isOpen() ? " (trading)" : "")); } } ``` -------------------------------- ### Java: Composing Async Calls with thenApply and thenCompose Source: https://www.marketdata.app/docs/sdk/java/client.md Demonstrates advanced asynchronous programming patterns in Java using CompletableFuture. It shows how to transform results with `thenApply` and chain dependent asynchronous calls with `thenCompose`, as well as executing independent calls in parallel. ```java import com.marketdata.sdk.options.OptionsLookupRequest; import com.marketdata.sdk.options.OptionsQuoteRequest; import com.marketdata.sdk.stocks.StockQuoteRequest; import java.util.concurrent.CompletableFuture; // thenApply — transform the result without blocking. CompletableFuture lastPrice = client.stocks() .quoteAsync(StockQuoteRequest.of("AAPL")) .thenApply(resp -> resp.values().get(0).last()); // thenCompose — chain a dependent async call (resolve a symbol, then quote it). var optionQuote = client.options() .lookupAsync(OptionsLookupRequest.of("AAPL 1/16/2026 $200 Call")) .thenCompose(sym -> client.options().quoteAsync(OptionsQuoteRequest.of(sym.values()))); // Independent calls in parallel, then use every result. var aapl = client.stocks().quoteAsync(StockQuoteRequest.of("AAPL")); var msft = client.stocks().quoteAsync(StockQuoteRequest.of("MSFT")); CompletableFuture.allOf(aapl, msft).join(); // wait for both double spread = aapl.join().values().get(0).last() - msft.join().values().get(0).last(); ``` -------------------------------- ### Make Test Request (Java) Source: https://www.marketdata.app/docs/sdk/java/authentication.md This Java snippet demonstrates how to make a test request for a stock quote using the MarketDataClient. The SDK automatically reads the authentication token from the environment variable or .env file. ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.stocks.StockQuoteRequest; import com.marketdata.sdk.exception.AuthenticationError; // No need to pass a token here — the SDK reads MARKETDATA_TOKEN automatically. try (MarketDataClient client = new MarketDataClient()) { var quote = client.stocks().quote(StockQuoteRequest.of("SPY")).values().get(0); System.out.println(quote.symbol() + " last=" + quote.last()); } catch (AuthenticationError e) { System.out.println("Authentication failed: " + e.getMessage()); } ``` -------------------------------- ### Get Per-Request Rate Limit Source: https://www.marketdata.app/docs/sdk/java/client.md Retrieves and prints the remaining and limit of API requests from a specific response's rate limit headers. Handles null rate limit information. ```java var response = client.stocks().quote(StockQuoteRequest.of("AAPL")); var rl = response.rateLimit(); if (rl != null) { System.out.println(rl.remaining() + " / " + rl.limit() + " requests left"); } ``` -------------------------------- ### Make Test Request (Kotlin) Source: https://www.marketdata.app/docs/sdk/java/authentication.md This Kotlin snippet demonstrates how to make a test request for a stock quote using the MarketDataClient. The SDK automatically reads the authentication token from the environment variable or .env file. ```kotlin import com.marketdata.sdk.MarketDataClient import com.marketdata.sdk.stocks.StockQuoteRequest import com.marketdata.sdk.exception.AuthenticationError MarketDataClient().use { client -> try { val quote = client.stocks().quote(StockQuoteRequest.of("SPY")).values()[0] println("${quote.symbol()} last=${quote.last()}") } catch (e: AuthenticationError) { println("Authentication failed: ${e.message}") } } ```