npm package: @liberfi.io/ui-tradingview
Description: TradingView K-line charting component for Liberfi React SDK
Author: liberfi.io
Latest version: 0.1.109

# @liberfi.io/ui-tradingview

TradingView K-line charting component for Liberfi React SDK. This package wraps the TradingView Charting Library with jotai-based state management and multi-instance support, providing a composable `TradingView` component with injectable DataFeed interface.

## Design Philosophy

- **Multi-instance isolation** — Every chart instance is keyed by a `storageId` (prefix). State atoms use `atomFamily(prefix)` so multiple charts coexist without creating extra jotai Providers or stores.
- **No RxJS** — All reactive state lives in jotai atoms. Internal bridge-level events (symbol changes, crosshair moves) use a lightweight `EventEmitter`.
- **Injectable DataFeed** — The consumer provides the `ITvChartDataFeedModule` implementation and the TradingView `Widget` constructor. This package does not bundle the charting library or data-fetching logic.
- **Composable toolbar** — The built-in toolbar ships default controls (resolutions, kline style, indicators, settings, fullscreen, snapshot) that can be individually toggled or fully replaced via slots.

## Installation

```bash
pnpm add @liberfi.io/ui-tradingview
```

### Peer Dependencies

The consumer must provide:

| Dependency  | Version   |
| ----------- | --------- |
| `react`     | >= 18     |
| `react-dom` | >= 18     |
| `jotai`     | >= 2.15.1 |

The TradingView Charting Library static files must be hosted by the consumer and the `Widget` constructor passed as a prop.

## API Reference

### Components

#### `TradingView`

Main entry component. Accepts chart configuration, the injected widget constructor, and toolbar options.

```tsx
<TradingView
  initConfig={config}
  widgetConstructor={window.TradingView.widget}
  libraryPath="/static/charting_library/"
  toolbar={{ showSnapshot: true, showFullscreen: true }}
  loadingOverlay={<Spinner />}
  onReady={() => console.log("chart ready")}
/>
```

**Props:**

| Prop                | Type                               | Default                                        | Description                        |
| ------------------- | ---------------------------------- | ---------------------------------------------- | ---------------------------------- |
| `initConfig`        | `TvChartConfig`                    | (required)                                     | Chart configuration object         |
| `widgetConstructor` | `WidgetConstructor`                | (required)                                     | TradingView Widget constructor     |
| `libraryPath`       | `string`                           | `"/static/charting_library/"`                  | Path to library static files       |
| `customCssUrl`      | `string`                           | `"/static/charting_library/custom-styles.css"` | Custom CSS URL                     |
| `toolbar`           | `TradingViewToolbarProps \| false` | `{}`                                           | Toolbar config, or `false` to hide |
| `loadingOverlay`    | `ReactNode`                        | -                                              | Overlay shown while loading        |
| `onReady`           | `() => void`                       | -                                              | Called when widget is ready        |
| `className`         | `string`                           | -                                              | Outer container class              |

#### `TradingViewToolbar`

Composable toolbar with slot-based customization.

| Prop                   | Type        | Default | Description                     |
| ---------------------- | ----------- | ------- | ------------------------------- |
| `showResolutions`      | `boolean`   | `true`  | Show resolution buttons         |
| `showKlineStyleSelect` | `boolean`   | `true`  | Show kline style selector       |
| `showOpenIndicator`    | `boolean`   | `true`  | Show indicator button           |
| `showOpenSettings`     | `boolean`   | `true`  | Show settings button            |
| `showFullscreen`       | `boolean`   | `true`  | Show fullscreen toggle          |
| `showSnapshot`         | `boolean`   | `true`  | Show snapshot button            |
| `prefix`               | `ReactNode` | -       | Slot before default items       |
| `suffix`               | `ReactNode` | -       | Slot after default items        |
| `children`             | `ReactNode` | -       | Override default items entirely |

#### Sub-components

- `TradingViewResolutions` — Resolution toggle buttons
- `TradingViewKlineStyleSelect` — K-line style dropdown
- `TradingViewOpenIndicator` — "Indicators" button
- `TradingViewOpenSettings` — "Settings" button
- `TradingViewFullscreen` — Fullscreen toggle
- `TradingViewSnapshot` — Screenshot download button
- `TradingViewAreaTitle` — Displays symbol/resolution for a chart area

### Hooks

