MarketData SDK

ClientBase
in package

AbstractYes

Abstract base class for Market Data API client.

This class provides core functionality for API communication, including parallel execution, async requests, and response handling.

Table of Contents

Constants

API_HOST  = "api.marketdata.app"
The host for the Market Data API.
API_URL  = "https://api.marketdata.app/"
The base URL for the Market Data API.
PACKAGE_NAME  = 'marketdataapp/sdk-php'
Composer package name for this SDK.
VERSION  = '1.0.0'
Fallback SDK version for User-Agent header.

Properties

$default_params  : Parameters
$logger  : LoggerInterface
$rate_limits  : RateLimits|null
$guzzle  : Client
$token  : string

Methods

__construct()  : mixed
ClientBase constructor.
execute()  : object
Execute a single API request with retry logic.
execute_in_parallel()  : array<string|int, mixed>
Execute multiple API calls in parallel with concurrency limiting.
extractRateLimitsFromResponse()  : RateLimits|null
Extract rate limit information from response headers.
getUserAgent()  : string
Build SDK User-Agent value.
getVersion()  : string
Resolve SDK version from Composer metadata when available.
makeRawRequest()  : ResponseInterface
Make a raw API request and return the response object.
setGuzzle()  : void
Set a custom Guzzle client.
validateResponseStatusCode()  : void
Validate response status code and raise appropriate exceptions.
_setup_rate_limits()  : void
Set up initial rate limits by fetching from the /user/ endpoint.
async()  : PromiseInterface
Perform an asynchronous API request with retry logic.
calculateBackoffDelay()  : float
Calculate exponential backoff delay.
createDelayedPromise()  : PromiseInterface
Create a promise that resolves after a delay.
getErrorMessage()  : string
Get error message from response.
getServicePath()  : string|null
Get service path from method path using hardcoded mapping.
headers()  : array<string|int, mixed>
Generate headers for API requests.
isInternalRequest()  : bool
Check if a URL is for an internal request.
logRequest()  : void
Log a completed HTTP request.
processResponse()  : object
Process the response and return the appropriate object.
shouldSkipRetryDueToOfflineService()  : bool
Check if service is offline and should skip retries.
waitForRetry()  : void
Wait for retry with exponential backoff.

Constants

API_HOST

The host for the Market Data API.

public mixed API_HOST = "api.marketdata.app"

API_URL

The base URL for the Market Data API.

public mixed API_URL = "https://api.marketdata.app/"

PACKAGE_NAME

Composer package name for this SDK.

public mixed PACKAGE_NAME = 'marketdataapp/sdk-php'

VERSION

Fallback SDK version for User-Agent header.

public mixed VERSION = '1.0.0'

Properties

$default_params

public Parameters $default_params

Default universal parameters for all API requests. Can be modified programmatically: $client->default_params->format = Format::CSV; Method-level parameters override these defaults.

$logger

public LoggerInterface $logger

PSR-3 logger instance for request logging.

$rate_limits

public RateLimits|null $rate_limits = null

Current rate limit information, automatically updated after each request. Tracks credits (not requests), as some requests may consume multiple credits.

$guzzle

protected Client $guzzle

The Guzzle HTTP client instance.

$token

protected string $token

The API token for authentication.

Methods

__construct()

ClientBase constructor.

public __construct([string|null $token = null ][, LoggerInterface|null $logger = null ]) : mixed
Parameters
$token : string|null = null

The API token for authentication. If not provided, the token will be automatically resolved from MARKETDATA_TOKEN environment variable or .env file. An empty string is allowed for accessing free symbols like AAPL. A valid token is required for authenticated endpoints. An invalid token will throw UnauthorizedException during construction.

$logger : LoggerInterface|null = null

PSR-3 logger instance. If not provided, uses the default logger.

Tags
throws
UnauthorizedException

If the token is invalid (non-empty but returns 401 from /user endpoint)

execute()

Execute a single API request with retry logic.

public execute(string $method[, array<string|int, mixed> $arguments = [] ]) : object
Parameters
$method : string

The API method to call.

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

The arguments for the API call.

Tags
throws
GuzzleException
throws
ApiException
throws
RequestError
throws
BadStatusCodeError
throws
UnauthorizedException
Return values
object

The API response as an object.

execute_in_parallel()

Execute multiple API calls in parallel with concurrency limiting.

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

Uses Guzzle's EachPromise to maintain a sliding window of concurrent requests. Unlike batch processing, this approach starts new requests as soon as previous ones complete, maintaining optimal throughput up to MAX_CONCURRENT_REQUESTS (50).

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

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

$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, allowing callers to handle partial failures.

Tags
throws
Throwable

When $failedRequests is not provided and any request fails.

Return values
array<string|int, mixed>

An array of decoded JSON responses. When $failedRequests is provided, successful responses are keyed by their original call index. Otherwise, returns a sequential array.

extractRateLimitsFromResponse()

Extract rate limit information from response headers.

public extractRateLimitsFromResponse(ResponseInterface $response) : RateLimits|null

This method extracts rate limit data from API response headers and returns a RateLimits object. Returns null if headers are missing, allowing graceful degradation. This method is designed to be reusable for future automatic rate limit tracking across all API requests.

Parameters
$response : ResponseInterface

The HTTP response.

Return values
RateLimits|null

The rate limit information, or null if headers are missing.

getUserAgent()

Build SDK User-Agent value.

public static getUserAgent() : string
Return values
string

