MarketData SDK

Stocks
in package
uses UniversalParameters, ValidatesInputs

Stocks class for handling stock-related API endpoints.

Table of Contents

Constants

BASE_URL  = "v1/stocks/"

Properties

$client  : Client

Methods

__construct()  : mixed
Stocks constructor.
bulkCandles()  : BulkCandles
Get bulk candle data for stocks.
candles()  : Candles
Get historical price candles for a stock.
earnings()  : Earnings
Get historical earnings per share data or a future earnings calendar for a stock.
news()  : News
Retrieve news articles for a given stock symbol.
prices()  : Prices
Get real-time midpoint prices for one or more stocks.
quote()  : Quote
Get a real-time price quote for a stock.
quotes()  : Quotes
Get real-time price quotes for multiple stocks in a single API request.
candlesConcurrent()  : Candles
Fetch candles concurrently by splitting date range into year-long chunks.
candlesConcurrentCsv()  : Candles
Handle CSV format for concurrent candle requests.
canParseAsDate()  : bool
Check if a string can be parsed as a date.
execute()  : object
Execute a single API request with universal parameters.
execute_in_parallel()  : array<string|int, mixed>
Execute multiple API requests in parallel with universal parameters.
isIntradayResolution()  : bool
Check if a resolution is intraday (minutely or hourly).
isParseableDate()  : bool
Check if a date string can be parsed as an absolute date.
mergeCandleResponses()  : Candles
Merge multiple candle responses into a single Candles object.
mergeParameters()  : Parameters
Merge method-level parameters with client default parameters.
needsAutomaticSplitting()  : bool
Determine if a candles request needs automatic date range splitting.
parseDateToTimestamp()  : int|null
Parse a date string to unix timestamp.
parseUserDate()  : Carbon
Parse a user-provided date string into a Carbon instance.
splitDateRangeIntoYearChunks()  : array<string|int, mixed>
Split a date range into year-long chunks for concurrent fetching.
validateCountryCode()  : void
Validate ISO 3166 two-letter country code.
validateDateRange()  : void
Validate date range logic.
validateNonEmptyArray()  : void
Validate that an array is non-empty.
validateNonEmptyString()  : void
Validate that a string is non-empty.
validateNumericRange()  : void
Validate that min < max when both are provided.
validatePositiveInteger()  : void
Validate that an integer is positive if provided.
validatePositiveNumber()  : void
Validate that a number (int or float) is positive if provided.
validateResolution()  : void
Validate resolution format.
validateSymbols()  : void
Validate symbols array (trim and ensure non-empty).

Constants

BASE_URL

public string BASE_URL = "v1/stocks/"

The base URL for stock endpoints.

Properties

$client

private Client $client

The Market Data API client instance.

Methods

__construct()

Stocks constructor.

public __construct(Client $client) : mixed
Parameters
$client : Client

The Market Data API client instance.

bulkCandles()

Get bulk candle data for stocks.

public bulkCandles([array<string|int, mixed> $symbols = [] ][, string $resolution = 'D' ][, bool $snapshot = false ][, string|null $date = null ][, bool $adjust_splits = null ][, Parameters|null $parameters = null ]) : BulkCandles
APIYes

Get bulk candle data for stocks. This endpoint returns bulk daily candle data for multiple stocks. Unlike the standard candles endpoint, this endpoint returns a single daily for each symbol provided. The typical use-case for this endpoint is to get a complete market snapshot during trading hours, though it can also be used for bulk snapshots of historical daily candles.

Parameters
$symbols : array<string|int, mixed> = []

The ticker symbols to return in the response, separated by commas. The symbols parameter may be omitted if the snapshot parameter is set to true.

$resolution : string = 'D'

The duration of each candle. Only daily candles are supported at this time. Daily Resolutions: (daily, D, 1D, 2D, ...)

$snapshot : bool = false

Returns candles for all available symbols for the date indicated. The symbols parameter can be omitted if snapshot is set to true.

$date : string|null = null

The date of the candles to be returned. If no date is specified, during market hours the candles returned will be from the current session. If the market is closed the candles will be from the most recent session. Accepted timestamp inputs: ISO 8601, unix, spreadsheet.

$adjust_splits : bool = null

Adjust historical data for historical splits and reverse splits. Market Data uses the CRSP methodology for adjustment. Daily candles default: true.

$parameters : Parameters|null = null

Universal parameters for all methods (such as format).

Tags
link

API Documentation

see
candles()

For historical candles of a single symbol

example

// Get bulk candles for multiple symbols $candles = $client->stocks->bulkCandles(['AAPL', 'MSFT', 'GOOGL']);