| Hook                     | Return                      | Description                              |
| ------------------------ | --------------------------- | ---------------------------------------- |
| `useChartManager()`      | `ChartManager`              | Access the chart manager instance        |
| `useActiveAreaManager()` | `ChartAreaManager \| null`  | Active chart area manager                |
| `useSymbolInfo()`        | `LibrarySymbolInfo \| null` | Resolved symbol info for active area     |
| `useTvChartContext()`    | `TvChartContextValue`       | Full context (manager, settings, prefix) |
| `useTvChartManager()`    | `ChartManager`              | Shortcut for context.chartManager        |
| `useTvChartPrefix()`     | `string`                    | Current instance prefix (storageId)      |

### Types & Enums

| Type / Enum              | Description                                        |
| ------------------------ | -------------------------------------------------- |
| `TvChartConfig`          | Configuration passed to `initConfig`               |
| `TvChartResolution`      | `"1s" \| "5s" \| ... \| "1d"`                      |
| `TvChartKlineStyle`      | Candles, Bars, Line, Area, HeikenAshi, etc.        |
| `TvChartLayout`          | Layout presets (1A, 2A, 3A, etc.)                  |
| `TvChartTheme`           | `"light" \| "dark"`                                |
| `TvChartFeature`         | Feature flags (MultiCharts, VolumeForceOverlay...) |
| `ITvChartDataFeedModule` | Interface consumers implement for data fetching    |
| `ITvChartSymbolResolver` | Interface for symbol info resolution               |
| `ChartAreaState`         | Shape of per-area state in atoms                   |

### Atoms

All atoms are `atomFamily` instances keyed by `prefix` (storageId). Advanced consumers can read them directly:

- `chartLoadingFamily(prefix)` — `boolean`
- `chartFullscreenFamily(prefix)` — `boolean`
- `chartSelectedIndexFamily(prefix)` — `number`
- `chartPinnedResolutionsFamily(prefix)` — `TvChartResolution[]`
- `chartAreasFamily(prefix)` — `ChartAreaState[]`
- `settingsThemeFamily(prefix)` — `string`
- `settingsLayoutFamily(prefix)` — `TvChartLayout`
- `widgetReadyFamily(prefix)` — `boolean`
- `settingsDataFamily(prefix)` — Derived atom for auto-save

### Constants

- `ALL_TV_CHART_RESOLUTIONS` — All supported resolutions
- `DEFAULT_TV_CHART_RESOLUTIONS` — Default pinned resolutions
- `SUPPORTED_TV_CHART_LAYOUTS` — All layout presets
- `TV_CHART_THEME_COLORS` — Default color palette

## Usage Examples

### Basic Usage

```tsx
import { TradingView, type TvChartConfig } from "@liberfi.io/ui-tradingview";

const config: TvChartConfig = {
  storageId: "kline",
  tickerSymbol: "solana/So11111111111111111111111111111111111111112",
  datafeed: myDataFeedModule,
  resolution: "1m",
  layout: "1A",
  chartType: "TradingView",
  kLineStyle: 1,
  theme: "dark",
  timezone: "Etc/UTC",
  locale: "en",
};

function App() {
  return (
    <TradingView
      initConfig={config}
      widgetConstructor={window.TradingView.widget}
      libraryPath="/static/charting_library/"
    />
  );
}
```

### Multiple Instances

```tsx
function MultiChart() {
  return (
    <div className="flex gap-4">
      <TradingView
        initConfig={{ ...config, storageId: "chart-1" }}
        widgetConstructor={window.TradingView.widget}
      />
      <TradingView
        initConfig={{ ...config, storageId: "chart-2" }}
        widgetConstructor={window.TradingView.widget}
      />
    </div>
  );
}
```

### Custom Toolbar

```tsx
<TradingView
  initConfig={config}
  widgetConstructor={window.TradingView.widget}
  toolbar={{
    showSnapshot: false,
    prefix: <MyCustomSymbolSelector />,
    suffix: <MyCustomActions />,
  }}
/>
```

### Imperative API

```tsx
import { useRef } from "react";
import { TradingView, type TvChartHandle } from "@liberfi.io/ui-tradingview";

function App() {
  const ref = useRef<TvChartHandle>(null);

  const handleToggleTheme = () => {
    const current = ref.current?.theme();
    ref.current?.setTheme(current === "dark" ? "light" : "dark");
  };

  return (
    <>
      <button onClick={handleToggleTheme}>Toggle Theme</button>
      <TradingView
        ref={ref}
        initConfig={config}
        widgetConstructor={window.TradingView.widget}
      />
    </>
  );
}
```

## Future Improvements

- Add `TradingViewAreaTitle` injection into TradingView widget iframe for multi-chart layouts
- Support consumer-provided color palettes via props
- Add built-in `ITvChartDataFeedModule` implementation for common REST/WebSocket patterns
- Support chart comparison mode
- Add keyboard shortcut customization
- Expose drawing tools API