# Live market data

Live market data: prices for two markets and the trades of one, until 20 frames came.

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

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

const client = new PhoenixPerps();
const market = client.marketStream();
let n = 0;
const done = new Promise<void>((resolve) => {
  const count = () => ++n >= 20 && resolve();
  market.on('ticker', (f) => { console.log(`ticker ${f.symbol}: bid ${f.data.bid} ask ${f.data.ask}`); count(); });
  market.on('trades', (f) => { for (const t of f.data) console.log(`trade  ${f.symbol}: ${t.side} ${t.size} @ ${t.price}`); count(); });
});
market.on('reconnect', ({ in_ms, cause }) => console.log(`reconnecting in ${in_ms} ms after ${cause} (subscriptions are made again)`));
await market.subscribe('ticker', ['BTC-USD', 'ETH-USD'], { interval_ms: 500 });
await market.subscribe('trades', ['BTC-USD'], { history: 5 });
await done;
market.close();
```

```python
import asyncio

from phoenixperps import PhoenixPerps


async def main() -> None:
    client = PhoenixPerps()
    async with client.market_stream() as market:
        await market.subscribe("ticker", ["BTC-USD", "ETH-USD"], interval_ms=500)
        await market.subscribe("trades", ["BTC-USD"], history=5)
        n = 0
        async for frame in market:  # subscriptions are made again after a reconnect
            if frame["type"] == "ticker":
                print(f'ticker {frame["symbol"]}: bid {frame["data"]["bid"]} ask {frame["data"]["ask"]}')
            elif frame["type"] == "trades":
                for t in frame["data"]:
                    print(f'trade  {frame["symbol"]}: {t["side"]} {t["size"]} @ {t["price"]}')
            else:
                continue
            n += 1
            if n >= 20:
                return


asyncio.run(main())
```

```go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"

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

func main() {
	ctx := context.Background()
	client, err := phoenixperps.NewClient()
	if err != nil {
		log.Fatal(err)
	}
	stream := client.MarketStream(ctx) // subscriptions are made again after a reconnect
	defer stream.Close()
	if _, err := stream.Subscribe(ctx, "ticker", []string{"BTC-USD", "ETH-USD"}, map[string]any{"interval_ms": 500}); err != nil {
		log.Fatal(err)
	}
	if _, err := stream.Subscribe(ctx, "trades", []string{"BTC-USD"}, map[string]any{"history": 5}); err != nil {
		log.Fatal(err)
	}
	for n := 0; n < 20; {
		f, err := stream.Next(ctx)
		if err != nil {
			log.Fatal(err)
		}
		switch f.Type {
		case "ticker":
			var q struct{ Bid, Ask string }
			_ = json.Unmarshal(f.Data, &q)
			fmt.Printf("ticker %s: bid %s ask %s\n", f.Symbol, q.Bid, q.Ask)
		case "trades":
			var trades []struct{ Side, Size, Price string }
			_ = json.Unmarshal(f.Data, &trades)
			for _, t := range trades {
				fmt.Printf("trade  %s: %s %s @ %s\n", f.Symbol, t.Side, t.Size, t.Price)
			}
		default:
			continue
		}
		n++
	}
}
```

```csharp
#:package PhoenixPerps.Sdk@1.0.0
using PhoenixPerps;

using var client = new PhoenixPerpsClient();
await using var market = client.OpenMarketStream(); // subscriptions are made again after a reconnect
await market.SubscribeAsync("ticker", new[] { "BTC-USD", "ETH-USD" }, new Dictionary<string, object?> { ["interval_ms"] = 500 });
await market.SubscribeAsync("trades", new[] { "BTC-USD" }, new Dictionary<string, object?> { ["history"] = 5 });

