Skip to main content

Streaming & Events

The Java SDK includes handwritten streaming clients for stock market data, crypto market data, news, trading updates, Market Data corporate-actions SSE, Trading account-activity SSE, and Broker Events SSE.

Use the domain pages for REST workflows and the first streaming example for that API area: Market Data, Trading, and Broker. Use this page for the shared streaming model: listener callbacks, authentication confirmation, subscription confirmation, reconnect behavior, callback executors, and the differences between WebSocket and SSE streams.

Stream types​

AreaClientProtocolNotes
Market DataAlpacaStockStreamWebSocketStock trades, quotes, bars, statuses, corrections, and cancel/error events
Market DataAlpacaCryptoStreamWebSocketCrypto trades, quotes, bars, and orderbooks
Market DataAlpacaNewsStreamWebSocketReal-time news articles
Market DataCorporateActionsSseClientServer-Sent EventsTyped corporate-action mutations, filters, history cursors, and live updates
TradingAlpacaTradingStreamWebSocketOrder lifecycle updates for the authenticated account
TradingTradingEventsSseClientServer-Sent EventsTyped account activities, historical cursors, and live updates
BrokerBrokerEventsSseClientServer-Sent EventsBroker account, trade, funding, journal, system, and related event streams

Option live streaming is not currently exposed by this SDK. Option REST data is available from the generated OptionApi.

Callback model​

All listener interfaces provide empty default methods. Override only the events your application needs.

WebSocket callbacks run on OkHttp's reader thread by default. SSE callbacks are serialized per subscription, and stream parsing waits for each callback to complete to provide backpressure. The default SSE executor runs callbacks directly: event delivery runs on the transport thread, while opening and terminal delivery that is not already queued behind an active callback starts through separate bounded SDK dispatchers. The opening callback is admitted before opened() continuations run, so a continuation may close the subscription without preventing ordered onOpen and onClosed delivery. If a handler writes to a database, calls a network service, or performs blocking work, use a factory overload that accepts an application-owned Executor.

Transport lifecycle does not wait for user callbacks: close() cancels transport work and waits for lifecycle completion to settle before returning, while the serialized terminal listener callback runs after callbacks already admitted. If a failure wins a concurrent terminal transition, close() observes its settled exceptional completion without rethrowing it. Lifecycle timers also remain independent of callback execution. Event callbacks backpressure response parsing, however, so a blocked callback can delay detection of remote EOF and the following reconnect. Sharing one single-thread executor across subscriptions intentionally serializes their callbacks. Terminal listener delivery is admitted before lifecycle futures notify synchronous continuations, but invocation waits until lifecycle completion is settled. Closing a subscription whose opening callback is waiting in the bounded dispatcher releases its HTTP response thread; already-admitted listener callbacks remain ordered and may complete later. Lifecycle completion is settled away from the active callback path, so a callback may close the subscription even when a synchronous completion continuation waits for the ordered terminal listener.

The SDK opening and terminal dispatchers use finite primary worker pools and queues. If unrelated subscriptions saturate a primary dispatcher, its already-admitted callback falls back to the transport lifecycle executor instead of failing the subscription or dropping terminal delivery. That fallback can consume additional daemon workers when callbacks block, so callbacks should remain non-blocking; an application-owned executor can isolate opening and event work. Each opened() or completion() call returns an independently settled defensive future; cancelling or manually completing one does not affect the subscription or another saved future. Lifecycle completion uses a separate elastic, direct-handoff executor: a blocked synchronous continuation cannot delay another saved lifecycle future, queue another subscription's settlement, or occupy the scheduler. Synchronous lifecycle continuations must remain short because concurrently blocked continuations consume additional daemon workers. The documented waits for related opened() or terminal-listener delivery are supported; use an async continuation with an application-owned executor for unrelated or potentially unbounded blocking work. Opening-dispatch rejection fails the subscription with an AlpacaSseCallbackException. Under terminal-dispatch saturation, lifecycle completion remains authoritative, the pending terminal listener callback is rejected, and the SDK logs a warning.

The SSE transport retains the supplied OkHttp client's application interceptors, proxy, TLS, and connection pool, but each subscription uses its own one-call daemon dispatcher. The dispatcher is shut down when that subscription reaches a terminal state. This prevents long-lived streams from consuming REST dispatch slots, imposing a process-wide stream limit, or keeping the JVM alive. Cancel SSE through AlpacaSseSubscription; cancelAll() on the supplied client's dispatcher does not own derived SSE calls.

