# Live gold prices over WebSocket

> Stream live gold and currency prices over wss://api.pixcharp.com/v1/stream: connecting, snapshot and prices messages, symbol subscriptions, quota and WebSocket error codes.

Source: https://docs.pixcharp.com/en/websocket · Last updated: 2026-11-27

Get prices as they change instead of polling. On connect the stream sends every price, then only the ones that changed, at most once a second.

## Connecting and quota

Pro and Business plans can open a plain WebSocket to `wss://api.pixcharp.com/v1/stream`. Authenticate with the same API key as REST. You get all prices in one `snapshot` message on connect. After that, as prices change, you get at most one `prices` message a second with the latest value of every symbol that changed in that second. Each `snapshot` and `prices` message uses 1 request of your monthly quota; `ping`, `pong`, `error` and `subscribed` are free, and seconds with no change cost nothing. REST calls and all open connections share the quota. The connection handshake also counts toward the per-minute limit.

### Node.js

```javascript
// Install: npm install ws
import WebSocket from "ws";

const ws = new WebSocket("wss://api.pixcharp.com/v1/stream", {
  headers: { "X-API-Key": process.env.PIXCHARP_API_KEY },
});

ws.on("open", () => {
  // Optional: only the symbols you need. [] or ["*"] restores all.
  ws.send(JSON.stringify({ type: "subscribe", symbols: ["HAS", "USDTRY"] }));
});

ws.on("message", (raw) => {
  const message = JSON.parse(raw.toString());
  if (message.type === "snapshot") console.log(message.data.length, "symbols");
  if (message.type === "prices") for (const row of message.data) console.log(row.symbol, row.satis);
});
```

### Python

```python
# Install: pip install "websockets>=14"
import asyncio
import json
import os

import websockets

async def main():
    async with websockets.connect(
        "wss://api.pixcharp.com/v1/stream",
        additional_headers={"X-API-Key": os.environ["PIXCHARP_API_KEY"]},
    ) as ws:
        # Optional: only the symbols you need. [] or ["*"] restores all.
        await ws.send(json.dumps({"type": "subscribe", "symbols": ["HAS", "USDTRY"]}))
        async for raw in ws:
            message = json.loads(raw)
            if message["type"] == "prices":
                for row in message["data"]:
                    print(row["symbol"], row["satis"])

asyncio.run(main())
```

### Go

```go
// Install: go get github.com/gorilla/websocket
package main

import (
	"fmt"
	"net/http"
	"os"

	"github.com/gorilla/websocket"
)

func main() {
	header := http.Header{"X-API-Key": {os.Getenv("PIXCHARP_API_KEY")}}
	conn, _, err := websocket.DefaultDialer.Dial("wss://api.pixcharp.com/v1/stream", header)
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	// Optional: only the symbols you need. [] or ["*"] restores all.
	conn.WriteJSON(map[string]any{"type": "subscribe", "symbols": []string{"HAS", "USDTRY"}})

	for {
		var message struct {
			Type string           `json:"type"`
			Data []map[string]any `json:"data"`
		}
		if err := conn.ReadJSON(&message); err != nil {
			panic(err)
		}
		if message.Type == "prices" {
			for _, row := range message.Data {
				fmt.Println(row["symbol"], row["satis"])
			}
		}
	}
}
```

### C#

```csharp
// .NET 7+
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;

using var ws = new ClientWebSocket();
ws.Options.SetRequestHeader("X-API-Key", Environment.GetEnvironmentVariable("PIXCHARP_API_KEY"));
await ws.ConnectAsync(new Uri("wss://api.pixcharp.com/v1/stream"), CancellationToken.None);

// Optional: only the symbols you need. [] or ["*"] restores all.
var subscribe = Encoding.UTF8.GetBytes("""{"type":"subscribe","symbols":["HAS","USDTRY"]}""");
await ws.SendAsync(subscribe, WebSocketMessageType.Text, true, CancellationToken.None);

var buffer = new byte[64 * 1024];
while (ws.State == WebSocketState.Open)
{
    using var message = new MemoryStream();
    WebSocketReceiveResult result;
    do
    {
        result = await ws.ReceiveAsync(buffer, CancellationToken.None);
        message.Write(buffer, 0, result.Count);
    } while (!result.EndOfMessage);

    using var json = JsonDocument.Parse(message.ToArray());
    if (json.RootElement.GetProperty("type").GetString() == "prices")
        foreach (var row in json.RootElement.GetProperty("data").EnumerateArray())
            Console.WriteLine($"{row.GetProperty("symbol")} {row.GetProperty("satis")}");
}
```

### Browser

```javascript
// Browsers cannot set WebSocket headers, so the key goes in the URL.
// Use a dedicated key and an IP whitelist; prefer the header from servers.
const ws = new WebSocket("wss://api.pixcharp.com/v1/stream?apiKey=" + encodeURIComponent(key));

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  if (message.type === "prices") for (const row of message.data) console.log(row.symbol, row.satis);
};
```

## Messages

```text
// On connect, and again after "subscribe"
{"type":"snapshot","asOfUtc":"2026-11-14T10:24:13Z","market":"open","data":[{"symbol":"HAS","alis":6127.46,"satis":6155.99,...}]}

// As prices change, at most once a second (1 request of quota)
{"type":"prices","asOfUtc":"2026-11-14T10:24:14Z","data":[{"symbol":"USDTRY","alis":41.1,"satis":41.2,"asOfUtc":"2026-11-14T10:24:14Z","source":"harem","stale":false}]}

// Every 30 seconds (no reply needed)
{"type":"ping","ts":"2026-11-14T10:24:43Z"}

// A bad client message; the connection stays open
{"type":"error","code":"invalid_symbol","message":"..."}
```

## Connection errors

| HTTP | Code | Meaning |
| --- | --- | --- |
| 400 | `websocket_required` | The request was not a WebSocket upgrade. |
| 403 | `websocket_not_included` | Your plan has no WebSocket connections (Starter). |
| 403 | `ip_not_allowed` | The address is not on your IP whitelist. |
| 429 | `websocket_connection_limit` | All connections of your plan are open. Connections from all keys count together. |
| 429 | `monthly_quota_exceeded` | Your monthly quota is used up. New connections are refused until it resets on the 1st (UTC). |

## Connection checks and reconnecting

Open connections are re-checked every 60 seconds. If the key is revoked, the plan changes, the address leaves the whitelist or the monthly quota runs out, the server sends an `error` message and closes with code 1008. While the market keeps moving, one always-open connection lasts about 11 days on Pro and the whole month on Business. Reconnect with backoff after any close.

## Links

- Documentation home: https://docs.pixcharp.com/en
- Product page and plans: https://pixcharp.com/en/harem-gold-api
- Customer dashboard: https://panel.pixcharp.com/en/api/login
- JavaScript/TypeScript client (open source): https://github.com/Baristopal/harem-altin-api
- Türkçe sürüm: https://docs.pixcharp.com/websocket.md
- Contact: hello@pixcharp.com