var n = 0;
await foreach (var f in market.ReadAllAsync())
{
    if (f.Data is not { } data) continue;
    if (f.Type == "ticker")
        Console.WriteLine($"ticker {f.Symbol}: bid {data.GetProperty("bid")} ask {data.GetProperty("ask")}");
    else if (f.Type == "trades")
        foreach (var t in data.EnumerateArray())
            Console.WriteLine($"trade  {f.Symbol}: {t.GetProperty("side")} {t.GetProperty("size")} @ {t.GetProperty("price")}");
    else
        continue;
    if (++n >= 20) break;
}
```

```java
import com.fasterxml.jackson.databind.JsonNode;
import com.phoenixperpsfunding.sdk.MarketStream;
import com.phoenixperpsfunding.sdk.PhoenixPerpsClient;
import java.time.Duration;
import java.util.List;
import java.util.Map;

final class Example03 {
    public static void main(String[] args) {
        PhoenixPerpsClient client = PhoenixPerpsClient.fromEnv();
        try (MarketStream market = client.openMarketStream()) { // subscriptions are made again after a reconnect
            market.subscribe("ticker", List.of("BTC-USD", "ETH-USD"), Map.of("interval_ms", 500), Duration.ofSeconds(10));
            market.subscribe("trades", List.of("BTC-USD"), Map.of("history", 5), Duration.ofSeconds(10));
            int n = 0;
            for (MarketStream.Frame f : market) {
                if ("ticker".equals(f.type())) {
                    System.out.printf("ticker %s: bid %s ask %s%n", f.symbol(), f.data().path("bid").asText(), f.data().path("ask").asText());
                } else if ("trades".equals(f.type())) {
                    for (JsonNode t : f.data()) {
                        System.out.printf("trade  %s: %s %s @ %s%n", f.symbol(), t.path("side").asText(), t.path("size").asText(), t.path("price").asText());
                    }
                } else {
                    continue;
                }
                if (++n >= 20) break;
            }
        }
    }
}
```

```rust
use phoenixperps::Client;
use serde_json::{json, Map};

#[tokio::main]
async fn main() -> phoenixperps::Result<()> {
    let client = Client::from_env()?;
    let mut market = client.market_stream(); // subscriptions are made again after a reconnect
    let mut ticker = Map::new();
    ticker.insert("interval_ms".into(), json!(500));
    market.subscribe("ticker", &["BTC-USD", "ETH-USD"], ticker).await?;
    let mut trades = Map::new();
    trades.insert("history".into(), json!(5));
    market.subscribe("trades", &["BTC-USD"], trades).await?;

    let mut n = 0;
    while let Some(frame) = market.next().await {
        let frame = frame?;
        let (symbol, data) = (frame.symbol.unwrap_or_default(), frame.data.unwrap_or_default());
        match frame.r#type.as_str() {
            "ticker" => println!("ticker {symbol}: bid {} ask {}", data["bid"], data["ask"]),
            "trades" => {
                for t in data.as_array().into_iter().flatten() {
                    println!("trade  {symbol}: {} {} @ {}", t["side"], t["size"], t["price"]);
                }
            }
            _ => continue,
        }
        n += 1;
        if n >= 20 {
            break;
        }
    }
    Ok(())
}
```

```php
<?php
require 'vendor/autoload.php';

use PhoenixPerps\Client;

$client = new Client();
$market = $client->marketStream(); // subscriptions are made again after a reconnect
$market->subscribe('ticker', ['BTC-USD', 'ETH-USD'], ['interval_ms' => 500]);
$market->subscribe('trades', ['BTC-USD'], ['history' => 5]);

$n = 0;
foreach ($market as $f) {
    if ($f['type'] === 'ticker') {
        printf("ticker %s: bid %s ask %s\n", $f['symbol'], $f['data']['bid'], $f['data']['ask']);
    } elseif ($f['type'] === 'trades') {
        foreach ($f['data'] as $t) {
            printf("trade  %s: %s %s @ %s\n", $f['symbol'], $t['side'], $t['size'], $t['price']);
        }
    } else {
        continue;
    }
    if (++$n >= 20) {
        break;
    }
}
$market->close();
```
