PhoenixPerpetualsDocs API v1
Get an API key

Cookbook

A live copy of your accounts⁠.

A live copy of your accounts' positions and working orders: the snapshot first, then every event applied once.

View as Markdown

The whole program, in each language. Set PHOENIXPERPS_API_KEY to a sandbox key (ppk_test_...) and run it. After a reconnect the SDK resumes from the last event; events it could not resume are told as a gap, and the snapshot that follows rebuilds the copy. Ctrl+C to stop.

import { PhoenixPerps } from '@phoenixperps/sdk';

type Row = { id?: string; market?: string; status?: string; size?: string; side?: string };
const FINAL = new Set(['filled', 'canceled', 'rejected', 'expired']);
const mirror = new Map<string, { positions: Map<string, Row>; orders: Map<string, Row> }>();

const client = new PhoenixPerps();
const stream = client.accountStream();
stream.on('snapshot', (f: { account_id: string; positions: Row[]; orders: Row[]; error?: string }) => {
  // an account that could not be read now comes empty with the reason: not a flat account, so not mirrored
  if (f.error) {
    mirror.delete(f.account_id);
    console.log(`[snapshot] ${f.account_id}: not readable now (${f.error}); read it again by REST`);
    return;
  }
  mirror.set(f.account_id, {
    positions: new Map(f.positions.map((p) => [String(p.market), p])),
    orders: new Map(f.orders.map((o) => [String(o.id), o])),
  });
});
stream.on('ready', () => print('snapshot'));
stream.on('reconnect', ({ in_ms, cause }: { in_ms: number; cause: string }) => console.log(`reconnecting in ${in_ms} ms (${cause})`));
// the events missed are in GET /v1/events?after=; the copy itself comes back with the next snapshot
stream.on('gap', ({ after }: { after: string | null }) => console.log(`[gap] events after ${after ?? 'the start'} were not told: client.events.list({ after })`));

function print(why: string) {
  for (const [id, m] of mirror) {
    const pos = [...m.positions.values()].map((p) => `${p.market} ${p.side} ${p.size}`).join(', ') || 'none';
    console.log(`[${why}] ${id}: positions ${pos}; ${m.orders.size} working orders`);
  }
}

for await (const e of stream) {
  const m = mirror.get(e.account_id);
  if (!m) continue;
  const data = e.data as { order?: Row; position?: Row };
  if (data.order?.id) {
    if (FINAL.has(String(data.order.status))) m.orders.delete(data.order.id);
    else m.orders.set(data.order.id, data.order);
  }
  if (data.position?.market) {
    if (e.type === 'position.closed') m.positions.delete(data.position.market);
    else m.positions.set(data.position.market, data.position);
  }
  print(e.type);
}
import asyncio
from typing import Any, Dict

from phoenixperps import PhoenixPerps
from phoenixperps.types import Event

FINAL = {"filled", "canceled", "rejected", "expired"}
mirror: Dict[str, Dict[str, Dict[str, Any]]] = {}


def show(why: str) -> None:
    for account_id, m in mirror.items():
        positions = ", ".join(f'{p["market"]} {p["side"]} {p["size"]}' for p in m["positions"].values()) or "none"
        print(f'[{why}] {account_id}: positions {positions}; {len(m["orders"])} working orders')


def apply(event: Event) -> None:
    m = mirror.get(event["account_id"])
    if m is None:
        return
    order, position = event["data"].get("order"), event["data"].get("position")
    if order:
        if order["status"] in FINAL:
            m["orders"].pop(order["id"], None)
        else:
            m["orders"][order["id"]] = order
    if position:
        if event["type"] == "position.closed":
            m["positions"].pop(position["market"], None)
        else:
            m["positions"][position["market"]] = position


async def main() -> None:
    client = PhoenixPerps()
    async with client.account_stream() as stream:
        await stream.ready.wait()
        for account_id, snap in stream.snapshots.items():
            if snap.get("error"):  # not readable now: its orders and positions are unknown, not empty
                print(f'[snapshot] {account_id}: not mirrored ({snap["error"]}); read it again by REST')
                continue
            mirror[account_id] = {
                "positions": {p["market"]: p for p in snap["positions"]},
                "orders": {o["id"]: o for o in snap["orders"]},
            }
        show("snapshot")
        async for event in stream:
            if event["type"] == "notice":  # a gap: the events after event["after"] may be missing here
                if event["after"]:
                    for missed in client.events.list({"after": event["after"]}).auto_paging_iter():
                        apply(missed)
                show(f'gap after {event["after"]}')
                continue
            apply(event)
            show(event["type"])


asyncio.run(main())
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/signal"
	"strings"

	phoenixperps "github.com/phoenixperps/sdk/go"
)

type row = map[string]any

type copyOf struct {
	positions map[string]row // by market
	orders    map[string]row // by id
}

