# Tick charts (/vela-pro/charts/tick-charts)



Tick charts group market activity by a fixed number of trades (`nT`) rather than fixed wall-clock intervals. Each bar closes after `n` prints and opens a fresh bar on the next trade, letting traders inspect fast-moving markets with uniform activity per bar.

`enableVelaPro()` enables tick charts by default. Pass `tickCharts` to configure presets, anchoring, and data sources, pass `tickCharts: false` to disable tick support, or call `enableTickCharts()` standalone when enabling features selectively.

```ts
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';

enableVelaPro({
    tickCharts: {
        presets: ['1T', '10T', '100T', '1000T'],
        defaultAnchor: { mode: 'session' },
        anchors: {
            'CME:ES1!': { mode: 'timeOfDay', time: '09:30', timezone: 'America/New_York' },
        },
    },
});

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    timeframe: '100T',
    live: true,
    providers: { binance: () => new BinanceProvider() },
});
```

### Configuration options [#configuration-options]

| Option               | Type                         | Default                                   | Description                                                                                                                                                                    |
| -------------------- | ---------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `presets`            | `readonly string[]`          | `['1T', '10T', '100T', '1000T']`          | Tick resolutions prepended to the default timeframe dropdown when the workspace does not specify `timeframes`. Pass `[]` to omit tick presets from the menu.                   |
| `defaultAnchor`      | `TickAnchor`                 | `{ mode: 'session' }`                     | Fallback anchoring policy for markets without an explicit override.                                                                                                            |
| `anchors`            | `Record<string, TickAnchor>` | `{}`                                      | Initial per-market anchor map keyed by symbol (overridden by persisted entries or `setTickAnchor`).                                                                            |
| `marketKey`          | `(symbol: string) => string` | Uppercase trimmed symbol                  | Maps a chart symbol to its anchor key.                                                                                                                                         |
| `storage`            | `TickAnchorStorage \| false` | `localStorage` (`'vela-pro.tickAnchors'`) | Local storage adapter for per-market anchors. Pass `false` to disable `localStorage` persistence.                                                                              |
| `publicCryptoTrades` | `boolean`                    | `true`                                    | Automatically uses public exchange trade feeds for `'binance'`, `'binance.us'`, `'coinbase'`, and `'hyperliquid'` providers that do not implement `TickFeed` or `TickBarFeed`. |
| `maxHistoryRequests` | `number`                     | `12`                                      | Maximum historical REST trade pages fetched per load on public crypto trade feeds.                                                                                             |

## Tick resolution format [#tick-resolution-format]

Tick timeframes use uppercase `T` preceded by a positive integer count (`1T`, `10T`, `50T`, `100T`, `1000T`). A bare `T` normalizes to `1T`.

* **Topbar dropdown:** `enableTickCharts()` prepends `['1T', '10T', '100T', '1000T']` to the default timeframe list (separated above minute and calendar intervals) unless the workspace receives an explicit `timeframes` option. Pass `presets: []` to omit tick presets from the dropdown while still accepting typed or programmatic `nT` intervals.
* **Quick keyboard entry:** Typing any number followed by `T` (such as `25T` or `250T`) opens the quick timeframe entry dialog and switches to that exact tick count on Enter.
* **Programmatic API:** Pass any `nT` string to the `timeframe` workspace option or `workspace.active.setTimeframe('250T')`.

## Automatic line style on `1T` [#automatic-line-style-on-1t]

A `1T` bar contains a single trade (`open = high = low = close`), so candlesticks, OHLC bars, and Heikin Ashi collapse to flat dashes. When a chart enters `1T` while displaying `candles`, `bars`, or `heikinashi`, Vela Pro automatically switches the chart to `line` and remembers the prior style.

Leaving `1T` for any multi-tick (`10T`, `100T`) or time-based timeframe restores the remembered style automatically. The remembered style is saved with the chart's state, so a page reloaded on `1T` still returns to it. Non-OHLC styles (`area`, `baseline`, `line`, `stepline`) stay unchanged when entering `1T`, and picking a different style manually while on `1T` cancels the automatic restore so the user's explicit choice stays active.

## Bar anchoring [#bar-anchoring]

Unlike time-based bars that align to fixed clock boundaries, `nT` tick bars depend on where tick counting starts. Anchoring is a developer-configured setting (never an extra toolbar control) with a default policy plus optional per-market overrides.

### Anchor modes [#anchor-modes]

