Trading
Streams.
Live updates over WebSocket: every order, fill and position change on your accounts as it happens, and market data straight from the exchanges.
On this page
Two WebSocket streams keep your code up to date without polling. Both take the same key as the REST API, in the Authorization header of the upgrade, and both send JSON text frames. A browser cannot set that header: it offers the subprotocols pp.v1 and pp.key.<your key> instead, and the server answers pp.v1.
| Stream | Address | What it sends |
|---|---|---|
| Account | wss://api.phoenixperpsfunding.com/v1/stream (sandbox: wss://sandbox-api.phoenixperpsfunding.com/v1/stream) | A snapshot of each account, then every event once: orders, fills, positions, strategies, live risk |
| Market data | wss://stream.phoenixperpsfunding.com/v1/market-data | Prices, the order book, trades, candles and 24-hour statistics, for any key of either environment |
The SDKs reconnect by themselves, resume where they stopped and subscribe again; the rest of this page is what they do for you, and what to do if you write your own client.
The account stream#
const stream = client.accountStream({ risk: true });
stream.on("snapshot", (s) => console.log(s.account_id, s.positions.length, "positions"));
for await (const event of stream) console.log(event.type, event.data); // each event once, resumed after reconnectsfrom phoenixperps import AsyncPhoenixPerps
client = AsyncPhoenixPerps()
async with client.account_stream(risk=True) as stream:
async for event in stream: # each event once, resumed after reconnects
print(event["type"], event["data"])stream := client.AccountStream(ctx, phoenixperps.AccountStreamOptions{Risk: true})
defer stream.Close()
for event, err := range stream.Events() { // each event once, resumed after reconnects
if err != nil {
log.Fatal(err)
}
fmt.Println(event.Type, event.Data)
}await using var stream = client.OpenAccountStream(new AccountStreamOptions { Risk = true });
await foreach (var e in stream.ReadAllAsync()) // each event once, resumed after reconnects
Console.WriteLine($"{e.Type} {e.AccountId}");try (AccountStream stream = client.openAccountStream(AccountStream.options().risk(true))) {
for (Event e : stream) { // each event once, resumed after reconnects
System.out.println(e.type() + " " + e.data());
}
}let mut stream = client.account_stream(AccountStreamOptions { risk: true, ..Default::default() });
while let Some(event) = stream.next().await { // each event once, resumed after reconnects
let event = event?;
println!("{} {:?}", event.r#type, event.data);
}foreach ($client->accountStream(risk: true) as $event) { // blocks; each event once, resumed after reconnects
echo $event->type, ' ', json_encode($event->data), PHP_EOL;
}What goes over the wire#
The server says hello
{"type":"hello","session":"...","environment":"sandbox","heartbeat_ms":15000,"accounts":[...]}: the accounts your key reaches.You subscribe
{"op":"subscribe"}follows every account the key reaches, up to 50 on one stream, and those opened later too (each comes with its snapshot);{"op":"subscribe","accounts":["SANDBOX-00042-001"],"risk":true}follows the ones you name, with their live risk. Risk frames come only with"risk": true.A snapshot of each account
{"type":"snapshot","account_id":"...","orders":[...],"positions":[...],"risk":{...}}for each account, then{"type":"snapshot_end","accounts":[...]}. Build your state from these. A snapshot that could not be read now carries"error":"state_unavailable"with empty lists: it is not an empty account, read it again (GET .../positions) before you trust it. An account the key does not reach answers{"type":"error","code":"account_not_found","account_id":"..."}instead, and the SDKs end the stream with that error.Then every event, once
{"type":"event","seq":1,"event":{...}}. The event is the same object asGET /v1/eventsanswers, with itsid,type,account_id,time,sourceanddata.seqcounts this connection's events without a gap.
Your sandbox account stream, live
The hello, a snapshot of each account, then every event as it happens, exactly as your code gets them. Place an order with Try it, in the API reference, and watch its events arrive.
With risk: true, the stream also sends {"type":"risk","account_id":"...","data":{...}} when an account's risk changes, at most every 2 seconds: equity, margin and the room left to the daily loss and drawdown limits, as GET .../risk answers.
Events#
| Type | When |
|---|---|
order.created, order.edited | An order was placed or changed, from the API, a strategy or a trading platform |
order.filled, order.canceled, order.expired, order.rejected | An order ended |
fill.created | A fill, with its price, size and fee |
position.opened, position.changed, position.closed | A position appeared, grew or shrank, or closed: data.position is its market, side, size and average_price as the engine reported them, data.previous_size the size before (a reversal is a position.closed with close_reason: "reversal", then a position.opened; read GET .../positions/{market} for its margin, P&L and liquidation) |
strategy.created, strategy.leg_placed, strategy.leg_modified, strategy.leg_filled, strategy.leg_canceled, strategy.leg_rejected, strategy.orphan_repaired, strategy.slice, strategy.triggered, strategy.ended | What the API's exits and strategies did for you |
alert.triggered | One of the account's price alerts fired: data.alert is the alert as it fired |
tradingview.alert_executed, tradingview.alert_refused | A TradingView alert placed its orders, or was refused |
account.updated, account.passed, account.failed, account.payout_eligible, account.disabled, account.removed | The account's balance or status changed, it passed or failed, it can request a payout, it was disabled or removed |
risk.warning, risk.cleared | A warning came close (most of the daily loss used, liquidation near...), or went away |
key.loss_stop, key.expiring | A key reached its daily loss stop on the account (the account was flattened, the key stopped there until the day ends), or expires soon |
system.restarted | The trading engine restarted: every order and position of before it is gone |
Reconnecting without missing anything#
Connect again with ?resume=<the id of the last event you have>: the events you missed come first, then a fresh snapshot. The server keeps 15 minutes of events for this. When it cannot cover your gap (an older or unknown event), it says so before the snapshot: {"type":"notice","code":"resume_gap","after":"evt_..."}. Read what you missed from GET /v1/events?after= that id (the log keeps 7 days), then go on from the snapshot. The SDKs resume by themselves, tell each event once even when a resume replays it, and tell you of a gap.
The server sends {"type":"heartbeat"} every 15 seconds. Three heartbeats without a frame mean the connection is dead: reconnect. You can also send {"op":"ping"} and get {"type":"pong"}.
Why a stream closes#
| Code | Meaning | What to do |
|---|---|---|
4001 | The key was revoked or expired | Stop: a new key is needed |
4003 | A message it may not send | Fix the message |
4008 | Too far behind: the client did not read fast enough | Reconnect without resume, from the snapshot |
4009 | Too many messages from the client | Slow down, then reconnect |
1012 | The server restarts | Reconnect after a moment, with resume |
A key can hold 4 account streams at once. One too many is refused before it opens, with 429 rate_limited (its details.scope says which limit: stream_key, stream_customer or stream_ip) and a Retry-After: close another stream, or wait. Any other refusal of the upgrade is the REST error of the same name (401 invalid_api_key, for example).
The market data stream#
Market data comes straight from the exchanges, in real time, as market ids (BTC-USD), with prices and sizes as decimal strings.
const market = client.marketStream();
market.on("ticker", (f) => console.log(f.symbol, f.data.bid, f.data.ask));
await market.subscribe("ticker", ["BTC-USD", "ETH-USD"], { interval_ms: 250 });async with client.market_stream() as market:
await market.subscribe("ticker", ["BTC-USD", "ETH-USD"], interval_ms=250)
async for frame in market:
if "symbol" in frame: # data frames (subscribed and snapshot_end have none)
print(frame["symbol"], frame["data"])market := client.MarketStream(ctx)
defer market.Close()
if _, err := market.Subscribe(ctx, "ticker", []string{"BTC-USD", "ETH-USD"}, map[string]any{"interval_ms": 250}); err != nil {
log.Fatal(err)
}
for frame, err := range market.Frames() {
if err != nil {
log.Fatal(err)
}
fmt.Println(frame.Symbol, string(frame.Data))
}await using var market = client.OpenMarketStream();
await market.SubscribeAsync("ticker", new[] { "BTC-USD", "ETH-USD" }, new Dictionary<string, object?> { ["interval_ms"] = 250 });
await foreach (var frame in market.ReadAllAsync())
Console.WriteLine($"{frame.Symbol} {frame.Data}");try (MarketStream market = client.openMarketStream()) {
market.subscribe("ticker", List.of("BTC-USD", "ETH-USD"), Map.of("interval_ms", 250), Duration.ofSeconds(10));
for (MarketStream.Frame frame : market) {
if (frame.symbol() != null) System.out.println(frame.symbol() + " " + frame.data()); // data frames only
}
}let mut market = client.market_stream();
let mut params = serde_json::Map::new();
params.insert("interval_ms".into(), 250.into());
market.subscribe("ticker", &["BTC-USD", "ETH-USD"], params).await?;
while let Some(frame) = market.next().await {
let frame = frame?;
println!("{:?} {:?}", frame.symbol, frame.data);
}$market = $client->marketStream();
$market->subscribe('ticker', ['BTC-USD', 'ETH-USD'], ['interval_ms' => 250]);
foreach ($market as $frame) {
echo $frame['symbol'], ' ', json_encode($frame['data']), PHP_EOL;
}Channels#
| Channel | Options | Each frame's data |
|---|---|---|
ticker | interval_ms: 100, 250, 500 or 1000 (default 250) | bid, ask, last, time: the latest in each window |
book | depth: 1, 5, 10 or 20 (default 10) | bids and asks as [price, size], time: the whole top, at most every 250 ms |
trades | history: 0 to 200 trades first (default 20) | A list of id, price, size, side, time, batched every 100 ms |
candles | interval: 1m to 1M; history: 0 to 500 closed candles first (default 100) | A list of time, open, high, low, close, volume, final |
stats | symbols, or ["*"] for every market | last, change_24h, change_24h_pct, high_24h, low_24h, volume_24h (in the asset), notional_volume_24h (in USD), open_interest (in the asset), notional_open_interest (in USD), every 5 s. Without a stream, GET /v1/markets/stats answers the same for every market (no key needed). |
status | no symbols | feed: its state (live, degraded or down) and age_ms, when it changes |
A subscribe with history: 100 sends the last 100 closed candles in one frame, then the forming one in a frame of its own. A candle with final: false is still forming and comes again as it changes; the same time with final: true is the closed candle. If the closed candle's final figures differ a moment later, it comes once more with revised: true. An option out of its range, or one the channel does not take, is refused with invalid_parameter (never replaced by a default). Sizes come at least at the market's size decimals, prices at its tick.
Subscribing by hand#
Send {"op":"subscribe","id":1,"channel":"candles","symbols":["BTC-USD"],"interval":"1m","history":100}. The answer is {"type":"subscribed","id":1,"symbols":["BTC-USD"],"rejected":[]} (a market it does not know is in rejected with its code), then the channel's current state, then {"type":"snapshot_end","id":1}, then live frames {"type":"candles","symbol":"BTC-USD","data":[...]}. {"op":"list"} lists yours.
{"op":"unsubscribe","id":2,"channel":"candles","symbols":["BTC-USD"],"interval":"1m"} stops one. Without interval it stops every interval of those markets; without symbols (or with an empty list), every subscription of the channel. The answer names what ended, and what you named that was not followed: {"type":"unsubscribed","id":2,"channel":"candles","symbols":["BTC-USD"],"rejected":[],"interval":"1m"} (rejected holds { "symbol", "code": "not_subscribed" }).
Market data, live
One channel of one market, frame by frame, as your code gets it. It stops when you leave this tab, or after 2 minutes without activity.
One stream holds 200 subscriptions (each candle interval counts); a key holds 5 market streams. The hello says so too: {"type":"hello",...,"limits":{"subscriptions":200,"symbols_per_subscribe":50,"messages_per_s":20}}. The close codes are the account stream's: 4001, 4008 (too far behind), 4009 (too many messages) and 1012. Three heartbeats (the hello's heartbeat_ms apart) without a frame mean the connection is dead: reconnect, and subscribe again (the SDKs do).