The SDK removes its application-level AlpacaRetryInterceptor from the derived SSE client so it cannot layer retries beneath the SSE reconnect policy. Other caller-supplied interceptors remain installed; configure any custom retry interceptor to exclude SSE requests so reconnect attempts and backoff stay under AlpacaSseOptions. The transport also disables inherited read and whole-call timeouts because they would terminate healthy long-lived responses. Use AlpacaSseOptions for connection, idle, reconnect-cycle, and whole-subscription deadlines.

If a listener throws a RuntimeException, the SDK logs it and considers the event delivered, so its resume ID advances. Fatal non-runtime throwables are logged at severe level and make non-terminal dispatch fail; terminal lifecycle completion remains authoritative when a terminal listener fails. A callback-executor rejection is terminal. Applications should handle their own callback failures, persist work transactionally, and deduplicate by SSE event ID.

A complete event that cannot be converted to its generated model is logged and delivered to onEventFailure. This callback is non-terminal: after it is invoked, the malformed event is skipped, its ID becomes the committed resume cursor, and parsing continues on the same healthy connection. AlpacaSseListener.onEventFailure defaults to no action, so applications requiring complete event accounting should override it and persist or alert on the reported gap. AlpacaSseListener.onFailure(Throwable) remains reserved for terminal subscription failures. The Broker-specific listener retains its legacy two-argument onFailure delegation described below.

SSE subscriptions return immediately while the HTTP connection opens. Use opened() with a caller-chosen timeout instead of building a startup latch; it yields immutable response URI, status, and header metadata. connection() reports the most recently accepted connection and changes after reconnects, while opened() always retains the initial connection. Once response headers are accepted, opened() completes successfully and the ordered onOpen callback remains ahead of a concurrent terminal callback. User closure before the first response cancels the returned defensive future; cancelling that copy does not close the subscription.

var connection = subscription.opened().get(10, TimeUnit.SECONDS);
System.out.printf("%d %s%n", connection.statusCode(), connection.uri());

Configure transport options without supplying an executor, or configure both through the top-level client builder:

var events = AlpacaClientFactory.tradingEventsSseClient(tradingClient, sseOptions);

var client = AlpacaClient.builder(credentials)
.tradingSseOptions(sseOptions)
.tradingSseCallbackExecutor(callbackExecutor)
.dataSseOptions(sseOptions)
.dataSseCallbackExecutor(callbackExecutor)
.brokerSseOptions(brokerOptions)
.brokerSseCallbackExecutor(callbackExecutor)
.build();

The SDK never shuts down an application-owned callback executor.

Stock data stream​

Stock streams support trades, quotes, minute bars, daily bars, updated bars, trading statuses, and LULD updates. Subscribing to trades also enables trade corrections and cancel/error events for the same symbols.

import markets.alpaca.client.AlpacaClientFactory;
import markets.alpaca.client.AlpacaCredentials;
import markets.alpaca.client.ws.AlpacaStreamEnvironment;
import markets.alpaca.client.ws.StockSource;
import markets.alpaca.client.ws.StockStreamListener;
import markets.alpaca.client.ws.StockSubscription;
import markets.alpaca.client.ws.model.StockTrade;

var credentials = AlpacaCredentials.fromTradingApiEnvironmentVariables();

var stockStream = AlpacaClientFactory.stockStream(
credentials,
StockSource.IEX,
AlpacaStreamEnvironment.PRODUCTION,
new StockStreamListener() {
@Override
public void onTrade(StockTrade trade) {
System.out.println(trade);
}

@Override
public void onError(int code, String message) {
System.err.printf("stock stream error %d: %s%n", code, message);
}
});

stockStream.connect(StockSubscription.builder()
.trades("AAPL")
.quotes("AAPL")
.build());

Use StockSource.IEX or StockSource.SIP according to your data entitlement.

Crypto data stream​

Crypto streams are available in the production stream environment and support trades, quotes, bars, updated bars, daily bars, and orderbooks.

import markets.alpaca.client.ws.AlpacaStreamEnvironment;
import markets.alpaca.client.ws.CryptoStreamListener;
import markets.alpaca.client.ws.CryptoSubscription;
import markets.alpaca.client.ws.model.CryptoOrderbook;