| Mode                          | Shape                                                                 | Behavior                                                                                                                                                                                                                                                         |
| ----------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Asset session start (default) | `{ mode: 'session' }`                                                 | Resets tick counting at each trading session open. Uses `DataProvider.getCalendar` windows when available, falling back to DST-aware `SymbolInfo.session` (or `session_extended` in extended hours) in `SymbolInfo.timezone`, and `00:00 UTC` on `24x7` markets. |
| Custom time of day            | `{ mode: 'timeOfDay', time: '09:30', timezone?: 'America/New_York' }` | Resets tick counting daily at `HH:MM` in `timezone` (defaults to the symbol's `SymbolInfo.timezone`, or `'Etc/UTC'`).                                                                                                                                            |
| Exact timestamp               | `{ mode: 'timestamp', time: epochMs }`                                | Anchors tick `0` at an exact Unix epoch millisecond instant. Ticks before `time` align backward so a full `nT` bar finishes immediately before the anchor; ticks at or after `time` count forward.                                                               |
| Continuous (rolling)          | `{ mode: 'rolling' }`                                                 | Counts continuously from the first loaded tick with no periodic resets.                                                                                                                                                                                          |

Whenever a session or daily anchor boundary is crossed, any partial bar before the boundary closes early and the first print of the new session opens tick 1 of a fresh `nT` bar.

<Note>
  When Vela Pro builds the bars itself (from a `TickFeed`, from `1T` bars, or from the public crypto trade feeds), counting starts at the first tick it loaded and becomes exact at the first anchor boundary inside the loaded history. Until then, two loads taken at different moments can place bar boundaries a few ticks apart. Serve pre-aggregated bars through `TickBarFeed` when every load must show identical bars.
</Note>

### Updating anchors at runtime [#updating-anchors-at-runtime]

Use `setTickAnchor`, `getTickAnchor`, `resetTickAnchor`, and `onTickAnchorChange` to manage per-market anchors programmatically. Calling `setTickAnchor` reloads any open tick chart on that market in place and persists the override in the workspace state document (`ext['vela-pro.tickAnchors']`) and optional `localStorage` backing store.

```ts
import { getTickAnchor, resetTickAnchor, setTickAnchor } from '@luxalgo/vela-pro';

// Anchor ES futures to the 09:30 Eastern cash open while other markets use session start.
setTickAnchor('CME:ES1!', {
    mode: 'timeOfDay',
    time: '09:30',
    timezone: 'America/New_York',
});

const current = getTickAnchor('CME:ES1!');
console.log(current.mode); // 'timeOfDay'

// Revert back to the configured defaultAnchor.
resetTickAnchor('CME:ES1!');
```

Set `storage: false` in `enableTickCharts()` to disable `localStorage` persistence and rely solely on your host configuration or workspace state document. Pass a custom `marketKey` function (defaulting to trimmed uppercase symbol strings) if you want anchors shared across venues for the same base ticker.

## Connecting tick data [#connecting-tick-data]

Vela Pro resolves tick data through Vela's open-source core `registerSeriesAdapter` seam, supporting four integration paths in priority order so both new providers and existing datafeeds work without wrapping internals.

### 1. Pre-aggregated tick bars (`TickBarFeed`) [#1-pre-aggregated-tick-bars-tickbarfeed]

If your backend computes anchored `nT` bars server-side, implement `TickBarFeed` on your `DataProvider`. Vela Pro forwards the requested tick count and active per-market `TickAnchor` directly:

```ts
import type { BarRange, DataProvider, OHLCV } from '@luxalgo/vela/plugin';
import type { TickAnchor, TickBarFeed } from '@luxalgo/vela-pro';

export class ServerTickProvider implements DataProvider, TickBarFeed {
    async getBars(_ticker: string, _tf: string, _range: BarRange): Promise<OHLCV[]> {
        return [];
    }

    async getTickBars(ticker: string, ticksPerBar: number, range: BarRange, anchor: TickAnchor): Promise<OHLCV[]> {
        const res = await fetch(`/api/ticks/${encodeURIComponent(ticker)}?n=${ticksPerBar}&limit=${range.limit ?? 500}&anchor=${encodeURIComponent(JSON.stringify(anchor))}`);
        return (await res.json()) as OHLCV[];
    }

    subscribeTickBars(
        ticker: string,
        ticksPerBar: number,
        onBar: (bar: OHLCV) => void,
        opts?: { session?: string; anchor?: TickAnchor },
    ): () => void {
        const ws = new WebSocket(`wss://api.example.com/ticks?s=${encodeURIComponent(ticker)}&n=${ticksPerBar}&anchor=${encodeURIComponent(JSON.stringify(opts?.anchor ?? { mode: 'session' }))}`);
        ws.onmessage = (ev) => onBar(JSON.parse(String(ev.data)) as OHLCV);
        return () => ws.close();
    }
}
```

### 2. Raw trade prints (`TickFeed` or `withTickFeed`) [#2-raw-trade-prints-tickfeed-or-withtickfeed]

Implement `TickFeed` (`getTicks` and optional `subscribeTicks` / `supportsTicks`) on your provider—or attach a `TickFeed` onto any existing `DataProvider` instance using `withTickFeed`—and Vela Pro aggregates prints into any `nT` interval with the active per-market anchor:

```ts
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { withTickFeed, type TickPrint } from '@luxalgo/vela-pro';

