PhoenixPerpetualsDocs API v1
Get an API key

Cookbook

Candles to a CSV file⁠.

The last 100 closed one-minute candles of a market and the one forming (final false), written to candles.csv.

View as Markdown

The whole program, in each language. Set PHOENIXPERPS_API_KEY to a sandbox key (ppk_test_...) and run it.

import { writeFileSync } from 'node:fs';
import { PhoenixPerps } from '@phoenixperps/sdk';

type Candle = { time: number; open: string; high: string; low: string; close: string; volume: string; final: boolean };
const client = new PhoenixPerps();
const symbol = (process.argv[2] ?? 'BTC-USD').toUpperCase();
const candles = new Map<number, Candle>();

const market = client.marketStream();
const history = new Promise<void>((resolve) => {
  market.on('candles', (f: { data: Candle[] }) => {
    for (const c of f.data) candles.set(c.time, c);
  });
  market.once('snapshot_end', () => resolve());
});
await market.subscribe('candles', [symbol], { interval: '1m', history: 100 });
await history;
market.close();

const rows = [...candles.values()].sort((a, b) => a.time - b.time);
const lines = rows.map((c) => [new Date(c.time).toISOString(), c.open, c.high, c.low, c.close, c.volume, c.final].join(','));
writeFileSync('candles.csv', `time,open,high,low,close,volume,final\n${lines.join('\n')}\n`);
console.log(`${rows.length} candles of ${symbol} in candles.csv`);
import asyncio
import csv
import sys
from datetime import datetime, timezone
from typing import Any, Dict

from phoenixperps import PhoenixPerps

symbol = (sys.argv[1] if len(sys.argv) > 1 else "BTC-USD").upper()


