> ## 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.

# ohlcv channel

> Receive the current OHLCV candle of a pool or token after every trade that changes it.

`ohlcv` keeps one live candle for a pool or token at a period you choose. After each trade that changes the candle, it sends the whole current candle. Use it to keep a chart up to date after loading its history from REST.

**Weight:** 1 per subscription. See [Subscription weight](https://sonar-cf3aeac7.mintlify.site/websocket/limits-and-errors.md#subscription-weight).

## Parameters

| Param | Type | Required | Description |
| - | - | - | - |
| `chain` | string | Yes | Chain in `evm:<chainId>` form, for example `"evm:8453"`. |
| `period` | string | Yes | Candle size: `1s`, `5s`, `15s`, `30s`, `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `6h`, `12h`, `1d`, `1w`, `1M`. `1m` is one minute and `1M` is one month. **There is no default**, unlike REST where `period` defaults to `1h`. |
| `pool` | string | One of `pool` or `token` | Pool address (`0x` plus 40 hex characters) or 32-byte pool id (`0x` plus 64 hex characters). |
| `token` | string | One of `pool` or `token` | Token address, `0x` plus 40 hex characters. |
| `maxUpdatesPerMinute` | integer | No | 1 to 600. Samples the subscription: at most this many events per minute, no cursors, no resume. See [Sampling](https://sonar-cf3aeac7.mintlify.site/websocket/messages.md#sampling-with-maxupdatesperminute). |

Sending neither `pool` nor `token` fails with `INVALID_PARAMETERS`, message `pool or token is required`.

### Existence checks

`ohlcv` is the only channel that checks that what you follow exists. The subscribe fails with:

| Code | Message | When |
| - | - | - |
| `TOKEN_NOT_FOUND` | `Token or pool not found` | `token` without `pool`, and no pool was found for the token |
| `POOL_NOT_FOUND` | `Pool not found` | `pool` is not a known pool on that chain |
| `TOKEN_NOT_FOUND` | `Token is not in this pool` | `token` and `pool` given, and the token is not one of the pool's two tokens |

```json theme={null}
-> {"op":"subscribe","id":"chart","channel":"ohlcv","params":{"chain":"evm:8453","pool":"0x9999999999999999999999999999999999999999","period":"1m"}}
<- {"type":"error","id":"chart","code":"POOL_NOT_FOUND","message":"Pool not found"}
```

## Which pool and price the candle tracks

| You send | Candles come from | Price is the USD price of |
| - | - | - |
| `pool` only | That pool | The pool's base token |
| `token` only | The token's best pool | `token` |
| `pool` and `token` | That pool | `token` |

In `token` mode, the best pool is the one with the highest 24-hour volume among the token's pools. It is re-checked at most every 60 seconds, so the subscription can move to a new pool when volume shifts. Trades in the token's other pools are ignored. This is the same pool choice as REST [`GET /token/ohlcv`](https://sonar-cf3aeac7.mintlify.site/api-reference/token/get-token-ohlcv).

The [quote-token rule](https://sonar-cf3aeac7.mintlify.site/websocket/channels/fast-trade.md#the-quote-token-rule) of the trade channels does not apply here.

## How candles are updated

* Buckets are aligned in UTC. `1w` buckets start on Monday 00:00 UTC, and `1M` buckets are calendar months.
* The first time the server needs a candle, it seeds it from stored trades, so the first event already includes the trades earlier in the bucket.
* After each trade in the tracked pool, the server updates the candle and sends it in full. Several events in a row can have the same `t`. Replace your current candle with the newest one.
* When a trade falls in a new bucket, the new candle opens at the previous candle's close (`o = h = l = c = previous close`, `v = 0`) before the trade is applied. Consecutive candles therefore connect, as in REST OHLCV.
* Only **priced** trades move the price: the USD price must be above 0 and below 1e9, and the trade must be worth at least \$0.10. Every trade, priced or not, adds its USD value to `v`.

Events are not guaranteed for every trade. No event is sent:

* until the candle has an opening price, for example for a brand-new pool whose first trades are too small to be priced;
* for a trade that is older than, or the same as, one the server already applied to this candle;
* when building the candle takes longer than 2 seconds. The subscription's cursor still moves past that trade.

Because each event carries the full candle, a skipped event is corrected by the next one in the same bucket. The last update of a bucket can still be missed, so reload candles from REST after a reconnect.

> [!WARNING]
>
> With `maxUpdatesPerMinute`, the interval is used up by the first matching trade even when that trade produces no event. In `token` mode, a trade of the token in one of its other pools matches the subscription but is not part of the candle. So a sampled `token`-mode subscription can go longer than the interval without an update. Use `pool` mode (with `token` if needed) when you sample.

> [!NOTE]
>
> Resuming with `since` works, but trades the server has already counted into its live candle are not sent again. If you were disconnected across a bucket boundary, you may not receive the final state of the bucket that closed. After any reconnect, reload the most recent candles from REST and then apply live events.

## Event data

`data` is the current candle:

**pool** `string`

Pool the candle comes from. In `token` mode this is the current best pool.

**token** `string`

Token whose USD price the candle tracks: your `token`, or the pool's base token in `pool`-only mode.

**period** `string`

The period you subscribed with.

**t** `number`

Bucket start time in Unix epoch **milliseconds** (UTC).

**o** `number`

Open price in USD.

**h** `number`

High price in USD.

**l** `number`

Low price in USD.

**c** `number`

Close price in USD.

**v** `number`

Volume in USD. `0` when the bucket has no volume.

`v` is the USD volume of the bucket so far.

## Example

```json theme={null}
-> {"op":"subscribe","id":"chart","channel":"ohlcv","params":{"chain":"evm:8453","token":"0x1111111111111111111111111111111111111111","period":"1m"}}
<- {"type":"subscribed","id":"chart","channel":"ohlcv","cursor":"38123456-0"}
<- {"type":"event","id":"chart","channel":"ohlcv","cursor":"38123457-0:2","data":{"pool":"0x2222222222222222222222222222222222222222","token":"0x1111111111111111111111111111111111111111","period":"1m","t":1796291940000,"o":0.0099,"h":0.0101,"l":0.0098,"c":0.0101,"v":5077.5}}
<- {"type":"event","id":"chart","channel":"ohlcv","cursor":"38123461-0:0","data":{"pool":"0x2222222222222222222222222222222222222222","token":"0x1111111111111111111111111111111111111111","period":"1m","t":1796291940000,"o":0.0099,"h":0.0102,"l":0.0098,"c":0.0102,"v":5230.5}}
<- {"type":"event","id":"chart","channel":"ohlcv","cursor":"38123475-0:5","data":{"pool":"0x2222222222222222222222222222222222222222","token":"0x1111111111111111111111111111111111111111","period":"1m","t":1796292000000,"o":0.0102,"h":0.0102,"l":0.0100,"c":0.0100,"v":312.4}}
```

The third event opens a new bucket at the previous close, `0.0102`.

## Pair with REST history

Load history from REST with the same period, then apply live events:

* [`GET /token/ohlcv`](https://sonar-cf3aeac7.mintlify.site/api-reference/token/get-token-ohlcv) for `token` mode
* [`GET /market/ohlcv`](https://sonar-cf3aeac7.mintlify.site/api-reference/market/get-market-ohlcv) for `pool` mode

REST returns the same candle shape, `t`, `o`, `h`, `l`, `c` and `v`, oldest first.

```javascript Browser theme={null}
const API = "https://api.example.com/api/v1";
const chain = "evm:8453";
const token = "0x1111111111111111111111111111111111111111";
const period = "1m";

// 1. History, oldest first.
const res = await fetch(`${API}/token/ohlcv?address=${token}&chain=${chain}&period=${period}&limit=300`);
const candles = (await res.json()).data;

// 2. Live updates.
const ws = new WebSocket("wss://api.example.com/v1/ws");
ws.onopen = () => ws.send(JSON.stringify({
  op: "subscribe", id: "chart", channel: "ohlcv",
  params: { chain, token, period },
}));

ws.onmessage = (frame) => {
  const msg = JSON.parse(frame.data);
  if (msg.type !== "event") return;
  const { t, o, h, l, c, v } = msg.data;
  const last = candles[candles.length - 1];
  if (last && last.t === t) candles[candles.length - 1] = { t, o, h, l, c, v };
  else if (!last || t > last.t) candles.push({ t, o, h, l, c, v });
  render(candles);
};

function render(candles) { /* draw the chart */ }
```

```python Python (websockets) theme={null}
import asyncio
import json
import urllib.request

import websockets

API = "https://api.example.com/api/v1"
CHAIN = "evm:8453"
TOKEN = "0x1111111111111111111111111111111111111111"
PERIOD = "1m"

def load_history():
    url = f"{API}/token/ohlcv?address={TOKEN}&chain={CHAIN}&period={PERIOD}&limit=300"
    with urllib.request.urlopen(url) as res:
        return json.load(res)["data"]

async def main():
    candles = load_history()
    async with websockets.connect("wss://api.example.com/v1/ws") as ws:
        await ws.send(json.dumps({
            "op": "subscribe", "id": "chart", "channel": "ohlcv",
            "params": {"chain": CHAIN, "token": TOKEN, "period": PERIOD},
        }))
        async for raw in ws:
            msg = json.loads(raw)
            if msg["type"] != "event":
                continue
            d = msg["data"]
            candle = {k: d[k] for k in ("t", "o", "h", "l", "c", "v")}
            if candles and candles[-1]["t"] == candle["t"]:
                candles[-1] = candle
            elif not candles or candle["t"] > candles[-1]["t"]:
                candles.append(candle)
            print(candle)

asyncio.run(main())
```

See the [live price chart guide](https://sonar-cf3aeac7.mintlify.site/guides/live-price-chart.md) for a complete walkthrough.


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