const provider = withTickFeed(new BinanceProvider(), {
    async getTicks(ticker, range): Promise<TickPrint[]> {
        const res = await fetch(`/api/trades/${encodeURIComponent(ticker)}?limit=${range.limit ?? 5000}`);
        return (await res.json()) as TickPrint[];
    },
    subscribeTicks(ticker, onTicks) {
        const ws = new WebSocket(`wss://api.example.com/trades/${encodeURIComponent(ticker)}`);
        ws.onmessage = (ev) => onTicks(JSON.parse(String(ev.data)) as TickPrint[]);
        return () => ws.close();
    },
});
```

Populate the optional `id` field on each `TickPrint` when available so Vela Pro deduplicates overlapping trades during the handoff from REST history to the live WebSocket stream.

### 3. Standard `DataProvider` with `1T` or `nT` bars [#3-standard-dataprovider-with-1t-or-nt-bars]

Providers ported from TradingView Advanced Charts work with minimal changes:

* Return `timeframes: { finest: '1T', ticks: true }` (or `has_ticks: true`) from `getSymbolInfo(ticker)` and serve `1T` bars from `getBars(ticker, '1T', range)` and `subscribe(ticker, '1T', onBar)`. Vela Pro automatically aggregates those `1T` bars into any `nT` resolution using the configured anchor.
* Alternatively, list explicit tick resolutions such as `'100T'` in `info().supportedTimeframes` or `SymbolInfo.timeframes.list` to serve pre-built `nT` bars directly through `getBars`.

<Note>
  Multiple tick bars can open within the same millisecond on active markets. Vela Pro always hands the chart bars with strictly increasing open times: a bar that would share a millisecond with the previous one is stamped one millisecond later, so indicators, drawings, and exported series address every bar on its own.

  For pre-aggregated feeds, send each update of the forming bar with that bar's own `time`. If your bars can share a millisecond, add a monotonic `seq` number to each `OHLCV` bar so a live update matches the forming bar while a new bar in the same millisecond opens the next one. Without `seq`, a live bar at the newest bar's `time` updates it. When a source numbers its `1T` bars with `seq`, a tick served again at the handoff from history to live counts once.
</Note>

The live methods (`subscribeTickBars`, `subscribeTicks`) are optional. Without one, the chart shows the history and does not update.

### 4. Built-in public crypto trades [#4-built-in-public-crypto-trades]

When `publicCryptoTrades` is enabled (the default), providers registered under `'binance'`, `'binance.us'`, `'coinbase'`, or `'hyperliquid'` that do not implement `TickFeed` or `TickBarFeed` automatically stream historical and live trades from each exchange's public trade feed. Pass `publicCryptoTrades: false` to restrict tick charts strictly to your own feeds, or adjust `maxHistoryRequests` (default `12`) to cap REST history pagination.

History on these feeds is the newest trades only, up to that cap (about 12,000 trades on Binance by default, so about 120 bars on `100T`). Implement `TickFeed` or `TickBarFeed` for deeper history.

## Per-symbol availability and fallback [#per-symbol-availability-and-fallback]

When a symbol's provider offers no tick source (or `supportsTicks(ticker)` returns `false`), tick presets appear disabled in the timeframe dropdown and mobile drawer. Switching to a non-tick symbol while viewing an `nT` chart raises `DataUnavailableError` internally, prompting the workspace to fall back cleanly to the symbol's default or finest supported timeframe (such as `1h`) with a notification while remembering the user's `nT` selection for the next tick-capable symbol.

## Runtime behavior on tick charts [#runtime-behavior-on-tick-charts]

* **Bar-close countdown:** Hidden automatically on tick timeframes because bar close times depend on trade count rather than a wall clock.
* **Time formatting:** Crosshair timestamps and sub-minute time-axis ticks automatically display seconds (`HH:MM:SS`).
* **Gap healing:** Fixed-interval live gap healing stands down on tick timeframes so quiet periods never trigger false history refetches.
* **Order-flow overlays:** Minute-bucketed Footprint cells and order-flow pane indicators stand down cleanly on tick timeframes rather than aligning 1-minute slices onto variable-duration bars.
* **Pine Script® indicators:** Indicators and strategies run over tick bars with closed bars confirmed (`barstate.isconfirmed`). `timeframe.isticks` and `timeframe.multiplier` do not yet recognize `nT` resolutions in PineTS.