var cryptoStream = AlpacaClientFactory.cryptoStream(
credentials,
AlpacaStreamEnvironment.PRODUCTION,
new CryptoStreamListener() {
@Override
public void onOrderbook(CryptoOrderbook orderbook) {
System.out.println(orderbook);
}
});

cryptoStream.connect(CryptoSubscription.builder()
.trades("BTC/USD")
.quotes("BTC/USD")
.orderbooks("BTC/USD")
.build());

News stream​

Use NewsSubscription to subscribe to one or more symbols, or "*" for all available news.

import markets.alpaca.client.ws.NewsStreamListener;
import markets.alpaca.client.ws.NewsSubscription;
import markets.alpaca.client.ws.model.NewsArticle;

var newsStream = AlpacaClientFactory.newsStream(
credentials,
AlpacaStreamEnvironment.PRODUCTION,
new NewsStreamListener() {
@Override
public void onArticle(NewsArticle article) {
System.out.println(article.headline());
}
});

newsStream.connect(NewsSubscription.builder().symbols("AAPL", "TSLA").build());

Trading updates stream​

The trading stream sends order lifecycle events for the authenticated account. Use the paper stream with paper keys and the production stream with live keys.

import markets.alpaca.client.ws.TradingEnvironment;
import markets.alpaca.client.ws.TradingStreamListener;
import markets.alpaca.client.ws.TradingSubscription;
import markets.alpaca.client.ws.model.TradeUpdate;

var tradingStream = AlpacaClientFactory.tradingStream(
credentials,
TradingEnvironment.PAPER,
new TradingStreamListener() {
@Override
public void onTradeUpdate(TradeUpdate update) {
System.out.println(update);
}
});

tradingStream.connect(TradingSubscription.TRADE_UPDATES);

Authentication and subscription confirmation​

Streams authenticate after the socket opens. You can either react to listener callbacks or block for a short, caller-controlled timeout during startup.

import java.time.Duration;

stockStream.connect(StockSubscription.builder().quotes("AAPL").build());

var auth = stockStream.waitForAuthenticationResult(Duration.ofSeconds(10));
if (!auth.isAuthenticated()) {
throw new IllegalStateException(
"stream authentication failed: " + auth.status()
+ " code=" + auth.code()
+ " message=" + auth.message());
}

Market data streams fire onSubscriptionConfirmed(...) after subscribe or unsubscribe requests. Trading streams fire onListening(...) with the active stream names.

Reconnect behavior​

WebSocket clients reconnect automatically after unexpected disconnects using jittered exponential backoff. The default policy tries 10 times, starts at 1 second, caps delay at 64 seconds, and adds 20% jitter.

import java.time.Duration;
import markets.alpaca.client.ws.AlpacaStreamReconnectPolicy;

var reconnectPolicy = AlpacaStreamReconnectPolicy.builder()
.initialBackoff(Duration.ofSeconds(2))
.maxBackoff(Duration.ofSeconds(30))
.maxAttempts(20)
.build();

var resilientStream = AlpacaClientFactory.stockStream(
credentials,
StockSource.IEX,
AlpacaStreamEnvironment.PRODUCTION,
new StockStreamListener() {},
reconnectPolicy);

Use AlpacaStreamReconnectPolicy.disabled() when an application-level supervisor should own reconnect decisions.

Market Data corporate-actions SSE​

Corporate-action mutations use Server-Sent Events. Create the handwritten client through the factory; the generated subscribeToCorporateActionsEventsSSE method buffers the response and is not suitable for a live stream.

import markets.alpaca.client.data.sse.CorporateActionsSseRequest;
import markets.alpaca.client.data.sse.MarketDataSseEnvironment;
import markets.alpaca.client.openapi.data.model.CorporateActionEvent;
import markets.alpaca.client.openapi.data.model.CorporateActionEventCashDividend;
import markets.alpaca.client.openapi.data.model.CorporateActionEventType;
import markets.alpaca.client.sse.AlpacaSseEvent;
import markets.alpaca.client.sse.AlpacaSseListener;

var corporateActions = AlpacaClientFactory.corporateActionsSseClient(
dataClient, MarketDataSseEnvironment.PRODUCTION);

var request = CorporateActionsSseRequest.builder()
.eventTypes(CorporateActionEventType.CASH_DIVIDEND_CORPORATEACTION_EVENT)
.region(CorporateActionsSseRequest.Region.US)
.build();