var final = map[string]bool{"filled": true, "canceled": true, "rejected": true, "expired": true}

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	client, err := phoenixperps.NewClient()
	if err != nil {
		log.Fatal(err)
	}
	accounts, err := client.Accounts.List(ctx)
	if err != nil {
		log.Fatal(err)
	}
	stream := client.AccountStream(ctx, phoenixperps.AccountStreamOptions{OnGap: func(after string) {
		fmt.Printf("[gap] events after %s may be missing from the copy: client.Events.List after it has them\n", after)
	}})
	defer stream.Close()
	select {
	case <-stream.Ready():
	case <-ctx.Done():
		return
	}
	mirror := map[string]*copyOf{}
	for _, a := range accounts.Data {
		var snap struct {
			Positions, Orders []row
			Error             string // the account could not be read now: its snapshot is empty, not flat
		}
		if json.Unmarshal(stream.Snapshot(a.ID), &snap) != nil {
			continue
		}
		if snap.Error != "" {
			fmt.Printf("[snapshot] %s: not read (%s); read it again by REST\n", a.ID, snap.Error)
			continue
		}
		c := &copyOf{positions: map[string]row{}, orders: map[string]row{}}
		for _, p := range snap.Positions {
			c.positions[fmt.Sprint(p["market"])] = p
		}
		for _, o := range snap.Orders {
			c.orders[fmt.Sprint(o["id"])] = o
		}
		mirror[a.ID] = c
	}
	show(mirror, "snapshot")
	for {
		e, err := stream.Next(ctx)
		if err != nil {
			if ctx.Err() != nil {
				return
			}
			log.Fatal(err)
		}
		c := mirror[e.AccountID]
		if c == nil {
			continue
		}
		if o, ok := e.Data["order"].(map[string]any); ok {
			id := fmt.Sprint(o["id"])
			if final[fmt.Sprint(o["status"])] {
				delete(c.orders, id)
			} else {
				c.orders[id] = o
			}
		}
		if p, ok := e.Data["position"].(map[string]any); ok {
			m := fmt.Sprint(p["market"])
			if e.Type == "position.closed" {
				delete(c.positions, m)
			} else {
				c.positions[m] = p
			}
		}
		show(mirror, string(e.Type))
	}
}

func show(mirror map[string]*copyOf, why string) {
	for id, c := range mirror {
		var pos []string
		for _, p := range c.positions {
			pos = append(pos, fmt.Sprintf("%v %v %v", p["market"], p["side"], p["size"]))
		}
		if len(pos) == 0 {
			pos = []string{"none"}
		}
		fmt.Printf("[%s] %s: positions %s; %d working orders\n", why, id, strings.Join(pos, ", "), len(c.orders))
	}
}
#:package PhoenixPerps.Sdk@1.0.0
using System.Globalization;
using System.Text.Json;
using PhoenixPerps;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; // decimals print as 0.0001 on every machine

var final = new HashSet<string> { "filled", "canceled", "rejected", "expired" };
var mirror = new Dictionary<string, (Dictionary<string, JsonElement> Positions, Dictionary<string, JsonElement> Orders)>();
using var stop = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.Cancel(); };

using var client = new PhoenixPerpsClient();
var accounts = await client.Accounts.ListAsync();
await using var stream = client.OpenAccountStream(new AccountStreamOptions
{
    OnGap = after => Console.WriteLine($"[gap] events after {after ?? "the start"} were missed: the copy may be stale"),
});
await stream.Ready.WaitAsync(stop.Token);
foreach (var a in accounts.Data)
{
    if (stream.Snapshot(a.Id) is not { } snap) continue;
    if (snap.TryGetProperty("error", out var error))
    {
        // the account could not be read just now (its lists are empty, not flat): read it again by REST
        Console.WriteLine($"[snapshot] {a.Id}: not readable now ({error})");
        continue;
    }
    mirror[a.Id] = (
        snap.GetProperty("positions").EnumerateArray().ToDictionary(p => p.GetProperty("market").GetString()!),
        snap.GetProperty("orders").EnumerateArray().ToDictionary(o => o.GetProperty("id").GetString()!));
}
Show("snapshot");

try
{
    await foreach (var e in stream.ReadAllAsync(stop.Token))
    {
        if (!mirror.TryGetValue(e.AccountId, out var m)) continue;
        if (e.Data.TryGetValue("order", out var order))
        {
            var id = order.GetProperty("id").GetString()!;
            if (final.Contains(order.GetProperty("status").GetString()!)) m.Orders.Remove(id);
            else m.Orders[id] = order;
        }
        if (e.Data.TryGetValue("position", out var position))
        {
            var market = position.GetProperty("market").GetString()!;
            if (e.Type.ToString() == "position.closed") m.Positions.Remove(market);
            else m.Positions[market] = position;
        }
        Show(e.Type.ToString());
    }
}
catch (OperationCanceledException)
{
}