// Get a market snapshot of all symbols $snapshot = $client->stocks->bulkCandles(snapshot: true);

throws
ApiException
throws
GuzzleException
Return values
BulkCandles

candles()

Get historical price candles for a stock.

public candles(string $symbol, string $from[, string|null $to = null ][, string $resolution = 'D' ][, int|null $countback = null ][, bool $extended = false ][, bool $adjust_splits = null ][, Parameters|null $parameters = null ]) : Candles
APIYes
Parameters
$symbol : string

The company's ticker symbol.

$from : string

The leftmost candle on a chart (inclusive). If you use countback, to is not required. Accepted timestamp inputs: ISO 8601, unix, spreadsheet.

$to : string|null = null

The rightmost candle on a chart (inclusive). Accepted timestamp inputs: ISO 8601, unix, spreadsheet.

$resolution : string = 'D'

The duration of each candle.

  • Minutely Resolutions: (minutely, 1, 3, 5, 15, 30, 45, ...)
  • Hourly Resolutions: (hourly, H, 1H, 2H, ...)
  • Daily Resolutions: (daily, D, 1D, 2D, ...)
  • Weekly Resolutions: (weekly, W, 1W, 2W, ...)
  • Monthly Resolutions: (monthly, M, 1M, 2M, ...)
  • Yearly Resolutions:(yearly, Y, 1Y, 2Y, ...)
$countback : int|null = null

Will fetch a number of candles before (to the left of) to. If you use from, countback is not required.

$extended : bool = false

Include extended hours trading sessions when returning intraday candles. Daily resolutions never return extended hours candles. The default is false.

$adjust_splits : bool = null

Adjust historical data for for historical splits and reverse splits. Market Data uses the CRSP methodology for adjustment. Daily candles default: true. Intraday candles default: false.

$parameters : Parameters|null = null

Universal parameters for all methods (such as format).

Tags
link

API Documentation

see
bulkCandles()

For bulk daily candles across multiple symbols

example

// Get daily candles for AAPL $candles = $client->stocks->candles('AAPL', '2024-01-01', '2024-01-31');

// Get 5-minute candles with extended hours $candles = $client->stocks->candles('AAPL', '2024-01-15', '2024-01-15', '5', extended: true);

throws
GuzzleException|ApiException
Return values
Candles

earnings()

Get historical earnings per share data or a future earnings calendar for a stock.

public earnings(string $symbol[, string|null $from = null ][, string|null $to = null ][, int|null $countback = null ][, string|null $date = null ][, Parameters|null $parameters = null ]) : Earnings
APIYes

Premium subscription required.

Parameters
$symbol : string

The company's ticker symbol.

$from : string|null = null

The earliest earnings report to include in the output. Optional - if omitted without countback, returns recent/upcoming earnings.

$to : string|null = null

The latest earnings report to include in the output. Optional.

$countback : int|null = null

Countback will fetch a specific number of earnings reports before to. Optional.

$date : string|null = null

Retrieve a specific earnings report by date. Optional.

$parameters : Parameters|null = null

Universal parameters for all methods (such as format).

Tags
link

API Documentation

example

// Get upcoming earnings $earnings = $client->stocks->earnings('AAPL');

// Get historical earnings for a date range $earnings = $client->stocks->earnings('AAPL', from: '2023-01-01', to: '2023-12-31');

throws
ApiException
throws
GuzzleException
Return values
Earnings

news()

Retrieve news articles for a given stock symbol.

public news(string $symbol[, string|null $from = null ][, string|null $to = null ][, int|null $countback = null ][, string|null $date = null ][, Parameters|null $parameters = null ]) : News
APIYes

CAUTION: This endpoint is in beta.

Parameters
$symbol : string

The ticker symbol of the stock.

$from : string|null = null

The earliest news to include in the output. Optional - if omitted without countback, returns recent news.

$to : string|null = null

The latest news to include in the output. Optional.

$countback : int|null = null

Countback will fetch a specific number of news before to. Optional.

$date : string|null = null

Retrieve news for a specific day. Optional.

$parameters : Parameters|null = null

Universal parameters for all methods (such as format).

Tags
link

API Documentation

example

// Get recent news for a symbol $news = $client->stocks->news('AAPL');

// Get news for a specific date range $news = $client->stocks->news('AAPL', from: '2024-01-01', to: '2024-01-31');

throws
InvalidArgumentException
Return values
News

prices()

Get real-time midpoint prices for one or more stocks.

public prices(string|array<string|int, mixed> $symbols[, bool $extended = true ][, Parameters|null $parameters = null ]) : Prices
APIYes