var subscription = corporateActions.subscribeToCorporateActions(
request,
new AlpacaSseListener<>() {
@Override
public void onEvent(AlpacaSseEvent<CorporateActionEvent> event) {
if (event.data().getActualInstance()
instanceof CorporateActionEventCashDividend dividend) {
System.out.printf("%s %s%n", event.id(), dividend.getCa().getSymbol());
}
}
});

Select PRODUCTION, SANDBOX, or an explicit MarketDataSseEnvironment.custom(...) endpoint. This stream endpoint is independent from the generated Market Data REST base URL, so selecting a REST environment does not implicitly select the SSE environment.

Use CorporateActionsSseRequest.fromEventId(...) or throughEventId(...) for replay and bounded history. Corporate-action event IDs are validated uppercase ULIDs. The endpoint defines inclusive resume semantics, so reconnects can redeliver the cursor event; deduplicate by event ID when effects must be exactly once. After an empty SSE id:, requests with since or sinceId replay from that original lower bound, while cursorless requests fail closed instead of reconnecting with a possible gap. Cursorless requests also fail closed if an established connection drops before supplying any event ID. Unknown event_type values, malformed payloads, and payloads that do not validate against their generated concrete schema are not guessed: they are reported through onEventFailure, skipped, and committed as the resume cursor before delivery continues.

Trading account-activity SSE​

Account activities use Server-Sent Events and are separate from WebSocket trade_updates. Create the handwritten client through the factory; generated subscribeToActivitiesSSE methods buffer the response and are not suitable for a live stream.

import markets.alpaca.client.sse.AlpacaSseDeserializationException;
import markets.alpaca.client.sse.AlpacaSseEvent;
import markets.alpaca.client.sse.AlpacaSseListener;
import markets.alpaca.client.openapi.trading.model.ActivityEventV2;
import markets.alpaca.client.trading.sse.TradingEventsSseClient;

TradingEventsSseClient events =
AlpacaClientFactory.tradingEventsSseClient(tradingClient);

var subscription = events.subscribeToActivities(
new AlpacaSseListener<>() {
@Override
public void onEvent(AlpacaSseEvent<ActivityEventV2> event) {
System.out.printf("%s %s%n", event.id(), event.data().getActivityType());
}

@Override
public void onEventFailure(AlpacaSseDeserializationException failure) {
System.err.printf("skipped event %s (%s)%n",
failure.eventId(), failure.eventType());
}
});

// Later:
subscription.close();

For a bounded historical range, pass a validated cursor request:

import markets.alpaca.client.trading.sse.TradingActivitySseRequest;

var range = TradingActivitySseRequest.throughEventId(
"01K6F000000000000000000000",
"01K6G000000000000000000000");

var historical = events.subscribeToActivities(range, new AlpacaSseListener<>() {});

Live Trading SSE reconnects on transient failures by default. It follows the SSE protocol by persisting completed id: fields (including data-less ID blocks) and sending the cursor as the documented since_id query parameter and in Last-Event-ID on the replacement request. Resume state advances after a payload is successfully decoded and dispatched, or when a completed data-less id: block is observed. An empty id: clears Last-Event-ID; an unbounded stream then retains its request's original since or since_id lower bound so a reconnect cannot silently skip events emitted during backoff. That safe replay can redeliver earlier events. Malformed Trading payloads are reported and skipped, and their IDs advance the cursor after callback invocation. Date-bounded requests likewise retain their original date range on retry and can replay already processed events. Server replay can be inclusive, so applications requiring exactly-once effects must deduplicate persisted work by event ID. Because the Trading API returns no history without a lower bound, a cursorless live stream fails closed after an empty id: or when an established connection drops before supplying any event ID, rather than reconnecting with a silent gap. An interrupted ID-bounded stream also fails closed because the API requires since_id with until_id. until or untilId makes a request bounded; normal EOF then completes the subscription instead of reconnecting. Configure retry budgets, initial resume ID, idle timeout, and resource limits with AlpacaSseOptions factory overloads. An initial resume ID must not be empty and cannot be combined with a date-bounded Trading request because backend consumption of Last-Event-ID is not documented and date/ID cursor families cannot be mixed safely. Use an ID-bounded request instead; its initial ID must not be after untilId. AlpacaSseReconnectPolicy.maxElapsedTime(...) bounds one initial-open or established reconnect cycle. An established cycle remains bounded through backoff, reconnect headers, comments, and silence until an event is delivered; AlpacaSseOptions.maxDuration(...) separately bounds the lifetime of the whole subscription. initialBackoff(...) and maxBackoff(...) require whole-millisecond values of at least 1 ms. The initial backoff is also the minimum server-directed delay, preventing retry: 0 or Retry-After: 0 from creating a tight SDK reconnect loop; the transport handles Retry-After: 0 before OkHttp's immediate follow-up can bypass the configured attempt policy. Jitter never reduces a positive client delay to zero. The maximum caps client exponential backoff and server-provided delays. The connection timeout covers successful response-header validation and bounded non-success response-body capture, so a server cannot keep a subscription opening indefinitely by stalling an error body.