getVersion()

Resolve SDK version from Composer metadata when available.

public static getVersion() : string
Return values
string

makeRawRequest()

Make a raw API request and return the response object.

public makeRawRequest(string $method[, array<string|int, mixed> $arguments = [] ]) : ResponseInterface

This method is useful for endpoints that need access to response headers, such as the /user/ endpoint for rate limit information.

Parameters
$method : string

The API method to call (no API version prefix).

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

Optional query parameters.

Tags
throws
GuzzleException
throws
UnauthorizedException
Return values
ResponseInterface

The HTTP response.

setGuzzle()

Set a custom Guzzle client.

public setGuzzle(Client $guzzleClient) : void
Parameters
$guzzleClient : Client

The Guzzle client to use.

validateResponseStatusCode()

Validate response status code and raise appropriate exceptions.

public validateResponseStatusCode(ResponseInterface $response[, bool $raiseForStatus = true ][, string|null $requestUrl = null ]) : void
Parameters
$response : ResponseInterface

The HTTP response.

$raiseForStatus : bool = true

Whether to raise for non-2xx status codes.

$requestUrl : string|null = null

The URL that was requested.

Tags
throws
RequestError
throws
BadStatusCodeError
throws
UnauthorizedException

_setup_rate_limits()

Set up initial rate limits by fetching from the /user/ endpoint.

protected _setup_rate_limits() : void

This method is called during client construction to initialize rate limit information. If the request fails, rate_limits will remain null until the first successful request with rate limit headers.

Rate limits track credits, not requests. Most requests consume 1 credit, but bulk requests or options requests may consume multiple credits.

If the token is empty, validation is skipped to allow free symbols like AAPL. If the token is invalid (returns 401), an UnauthorizedException is thrown to prevent client creation.

Tags
throws
UnauthorizedException

If the token is invalid (non-empty but returns 401)

async()

Perform an asynchronous API request with retry logic.

protected async(string $method[, array<string|int, mixed> $arguments = [] ]) : PromiseInterface
Parameters
$method : string

The API method to call.

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

The arguments for the API call.

Tags
throws
RequestError
throws
BadStatusCodeError
throws
UnauthorizedException
Return values
PromiseInterface

calculateBackoffDelay()

Calculate exponential backoff delay.

protected calculateBackoffDelay(int $attempt) : float
Parameters
$attempt : int

The current attempt number (1-based).

Return values
float

The delay in seconds.

createDelayedPromise()

Create a promise that resolves after a delay.

protected createDelayedPromise(float $delay) : PromiseInterface

Note: PHP doesn't have native async timers, so this uses a micro-delay approach. For true non-blocking behavior, an event loop would be needed. This implementation provides the delay while maintaining promise chaining.

Parameters
$delay : float

The delay in seconds.

Return values
PromiseInterface

A promise that resolves after the delay.

getErrorMessage()

Get error message from response.

protected getErrorMessage(ResponseInterface $response) : string
Parameters
$response : ResponseInterface

The HTTP response.

Return values
string

The error message.

getServicePath()

Get service path from method path using hardcoded mapping.

protected getServicePath(string $method) : string|null

Maps method paths like "v1/stocks/quotes/AAPL" to service paths like "/v1/stocks/quotes/". Returns null for status endpoint (to avoid checking its own status) or unknown services.

Parameters
$method : string

The method path (e.g., "v1/stocks/quotes/AAPL").

Return values
string|null

The service path (e.g., "/v1/stocks/quotes/") or null if not found/special case.

headers()

Generate headers for API requests.

protected headers([string $format = 'json' ]) : array<string|int, mixed>
Parameters
$format : string = 'json'

The desired response format (json, csv, or html).

Return values
array<string|int, mixed>

An array of headers.

isInternalRequest()

Check if a URL is for an internal request.

protected isInternalRequest(string $url) : bool

Internal requests (rate limit setup, API status) are logged at DEBUG level. API requests are logged at INFO level.

Parameters
$url : string

The request URL.

Return values
bool

True if internal request, false otherwise.

logRequest()

Log a completed HTTP request.

protected logRequest(string $method, ResponseInterface $response, float $durationMs, string $url[, string $logLevel = 'info' ]) : void

Logs one line per request with format: METHOD STATUS DURATION REQUEST_ID URL

Parameters
$method : string

HTTP method (GET, POST, etc.).

$response : ResponseInterface

The HTTP response.

$durationMs : float

Request duration in milliseconds.

$url : string

The full request URL.

$logLevel : string = 'info'

Log level: 'info' for API requests, 'debug' for internal.

processResponse()

Process the response and return the appropriate object.

protected processResponse(ResponseInterface $response, string $format, array<string|int, mixed> $arguments[, string|null $requestUrl = null ]) : object
Parameters
$response : ResponseInterface

The HTTP response.

$format : string

The response format.

$arguments : array<string|int, mixed>

The request arguments.

$requestUrl : string|null = null

The URL that was requested.

Tags
throws
ApiException
Return values
object

The processed response.

shouldSkipRetryDueToOfflineService()

Check if service is offline and should skip retries.

protected shouldSkipRetryDueToOfflineService(string $method) : bool
Parameters
$method : string

The method path being called.

Return values
bool

True if service is offline (should skip retries), false otherwise.

waitForRetry()

Wait for retry with exponential backoff.

protected waitForRetry(int $attempt) : void
Parameters
$attempt : int

The current attempt number (1-based).


        
On this page

Search results