async def main() -> None:
    client = PhoenixPerps()
    candles: Dict[int, Dict[str, Any]] = {}
    async with client.market_stream() as market:
        await market.subscribe("candles", [symbol], interval="1m", history=100)
        async for frame in market:
            if frame["type"] == "candles":
                for c in frame["data"]:
                    candles[c["time"]] = c
            elif frame["type"] == "snapshot_end":
                break
    with open("candles.csv", "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["time", "open", "high", "low", "close", "volume", "final"])
        for t in sorted(candles):
            c = candles[t]
            w.writerow([datetime.fromtimestamp(t / 1000, timezone.utc).isoformat(), c["open"], c["high"], c["low"], c["close"], c["volume"], c["final"]])
    print(f"{len(candles)} candles of {symbol} in candles.csv")


asyncio.run(main())
package main

import (
	"context"
	"encoding/csv"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"sort"
	"strconv"
	"strings"
	"time"

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

type candle struct {
	Time                           int64
	Open, High, Low, Close, Volume string
	Final                          bool
}

func main() {
	ctx := context.Background()
	client, err := phoenixperps.NewClient()
	if err != nil {
		log.Fatal(err)
	}
	symbol := "BTC-USD"
	if len(os.Args) > 1 {
		symbol = strings.ToUpper(os.Args[1])
	}
	stream := client.MarketStream(ctx)
	if _, err := stream.Subscribe(ctx, "candles", []string{symbol}, map[string]any{"interval": "1m", "history": 100}); err != nil {
		log.Fatal(err)
	}
	candles := map[int64]candle{}
	for {
		f, err := stream.Next(ctx)
		if err != nil {
			log.Fatal(err)
		}
		if f.Type == "snapshot_end" {
			break
		}
		if f.Type != "candles" {
			continue
		}
		var cs []candle
		if err := json.Unmarshal(f.Data, &cs); err != nil {
			log.Fatal(err)
		}
		for _, c := range cs {
			candles[c.Time] = c
		}
	}
	_ = stream.Close()

	times := make([]int64, 0, len(candles))
	for t := range candles {
		times = append(times, t)
	}
	sort.Slice(times, func(i, j int) bool { return times[i] < times[j] })
	file, err := os.Create("candles.csv")
	if err != nil {
		log.Fatal(err)
	}
	w := csv.NewWriter(file)
	_ = w.Write([]string{"time", "open", "high", "low", "close", "volume", "final"})
	for _, t := range times {
		c := candles[t]
		_ = w.Write([]string{time.UnixMilli(t).UTC().Format(time.RFC3339), c.Open, c.High, c.Low, c.Close, c.Volume, strconv.FormatBool(c.Final)})
	}
	w.Flush()
	if err := file.Close(); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%d candles of %s in candles.csv\n", len(times), symbol)
}
#:package PhoenixPerps.Sdk@1.0.0
using System.Text.Json;
using PhoenixPerps;

using var client = new PhoenixPerpsClient();
var symbol = (args.Length > 0 ? args[0] : "BTC-USD").ToUpperInvariant();
var candles = new SortedDictionary<long, JsonElement>();

await using (var market = client.OpenMarketStream())
{
    await market.SubscribeAsync("candles", new[] { symbol }, new Dictionary<string, object?> { ["interval"] = "1m", ["history"] = 100 });
    await foreach (var f in market.ReadAllAsync())
    {
        if (f.Type == "snapshot_end") break;
        if (f.Type != "candles" || f.Data is not { } data) continue;
        foreach (var c in data.EnumerateArray()) candles[c.GetProperty("time").GetInt64()] = c;
    }
}

using (var csv = new StreamWriter("candles.csv"))
{
    csv.WriteLine("time,open,high,low,close,volume,final");
    foreach (var (t, c) in candles)
        csv.WriteLine(string.Join(",", DateTimeOffset.FromUnixTimeMilliseconds(t).ToString("O"),
            c.GetProperty("open"), c.GetProperty("high"), c.GetProperty("low"), c.GetProperty("close"), c.GetProperty("volume"),
            c.GetProperty("final").GetBoolean() ? "true" : "false"));
}
Console.WriteLine($"{candles.Count} candles of {symbol} in candles.csv");
import com.fasterxml.jackson.databind.JsonNode;
import com.phoenixperpsfunding.sdk.MarketStream;
import com.phoenixperpsfunding.sdk.PhoenixPerpsClient;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

final class Example10 {
    public static void main(String[] args) throws IOException {
        PhoenixPerpsClient client = PhoenixPerpsClient.fromEnv();
        String symbol = (args.length > 0 ? args[0] : "BTC-USD").toUpperCase(Locale.ROOT);
        TreeMap<Long, JsonNode> candles = new TreeMap<>();

        try (MarketStream market = client.openMarketStream()) {
            market.subscribe("candles", List.of(symbol), Map.of("interval", "1m", "history", 100), Duration.ofSeconds(10));
            for (MarketStream.Frame f : market) {
                if ("snapshot_end".equals(f.type())) break;
                if (!"candles".equals(f.type())) continue;
                for (JsonNode c : f.data()) candles.put(c.path("time").asLong(), c);
            }
        }

        try (PrintWriter csv = new PrintWriter("candles.csv", StandardCharsets.UTF_8)) {
            csv.println("time,open,high,low,close,volume,final");
            for (Map.Entry<Long, JsonNode> e : candles.entrySet()) {
                JsonNode c = e.getValue();
                csv.println(String.join(",", Instant.ofEpochMilli(e.getKey()).toString(), c.path("open").asText(), c.path("high").asText(),
                        c.path("low").asText(), c.path("close").asText(), c.path("volume").asText(), c.path("final").asText()));
            }
        }
        System.out.printf("%d candles of %s in candles.csv%n", candles.size(), symbol);
    }
}
use std::collections::BTreeMap;
use std::io::Write;

use phoenixperps::Client;
use serde_json::{json, Map, Value};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::from_env()?;
    let symbol = std::env::args().nth(1).unwrap_or_else(|| "BTC-USD".into()).to_uppercase();
    let mut market = client.market_stream();
    let mut params = Map::new();
    params.insert("interval".into(), json!("1m"));
    params.insert("history".into(), json!(100));
    market.subscribe("candles", &[symbol.as_str()], params).await?;

    let mut candles: BTreeMap<i64, Value> = BTreeMap::new();
    while let Some(frame) = market.next().await {
        let frame = frame?;
        match frame.r#type.as_str() {
            "snapshot_end" => break,
            "candles" => {
                for c in frame.data.as_ref().and_then(Value::as_array).into_iter().flatten() {
                    candles.insert(c["time"].as_i64().unwrap_or_default(), c.clone());
                }
            }
            _ => {}
        }
    }

    let mut csv = std::fs::File::create("candles.csv")?;
    writeln!(csv, "time,open,high,low,close,volume,final")?;
    let text = |v: &Value| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string());
    for (t, c) in &candles {
        writeln!(csv, "{t},{},{},{},{},{},{}", text(&c["open"]), text(&c["high"]), text(&c["low"]), text(&c["close"]), text(&c["volume"]), c["final"])?;
    }
    println!("{} candles of {symbol} in candles.csv (time in ms)", candles.len());
    Ok(())
}
<?php
require 'vendor/autoload.php';

use PhoenixPerps\Client;

$client = new Client();
$symbol = strtoupper($argv[1] ?? 'BTC-USD');
$market = $client->marketStream();
$market->subscribe('candles', [$symbol], ['interval' => '1m', 'history' => 100]);

$candles = [];
foreach ($market as $f) {
    if ($f['type'] === 'snapshot_end') {
        break;
    }
    if ($f['type'] === 'candles') {
        foreach ($f['data'] as $c) {
            $candles[$c['time']] = $c;
        }
    }
}
$market->close();
ksort($candles);

$csv = fopen('candles.csv', 'w');
fputcsv($csv, ['time', 'open', 'high', 'low', 'close', 'volume', 'final'], ',', '"', '');
foreach ($candles as $t => $c) {
    fputcsv($csv, [gmdate('Y-m-d\TH:i:s\Z', intdiv($t, 1000)), $c['open'], $c['high'], $c['low'], $c['close'], $c['volume'], $c['final'] ? 'true' : 'false'], ',', '"', '');
}
fclose($csv);
printf("%d candles of %s in candles.csv\n", count($candles), $symbol);

Guides, endpoints, fields and error codes.