### Run Funds Demo with Mock Server Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/FUNDS_REVIEW_GUIDE.md Instructions to run a full funds demo against a mock server. This requires starting the mock server and then running the demo or the Gradle task. ```bash # Full funds demo against the mock server (all params, CSV facet, columns projection, # Option A, the no-chunking proof). Needs the mock server up: make publish && make mock-server # (in one terminal) make demo-funds # (in another) — or: ./gradlew -p examples/consumer-test runFunds ``` -------------------------------- ### MarketStatusRequest Builder Example Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/MARKETS_REVIEW_GUIDE.md Illustrates the builder pattern for creating MarketStatusRequest objects. All parameters are optional, allowing for flexible query construction. ```java com.marketdata.sdk.markets.MarketStatusRequest (Builder-based request — every param optional) ``` -------------------------------- ### Kotlin Usage Example for MarketDataClient Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/java-sdk-requirements.md Demonstrates how to instantiate and use the MarketDataClient in Kotlin, including fetching stock quotes. Ensure you have the necessary API key. ```kotlin val client = MarketDataClient( apiKey = "KEY", baseUrl = null, apiVersion = null, validateOnStartup = true, ) val quote = client.stocks().quote("AAPL") println(quote) ``` -------------------------------- ### Local Verification Commands Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Execute these commands to build, start a mock server, and run the exceptions demo locally. The demo simulates various error conditions to test exception handling. ```bash make publish ``` ```bash make mock-server # terminal 2 ``` ```bash make demo-exceptions # terminal 3 ``` -------------------------------- ### Client Configuration Cascade Example Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/settings.md Demonstrates how explicit constructor arguments take precedence over environment variables for client configuration. A null value for an argument allows the cascade to resolve it from environment variables or defaults. ```java new MarketDataClient("explicit-token", null, null, true); ``` -------------------------------- ### Run Market Data Demo with Mock Server Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/MARKETS_REVIEW_GUIDE.md Commands to run a full market data demo against a mock server. This involves starting the mock server in one terminal and running the demo in another. It showcases various parameters and response formats. ```bash # Full markets demo against the mock server (all params, null status cells, CSV facet, # columns projection, Option A). Needs the mock server up: make publish && make mock-server # (in one terminal) make demo-markets # (in another) — or: ./gradlew -p examples/consumer-test runMarkets ``` -------------------------------- ### Request Class Convention Examples Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/OPTIONS_REVIEW_GUIDE.md Illustrates the convention for creating request objects using factory methods or builders. Use `of(...)` for simple requests and `builder(...)` for requests with optional parameters. ```java OptionsLookupRequest.of("AAPL 1/16/2026 $200 Call"); // no-optionals: of(...) OptionsExpirationsRequest.builder("AAPL").strike(150.0).build(); // optionals: builder(...)…build() ``` -------------------------------- ### Kotlin Example: Fetching Option Chain Data Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/options/chain.md This snippet shows how to fetch option chain data for a given symbol using the MarketDataClient in Kotlin. It retrieves the 5 nearest calls and prints their details. ```kotlin import com.marketdata.sdk.MarketDataClient import com.marketdata.sdk.options.OptionSide import com.marketdata.sdk.options.OptionsChainRequest MarketDataClient().use { client -> val chain = client.options().chain( OptionsChainRequest.builder("AAPL") .side(OptionSide.CALL) .strikeLimit(5) .build()) .values() for (c in chain) { println("${c.optionSymbol()} strike=${c.strike()} delta=${c.delta()}") } } ``` -------------------------------- ### Composing Async Calls with thenCompose in Java Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/client.md Illustrates chaining dependent asynchronous calls using `thenCompose`. This example first looks up an option symbol and then uses that symbol to fetch its quote. ```java import com.marketdata.sdk.options.OptionsLookupRequest; import com.marketdata.sdk.options.OptionsQuoteRequest; import com.marketdata.sdk.stocks.StockQuoteRequest; import java.util.concurrent.CompletableFuture; // 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()))); ``` -------------------------------- ### Fetch Daily Stock Candles in Java Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/stocks/candles.md Retrieves daily candles for a given symbol over a date range. Includes an example of iterating through the results and printing candle details. ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.stocks.StockCandle; import com.marketdata.sdk.stocks.StockCandlesRequest; import com.marketdata.sdk.stocks.StockResolution; import java.time.LocalDate; try (MarketDataClient client = new MarketDataClient()) { // Daily candles over a date range. var candles = client.stocks().candles( StockCandlesRequest.builder(StockResolution.DAILY, "AAPL") .from(LocalDate.now().minusWeeks(1)) .to(LocalDate.now()) .build()); for (StockCandle bar : candles.values()) { System.out.printf("%s O=%.2f H=%.2f L=%.2f C=%.2f V=%d%n", bar.time(), bar.open(), bar.high(), bar.low(), bar.close(), bar.volume()); } // The last 10 sessions, using countback instead of a left edge. var lastTen = client.stocks().candles( StockCandlesRequest.builder(StockResolution.DAILY, "AAPL") .to(LocalDate.now()) .countback(10) .build()); } ``` -------------------------------- ### Retrieve Stock News (Kotlin) Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/stocks/news.md Shows how to retrieve stock news articles for a given symbol and date range using the Kotlin SDK. The example iterates over the news articles and prints relevant details. ```kotlin import com.marketdata.sdk.MarketDataClient import com.marketdata.sdk.stocks.StockNewsRequest import java.time.LocalDate MarketDataClient().use { client -> val news = client.stocks().news( StockNewsRequest.builder("AAPL") .from(LocalDate.now().minusDays(7)) .to(LocalDate.now()) .build()) for (a in news.values()) { println("${a.publicationDate()} ${a.headline()} (${a.source()})") } } ``` -------------------------------- ### Get Stock Quote (Java) Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/README.md Demonstrates how to instantiate the MarketDataClient and retrieve a stock quote for AAPL using a try-with-resources block. The client automatically reads the MARKETDATA_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()); } ``` -------------------------------- ### MarketStatus Record Example Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/MARKETS_REVIEW_GUIDE.md Represents a single row of market status data, including date and status information. Provides helper methods to check if the market was open or closed. ```java com.marketdata.sdk.markets.MarketStatus (row record: date/status + isOpen()/isClosed()) ``` -------------------------------- ### Get Stock Prices (Kotlin) Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/stocks/prices.md Fetches the latest mid and change prices for specified stock symbols using Kotlin. The `use` extension function ensures the client is closed. ```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()}") } } ``` -------------------------------- ### Java Example: Fetching 5 Calls Nearest the Money Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/options/chain.md This snippet demonstrates fetching the 5 call options closest to the money for a given symbol using the MarketDataClient in Java. It iterates through the results and prints basic option details. ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.options.ExpirationFilter; import com.marketdata.sdk.options.OptionQuote; import com.marketdata.sdk.options.OptionSide; import com.marketdata.sdk.options.OptionsChainRequest; import com.marketdata.sdk.options.StrikeFilter; import java.util.List; try (MarketDataClient client = new MarketDataClient()) { // The 5 calls nearest the money. List chain = client.options().chain( OptionsChainRequest.builder("AAPL") .side(OptionSide.CALL) .strikeLimit(5) .build()) .values(); for (OptionQuote c : chain) { System.out.println(c.optionSymbol() + " strike=" + c.strike() + " bid/ask=" + c.bid() + "/" + c.ask() + " delta=" + c.delta()); } // Sealed filters: contracts within 45 days, strikes between 150 and 250. var filtered = client.options().chain( OptionsChainRequest.builder("AAPL") .expirationFilter(ExpirationFilter.dte(45)) .strikeFilter(StrikeFilter.range(150, 250)) .side(OptionSide.CALL) .build()); } ``` -------------------------------- ### Java Example: Fetching Single and Multiple Stock Quotes Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/stocks/quotes.md Demonstrates fetching a quote for a single symbol (AAPL) and multiple symbols (AAPL, MSFT, GOOGL) using the MarketDataClient. Includes printing the retrieved quote details. ```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()); } } ``` -------------------------------- ### Kotlin Example: Fetching Single and Multiple Stock Quotes Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/stocks/quotes.md Shows how to retrieve quotes for a single stock (AAPL) and multiple stocks (AAPL, MSFT, GOOGL) in Kotlin using the MarketDataClient. Prints the symbol and last price for each retrieved quote. ```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()}") } } ``` -------------------------------- ### Get Funds Data as CSV Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/funds/README.md Retrieve data from the Funds endpoint in CSV format using the Market Data Java SDK. This is a convenient way to get structured data for analysis. ```java client.funds().asCsv() ``` -------------------------------- ### Kotlin Error Handling Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/client.md Provides a basic example of catching MarketDataException and its specific subtypes in Kotlin, similar to the Java approach. ```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) } ``` -------------------------------- ### Run Options Demo with Mock Server Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/OPTIONS_REVIEW_GUIDE.md Commands to run a full options demo against a mock server. This demonstrates all endpoints, parameters, CSV facet, and column projection. ```bash make publish && make mock-server # (in one terminal) make demo-options # (in another) — or: ./gradlew -p examples/consumer-test runOptions ``` -------------------------------- ### Instantiate MarketDataClient in Java Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/client.md Demonstrates creating 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 Stock Prices Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/stocks/prices.md Fetches the latest mid and change prices for specified stock symbols. Ensure the MarketDataClient is properly initialized and 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()); } } ``` -------------------------------- ### Execute Build Commands Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Commands to publish the project and run a live demo against the API. ```bash make publish make demo-live # hits api.marketdata.app — needs MARKETDATA_TOKEN ``` -------------------------------- ### Get Stock Prices Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/stocks/prices.md Retrieves the latest mid-price and change for one or more stock symbols. This method provides a lighter payload compared to a full quote. ```APIDOC ## Get Stock Prices ### Description Retrieves the latest mid-price and change for one or more stock symbols. This method provides a lighter payload compared to a full quote. ### Method `prices(StockPricesRequest request)` `pricesAsync(StockPricesRequest request)` ### Endpoint `/stocks/prices` (Implied) ### Parameters #### Request Body - **request** (StockPricesRequest) - Required - An object specifying the stock symbols for which to retrieve prices. ### Request Example ```java StockPricesRequest request = StockPricesRequest.of("AAPL", "MSFT"); // or using builder: // StockPricesRequest request = StockPricesRequest.builder("AAPL", "MSFT") // .addSymbol("GOOG") // .build(); ``` ### Response #### Success Response - **values** (List) - A list of stock price objects. #### StockPrice Object - **symbol** (String) - The stock symbol. - **mid** (Double) - The mid-price of the stock. - **change** (Double) - The price change. - **changepct** (Double) - The percentage price change. - **updated** (ZonedDateTime) - The timestamp when the price was last updated. #### Response Example ```json { "values": [ { "symbol": "AAPL", "mid": 170.50, "change": 1.25, "changepct": 0.74, "updated": "2023-10-27T10:00:00Z" }, { "symbol": "MSFT", "mid": 330.00, "change": -0.50, "changepct": -0.15, "updated": "2023-10-27T10:00:00Z" } ] } ``` ``` -------------------------------- ### Get Stock News Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/stocks/news.md Retrieves a list of news articles for a given stock symbol. You can specify a date range or a countback period to filter the results. ```APIDOC ## Get Stock News ### Description Retrieves news articles for a specified stock symbol. Supports filtering by date range or a number of articles before a specific date. ### Method `news(StockNewsRequest request)` or `newsAsync(StockNewsRequest request)` ### Endpoint N/A (SDK method) ### Parameters #### Request Object (`StockNewsRequest`) - **symbol** (String) - Required - The stock symbol to retrieve news for. - **date** (LocalDate) - Optional - A single day to retrieve news for. - **from** (LocalDate) - Optional - The start date of the window to retrieve news from. - **to** (LocalDate) - Optional - The end date of the window to retrieve news for. - **countback** (int) - Optional - The number of articles to retrieve before the `to` date. ### Request Example (Java) ```java StockNewsRequest.builder("AAPL") .from(LocalDate.now().minusDays(7)) .to(LocalDate.now()) .build() ``` ### Response #### Success Response (`StockNewsResponse`) Returns a `StockNewsResponse` object which wraps a `List`. `StockNewsArticle` contains: - **symbol** (String) - The stock symbol. - **headline** (String) - The news headline. - **content** (String) - The news content. - **source** (String) - The source of the news article. - **publicationDate** (ZonedDateTime) - The date and time the article was published. ### Response Example (Java) ```java // Assuming 'news' is the StockNewsResponse object for (StockNewsArticle a : news.values()) { System.out.println(a.publicationDate() + " " + a.headline() + " (" + a.source() + ")"); } ``` ``` -------------------------------- ### Initialize and Use MarketDataClient in Java Source: https://github.com/marketdataapp/sdk-java/blob/main/README.md Demonstrates how to initialize the MarketDataClient and fetch options expirations data for a given symbol. Ensure MARKETDATA_TOKEN is set in your environment. ```java try (var client = new MarketDataClient()) { var resp = client.options().expirations(OptionsExpirationsRequest.of("AAPL")); System.out.println(resp.values()); // values() is the typed payload (a List) } ``` -------------------------------- ### MarketDataClient Constructors Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/client.md Demonstrates how to create instances of the MarketDataClient. The no-arg constructor uses the configuration cascade and validates the token on startup. The four-arg constructor allows explicit configuration and optionally skips startup validation. ```APIDOC ## MarketDataClient Constructors ### Description The `MarketDataClient` is the entry point to the SDK. It handles API requests, response parsing, rate-limit tracking, retries with exponential backoff, and logging. A single client gives you access to all five resources: stocks, options, funds, markets, and utilities. The client is immutable, thread-safe, and `AutoCloseable`. Create one per application (it holds a shared HTTP client and a 50-request concurrency pool) and close it when you're done. ### Constructors - **`public MarketDataClient()`** - Production constructor. Resolves token and settings from the configuration cascade and validates the token on startup. - **`public MarketDataClient(@Nullable String apiKey, @Nullable String baseUrl, @Nullable String apiVersion, boolean validateOnStartup)`** - Full control constructor. Any null arguments fall back to the cascade or default for that slot. Useful for tests or environments where startup validation is not desired. ``` -------------------------------- ### Get Option Expirations for a Symbol (Java) Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/options/expirations.md Fetches and prints the expiration dates for a given stock symbol. Ensure the MarketDataClient is properly closed 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()); } } ``` -------------------------------- ### Get Stock Quote (Kotlin) Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/README.md Shows how to use the MarketDataClient in Kotlin with the `use {}` block for automatic resource management. Retrieves a stock quote for AAPL. ```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()}") } ``` -------------------------------- ### Build MarketDataApp SDK with Gradle Source: https://github.com/marketdataapp/sdk-java/blob/main/README.md Use the Gradle wrapper to build the project, run unit tests, format code with Spotless, and generate coverage reports. Ensure JDK 17+ is available. ```bash ./gradlew build ``` ```bash ./gradlew test ``` ```bash ./gradlew spotlessApply ``` ```bash ./gradlew jacocoTestReport ``` -------------------------------- ### Get Option Expirations for a Symbol (Kotlin) Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/options/expirations.md Fetches the expiration dates for a given stock symbol using Kotlin. The `use` extension function ensures the client is closed. ```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") } ``` -------------------------------- ### Demo Funds Creation Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/FUNDS_REVIEW_GUIDE.md Ensures the 'make demo-funds' command succeeds and the funds section in QuickstartApp is enabled. ```bash make demo-funds ``` -------------------------------- ### Initialize MarketDataClient with Constructor Parameters Source: https://github.com/marketdataapp/sdk-java/blob/main/README.md Instantiate the MarketDataClient by passing API key, base URL, and API version directly to the constructor. The `validateOnStartup` parameter controls initial validation. An empty constructor skips explicit parameter configuration. ```java new MarketDataClient(apiKey, baseUrl, apiVersion, validateOnStartup) ``` ```java new MarketDataClient() ``` -------------------------------- ### Build and Test Commands Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/STOCKS_REVIEW_GUIDE.md Commands for building the project, running unit and integration tests, and executing the stocks demo against a mock server. Integration tests require a MARKETDATA_RUN_INTEGRATION_TESTS environment variable set to true and a valid token. ```bash make build # unit tests + Spotless + JaCoCo (JDK 17) # Integration tests hit the live API (gated). A token in .env or the env is required: MARKETDATA_RUN_INTEGRATION_TESTS=true ./gradlew integrationTest # Full stocks demo against the mock server (every endpoint + all params, CSV facet, # columns projection, Option A). Needs the mock server up: make publish && make mock-server # (in one terminal) make demo-stocks # (in another) — or: ./gradlew -p examples/consumer-test runStocks ``` -------------------------------- ### Local Verification Commands Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Commands to set up a mock server and run a demo response for local testing and verification of API interactions. ```bash make publish make mock-server # terminal 2 make demo-response # terminal 3 ``` -------------------------------- ### Instantiate MarketDataClient in Kotlin Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/client.md Shows how to create a MarketDataClient instance in Kotlin using the 'use' block for automatic resource management, with options for default or explicit configuration. ```kotlin import com.marketdata.sdk.MarketDataClient MarketDataClient().use { client -> // ... } MarketDataClient("your_token", null, null, false).use { client -> // ... } ``` -------------------------------- ### Common Makefile Targets for SDK Development Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Lists essential Makefile targets for building, publishing, and running demos of the SDK. Use 'make publish' before running any demo. ```bash make help # list all targets make publish # publish SDK to ~/.m2 — prereq for any demo # Each mock-server demo needs the mock running in a separate terminal: make mock-server # terminal 2 (blocks; Ctrl+C to stop) make demo-config # terminal 3 — runs DemoAndConfigApp make demo-retry # ...etc make demo-live # hits api.marketdata.app (needs MARKETDATA_TOKEN, no mock needed) make demos-all # runs the five mock-server demos back-to-back ``` -------------------------------- ### Local Verification Commands Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Commands to build, run a mock server, and execute a retry demonstration locally. ```bash make publish make mock-server # terminal 2 make demo-retry # terminal 3 ``` -------------------------------- ### Get Single Stock Quote Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/stocks/quotes.md Fetches real-time quote data for a single stock symbol. You can optionally include extended session prices, OHLC candle data, and 52-week high/low information. ```APIDOC ## Get Single Stock Quote ### Description Retrieves real-time quote data for a single stock symbol. Supports options to include extended session prices, OHLC candle data, and 52-week high/low information. ### Method Signature ```java StockQuotesResponse quote(StockQuoteRequest request) CompletableFuture quoteAsync(StockQuoteRequest request) ``` ### Request Type `StockQuoteRequest` #### Static Factory Methods - `StockQuoteRequest.of(String symbol)`: Creates a request for a single symbol. - `StockQuoteRequest.builder(String symbol)`: Creates a builder for a single symbol request. #### Builder Options - `.extended(boolean extended)`: Include extended-session prices. - `.candle(boolean candle)`: Add OHLC (Open, High, Low, Close) columns. - `.week52(boolean week52)`: Add 52-week high/low columns. - `.build()`: Constructs the `StockQuoteRequest` object. ### Response `StockQuotesResponse` wrapping a `List` (containing a single element for a single symbol request). #### `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)`) ``` -------------------------------- ### Market Status Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/markets/status.md Use the `status()` method on the `markets` resource to get the exchange open/closed calendar. Every parameter is optional; a bare request returns today's status for the US market. ```APIDOC ## Market Status ### Description Retrieves the exchange open/closed calendar for a specified date or date range. ### Method `status(MarketStatusRequest request)` `statusAsync(MarketStatusRequest request)` ### Parameters #### Request Body (`MarketStatusRequest`) - `country` (String) - Optional - ISO 3166, 2-letter country code (default: US). - `date` (LocalDate) - Optional - A single specific date to check. - `from` (LocalDate) - Optional - The start date of the range (inclusive). - `to` (LocalDate) - Optional - The end date of the range (inclusive). - `countback` (int) - Optional - Number of days before `to` to include in the check. ### Request Example ```java // Example using builder for a date range MarketStatusRequest request = MarketStatusRequest.builder() .from(LocalDate.now().minusDays(7)) .to(LocalDate.now()) .build(); ``` ### Response #### Success Response (`MarketStatusResponse`) Returns a `MarketStatusResponse` object which contains a list of `MarketStatus` objects. `MarketStatus` object contains: - `date` (ZonedDateTime) - The date of the status. - `status` (String) - The status of the market on that date ("open", "closed", or null if outside coverage). - `isOpen()` (boolean) - A convenience method to check if the market is open. ``` -------------------------------- ### Run Startup Validation Logic Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Performs the actual startup validation. Skips validation in demo mode. It attempts to validate authentication via `utilities.validateAuth()`. If any error occurs during validation, it ensures the transport is closed before re-throwing the exception. ```java if (DemoMode.isDemo(config)) { LOGGER.info(() -> "validateOnStartup skipped: demo mode is active (no token configured)."); return; } try { utilities.validateAuth(); } catch (Throwable t) { try { close(); } catch (Throwable closeFailure) { t.addSuppressed(closeFailure); } throw t; } ``` -------------------------------- ### Composing Async Calls with thenCompose in Kotlin Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/client.md Illustrates chaining dependent asynchronous calls using `thenCompose` in Kotlin. This example first looks up an option symbol and then uses that symbol to fetch its quote. ```kotlin import com.marketdata.sdk.options.OptionsLookupRequest import com.marketdata.sdk.options.OptionsQuoteRequest import com.marketdata.sdk.stocks.StockQuoteRequest import java.util.concurrent.CompletableFuture // 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())) } ``` -------------------------------- ### Build and Test MarketDataApp SDK Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/FUNDS_REVIEW_GUIDE.md Commands to build the project, run unit tests, and execute integration tests against the live API. Ensure MARKETDATA_RUN_INTEGRATION_TESTS is set for integration tests. ```bash make build # unit tests + Spotless + JaCoCo (JDK 17) # Integration tests hit the live API (gated). A token in .env or the env is required: MARKETDATA_RUN_INTEGRATION_TESTS=true ./gradlew integrationTest ``` -------------------------------- ### Re-checking Cache Status After Trigger Refresh Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Ensures the cache status is re-evaluated after triggering a refresh, especially in test environments with synchronous fetchers. This prevents incorrect ALLOW decisions on cold starts. ```java StatusCache.java:69 ``` -------------------------------- ### Running Unit Tests with Specific JDKs Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Demonstrates how to execute unit tests using specific Java Development Kit versions via Gradle. CI uses a matrix of JDKs 17, 21, and 25. ```bash make test # ./gradlew test make build # full build: tests + Spotless + JaCoCo ./gradlew -PtestJdk=21 test # JDK 21 unit tests (also works for 25) ``` -------------------------------- ### Running Demo Scripts Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Execute these commands to run the preflight check demo. Ensure the mock server and demo retry scripts are run in separate terminals. ```bash make publish make mock-server # terminal 2 make demo-retry # terminal 3 — scroll to "§10.3 preflight" output ``` -------------------------------- ### Get Service Status Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/utilities/status.md Use the `status()` method on the `utilities` resource to retrieve the health of the Market Data API's services. This method takes no parameters and is public, meaning it works without authentication. ```APIDOC ## Get Service Status ### Description Retrieves the health of the Market Data API's services, serving as a liveness check. ### Method ```java UtilitiesStatusResponse status() CompletableFuture statusAsync() ``` ### Returns `UtilitiesStatusResponse` which wraps a `List`. Each `ServiceStatus` object contains the service name, its status string, an `online()` boolean flag, uptime percentiles, and a timestamp of the last update. ### Request Example ```java import com.marketdata.sdk.MarketDataClient; import com.marketdata.sdk.utilities.ServiceStatus; try (MarketDataClient client = new MarketDataClient()) { var status = client.utilities().status(); long online = status.values().stream().filter(ServiceStatus::online).count(); System.out.println(online + " of " + status.values().size() + " services online"); } ``` ### Kotlin Example ```kotlin import com.marketdata.sdk.MarketDataClient import com.marketdata.sdk.utilities.ServiceStatus MarketDataClient().use { client -> val status = client.utilities().status() val online = status.values().count { it.online() } println("$online of ${status.values().size} services online") } ``` ``` -------------------------------- ### Chaining Universal Parameters in Java Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/settings.md Illustrates how to chain universal parameters like dateFormat, mode, and columns on a resource before making a request. Each setter returns a configured copy of the resource. ```java import com.marketdata.sdk.DateFormat; import com.marketdata.sdk.Mode; import com.marketdata.sdk.stocks.StockCandlesRequest; import com.marketdata.sdk.stocks.StockResolution; var candles = client.stocks() .dateFormat(DateFormat.TIMESTAMP) // how dates are sent on the wire .mode(Mode.DELAYED) // live vs delayed vs cached data .columns("symbol", "close") // project only the columns you need .candles(StockCandlesRequest.builder(StockResolution.DAILY, "AAPL") .from(LocalDate.now().minusMonths(1)) .to(LocalDate.now()) .build()); ``` -------------------------------- ### Run Integration Tests with Gradle Source: https://github.com/marketdataapp/sdk-java/blob/main/README.md Execute integration tests by setting the MARKETDATA_RUN_INTEGRATION_TESTS environment variable and running the appropriate Gradle task. This hits the live API. ```bash MARKETDATA_RUN_INTEGRATION_TESTS=true ./gradlew integrationTest ``` -------------------------------- ### Buffering and Replaying Warnings During Initialization Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md This snippet shows how initialization warnings from DotEnvLoader are buffered and replayed after MarketDataLogging is configured to ensure they are logged correctly. ```Java List pendingWarnings = new ArrayList<>(); try { this.config = Configuration.resolve(apiKey, baseUrl, apiVersion, env, dotEnvPath, pendingWarnings::add); } catch (RuntimeException e) { attachWarningsAsSuppressed(e, pendingWarnings); throw e; } ``` -------------------------------- ### Get Request Headers (Kotlin) Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/utilities/headers.md Retrieves the HTTP headers the server received for the current request using the Kotlin SDK. A valid token is required for authentication. The response provides a map of header keys to values. ```kotlin import com.marketdata.sdk.MarketDataClient MarketDataClient().use { client -> val headers = client.utilities().headers().values() println("Server saw ${headers.size} request headers") } ``` -------------------------------- ### Get Request Headers (Java) Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/utilities/headers.md Retrieves the HTTP headers the server received for the current request using the Java SDK. Ensure you have a valid token for authentication. The response contains a map of header keys to values. ```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"); } ``` -------------------------------- ### Fetch Options Chain with Filters Source: https://github.com/marketdataapp/sdk-java/blob/main/README.md Retrieves an options chain for a given symbol, allowing filtering by expiration, strike price range, option side, and strike limit. Use this to get a specific subset of options contracts. ```java try (var client = new MarketDataClient()) { var resp = client.options().chain( OptionsChainRequest.builder("AAPL") .expirationFilter(ExpirationFilter.all()) // every expiration, not just front-month .strikeFilter(StrikeFilter.range(150, 200)) // 150 <= strike <= 200 .side(OptionSide.CALL) .strikeLimit(5) .build()); for (OptionQuote q : resp.values()) { // values() is a List System.out.printf("%s delta=%s rho=%s%n", q.optionSymbol(), q.delta(), q.rho()); // delta/rho are @Nullable Double } } ``` -------------------------------- ### Initialize and Use MarketDataClient in Kotlin Source: https://github.com/marketdataapp/sdk-java/blob/main/README.md Shows how to initialize the MarketDataClient and retrieve options expiration dates for a stock symbol. The SDK defaults to using the MARKETDATA_TOKEN environment variable. ```kotlin MarketDataClient().use { client -> val resp = client.options().expirations(OptionsExpirationsRequest.of("AAPL")) println(resp.values()) // List } ``` -------------------------------- ### Configure .env File Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/authentication.md Defines the MARKETDATA_TOKEN in a .env file for automatic loading by the SDK. Ensure this file is added to .gitignore. ```env MARKETDATA_TOKEN=your_api_token ``` -------------------------------- ### Get Multiple Stock Quotes Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/stocks/quotes.md Fetches real-time quote data for multiple stock symbols in a single request. The backend batches symbols into a comma-separated list. Options for extended session, candle data, and 52-week information are available. ```APIDOC ## Get Multiple Stock Quotes ### Description Retrieves real-time quote data for multiple stock symbols efficiently in a single request. The backend processes symbols as a comma-separated list. Options for extended session prices, OHLC candle data, and 52-week high/low information can be included. ### Method Signature ```java StockQuotesResponse quotes(StockQuotesRequest request) CompletableFuture quotesAsync(StockQuotesRequest request) ``` ### Request Type `StockQuotesRequest` #### Static Factory Methods - `StockQuotesRequest.of(String first, String... rest)`: Shortcut to create a request with symbols only. - `StockQuotesRequest.builder(String first, String... rest)`: Creates a builder for multiple symbol requests. #### Builder Options - `.addSymbol(String symbol)`: Adds another symbol to the request. - `.extended(boolean extended)`: Include extended-session prices. - `.candle(boolean candle)`: Add OHLC (Open, High, Low, Close) columns. - `.week52(boolean week52)`: Add 52-week high/low columns. - `.build()`: Constructs the `StockQuotesRequest` object. ### Response `StockQuotesResponse` wrapping a `List` (one element per symbol requested). #### `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)`) ``` -------------------------------- ### Running Concurrency Demo Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Execute these commands in separate terminals to run the concurrency demo. The demo verifies the peak in-flight requests and total wall-time for parallel asynchronous calls. ```bash make publish make mock-server # terminal 2 make demo-concurrency # terminal 3 ``` -------------------------------- ### Async Stock Quote Request with Error Handling (Kotlin) Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/client.md Fetches a stock quote asynchronously and handles potential `RateLimitError` by checking the cause of a `CompletionException`. This Kotlin version mirrors the Java example for asynchronous operations and error management. ```kotlin import com.marketdata.sdk.exception.RateLimitError import com.marketdata.sdk.stocks.StockQuoteRequest import java.util.concurrent.CompletionException client.stocks().quoteAsync(StockQuoteRequest.of("AAPL")) .thenApply { resp -> resp.values()[0].last() } .exceptionally { ex -> val cause = if (ex is CompletionException && ex.cause != null) ex.cause else ex if (cause is RateLimitError) println("Rate limited — backing off") null } .join() ``` -------------------------------- ### Market Data Support Info Formatting Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Illustrates the formatted output of the getSupportInfo() method from MarketDataException. This multi-line string is designed for easy pasting into support tickets, including request details, error messages, and exception types. ```text --- MARKET DATA SUPPORT INFO --- request_id: 76a40b21d5e1c0a4-IAD request_url: /user/?... status_code: 401 timestamp: 2026-05-21 09:12:34 message: Authentication failed exception_type: AuthenticationError -------------------------------- ``` -------------------------------- ### Fetch Options Chain with Filters (Kotlin) Source: https://github.com/marketdataapp/sdk-java/blob/main/README.md Retrieves an options chain for a given symbol in Kotlin, allowing filtering by expiration, strike price range, option side, and strike limit. Use this to get a specific subset of options contracts. ```kotlin MarketDataClient().use { client -> val resp = client.options().chain( OptionsChainRequest.builder("AAPL") .expirationFilter(ExpirationFilter.all()) .strikeFilter(StrikeFilter.range(150.0, 200.0)) .side(OptionSide.CALL) .strikeLimit(5) .build() ) resp.values().forEach { q -> println("${q.optionSymbol} delta=${q.delta} rho=${q.rho}") // delta/rho are nullable } } ``` -------------------------------- ### Conditional Startup Validation Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/REFACTOR_REVIEW_GUIDE.md Executes startup validation checks if the 'validateOnStartup' flag is true. This includes an authentication validation step to ensure the client can communicate with the API. ```java if (validateOnStartup) { runStartupValidation(); } ``` -------------------------------- ### Universal Parameters and CSV Output Source: https://github.com/marketdataapp/sdk-java/blob/main/README.md Demonstrates the use of universal parameters for configuring API calls, such as date format, mode, and column projection. Also shows how to retrieve data in CSV format. ```APIDOC ## Universal Parameters and CSV Output ### Description Demonstrates the use of universal parameters for configuring API calls, such as date format, mode, and column projection. Also shows how to retrieve data in CSV format. ### Method `client.options().dateFormat(...).mode(...).limit(...).columns(...).chain(...) `client.options().asCsv().columns(...).chain(...) ### Parameters Universal parameters can be set fluently on the `client.options()` resource before calling specific methods like `chain()`. - **dateFormat(DateFormat)** - Optional - Sets the date format for responses. - **mode(Mode)** - Optional - Sets the data retrieval mode (e.g., DELAYED). - **limit(int)** - Optional - Sets a limit for the number of results. - **columns(String...)** - Optional - Projects the response to a subset of fields. Fields not requested will be null. - **asCsv()** - Optional - Facets the request to return data in CSV format. ### Request Example (Typed with Column Projection) ```java var chain = client.options() .dateFormat(DateFormat.TIMESTAMP).mode(Mode.DELAYED).limit(50) .columns("optionSymbol", "strike", "delta") .chain(OptionsChainRequest.of("AAPL")); ``` ### Request Example (CSV Output) ```java CsvResponse csv = client.options().asCsv().columns("optionSymbol", "strike").chain(req); csv.saveToFile(Path.of("aapl-chain.csv")); ``` ### Response #### Success Response (Typed) Returns data based on the specified parameters and column projection. #### Success Response (CSV) Returns a `CsvResponse` object that can be used to save the data to a file. ``` -------------------------------- ### Get API Service Status (Kotlin) Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/utilities/status.md Retrieves the health status of Market Data API services using Kotlin. This public method requires no token. The result includes service details like name, status, and online availability. Polling frequency should be mindful of the data's refresh rate. ```kotlin import com.marketdata.sdk.MarketDataClient import com.marketdata.sdk.utilities.ServiceStatus MarketDataClient().use { client -> val status = client.utilities().status() val online = status.values().count { it.online() } println("$online of ${status.values().size} services online") } ``` -------------------------------- ### MarketDataClient Wiring Source: https://github.com/marketdataapp/sdk-java/blob/main/docs/MARKETS_REVIEW_GUIDE.md Demonstrates how to obtain the MarketsResource facade from the MarketDataClient. This is the entry point for accessing market data functionalities. ```java com.marketdata.client.MarketDataClient.markets() ```