Malformed Trading activity payloads invoke onEventFailure and are skipped without closing the healthy stream. Activity detail models are selected by the OAS type/subtype mapping. The two schemas whose OAS definitions currently lack discriminants (fixed-income redemption and rights distribution) use a unique-most-specific structural fallback; ties are reported as malformed instead of being guessed. The same decoder behavior applies to Broker Activity V2 events. Until the upstream contract provides a dedicated CSD detail schema, CSD events retain their activity type but expose details through CSWActivityV2; additional payload fields remain available through getAdditionalProperties(). The OAS-valid DIVTXEX type likewise retains its activity type and uses the structurally compatible CDIVActivityV2 detail model until a dedicated schema exists.

Broker Events SSE​

Broker Events are exposed through the Broker SSE client, not a WebSocket stream.

import markets.alpaca.client.AlpacaClientFactory;
import markets.alpaca.client.broker.sse.BrokerSseDateOptions;
import markets.alpaca.client.broker.sse.BrokerSseEventListener;
import markets.alpaca.client.openapi.broker.model.TradeUpdateEventV2;

var brokerEvents = AlpacaClientFactory.brokerEventsSseClient(brokerClient);
var subscription = brokerEvents.subscribeToTradeEvents(
BrokerSseDateOptions.empty(),
new BrokerSseEventListener<TradeUpdateEventV2>() {
@Override
public void onEvent(TradeUpdateEventV2 event) {
System.out.println(event);
}
});

subscription.close();

Existing Broker client constructors preserve the previous one-connection behavior. Use the AlpacaSseOptions factory overload to opt into resilient reconnect behavior. Broker listener callbacks are serialized and provide backpressure; use a dedicated executor for blocking work. BrokerSseSubscription implements the shared AlpacaSseSubscription lifecycle contract, while retaining Broker-specific compatibility methods. For compatibility, a malformed Broker event invokes onFailure for that event and the healthy connection continues. Its SSE ID becomes the Last-Event-ID transport cursor after the callback. Admin-action streams retain the generated SubscribeToAdminActionSSE200ResponseInner listener type, while the required type field selects its concrete generated model without relying on the ambiguous generated oneOf adapter. Rebalancer streams use subscribeToRebalancerEvents and select RebalancerEvent from event_type the same way. That stream also accepts lastEventId, sent as the documented Last-Event-Id header. Broker endpoints document endpoint-specific since/since_id/since_ulid query cursors. After an empty SSE id:, a configured initial ID or that original lower-bound query keeps replay possible. The rebalancer stream also keeps a supplied Last-Event-Id header as its lower bound. Cursorless subscriptions fail closed rather than reconnecting with a possible gap, including when an established connection drops before supplying any event ID. Applications that require gap replay should configure the appropriate request option and deduplicate. Protocol and non-retryable HTTP failures are terminal; retryable HTTP and transport failures follow the configured reconnect policy.

New listeners can override onEventFailure(AlpacaSseDeserializationException) to distinguish one malformed event from terminal failures and inspect its event ID/type. onRetryChanged(Duration) reports server retry: fields, onHttpFailure(...) exposes structured HTTP failures, and onClosed(AlpacaSseCloseResult) exposes the normal close reason. Defaults preserve the original callback shapes: malformed events pass their original cause, HTTP failures pass a bounded compatibility response with no throwable, and user cancellation passes IOException("canceled") with no response. Rich overrides receive one callback instead.

Applications upgrading Broker SSE from 0.1.4 should follow the SSE migration guide, especially when they use eventSource(), inspect raw failure types, or block inside callbacks.

The deprecated /v1/events/transfers/status operation is inventoried but intentionally has no handwritten wrapper. Use Broker funding-status events for supported transfer/funding updates.