# How to Stream Real-Time Rates via WebSocket using Currencies API

## How to Stream Real-Time Rates via WebSocket using Currencies API

This tutorial shows how to connect to FinFeedAPI’s Currencies WebSocket, authenticate with an API key, subscribe to one or more currency pairs, and consume live `exrate` messages (real-time exchange rates).

## What you’ll build

By the end, you’ll have a working WebSocket client that:

* Connects to the production endpoint
* Authenticates using an API key
* Subscribes to specific asset pairs (e.g., `BTC/EUR`, `ETH/CNY`)
* Prints incoming exchange-rate updates (`type: "exrate"`)
* Handles server messages like `heartbeat`, `reconnect`, and `error`

## What you need

* A FinFeedAPI API key (from the FinFeed/API Bricks console)
* A WebSocket client:
  * Quick test: `wscat` (Node)
  * App code: Python

## Key details to know first

### Production WebSocket endpoint

Use:

```
wss://api-realtime.fx.finfeedapi.com
```

### Ping/Pong requirement (important)

Your client must respond with WebSocket **Pong** frames when the server sends **Ping** (about every minute), or the server may close the connection.

### The message you’ll receive: `exrate`

Exchange-rate updates arrive like:

```json
{
  "type":"exrate",
  "asset_id_base":"BTC",
  "asset_id_quote":"USD",
  "rate_type":"BASE_ALL_CROSSES_TO_REF",
  "time":"2019-06-11T15:26:00.0000000Z",
  "rate":10065.0319541
}
```

FinFeedAPI describes this exchange rate as a **rolling VWAP-24H** (volume-weighted average price across selected data sources).

## Step 1 — Decide how you’ll authenticate

FinFeedAPI supports multiple API-key authentication methods (including for WebSocket). The two most practical for WebSocket clients are:

### Option A (common): API key as a query parameter

Connect to:

```
wss://api-realtime.fx.finfeedapi.com?apikey=YOUR_API_KEY
```

``

### Option B: API key as a header (if your client supports custom headers)

Send:

```
X-APIBricks-Key: YOUR_API_KEY
```

> Some environments don’t let you set arbitrary WebSocket headers. In those cases, use the query string approach.

## Step 2 — Send a `hello` message to start (or reset) subscriptions

After connecting, send a `hello` message to define your subscription scope.

Example:

```json
{
  "type":"hello",
  "heartbeat":false,
  "subscribe_filter_asset_id": ["BTC/EUR"]
}
```

### What these fields do

* `type`: `hello` (initializes a fresh subscription scope)
* `heartbeat`: if `true`, you’ll receive a heartbeat message when there’s been 1 second of silence
* `subscribe_filter_asset_id`: list of assets or asset pairs (e.g., `BTC/EUR`)

## Step 3 — (Optional) Add/remove subscriptions without resetting

Instead of sending another `hello` (which overrides scope), you can dynamically adjust with:

### Subscribe (adds more pairs)

```json
{
  "type":"subscribe",
  "heartbeat":true,
  "subscribe_filter_asset_id": ["ETH/CNY"]
}
```

### Unsubscribe (removes pairs)

```json
{
  "type":"unsubscribe",
  "heartbeat":true,
  "subscribe_filter_asset_id": ["BTC/EUR"]
}
```

FinFeedAPI’s doc summary:

* **subscribe** expands scope
* **unsubscribe** removes items
* **hello** replaces the scope

## Step 4 — Quick test with `wscat`

FinFeedAPI recommends `wscat` for debugging.

### Install

```sh
npm i-g wscat
```

### Connect (query parameter auth)

```sh
wscat-c"wss://api-realtime.fx.finfeedapi.com?apikey=YOUR_API_KEY
```

### Then paste your `hello` message

```json
{"type":"hello","heartbeat":true,"subscribe_filter_asset_id":["BTC/EUR","ETH/CNY"],"subscribe_update_limit_ms_exrate":1000}
```

If auth + payload are valid, you should start seeing `exrate` updates and/or `heartbeat` messages.

## Step 5 — Build a simple Python client

Install:

```
pip install websockets
```

Example client (prints rates, handles basic message types):

```python
importasyncio
importjson
importwebsockets

API_KEY="YOUR_API_KEY"
WS_URL=f"wss://api-realtime.fx.finfeedapi.com?apikey={API_KEY}"

HELLO= {
"type":"hello",
"heartbeat":True,
"subscribe_filter_asset_id": ["BTC/EUR","ETH/CNY"],
"subscribe_update_limit_ms_exrate":1000
}

asyncdefmain():
asyncwithwebsockets.connect(WS_URL,ping_interval=None)asws:
# Send subscription scope
awaitws.send(json.dumps(HELLO))

whileTrue:
raw=awaitws.recv()
msg=json.loads(raw)

t=msg.get("type")
ift=="exrate":
print(f'{msg["time"]}{msg["asset_id_base"]}/{msg["asset_id_quote"]} '
f'({msg.get("rate_type")}):{msg["rate"]}')
elift=="heartbeat":
# Useful for detecting a dead connection vs “no market updates”
print("heartbeat")
elift=="reconnect":
# Server asks you to reconnect within a time window
print(f"reconnect requested:{msg}")
# A simple approach is to break and let your outer loop reconnect.
break
elift=="error":
# Server will close connection after sending an error
raiseRuntimeError(msg.get("message","Unknown error"))
else:
print(f"other message:{msg}")

if__name__=="__main__":
asyncio.run(main())

```

Notes:

* The server sends Ping frames; most WebSocket libraries respond with Pong automatically, but don’t disable that behavior.
* If you receive an `error` message, FinFeedAPI treats it as permanent and expects the connection to be closed afterward

## Troubleshooting

* You receive `{ "type": "error", "message": "Invalid API key" }`
  * Confirm you’re passing the key via query string or supported auth header format.
* You get disconnected under heavy load / broad subscriptions
  * FinFeedAPI may disconnect if your client can’t read fast enough and the server’s buffer fills (“Reached maximum allowed buffered messages…”). Keep your receive loop lightweight and offload processing elsewhere.

## Where to find valid asset IDs

* Metadata tables provide downloadable asset lists (and the API can list assets via `GET /v1/assets`)

## Congratulations 🎉

You’ve now got a working real-time currency-rate stream over WebSocket: connected to the production endpoint, authenticated with an API key, subscribed to asset pairs, and consuming `exrate` updates (plus `heartbeat` / `reconnect` / `error` handling).