void Show(string why)
{
    foreach (var (id, m) in mirror)
    {
        var positions = string.Join(", ", m.Positions.Values.Select(p => $"{p.GetProperty("market")} {p.GetProperty("side")} {p.GetProperty("size")}"));
        Console.WriteLine($"[{why}] {id}: positions {(positions.Length > 0 ? positions : "none")}; {m.Orders.Count} working orders");
    }
}
import com.fasterxml.jackson.databind.JsonNode;
import com.phoenixperpsfunding.sdk.AccountStream;
import com.phoenixperpsfunding.sdk.PhoenixPerpsClient;
import com.phoenixperpsfunding.sdk.gen.Account;
import com.phoenixperpsfunding.sdk.gen.Event;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

final class Example08 {
    private static final Set<String> FINAL = Set.of("filled", "canceled", "rejected", "expired");
    private static final Map<String, Map<String, Object>> POSITIONS = new HashMap<>(); // account -> market -> position
    private static final Map<String, Map<String, Object>> ORDERS = new HashMap<>(); // account -> id -> order

    public static void main(String[] args) throws Exception {
        PhoenixPerpsClient client = PhoenixPerpsClient.fromEnv();
        List<Account> accounts = client.accounts().list().data();
        AccountStream.Options options = AccountStream.options()
                .onGap(after -> System.out.printf("[gap] events after %s may be missing: read GET /v1/events?after=%s%n", after, after));
        try (AccountStream stream = client.openAccountStream(options)) {
            stream.ready().get(); // throws what ended the stream before it was ready (a refused key, too many accounts)
            for (Account a : accounts) {
                JsonNode snap = stream.snapshot(a.id());
                if (snap == null) continue;
                if (snap.hasNonNull("error")) { // its orders and positions are empty because they could not be read
                    System.out.printf("[snapshot] %s: not readable now (%s): read it by REST%n", a.id(), snap.get("error").asText());
                    continue;
                }
                Map<String, Object> positions = new HashMap<>();
                Map<String, Object> orders = new HashMap<>();
                for (JsonNode p : snap.path("positions")) positions.put(p.path("market").asText(), p);
                for (JsonNode o : snap.path("orders")) orders.put(o.path("id").asText(), o);
                POSITIONS.put(a.id(), positions);
                ORDERS.put(a.id(), orders);
            }
            show("snapshot");
            for (Event e : stream) {
                Map<String, Object> positions = POSITIONS.get(e.accountId());
                Map<String, Object> orders = ORDERS.get(e.accountId());
                if (positions == null || orders == null) continue;
                if (e.data().get("order") instanceof Map<?, ?> order) {
                    String id = String.valueOf(order.get("id"));
                    if (FINAL.contains(String.valueOf(order.get("status")))) orders.remove(id);
                    else orders.put(id, order);
                }
                if (e.data().get("position") instanceof Map<?, ?> position) {
                    String market = String.valueOf(position.get("market"));
                    if ("position.closed".equals(e.type().toString())) positions.remove(market);
                    else positions.put(market, position);
                }
                show(e.type().toString());
            }
        }
    }

    private static void show(String why) {
        for (String id : POSITIONS.keySet()) {
            List<String> pos = new ArrayList<>();
            for (Object p : POSITIONS.get(id).values()) pos.add(describe(p));
            System.out.printf("[%s] %s: positions %s; %d working orders%n", why, id, pos.isEmpty() ? "none" : String.join(", ", pos), ORDERS.get(id).size());
        }
    }

    private static String describe(Object p) {
        if (p instanceof JsonNode n) return n.path("market").asText() + " " + n.path("side").asText() + " " + n.path("size").asText();
        if (p instanceof Map<?, ?> m) return m.get("market") + " " + m.get("side") + " " + m.get("size");
        return String.valueOf(p);
    }
}
use std::collections::HashMap;

use futures_util::StreamExt;
use phoenixperps::{AccountMessage, AccountStreamOptions, Client, Event, EventsListParams, RequestOptions};
use serde_json::Value;

#[derive(Default)]
struct Copy {
    positions: HashMap<String, Value>, // by market
    orders: HashMap<String, Value>,    // by id
}

const FINAL: [&str; 4] = ["filled", "canceled", "rejected", "expired"];

fn show(mirror: &HashMap<String, Copy>, why: &str) {
    for (id, c) in mirror {
        let positions: Vec<String> = c.positions.values().map(|p| format!("{} {} {}", p["market"], p["side"], p["size"])).collect();
        let positions = if positions.is_empty() { "none".to_string() } else { positions.join(", ") };
        println!("[{why}] {id}: positions {positions}; {} working orders", c.orders.len());
    }
}

