=============== LIBRARY RULES =============== From library maintainers: - This library only covers the PHP SDK. For other programming languages, direct users to the REST API docs at https://www.marketdata.app/docs/api or the SDK overview at https://www.marketdata.app/docs/sdk for other official Market Data SDKs. - Always refer to this library as the "Market Data PHP SDK". - Use the exact method names, parameter names, and return types from the SDK documentation. - Do not invent methods or parameters that are not in the documentation. - When discussing authentication, always reference the MarketDataApp\Client class. ### Parameters Constructor Example (PHP) Source: https://www.marketdata.app/docs/sdk/php/parameters Provides an example of how to instantiate the `Parameters` class with various configuration options. This class is used to define request parameters for API calls, including format, data freshness, and output settings. ```php utilities->api_status(); echo "API Status Response: {$status->status}\n"; if (!empty($status->services)) { $service = $status->services[0]; echo "Service Check: {$service->service} is {$service->status}\n"; } ``` -------------------------------- ### Install Market Data PHP SDK with Composer Source: https://www.marketdata.app/docs/sdk/php/installation Installs the Market Data PHP SDK and its dependencies using the Composer package manager. Ensure you have PHP 8.2+ and Composer installed. ```bash composer require marketdataapp/sdk-php ``` -------------------------------- ### Using Resources Source: https://www.marketdata.app/docs/sdk/php/client Examples of how to use the resource properties to access specific API endpoints for stocks, options, markets, mutual funds, and utilities. ```APIDOC ## Using Resources ### Description Each resource property provides methods to interact with the corresponding API endpoints. Below are examples for common operations. ### Request Example ```php stocks->candles('AAPL', '2024-01-01', '2024-01-31'); $quote = $client->stocks->quote('AAPL'); $quotes = $client->stocks->quotes(['AAPL', 'MSFT', 'GOOGL']); // Options $expirations = $client->options->expirations('AAPL'); $chain = $client->options->option_chain('AAPL', expiration: '2025-01-17'); // Markets $status = $client->markets->status(); // Mutual Funds $fundCandles = $client->mutual_funds->candles('VFINX', '2024-01-01', '2024-01-31'); // Utilities $apiStatus = $client->utilities->api_status(); $user = $client->utilities->user(); ``` ``` -------------------------------- ### Get Support Info from ApiException in PHP Source: https://www.marketdata.app/docs/sdk/php/errors Shows how to use the getSupportInfo() method on an ApiException to retrieve a human-readable string containing request details, useful for debugging and support tickets. ```php getSupportInfo(); // Returns formatted string like: // Request URL: https://api.marketdata.app/v1/stocks/quotes/?symbol=INVALID // HTTP Status: 400 // Error Message: Symbol not found echo $supportInfo; } ``` -------------------------------- ### Get Support Context from ApiException in PHP Source: https://www.marketdata.app/docs/sdk/php/errors Demonstrates using getSupportContext() on an ApiException to obtain a structured associative array of error details, ideal for logging purposes in monitoring systems. ```php getSupportContext(); // Returns array like: // [ // 'request_url' => 'https://api.marketdata.app/v1/stocks/quotes/?symbol=INVALID', // 'http_status' => 400, // 'error_message' => 'Symbol not found' // ] // Log to your monitoring system $logger->error('API call failed', $context); } ``` -------------------------------- ### Update Market Data PHP SDK with Composer Source: https://www.marketdata.app/docs/sdk/php/installation Updates the Market Data PHP SDK to the latest available version using Composer. This command fetches the newest version and updates any dependencies as needed. ```bash composer update marketdataapp/sdk-php ``` -------------------------------- ### Handle API Exceptions Source: https://www.marketdata.app/docs/sdk/php/client Provides an example of how to handle potential errors during API interactions using try-catch blocks. It demonstrates catching specific exceptions like `UnauthorizedException`, `ApiException`, and `BadStatusCodeError`. ```php stocks->quote('INVALID_SYMBOL'); } catch (UnauthorizedException $e) { echo "Authentication failed: " . $e->getMessage(); } catch (ApiException $e) { echo "API error: " . $e->getMessage(); echo "\nSupport info: " . $e->getSupportInfo(); } catch (BadStatusCodeError $e) { echo "Request failed: " . $e->getMessage(); } ``` -------------------------------- ### Handle Invalid API Token Exception (PHP) Source: https://www.marketdata.app/docs/sdk/php/authentication This PHP example shows how to catch the UnauthorizedException that is thrown when an invalid API token is used during client initialization. It includes a try-catch block to gracefully handle authentication errors. ```php getMessage(); } ``` -------------------------------- ### Fetch Option Chain as CSV - PHP Source: https://www.marketdata.app/docs/sdk/php/options/chain Retrieves an option chain and formats the response as CSV. This example shows how to specify the desired format using the `Parameters` object and then access the raw CSV data using the `getCsv()` method. ```php options->option_chain( symbol: 'AAPL', expiration: '2025-01-17', side: Side::CALL, strike_limit: 10, parameters: new Parameters(format: Format::CSV) ); echo $chain->getCsv(); ``` -------------------------------- ### Get Trading Days Count with PHP Source: https://www.marketdata.app/docs/sdk/php/markets/status Fetches the market status for a specified period and counts the number of trading days (when the market was 'open'). This example uses the `to` and `countback` parameters to look back a certain number of days. ```php markets->status( to: 'today', countback: 20 ); $tradingDays = 0; foreach ($statuses->statuses as $status) { if ($status->status === 'open') { $tradingDays++; } } echo "Last " . count($statuses->statuses) . " days included " . $tradingDays . " trading days.\n"; ``` -------------------------------- ### Get Historical Option Quote for a Specific Date (PHP) Source: https://www.marketdata.app/docs/sdk/php/options/quotes Retrieves historical option quote data for a specific date using the MarketData App SDK. This is useful for analyzing past market conditions for a particular option contract. The example shows how to access the last traded price and implied volatility. ```php options->quotes( option_symbols: 'AAPL250117C00200000', date: '2024-01-15' ); echo "Historical Quote (2024-01-15):\n"; foreach ($quotes->quotes as $quote) { echo "Last: $" . $quote->last . "\n"; echo "IV: " . number_format($quote->iv * 100, 1) . "%\n"; } ``` -------------------------------- ### Client Initialization Source: https://www.marketdata.app/docs/sdk/php/client Demonstrates how to create an instance of the Market Data SDK Client, with options for using environment variables, explicit API tokens, and custom loggers. ```APIDOC ## Client Initialization ### Description Instantiate the Market Data SDK Client. You can authenticate using an environment variable, an explicit API token, or provide a custom PSR-3 logger. ### Method `__construct(string $token = null, LoggerInterface $logger = null)` ### Parameters - **token** (string, optional) - Your Market Data API token. If not provided, the SDK looks for the `MARKETDATA_TOKEN` environment variable or `.env` file. - **logger** (LoggerInterface, optional) - A PSR-3 compatible logger instance. If not provided, a default logger is created based on `MARKETDATA_LOGGING_LEVEL`. ### Request Example ```php stocks->quote('AAPL'); // Uses: format=CSV, date_format=TIMESTAMP ``` -------------------------------- ### Parameters Constructor Source: https://www.marketdata.app/docs/sdk/php/parameters Details the constructor for the `Parameters` class, outlining the available options for customizing API requests. ```APIDOC ## Parameters Constructor The `Parameters` class is used to define and pass universal parameters to API requests. It accepts various options to customize the response format, data freshness, and output details. ### Available Options for `Parameters` Constructor - **`format`** (`MarketDataApp\Enums\Format`): Specifies the response format (e.g., `Format::JSON`, `Format::CSV`). - **`use_human_readable`** (`bool`): If `true`, returns human-readable values. - **`mode`** (`MarketDataApp\Enums\Mode`): Sets the data freshness mode (e.g., `Mode::CACHED`, `Mode::REALTIME`). - **`maxage`** (`int`): The maximum age of cached data in seconds. - **`date_format`** (`MarketDataApp\Enums\DateFormat`): The date format for CSV/HTML responses (e.g., `DateFormat::UNIX`, `DateFormat::TIMESTAMP`). - **`columns`** (`array`): An array of column names to select for CSV/HTML output. - **`add_headers`** (`bool`): If `true`, includes headers in CSV/HTML output. - **`filename`** (`string`): The output file path for CSV/HTML responses. ### Example Usage of `Parameters` Constructor ```php options->option_chain('AAPL'); echo "AAPL Options Chain\n"; echo "==================\n"; echo "Total contracts: " . count($chain->options) . "\n\n"; // Display first few contracts foreach (array_slice($chain->options, 0, 5) as $option) { echo sprintf( "%s: Bid $%.2f / Ask $%.2f (Vol: %d, OI: %d)\n", $option->option_symbol, $option->bid, $option->ask, $option->volume, $option->open_interest ); } ?> ``` ### Response #### Success Response (200) - **status** (string) - Response status (`"ok"` or `"no_data"`). - **options** (array) - Array of option contracts, each containing: - **option_symbol** (string): OCC-formatted option symbol - **underlying** (string): Underlying ticker symbol - **expiration** (Carbon): Expiration date - **side** (string): "call" or "put" - **strike** (float): Strike price - **bid** (float): Bid price - **bid_size** (int): Bid size - **ask** (float): Ask price - **ask_size** (int): Ask size - **mid** (float): Midpoint price - **last** (float): Last trade price - **volume** (int): Daily volume - **open_interest** (int): Open interest - **delta** (float|null): Delta greek - **gamma** (float|null): Gamma greek - **theta** (float|null): Theta greek - **vega** (float|null): Vega greek - **iv** (float|null): Implied volatility - **updated** (Carbon): Last update timestamp #### Response Example ```json { "status": "ok", "options": [ { "option_symbol": "AAPL250117C00150000", "underlying": "AAPL", "expiration": "2025-01-17 00:00:00", "side": "call", "strike": 150.0, "bid": 50.25, "bid_size": 10, "ask": 50.50, "ask_size": 5, "mid": 50.375, "last": 50.30, "volume": 1500, "open_interest": 5000, "delta": 0.75, "gamma": 0.15, "theta": -0.05, "vega": 0.10, "iv": 0.20, "updated": "2024-01-15 10:30:00" } // ... more option contracts ] } ``` ``` -------------------------------- ### Stocks - Quote Source: https://www.marketdata.app/docs/sdk/php/stocks Get a real-time price quote for a single stock symbol. ```APIDOC ## GET /stocks/quote ### Description Get a real-time price quote for a single stock symbol. ### Method GET ### Endpoint /stocks/quote ### Parameters #### Query Parameters - **symbol** (string) - Required - The stock symbol (e.g., AAPL). ### Request Example ``` GET /stocks/quote?symbol=AAPL ``` ### Response #### Success Response (200) - **symbol** (string) - The stock symbol. - **open** (float) - The opening price. - **high** (float) - The highest price. - **low** (float) - The lowest price. - **close** (float) - The closing price. - **volume** (integer) - The trading volume. - **timestamp** (integer) - The Unix timestamp of the quote. #### Response Example ```json { "symbol": "AAPL", "open": 168.00, "high": 171.00, "low": 167.50, "close": 170.50, "volume": 50000000, "timestamp": 1678886400 } ``` ``` -------------------------------- ### Available Environment Variables Source: https://www.marketdata.app/docs/sdk/php/parameters Lists universal environment variables that can be set to configure parameters globally across the SDK. ```APIDOC ## Available Environment Variables You can set the following environment variables to configure universal parameters globally: | Variable | Values | Description | | ------------------------- | ------------------------------------- | ------------------------------------------------ | | `MARKETDATA_FORMAT` | `json`, `csv`, `html` | Output format | | `MARKETDATA_DATE_FORMAT` | `timestamp`, `unix`, `spreadsheet` | Date format for CSV/HTML | | `MARKETDATA_COLUMNS` | Comma-separated list | Columns to include | | `MARKETDATA_ADD_HEADERS` | `true`, `false` | Include headers in CSV/HTML | | `MARKETDATA_USE_HUMAN_READABLE` | `true`, `false` | Human-readable format | | `MARKETDATA_MODE` | `live`, `cached`, `delayed` | Data mode | ``` -------------------------------- ### Options Quotes API Source: https://www.marketdata.app/docs/sdk/php/options Get current or historical end-of-day quotes for one or more options contracts. ```APIDOC ## GET /websites/marketdata_app_sdk_php/options/quotes ### Description Get current or historical end-of-day quotes for one or more options contracts. ### Method GET ### Endpoint /websites/marketdata_app_sdk_php/options/quotes ### Parameters #### Query Parameters - **option_symbols** (array) - Required - A list of OCC option symbols. - **historical** (boolean) - Optional - Set to true to retrieve historical quotes. ### Response #### Success Response (200) - **quotes** (object) - An object where keys are option symbols and values are quote details (bid, ask, last_price, etc.). #### Response Example ```json { "quotes": { "231215C00170000": { "bid": 2.50, "ask": 2.60, "last_price": 2.55, "volume": 1000, "open_interest": 5000 }, "231215P00170000": { "bid": 1.50, "ask": 1.60, "last_price": 1.55, "volume": 800, "open_interest": 4500 } } } ``` ``` -------------------------------- ### Configuration Priority and Usage Source: https://www.marketdata.app/docs/sdk/php/parameters This section details how universal parameters like output format and date format are configured in the Market Data PHP SDK. It explains the priority order: Environment Variables (lowest), Client Default Parameters, and Direct Method Parameters (highest). ```APIDOC ## Configuration Priority and Usage The Market Data PHP SDK allows for flexible configuration of universal parameters, which are applied to API requests. The SDK supports a priority hierarchy for these configurations: 1. **Environment Variables**: Lowest priority. Set globally using variables like `MARKETDATA_FORMAT`. 2. **Client Default Parameters (`$client->default_params`)**: Medium priority. Set on a specific client instance and applied to all its requests unless overridden. 3. **Direct Method Parameters**: Highest priority. Passed directly to resource methods and override all other settings for that specific call. When an API call is made, the SDK merges these parameters, with higher priority settings overriding lower ones. This ensures that specific calls can override global or client-level defaults. ### Example: Setting Environment Variables ```php stocks->quote('AAPL'); // Uses: format=CSV, date_format=TIMESTAMP ``` ### Example: Setting Client Default Parameters ```php default_params = new Parameters( format: Format::JSON, date_format: DateFormat::TIMESTAMP ); // All calls will use JSON format and timestamp date format // (unless overridden by method parameters) $quote = $client->stocks->quote('AAPL'); // Uses: format=JSON, date_format=TIMESTAMP $quotes = $client->stocks->quotes(['AAPL', 'MSFT']); // Uses: format=JSON, date_format=TIMESTAMP ``` **Note:** `$client->default_params` overrides environment variables. ### Example: Passing Parameters Directly to Resource Methods ```php default_params = new Parameters( format: Format::JSON, date_format: DateFormat::TIMESTAMP ); // Direct method parameters override default_params $candles = $client->stocks->candles( 'AAPL', '2024-01-01', '2024-01-31', parameters: new Parameters( format: Format::CSV, // Overrides JSON date_format: DateFormat::UNIX // Overrides TIMESTAMP ) ); // Uses: format=CSV, date_format=UNIX // This call still uses default_params $quote = $client->stocks->quote('AAPL'); // Uses: format=JSON, date_format=TIMESTAMP ``` **Note:** Direct method parameters override both environment variables and `$client->default_params`. ``` -------------------------------- ### Stocks - Quotes Source: https://www.marketdata.app/docs/sdk/php/stocks Get real-time price quotes for multiple stocks in a single API request. ```APIDOC ## GET /stocks/quotes ### Description Get real-time price quotes for multiple stocks in a single API request. ### Method GET ### Endpoint /stocks/quotes ### Parameters #### Query Parameters - **symbols** (string) - Required - A comma-separated list of stock symbols (e.g., AAPL,MSFT). ### Request Example ``` GET /stocks/quotes?symbols=AAPL,MSFT ``` ### Response #### Success Response (200) - **symbol** (string) - The stock symbol. - **open** (float) - The opening price. - **high** (float) - The highest price. - **low** (float) - The lowest price. - **close** (float) - The closing price. - **volume** (integer) - The trading volume. - **timestamp** (integer) - The Unix timestamp of the quote. #### Response Example ```json { "data": [ { "symbol": "AAPL", "open": 168.00, "high": 171.00, "low": 167.50, "close": 170.50, "volume": 50000000, "timestamp": 1678886400 }, { "symbol": "MSFT", "open": 278.00, "high": 281.00, "low": 277.50, "close": 280.25, "volume": 30000000, "timestamp": 1678886400 } ] } ``` ``` -------------------------------- ### Pass Parameters Directly to Resource Methods (PHP) Source: https://www.marketdata.app/docs/sdk/php/parameters Illustrates how to pass parameters directly to resource methods, providing the highest priority for configuration. These parameters override both environment variables and client default parameters for the specific API call. The `Parameters` object is used for this purpose. ```php default_params = new Parameters( format: Format::JSON, date_format: DateFormat::TIMESTAMP ); // Direct method parameters override default_params $candles = $client->stocks->candles( 'AAPL', '2024-01-01', '2024-01-31', parameters: new Parameters( format: Format::CSV, // Overrides JSON date_format: DateFormat::UNIX // Overrides TIMESTAMP ) ); // Uses: format=CSV, date_format=UNIX // This call still uses default_params $quote = $client->stocks->quote('AAPL'); // Uses: format=JSON, date_format=TIMESTAMP ``` -------------------------------- ### Stocks - Prices Source: https://www.marketdata.app/docs/sdk/php/stocks Get real-time midpoint prices for one or more stocks using the SmartMid model. ```APIDOC ## GET /stocks/prices ### Description Get real-time midpoint prices for one or more stocks using the SmartMid model. ### Method GET ### Endpoint /stocks/prices ### Parameters #### Query Parameters - **symbols** (string) - Required - A comma-separated list of stock symbols (e.g., AAPL,MSFT). ### Request Example ``` GET /stocks/prices?symbols=AAPL,MSFT ``` ### Response #### Success Response (200) - **symbol** (string) - The stock symbol. - **price** (float) - The real-time midpoint price. - **timestamp** (integer) - The Unix timestamp of the price. #### Response Example ```json { "data": [ { "symbol": "AAPL", "price": 170.50, "timestamp": 1678886400 }, { "symbol": "MSFT", "price": 280.25, "timestamp": 1678886400 } ] } ``` ``` -------------------------------- ### Stocks - Earnings Source: https://www.marketdata.app/docs/sdk/php/stocks Get historical earnings per share data or a future earnings calendar for a stock. ```APIDOC ## GET /stocks/earnings ### Description Get historical earnings per share data or a future earnings calendar for a stock. ### Method GET ### Endpoint /stocks/earnings ### Parameters #### Query Parameters - **symbol** (string) - Required - The stock symbol (e.g., AAPL). - **from** (integer) - Optional - The start date (Unix epoch time) for historical earnings. - **to** (integer) - Optional - The end date (Unix epoch time) for historical earnings or future earnings calendar. ### Request Example ``` GET /stocks/earnings?symbol=AAPL&from=1640995200&to=1672531200 ``` ### Response #### Success Response (200) - **symbol** (string) - The stock symbol. - **eps_actual** (float) - The actual earnings per share. - **eps_estimate** (float) - The estimated earnings per share. - **surprise** (float) - The surprise percentage. - **date** (string) - The earnings date. #### Response Example ```json { "symbol": "AAPL", "historical_earnings": [ { "eps_actual": 1.52, "eps_estimate": 1.40, "surprise": 8.57, "date": "2023-01-27" }, { "eps_actual": 1.24, "eps_estimate": 1.20, "surprise": 3.33, "date": "2022-10-27" } ], "upcoming_earnings": [ { "date": "2023-04-27" } ] } ``` ``` -------------------------------- ### Configure Data Mode in PHP Source: https://www.marketdata.app/docs/sdk/php/parameters Control API request fulfillment, data freshness, and credit usage by setting the data mode. Available modes are LIVE, CACHED, and DELAYED. This setting impacts paid plans, with free/trial plans defaulting to DELAYED. Configuration can be done via environment variables, client defaults, or direct parameters. ```php options->option_chain( 'SPY', expiration: '2025-01-17', parameters: new Parameters(mode: Mode::CACHED) ); // Use live mode for real-time quotes $quote = $client->stocks->quote( 'AAPL', parameters: new Parameters(mode: Mode::LIVE) ); ``` -------------------------------- ### Options Strikes API Source: https://www.marketdata.app/docs/sdk/php/options Get a list of current or historical option strike prices for an underlying symbol. ```APIDOC ## GET /websites/marketdata_app_sdk_php/options/strikes ### Description Get a list of current or historical option strike prices for an underlying symbol. ### Method GET ### Endpoint /websites/marketdata_app_sdk_php/options/strikes ### Parameters #### Query Parameters - **underlying_symbol** (string) - Required - The ticker symbol of the underlying asset. - **expiration_date** (string) - Required - The expiration date in YYYY-MM-DD format. - **historical** (boolean) - Optional - Set to true to retrieve historical strike prices. ### Response #### Success Response (200) - **strikes** (array) - A list of strike prices. #### Response Example ```json { "strikes": [ 160.00, 165.00, 170.00, 175.00 ] } ``` ``` -------------------------------- ### Options Expirations API Source: https://www.marketdata.app/docs/sdk/php/options Get a list of current or historical option expiration dates for an underlying symbol. ```APIDOC ## GET /websites/marketdata_app_sdk_php/options/expirations ### Description Get a list of current or historical option expiration dates for an underlying symbol. ### Method GET ### Endpoint /websites/marketdata_app_sdk_php/options/expirations ### Parameters #### Query Parameters - **underlying_symbol** (string) - Required - The ticker symbol of the underlying asset. - **historical** (boolean) - Optional - Set to true to retrieve historical expiration dates. ### Response #### Success Response (200) - **expiration_dates** (array) - A list of expiration dates in YYYY-MM-DD format. #### Response Example ```json { "expiration_dates": [ "2023-12-15", "2024-01-19", "2024-02-16" ] } ``` ``` -------------------------------- ### Default Parameters Source: https://www.marketdata.app/docs/sdk/php/client How to configure default parameters that will be applied to all API requests made through the client instance. ```APIDOC ## Default Parameters ### Description Set universal parameters that apply to all API calls made by the client. This is useful for setting default formats or modes. ### Request Example ```php default_params = new Parameters( format: Format::JSON, mode: Mode::CACHED ); // These calls will use the default parameters $candles = $client->stocks->candles('AAPL', '2024-01-01', '2024-01-31'); $quote = $client->stocks->quote('AAPL'); ``` See [Parameters](link_to_parameters_docs) for all available options. ``` -------------------------------- ### Options Chain API Source: https://www.marketdata.app/docs/sdk/php/options Get a current or historical end-of-day options chain for an underlying ticker symbol with extensive filtering options. ```APIDOC ## GET /websites/marketdata_app_sdk_php/options/chain ### Description Get a current or historical end-of-day options chain for an underlying ticker symbol with extensive filtering options. ### Method GET ### Endpoint /websites/marketdata_app_sdk_php/options/chain ### Parameters #### Query Parameters - **underlying_symbol** (string) - Required - The ticker symbol of the underlying asset. - **expiration_date** (string) - Required - The expiration date in YYYY-MM-DD format. - **historical** (boolean) - Optional - Set to true to retrieve historical option chain data. - **strike_range** (string) - Optional - Filter strikes within a range (e.g., '160-180'). - **option_type** (string) - Optional - Filter by option type ('call' or 'put'). ### Response #### Success Response (200) - **chain** (array) - A list of option contracts with their details (strike, type, bid, ask, etc.). #### Response Example ```json { "chain": [ { "strike": 170.00, "type": "call", "bid": 2.50, "ask": 2.60, "last_price": 2.55, "volume": 1000, "open_interest": 5000 }, { "strike": 170.00, "type": "put", "bid": 1.50, "ask": 1.60, "last_price": 1.55, "volume": 800, "open_interest": 4500 } ] } ``` ``` -------------------------------- ### Handle Various Option Description Formats (PHP) Source: https://www.marketdata.app/docs/sdk/php/options/lookup Illustrates the flexibility of the `lookup()` method's input parser by converting various human-readable option descriptions, including different date formats and orderings, into OCC symbols. This showcases the robustness of the SDK in handling diverse user inputs. ```php options->lookup($input); echo sprintf("%-35s → %s\n", $input, $lookup->option_symbol); } ``` -------------------------------- ### GET /stocks/news Source: https://www.marketdata.app/docs/sdk/php/stocks/news Retrieve news articles for a given stock symbol. This endpoint is currently in beta. ```APIDOC ## GET /stocks/news ### Description Retrieve news articles for a given stock symbol. This endpoint is currently in beta and its features or response formats may change. ### Method GET ### Endpoint /stocks/news ### Parameters #### Query Parameters - **symbol** (string) - Required - The stock ticker symbol (e.g., "AAPL"). - **from** (string, optional) - The earliest news to include. If omitted without `countback`, returns recent news. Accepted formats: ISO 8601, Unix timestamp. - **to** (string, optional) - The latest news to include. Accepted formats: ISO 8601, Unix timestamp. - **countback** (int, optional) - Number of news articles to return before `to`. Use instead of `from`. - **date** (string, optional) - Retrieve news for a specific day. Accepted formats: ISO 8601, Unix timestamp. - **parameters** (Parameters, optional) - Universal parameters for customizing the output format. See Parameters for details. ### Request Example ```php stocks->news('AAPL', from: '2024-01-01'); echo $news; // Or display individual articles foreach ($news->articles as $article) { echo $article . "\n\n"; } ?> ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the request (e.g., "ok"). - **articles** (array of Article objects) - An array containing news article objects. #### Response Example ```json { "status": "ok", "articles": [ { "symbol": "AAPL", "headline": "Apple Reports Record Q1 Earnings", "publication_date": "2024-01-25T16:30:00+00:00", "source": "https://www.reuters.com/...", "content": "Apple Inc reported record quarterly earnings on Thursday..." } ] } ``` ### Error Handling - **400 Bad Request**: Invalid parameters provided. - **404 Not Found**: Symbol not found or no news available for the specified criteria. - **500 Internal Server Error**: Server-side error. ``` -------------------------------- ### Set Universal Parameters via Client Default Params (PHP) Source: https://www.marketdata.app/docs/sdk/php/parameters Shows how to configure universal parameters using the `$client->default_params` property. These parameters override environment variables and apply to all API calls made with that specific client instance. The `Parameters` class is used to define these settings. ```php default_params = new Parameters( format: Format::JSON, date_format: DateFormat::TIMESTAMP ); // All calls will use JSON format and timestamp date format // (unless overridden by method parameters) $quote = $client->stocks->quote('AAPL'); // Uses: format=JSON, date_format=TIMESTAMP $quotes = $client->stocks->quotes(['AAPL', 'MSFT']); // Uses: format=JSON, date_format=TIMESTAMP ``` -------------------------------- ### Snapshot of All Symbols Source: https://www.marketdata.app/docs/sdk/php/stocks/bulk-candles Fetches a snapshot of all available stock symbols. This is useful for getting a general overview of the market or for identifying top gainers/losers. ```APIDOC ## Snapshot of All Symbols ### Description Fetches a snapshot of all available stock symbols. This is useful for getting a general overview of the market or for identifying top gainers/losers. ### Method POST ### Endpoint /stocks/bulkCandles ### Parameters #### Query Parameters - **snapshot** (boolean) - Required - Set to `true` to retrieve a snapshot of all available symbols. ### Request Example ```php stocks->bulkCandles( snapshot: true ); echo "Total symbols: " . count($bulkCandles->candles) . "\n"; // Find top gainers $gainers = array_filter($bulkCandles->candles, function($candle) { return $candle->close > $candle->open; }); echo "Gainers today: " . count($gainers) . "\n"; ?> ``` ### Response #### Success Response (200) - **status** (string) - The status of the response (`"ok"` or `"no_data"`). - **candles** (array) - An array of Candle objects, one per symbol available. Each Candle object contains the same properties as described in the `POST /stocks/bulkCandles` endpoint. ``` -------------------------------- ### API Format Configuration Source: https://www.marketdata.app/docs/sdk/php/parameters Controls the format of the API response data. Available formats include JSON, CSV, and HTML (reserved for future use). Configuration can be done via environment variables, client defaults, or direct parameters. ```APIDOC ## API Format Configuration ### Description Controls the format of the API response data. Available formats include JSON, CSV, and HTML (reserved for future use). Configuration can be done via environment variables, client defaults, or direct parameters. ### Available Values * `Format::JSON` (default): Returns data as typed PHP objects * `Format::CSV`: Returns CSV data (writes to file if `filename` specified) * `Format::HTML`: Reserved for future API support (not yet implemented) ### Configuration Methods 1. **Environment Variable:** `MARKETDATA_FORMAT` (values: `json`, `csv`, `html`) 2. **Client Default:** `$client->default_params = new Parameters(format: Format::CSV)` 3. **Direct Parameter:** `parameters: new Parameters(format: Format::JSON)` ### Request Example ```php default_params = new Parameters(format: Format::CSV); // Method 3: Direct parameter (highest priority) $candles = $client->stocks->candles( 'AAPL', '2024-01-01', '2024-01-31', parameters: new Parameters(format: Format::JSON) ); ``` ``` -------------------------------- ### Configure API Token using .env File Source: https://www.marketdata.app/docs/sdk/php/authentication This shows how to create a .env file to store your API token. The Market Data PHP SDK automatically loads this file using the phpdotenv library, making the token available for authentication. ```dotenv MARKETDATA_TOKEN=your_api_token_here ```