This endpoint returns real-time prices for stocks, using the SmartMid model. The endpoint supports both single symbol (path parameter) and multiple symbols (query parameter) formats.

Parameters
$symbols : string|array<string|int, mixed>

The ticker symbol(s). Can be a single string or an array of strings.

$extended : bool = true

Control the inclusion of extended hours data in the price output. Defaults to true if omitted.

  • When set to true, the most recent price is always returned, without regard to whether the market is open for primary trading or extended hours trading.
  • When set to false, only prices from the primary trading session are returned. When the market is closed or in extended hours, a historical price from the last closing bell of the primary trading session is returned instead of an extended hours price.
$parameters : Parameters|null = null

Universal parameters for all methods (such as format).

Tags
link

API Documentation

see
quote()

For full quote data including bid/ask

example

// Get price for a single symbol $prices = $client->stocks->prices('AAPL');

// Get prices for multiple symbols $prices = $client->stocks->prices(['AAPL', 'MSFT', 'GOOGL']);

throws
GuzzleException|ApiException
Return values
Prices

quote()

Get a real-time price quote for a stock.

public quote(string $symbol[, bool $fifty_two_week = false ][, bool $extended = true ][, Parameters|null $parameters = null ]) : Quote
APIYes
Parameters
$symbol : string

The company's ticker symbol.

$fifty_two_week : bool = false

Enable the output of 52-week high and 52-week low data in the quote output. By default this parameter is false if omitted.

$extended : bool = true

Control the inclusion of extended hours data in the quote output. Defaults to true if omitted.

  • When set to true, the most recent quote is always returned, without regard to whether the market is open for primary trading or extended hours trading.
  • When set to false, only quotes from the primary trading session are returned. When the market is closed or in extended hours, a historical quote from the last closing bell of the primary trading session is returned instead of an extended hours quote.
$parameters : Parameters|null = null

Universal parameters for all methods (such as format).

Tags
link

API Documentation

see
quotes()

For quotes of multiple symbols in a single request

see
prices()

For SmartMid midpoint prices

example

// Get a real-time quote $quote = $client->stocks->quote('AAPL'); echo $quote->last; // Last traded price

// Get quote with 52-week high/low $quote = $client->stocks->quote('AAPL', fifty_two_week: true);

throws
GuzzleException|ApiException
Return values
Quote

quotes()

Get real-time price quotes for multiple stocks in a single API request.

public quotes(array<string|int, mixed> $symbols[, bool $fifty_two_week = false ][, bool $extended = true ][, Parameters|null $parameters = null ]) : Quotes
APIYes
Parameters
$symbols : array<string|int, mixed>

The ticker symbols to return in the response.

$fifty_two_week : bool = false

Enable the output of 52-week high and 52-week low data in the quote output.

$extended : bool = true

Control the inclusion of extended hours data in the quote output. Defaults to true if omitted.

  • When set to true, the most recent quote is always returned, without regard to whether the market is open for primary trading or extended hours trading.
  • When set to false, only quotes from the primary trading session are returned. When the market is closed or in extended hours, a historical quote from the last closing bell of the primary trading session is returned instead of an extended hours quote.
$parameters : Parameters|null = null

Universal parameters for all methods (such as format).

Tags
link

API Documentation

see
quote()

For a single symbol quote

see
bulkCandles()

For bulk daily candle data

example

// Get quotes for multiple symbols $quotes = $client->stocks->quotes(['AAPL', 'MSFT', 'GOOGL']); foreach ($quotes->quotes as $q) { echo "{$q->symbol}: ${$q->last}\n"; }

throws
GuzzleException|ApiException
Return values
Quotes

candlesConcurrent()

Fetch candles concurrently by splitting date range into year-long chunks.

protected candlesConcurrent(string $symbol, string $from, string $to, string $resolution, bool $extended, bool|null $adjust_splits, Parameters|null $parameters) : Candles

This method is called automatically when:

  1. Resolution is intraday (minutely or hourly)
  2. The date range spans more than 1 year
  3. countback is not specified

The date range is split into year-long chunks, which are fetched concurrently (up to MAX_CONCURRENT_REQUESTS at a time). The responses are then merged into a single Candles object.

Parameters
$symbol : string

The stock symbol.

$from : string

The start date.

$to : string

The end date.

$resolution : string

The candle resolution.

$extended : bool

Include extended hours.

$adjust_splits : bool|null

Adjust for splits.

$parameters : Parameters|null

Universal parameters.

Tags
throws
Throwable
Return values
Candles

