npm package: @hodlbase/realtime
Description: HodlBase real-time WebSocket client for streaming Bitcoin treasury metrics
Latest version: 0.1.0

# @hodlbase/realtime

TypeScript SDK for streaming real-time Bitcoin treasury metrics from HodlBase.

Zero runtime dependencies. Works in browsers and Node.js 21+.

## Installation

```bash
npm install @hodlbase/realtime
```

## Quick Start

```typescript
import { HodlbaseRealtime } from '@hodlbase/realtime';

const client = new HodlbaseRealtime({ apiKey: 'hb_YOUR_API_KEY' });

// Subscribe to MicroStrategy company data
client.subscribe('company', 'MSTR', {
  metrics: ['mnav', 'market_cap', 'common_stock_price'],
  interval: 5, // seconds between updates
  onUpdate: (msg) => {
    console.log(`MSTR:`, msg.data);
    // { mnav: "2.34", market_cap: "115000000000", common_stock_price: "398.50" }
  },
});

// Global event listeners
client.on('welcome', (msg) => console.log('Plan:', msg.plan));
client.on('error', (msg) => console.error('Error:', msg.message));
client.on('statusChange', (status) => console.log('Status:', status));
```

## React

```tsx
import { HodlbaseProvider, useHodlbaseRealtime } from '@hodlbase/realtime/react';

// Wrap your app with the provider (creates one shared WebSocket connection)
function App() {
  return (
    <HodlbaseProvider apiKey="hb_YOUR_API_KEY">
      <Dashboard />
    </HodlbaseProvider>
  );
}

// Use the hook in any component
function MSTRCard() {
  const { data, status, updatedAt } = useHodlbaseRealtime('company', 'MSTR', {
    metrics: ['mnav', 'market_cap'],
    interval: 5,
  });

  if (!data) return <div>Loading...</div>;

  return (
    <div>
      <p>mNAV: {data.mnav}</p>
      <p>Market Cap: ${Number(data.market_cap).toLocaleString()}</p>
      <p>Updated: {updatedAt}</p>
      <p>Status: {status}</p>
    </div>
  );
}
```

## API Reference

### `new HodlbaseRealtime(options)`

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | `string` | *required* | Your HodlBase API key |
| `baseUrl` | `string` | `"wss://api.hodlbase.io"` | WebSocket server URL |
| `autoConnect` | `boolean` | `true` | Connect on construction |
| `reconnect` | `boolean` | `true` | Auto-reconnect on disconnect |
| `maxReconnectAttempts` | `number` | `0` (unlimited) | Max reconnect attempts |
| `debug` | `boolean` | `false` | Log to console |

### Methods

- **`connect()`** — Connect to the server. Returns a Promise.
- **`disconnect()`** — Disconnect and clear all subscriptions.
- **`subscribe(channel, ticker, options?)`** — Subscribe to an entity. Returns a `Subscription` handle with an `unsubscribe()` method.
- **`unsubscribe(channel, ticker)`** — Unsubscribe from an entity.
- **`unsubscribeAll()`** — Unsubscribe from all entities.
- **`getUsage()`** — Request usage info. Returns a Promise.
- **`on(event, handler)`** — Listen for events: `welcome`, `update`, `subscribed`, `unsubscribed`, `error`, `pong`, `statusChange`.
- **`off(event, handler)`** — Remove an event listener.

### Subscribe Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `metrics` | `string[]` | all allowed | Specific metrics to receive |
| `interval` | `number` | `0` | Seconds between updates (0 = real-time) |
| `onUpdate` | `(msg) => void` | — | Per-subscription update callback |

### Features

- **Auto-reconnect**: Exponential backoff from 1s to 30s. Resubscribes all active subscriptions on reconnect.
- **Heartbeat**: Sends ping every 25s. Forces reconnect if no pong within 10s.
- **TypeScript**: Full type definitions for all protocol messages.

## Channels & Metrics

### Company (`channel: "company"`)
Tickers: `MSTR`, `ASST`, `3350.T`

Metrics: `mnav`, `btc_reserve_usd`, `common_stock_price`, `market_cap`, `amplification`, `net_leverage`, `net_leverage_pure`, `enterprise_value_usd` (enterprise+), ...

### Security (`channel: "security"`)
Tickers: `STRK`, `STRF`, `STRD`, `STRC`, `STRE`

Metrics: `close_price`, `effective_yield`, `market_cap`, `btc_rating`, `cs_aaa`, `cs_sofr`, `cs_us10y`, `duration`, ...

## Plan Limits

| Plan | Connections | Entity Subs | Min Interval |
|------|-------------|-------------|--------------|
| Explorer | 1 | 1 | 15s |
| Professional | 5 | 3 | 10s |
| Enterprise | 20 | 10 | 5s |
| Partner | 50 | unlimited | 0s |