> ## Documentation Index
> Fetch the complete documentation index at: https://sonar-cf3aeac7.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a live price chart

> Load candle history from the REST API, then keep the chart live with the ohlcv WebSocket channel, including reconnects, gaps and expired cursors.

This guide builds a candlestick chart for one token that loads its history over REST and then updates as trades happen. It uses two endpoints:

* [`GET /token/ohlcv`](https://sonar-cf3aeac7.mintlify.site/api-reference/token/get-token-ohlcv) for history.
* The [`ohlcv` channel](https://sonar-cf3aeac7.mintlify.site/websocket/channels/ohlcv) on `wss://api.example.com/v1/ws` for live updates.

Both build candles from the same pool and the same trades, so live updates continue the REST series. The examples follow WETH on Base (`0x4200000000000000000000000000000000000006`) with 1-minute candles. They run on Node.js 22 or later, which has `fetch` and `WebSocket` built in.

## How the pieces fit

| | REST `GET /token/ohlcv` | WebSocket `ohlcv` channel |
| - | - | - |
| Token | `address` | `token` |
| Chain | `chain`: `8453` or `evm:8453` | `chain`: `evm:8453` only |
| Period | `period`, default `1h` | `period`, required |
| Output | Array of candles `{ t, o, h, l, c, v }`, oldest first | One event per trade with the full current candle `{ pool, token, period, t, o, h, l, c, v }` |

Both accept the same periods: `1s`, `5s`, `15s`, `30s`, `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `6h`, `12h`, `1d`, `1w`, `1M`. `1m` is one minute and `1M` is one calendar month. All buckets are aligned to UTC, and `1w` buckets start on Monday.

`t` is the bucket start in Unix milliseconds on both sides, so it is the key you merge on. Prices are in USD.

Use the `evm:8453` form everywhere. The WebSocket API rejects a bare `8453`.

## Steps

**1. Subscribe to live candles first**

Open the socket and subscribe before you fetch history. Keep any events that arrive while the REST request runs, so nothing is lost between the two.

```json theme={null}
{
  "op": "subscribe",
  "id": "chart",
  "channel": "ohlcv",
  "params": { "chain": "evm:8453", "token": "0x4200000000000000000000000000000000000006", "period": "1m" }
}
```

The server answers with `subscribed` and a `cursor`. If the token has no pool, it answers with an error of code `TOKEN_NOT_FOUND` and message `Token or pool not found`.

**2. Load history**

```bash theme={null}
curl "https://api.example.com/api/v1/token/ohlcv?address=0x4200000000000000000000000000000000000006&chain=evm:8453&period=1m&limit=500&fill=true"
```

* `limit` is 1 to 2000 candles (default 500). Without `from`, the request covers the last `limit` periods up to `to` (default now), so you get at most `limit` candles from that window.
* `fill=true` inserts flat candles (`o = h = l = c` = previous close, `v = 0`) for buckets without trades between the first and last candle. Without it, those buckets are missing.
* Candles come back oldest first. The last one is the newest bucket that had a trade, which is the bucket in progress if a trade already happened in it.

```json theme={null}
{
  "status": "success",
  "data": [
    { "t": 1796306580000, "o": 3421.8, "h": 3424.1, "l": 3420.9, "c": 3423.5, "v": 182340.2 },
    { "t": 1796306640000, "o": 3423.5, "h": 3426.0, "l": 3422.7, "c": 3425.1, "v": 96410.8 }
  ]
}
```

**3. Merge live updates by t**

Each `ohlcv` event carries the **whole** current candle, not a delta. Merge it by `t`:

* Same `t` as your last candle: replace the last candle.
* Greater `t`: a new bucket started; append it.
* Smaller `t`: ignore it.

Apply the buffered events first, then every event as it arrives.

**4. Load older candles on scroll**

To page back, request the same period with `to` set to one millisecond before your oldest candle:

```bash theme={null}
curl "https://api.example.com/api/v1/token/ohlcv?address=0x4200000000000000000000000000000000000006&chain=evm:8453&period=1m&limit=500&fill=true&to=1796306579999"
```

Here the oldest candle has `t` = `1796306580000`, so `to` is `1796306579999` (`candles[0].t - 1`). Prepend the result. The request only looks back `limit` periods before `to`, so an empty array means there were no trades in that window, not necessarily that there is no older data. To keep going back, move `to` further back or switch to a longer period.

## Full example

```js JavaScript theme={null}
const REST = "https://api.example.com/api/v1";
const WS = "wss://api.example.com/v1/ws";
const CHAIN = "evm:8453";
const TOKEN = "0x4200000000000000000000000000000000000006";
const PERIOD = "1m";

let candles = [];       // oldest first
let buffered = [];      // live events received before history loaded
let historyLoaded = false;
let cursor;             // newest cursor, for resuming
let attempt = 0;

async function fetchCandles({ to, limit = 500 } = {}) {
  const q = new URLSearchParams({ address: TOKEN, chain: CHAIN, period: PERIOD, limit: String(limit), fill: "true" });
  if (to !== undefined) q.set("to", String(to));
  const res = await fetch(`${REST}/token/ohlcv?${q}`);
  const body = await res.json();
  if (body.status !== "success") throw new Error(`${body.code}: ${body.message}`);
  return body.data;
}

function merge(c) {
  const last = candles.at(-1);
  const candle = { t: c.t, o: c.o, h: c.h, l: c.l, c: c.c, v: c.v };
  if (!last || candle.t > last.t) candles.push(candle);
  else if (candle.t === last.t) candles[candles.length - 1] = candle;
  // older buckets are ignored
  render();
}

async function loadHistory() {
  historyLoaded = false;
  candles = await fetchCandles();
  historyLoaded = true;
  for (const c of buffered) merge(c);
  buffered = [];
  render();
}

async function loadOlder() {
  if (candles.length === 0) return;
  const older = await fetchCandles({ to: candles[0].t - 1 });
  candles = older.concat(candles);
  render();
}

function subscribe(ws, since) {
  ws.send(JSON.stringify({
    op: "subscribe",
    id: "chart",
    channel: "ohlcv",
    params: { chain: CHAIN, token: TOKEN, period: PERIOD },
    ...(since && { since }),
  }));
}

function connect() {
  const ws = new WebSocket(WS);
  ws.onopen = () => subscribe(ws, cursor);
  ws.onmessage = async ({ data }) => {
    const msg = JSON.parse(data);
    switch (msg.type) {
      case "subscribed":
        attempt = 0;
        if (!historyLoaded || !cursor) {
          // first connection: load history while events are buffered
          cursor = msg.cursor;
          loadHistory().catch(console.error);
        }
        break;
      case "event":
        cursor = msg.cursor;
        if (historyLoaded) merge(msg.data);
        else buffered.push(msg.data);
        break;
      case "cursor":
        cursor = msg.cursor;
        break;
      case "gap":
        // trades in these blocks won't be streamed: reload recent candles from REST
        await loadHistory();
        break;
      case "error":
        if (msg.code === "RESUME_EXPIRED") {
          // too long offline: start live again and reload history
          cursor = undefined;
          historyLoaded = false;
          subscribe(ws);
        } else {
          console.error(msg.code, msg.message, msg.details);
        }
        break;
    }
  };
  ws.onclose = () => setTimeout(connect, Math.min(30_000, 1000 * 2 ** attempt++));
}

function render() {
  const last = candles.at(-1);
  if (last) console.log(new Date(last.t).toISOString(), last.o, last.h, last.l, last.c, last.v.toFixed(2));
}

connect();
```

```python Python theme={null}
# pip install websockets
import asyncio, json, urllib.parse, urllib.request
import websockets

REST = "https://api.example.com/api/v1"
WS = "wss://api.example.com/v1/ws"
CHAIN, TOKEN, PERIOD = "evm:8453", "0x4200000000000000000000000000000000000006", "1m"

candles = []  # oldest first

def fetch_candles(to=None, limit=500):
    q = {"address": TOKEN, "chain": CHAIN, "period": PERIOD, "limit": limit, "fill": "true"}
    if to is not None:
        q["to"] = to
    with urllib.request.urlopen(f"{REST}/token/ohlcv?{urllib.parse.urlencode(q)}") as res:
        return json.load(res)["data"]

def merge(c):
    candle = {k: c[k] for k in ("t", "o", "h", "l", "c", "v")}
    if not candles or candle["t"] > candles[-1]["t"]:
        candles.append(candle)
    elif candle["t"] == candles[-1]["t"]:
        candles[-1] = candle

async def run():
    global candles
    cursor, delay = None, 1
    while True:
        try:
            async with websockets.connect(WS) as ws:
                msg = {"op": "subscribe", "id": "chart", "channel": "ohlcv",
                       "params": {"chain": CHAIN, "token": TOKEN, "period": PERIOD}}
                if cursor:
                    msg["since"] = cursor
                await ws.send(json.dumps(msg))
                async for raw in ws:
                    m = json.loads(raw)
                    if m["type"] == "subscribed":
                        delay = 1
                        if cursor is None:
                            cursor = m.get("cursor")
                            candles = await asyncio.to_thread(fetch_candles)
                    elif m["type"] == "event":
                        cursor = m["cursor"]
                        merge(m["data"])
                        print(candles[-1])
                    elif m["type"] == "cursor":
                        cursor = m["cursor"]
                    elif m["type"] == "gap":
                        candles = await asyncio.to_thread(fetch_candles)
                    elif m["type"] == "error" and m["code"] == "RESUME_EXPIRED":
                        cursor = None
                        msg.pop("since", None)
                        await ws.send(json.dumps(msg))
        except (websockets.WebSocketException, OSError):
            pass
        await asyncio.sleep(delay)
        delay = min(delay * 2, 30)

asyncio.run(run())
```

In the Python version, events that arrive while history is loading wait in the socket's receive queue and are merged afterwards, so no separate buffer is needed.

## Reconnects, gaps and expired cursors

* **Reconnect.** Keep the newest `cursor` from events and from `cursor` checkpoints (sent every 30 seconds). After a disconnect, subscribe again with `since` set to it. The server replays the updates you missed, then continues live. See [Cursors and resume](https://sonar-cf3aeac7.mintlify.site/websocket/cursors-and-resume.md).
* **`RESUME_EXPIRED`.** The stream keeps about 10 minutes of history. If you were away longer, the subscription is refused. Subscribe again without `since` and reload the candles from REST.
* **`gap`.** If the stream had to skip blocks, you get a `gap` message with an inclusive `fromBlock`..`toBlock` range. Trades in those blocks never reach the channel, so your last candles may be incomplete. Reload the recent candles from REST, which reads from storage.
* **Restarts.** A `{"type":"reconnect"}` message followed by close code `1012` means the server is restarting. Reconnect and resume as above. See [Limits and errors](https://sonar-cf3aeac7.mintlify.site/websocket/limits-and-errors.md).

## Things to know

* **Which pool.** For a token, both endpoints use the token's best pool: the one with the highest 24-hour volume. The REST endpoint picks it on every request; the live channel re-checks it at most once a minute. Each event's `data.pool` tells you which pool it came from. If it changes, the best pool changed, so reload history from REST. To follow one pool regardless, use [`GET /market/ohlcv`](https://sonar-cf3aeac7.mintlify.site/api-reference/market/get-market-ohlcv) and subscribe with `pool` instead of `token`.
* **Launchpad tokens.** For a token that graduated from a bonding curve, REST history can include older candles from the curve before graduation. Live updates only come from the current pool.
* **Updates come with trades.** The channel sends a candle only after a trade changes it. Quiet buckets produce no event, and a new bucket opens at the previous close when the next trade arrives. If you want flat candles for quiet periods, like `fill=true` does, insert them yourself between the last candle and the new one.
* **Not every trade produces an event.** No event is sent until the candle has an opening price, and an update can be skipped if the server is slow to compute it. The next event carries the full candle again, so replacing by `t` keeps the chart correct.
* **Too many updates.** For a busy token, add `maxUpdatesPerMinute` (1 to 600) to the subscription params to sample updates. Sampled subscriptions have no cursors and can't resume, so on reconnect subscribe again without `since` and reload recent candles from REST.
* **Sub-minute periods.** For `1s` to `30s`, REST looks back at most `limit` × period before `to`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.