The merged candles response.

candlesConcurrentCsv()

Handle CSV format for concurrent candle requests.

protected candlesConcurrentCsv(string $symbol, string $from, string $to, string $resolution, bool $extended, bool|null $adjust_splits, Parameters|null $parameters, Parameters $mergedParams) : Candles

Makes separate requests for each date chunk, with headers=true on ALL requests (unless user explicitly set add_headers=false). This ensures headers are present even if the first chunk fails. Duplicate headers are stripped when combining.

Parameters
$symbol : string

The stock symbol.

$from : string

The start date.

$to : string

The end date.

$resolution : string

The candle resolution.

$extended : bool

Include extended hours.

$adjust_splits : bool|null

Adjust for splits.

$parameters : Parameters|null

Original parameters from caller.

$mergedParams : Parameters

Merged parameters with defaults applied.

Tags
throws
Throwable
Return values
Candles

Candles object containing combined CSV.

canParseAsDate()

Check if a string can be parsed as a date.

protected canParseAsDate(string|null $value) : bool

Similar to Python SDK's check_is_date() function. Returns true if the value contains "-" or "/" (indicating parseable date format) or is numeric (unix timestamp or spreadsheet format).

This allows relative dates ("today", "yesterday", "-5 days") and option expiration dates ("December expiration") to pass through without validation.

Parameters
$value : string|null

The value to check

Return values
bool

True if the value can be parsed as a date

execute()

Execute a single API request with universal parameters.

protected execute(string $method, array<string|int, mixed> $arguments, Parameters|null $parameters) : object
Parameters
$method : string

The API method to call.

$arguments : array<string|int, mixed>

The arguments for the API call.

$parameters : Parameters|null

Optional Parameters object for additional settings.

Return values
object

The API response as an object.

execute_in_parallel()

Execute multiple API requests in parallel with universal parameters.

protected execute_in_parallel(array<string|int, mixed> $calls[, Parameters|null $parameters = null ][, array<string|int, mixed>|null &$failedRequests = null ]) : array<string|int, mixed>
Parameters
$calls : array<string|int, mixed>

An array of method calls, each containing the method name and arguments.

$parameters : Parameters|null = null

Optional Parameters object for additional settings.

$failedRequests : array<string|int, mixed>|null = null

Optional by-reference array to collect failed requests instead of throwing. When provided, exceptions are stored here keyed by their call index.

Tags
throws
Throwable

When $failedRequests is not provided and any request fails.

Return values
array<string|int, mixed>

An array of API responses. When $failedRequests is provided, results are keyed by original call index.

isIntradayResolution()

Check if a resolution is intraday (minutely or hourly).

protected isIntradayResolution(string $resolution) : bool

Intraday resolutions include:

  • Minutely: 1, 3, 5, 15, 30, 45, minutely, or any number followed by optional suffix
  • Hourly: H, 1H, 2H, hourly, or any number followed by H
Parameters
$resolution : string

The resolution to check.

Return values
bool

True if the resolution is intraday, false otherwise.

isParseableDate()

Check if a date string can be parsed as an absolute date.

protected isParseableDate(string $date) : bool

This is used to determine if we can calculate date ranges for automatic splitting. Relative dates (like "today", "-5 days") or unparseable dates will return false. Unix timestamps (pure digit strings) are accepted.

Parameters
$date : string

The date string to check.

Return values
bool

True if the date can be parsed, false otherwise.

mergeCandleResponses()

Merge multiple candle responses into a single Candles object.

protected mergeCandleResponses(array<string|int, mixed> $responses, string $symbol) : Candles

This method combines candles from multiple API responses, typically from concurrent requests for different date chunks. The candles are sorted by timestamp to maintain chronological order.

Parameters
$responses : array<string|int, mixed>

Array of raw response objects from the API.

$symbol : string

The symbol to associate with all candles.

Return values
Candles

A single Candles object containing all candles.

mergeParameters()

Merge method-level parameters with client default parameters.

protected mergeParameters(Parameters|null $methodParams) : Parameters

Priority order (highest to lowest):

  1. Method-level parameters (if provided)
  2. Client default parameters ($this->client->default_params)
  3. Default Parameters() values
Parameters
$methodParams : Parameters|null

Method-level parameters, or null to use only client defaults.

Return values
Parameters

Merged parameters instance.

needsAutomaticSplitting()

Determine if a candles request needs automatic date range splitting.

protected needsAutomaticSplitting(string $resolution, string $from, string|null $to, int|null $countback) : bool