fn apply(mirror: &mut HashMap<String, Copy>, event: &Event) {
    let Some(c) = mirror.get_mut(&event.account_id) else { return };
    if let Some(order) = event.data.get("order") {
        let id = order["id"].as_str().unwrap_or_default().to_string();
        if FINAL.contains(&order["status"].as_str().unwrap_or_default()) {
            c.orders.remove(&id);
        } else {
            c.orders.insert(id, order.clone());
        }
    }
    if let Some(position) = event.data.get("position") {
        let market = position["market"].as_str().unwrap_or_default().to_string();
        if event.r#type.to_string() == "position.closed" {
            c.positions.remove(&market);
        } else {
            c.positions.insert(market, position.clone());
        }
    }
    show(mirror, &event.r#type.to_string());
}

#[tokio::main]
async fn main() -> phoenixperps::Result<()> {
    let client = Client::from_env()?;
    let accounts = client.accounts().list().await?;
    let mut stream = client.account_stream(AccountStreamOptions::default());
    stream.ready().await;

    let mut mirror: HashMap<String, Copy> = HashMap::new();
    for a in &accounts.data {
        let Some(snap) = stream.snapshot(&a.id) else { continue };
        if let Some(why) = snap["error"].as_str() {
            // not readable now: an empty snapshot here is not a flat account
            println!("[snapshot] {}: unreadable ({why}), read it again by REST", a.id);
            continue;
        }
        let mut c = Copy::default();
        for p in snap["positions"].as_array().into_iter().flatten() {
            c.positions.insert(p["market"].as_str().unwrap_or_default().to_string(), p.clone());
        }
        for o in snap["orders"].as_array().into_iter().flatten() {
            c.orders.insert(o["id"].as_str().unwrap_or_default().to_string(), o.clone());
        }
        mirror.insert(a.id.clone(), c);
    }
    show(&mirror, "snapshot");

    while let Some(message) = stream.next_message().await {
        match message? {
            AccountMessage::Event(e) => apply(&mut mirror, &e.event),
            AccountMessage::Gap { after } => {
                // events may be missing here: read them by REST, after the last one told
                let (params, options) = (EventsListParams { after, ..Default::default() }, RequestOptions::default());
                let mut missed = client.events().list_auto_paging(Some(&params), &options);
                while let Some(event) = missed.next().await {
                    apply(&mut mirror, &event?);
                }
            }
            _ => {} // risk frames (AccountStreamOptions::risk)
        }
    }
    Ok(())
}
<?php
require 'vendor/autoload.php';

use PhoenixPerps\Client;

const FINAL_STATES = ['filled', 'canceled', 'rejected', 'expired'];

$client = new Client();
$mirror = []; // account => ['positions' => [market => position], 'orders' => [id => order]]
$unread = []; // account => why its snapshot is empty
$stream = $client->accountStream(onGap: function (?string $after) use (&$mirror, &$unread): void {
    printf("[gap] events after %s may be missing: the copy starts again from the next snapshot\n", $after ?? 'the start');
    [$mirror, $unread] = [[], []];
});

function show(array $mirror, string $why): void
{
    foreach ($mirror as $id => $m) {
        $positions = array_map(fn ($p) => "{$p['market']} {$p['side']} {$p['size']}", $m['positions']);
        printf("[%s] %s: positions %s; %d working orders\n", $why, $id, $positions ? implode(', ', $positions) : 'none', count($m['orders']));
    }
}

foreach ($stream as $e) { // blocks; each event once, after the accounts' snapshots
    if (isset($unread[$e->accountId])) {
        continue;
    }
    if (!isset($mirror[$e->accountId])) {
        $snap = $stream->snapshot($e->accountId) ?? ['positions' => [], 'orders' => []];
        if (isset($snap['error'])) { // its orders and positions are unknown, not empty
            $unread[$e->accountId] = $snap['error'];
            printf("[snapshot] %s: not readable now (%s): read it by REST\n", $e->accountId, $snap['error']);
            continue;
        }
        $mirror[$e->accountId] = [
            'positions' => array_column($snap['positions'], null, 'market'),
            'orders' => array_column($snap['orders'], null, 'id'),
        ];
    }
    $m = &$mirror[$e->accountId];
    if (isset($e->data['order'])) {
        $order = $e->data['order'];
        if (in_array($order['status'], FINAL_STATES, true)) {
            unset($m['orders'][$order['id']]);
        } else {
            $m['orders'][$order['id']] = $order;
        }
    }
    if (isset($e->data['position'])) {
        $position = $e->data['position'];
        if ($e->type === 'position.closed') {
            unset($m['positions'][$position['market']]);
        } else {
            $m['positions'][$position['market']] = $position;
        }
    }
    unset($m);
    show($mirror, $e->type);
}

Guides, endpoints, fields and error codes.