Stellar PHP SDK API Documentation

TradesRequestBuilder extends RequestBuilder

Builds requests for the trades endpoint in Horizon

This class provides methods to query trades on the Stellar network. Trades represent actual exchanges of assets that occur either through the orderbook or via liquidity pools. Each trade records the assets exchanged, amounts, price, and participating accounts.

Query Methods:

  • forAccount(): Get trades for a specific account
  • forOffer(): Get trades for a specific offer ID
  • forLiquidityPool(): Get trades for a specific liquidity pool
  • forTradeType(): Filter by trade type (all, orderbook, liquidity_pools)
  • forBaseAsset(): Filter by base asset
  • forCounterAsset(): Filter by counter asset

Trades can be filtered by asset pair to analyze specific trading pairs or by account to track trading activity.

Usage Examples:

// Get recent trades for an account $trades = $sdk->trades() ->forAccount("GDAT5...") ->limit(20) ->order("desc") ->execute();

// Get trades for a specific asset pair $baseAsset = Asset::createNonNativeAsset("USD", "GBBD..."); $counterAsset = Asset::native(); $trades = $sdk->trades() ->forBaseAsset($baseAsset) ->forCounterAsset($counterAsset) ->execute();

// Stream real-time trades $sdk->trades() ->cursor("now") ->stream(function(TradeResponse $trade) { echo "Trade: " . $trade->getBaseAmount() . " " . $trade->getBaseAssetCode() . PHP_EOL; });

Tags
see
TradesPageResponse

For the response format

see
https://developers.stellar.org

Stellar developer docs Horizon API Trades endpoint

Table of Contents

Constants

HEADERS  = ["X-Client-Name" => "stellar_php_sdk", "X-Client-Version" => \Soneso\StellarSDK\StellarSDK::VERSION_NR]

Properties

$httpClient  : Client
$queryParameters  : array<string|int, mixed>
$segments  : array<string|int, mixed>

Methods

__construct()  : mixed
Constructor
buildUrl()  : string
Builds the complete request URL with all segments and query parameters
cursor()  : TradesRequestBuilder
Sets <code>cursor</code> parameter on the request.
execute()  : Response
Build and execute request.
executeRequest()  : Response
Executes an HTTP request to Horizon and returns a parsed response object
forAccount()  : TradesRequestBuilder
Builds request to <code>GET /accounts/{accountId}/trades</code>
forBaseAsset()  : TradesRequestBuilder
Returns all trades for the given base asset.
forCounterAsset()  : TradesRequestBuilder
Returns all trades for the given counter asset.
forLiquidityPool()  : TradesRequestBuilder
Builds request to <code>GET /liquidity_pools/{poolID}/trades</code>
forOffer()  : TradesRequestBuilder
Builds request to <code>GET /trades</code> filtered by offer_id query parameter.
forTradeType()  : TradesRequestBuilder
Returns all trades that of a specific type.
getAndStream()  : void
Streams Server-Sent Events from Horizon to a callback function
limit()  : TradesRequestBuilder
Sets <code>limit</code> parameter on the request.
order()  : TradesRequestBuilder
Sets <code>order</code> parameter on the request.
request()  : TradesPageResponse
Requests specific <code>url</code> and returns {@link TradesPageResponse}.
stream()  : mixed
Streams TradeResponse objects to $callback
setSegments()  : RequestBuilder
Sets the URL path segments for this request

Constants

HEADERS

public mixed HEADERS = ["X-Client-Name" => "stellar_php_sdk", "X-Client-Version" => \Soneso\StellarSDK\StellarSDK::VERSION_NR]

Properties

$queryParameters

protected array<string|int, mixed> $queryParameters

Methods

__construct()

Constructor

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

The HTTP client used for making requests to Horizon

buildUrl()

Builds the complete request URL with all segments and query parameters

public buildUrl() : string

Combines the URL path segments with query parameters to create the final request URL string that will be sent to Horizon.

Return values
string

The constructed URL with query parameters

cursor()

Sets <code>cursor</code> parameter on the request.

public cursor(string $cursor) : TradesRequestBuilder

A cursor is a value that points to a specific location in a collection of resources. The cursor attribute itself is an opaque value meaning that users should not try to parse it.

Parameters
$cursor : string
Tags
see
https://developers.stellar.org

Stellar developer docs Page documentation

Return values
TradesRequestBuilder

executeRequest()

Executes an HTTP request to Horizon and returns a parsed response object

public executeRequest(string $url, string $requestType[, string|null $requestMethod = "GET" ]) : Response

This method sends the HTTP request to the Horizon server, handles errors, and parses the JSON response into the appropriate response type.

Parameters
$url : string

The complete request URL to fetch

$requestType : string

The expected response type for parsing

$requestMethod : string|null = "GET"

The HTTP method to use (default: "GET")

Tags
throws
HorizonRequestException

If the request fails or response cannot be parsed

Return values
Response

The parsed response object of the specified type

getAndStream()

Streams Server-Sent Events from Horizon to a callback function

public getAndStream(string $relativeUrl, callable $callback[, bool $retryOnServerException = true ]) : void

This method establishes a persistent connection to Horizon's streaming endpoints using Server-Sent Events (SSE). It processes each event and passes the parsed data to the provided callback function. The stream automatically reconnects on server exceptions if retryOnServerException is true.

Horizon streaming uses SSE to push real-time updates. The stream sends:

  • "hello" message on connection
  • "byebye" message on disconnection
  • JSON data objects for actual events
Parameters
$relativeUrl : string

The relative URL to stream from

$callback : callable

Function to receive parsed event data

$retryOnServerException : bool = true

If true, automatically retry on server errors (default: true)

Tags
throws
GuzzleException

If a network error occurs and retryOnServerException is false

Return values
void

This method runs indefinitely until interrupted

limit()

Sets <code>limit</code> parameter on the request.

public limit(int $number) : TradesRequestBuilder

It defines maximum number of records to return. For range and default values check documentation of the endpoint requested.

Parameters
$number : int

Maximum number of records to return

Return values
TradesRequestBuilder

stream()

Streams TradeResponse objects to $callback

public stream([callable|null $callback = null ]) : mixed

$callback should have arguments: TradeResponse

For example:

$sdk = StellarSDK::getTestNetInstance(); $sdk->trades()->cursor("now")->stream(function(TradeResponse $trade) { printf('Trade ID: %s, Amount: %s %s for %s %s' . PHP_EOL, $trade->getId(), $trade->getBaseAmount(), $trade->getBaseAssetCode() ?? 'XLM', $trade->getCounterAmount(), $trade->getCounterAssetCode() ?? 'XLM' ); });

Parameters
$callback : callable|null = null
Tags
throws
GuzzleException

setSegments()

Sets the URL path segments for this request

protected setSegments(string ...$segments) : RequestBuilder

This method constructs the URL path by combining multiple segments. Can only be called once per request builder instance.

Parameters
$segments : string

Variable number of URL path segments

Tags
throws
RuntimeException

If segments have already been set

Return values
RequestBuilder

This instance for method chaining


        
On this page

Search results