Splitting is needed when:

  1. Resolution is intraday (minutely or hourly)
  2. Both from and to dates are parseable
  3. The date range spans more than 1 year
  4. countback is not specified (we can't split countback requests)
Parameters
$resolution : string

The candle resolution.

$from : string

The start date.

$to : string|null

The end date.

$countback : int|null

The countback value.

Return values
bool

True if automatic splitting is needed, false otherwise.

parseDateToTimestamp()

Parse a date string to unix timestamp.

protected parseDateToTimestamp(string|null $value) : int|null

Handles ISO 8601, unix timestamps, spreadsheet dates, and American format.

Parameters
$value : string|null

The date string to parse

Return values
int|null

Unix timestamp or null if cannot be parsed

parseUserDate()

Parse a user-provided date string into a Carbon instance.

protected parseUserDate(string $date) : Carbon

Handles both standard date formats and unix timestamps (9-10 digit strings). This should be used whenever parsing user input that could be a unix timestamp.

Parameters
$date : string

The date string to parse (ISO 8601, unix timestamp, etc.).

Return values
Carbon

The parsed Carbon instance.

splitDateRangeIntoYearChunks()

Split a date range into year-long chunks for concurrent fetching.

protected splitDateRangeIntoYearChunks(string $from, string $to) : array<string|int, mixed>

This method splits a date range into chunks of approximately 1 year each, which is the maximum recommended range for intraday data requests.

Parameters
$from : string

The start date (ISO 8601 format).

$to : string

The end date (ISO 8601 format).

Return values
array<string|int, mixed>

Array of [from, to] date pairs representing each chunk.

validateCountryCode()

Validate ISO 3166 two-letter country code.

protected validateCountryCode(string $country) : void
Parameters
$country : string

The country code to validate

Tags
throws
InvalidArgumentException

If country code is invalid

validateDateRange()

Validate date range logic.

protected validateDateRange(string|null $from, string|null $to[, int|null $countback = null ][, string $context = '' ]) : void

Rules:

  • If to is provided, it requires either from OR countback (but not both)
  • If both from and to are parseable dates, validates that from < to
  • If countback is provided, it must be a positive integer

This allows relative dates and option expiration dates to pass through without strict format validation.

Parameters
$from : string|null

The start date

$to : string|null

The end date

$countback : int|null = null

The countback value

$context : string = ''

Optional context for error messages

Tags
throws
InvalidArgumentException

If validation fails

validateNonEmptyArray()

Validate that an array is non-empty.

protected validateNonEmptyArray(array<string|int, mixed> $value, string $fieldName) : void
Parameters
$value : array<string|int, mixed>

The value to validate

$fieldName : string

The field name for error messages

Tags
throws
InvalidArgumentException

If array is empty

validateNonEmptyString()

Validate that a string is non-empty.

protected validateNonEmptyString(string $value, string $fieldName) : void
Parameters
$value : string

The value to validate

$fieldName : string

The field name for error messages

Tags
throws
InvalidArgumentException

If value is empty

validateNumericRange()

Validate that min < max when both are provided.

protected validateNumericRange(float|null $min, float|null $max, string $minField, string $maxField) : void
Parameters
$min : float|null

The minimum value

$max : float|null

The maximum value

$minField : string

The minimum field name for error messages

$maxField : string

The maximum field name for error messages

Tags
throws
InvalidArgumentException

If min >= max

validatePositiveInteger()

Validate that an integer is positive if provided.

protected validatePositiveInteger(int|null $value, string $fieldName) : void
Parameters
$value : int|null

The value to validate

$fieldName : string

The field name for error messages

Tags
throws
InvalidArgumentException

If value is not positive

validatePositiveNumber()

Validate that a number (int or float) is positive if provided.

protected validatePositiveNumber(int|float|null $value, string $fieldName) : void
Parameters
$value : int|float|null

The value to validate

$fieldName : string

The field name for error messages

Tags
throws
InvalidArgumentException

If value is not positive

validateResolution()

Validate resolution format.

protected validateResolution(string $resolution) : void

Valid resolutions: minutely, hourly, daily, weekly, monthly, yearly, or numeric with optional suffix (1, 3, 5, 15, 30, 45, H, 1H, 2H, D, 1D, 2D, etc.)

Parameters
$resolution : string

The resolution to validate

Tags
throws
InvalidArgumentException

If resolution is invalid

validateSymbols()

Validate symbols array (trim and ensure non-empty).

protected validateSymbols(array<string|int, mixed> $symbols) : void
Parameters
$symbols : array<string|int, mixed>

The symbols array to validate

Tags
throws
InvalidArgumentException

If symbols array is invalid


        
On this page

Search results