npm package: @fipulse/crypto-chart-sdk
Description: TypeScript SDK for fetching and managing cryptocurrency chart data with real-time WebSocket updates
Author: Alvin LK
Latest version: 0.0.1

# @fipulse/crypto-chart-sdk

TypeScript SDK for fetching and managing cryptocurrency chart data with real-time WebSocket updates.

## Features

- 📊 Historical candle data fetching
- 🔄 Real-time WebSocket updates
- 🎯 Framework-agnostic (works with any JavaScript/TypeScript framework)
- 📦 Zero dependencies (uses native WebSocket and Fetch APIs)
- 🔧 Fully typed with TypeScript
- 🚀 Easy to integrate

## Installation

```bash
npm install @fipulse/crypto-chart-sdk
# or
yarn add @fipulse/crypto-chart-sdk
# or
pnpm add @fipulse/crypto-chart-sdk
```

## Quick Start

```typescript
import { CryptoChartSDK } from '@fipulse/crypto-chart-sdk';

// Initialize SDK
const sdk = new CryptoChartSDK(
  {
    baseUrl: 'https://api.fipulse.xyz',
    timeouts: {
      httpRequest: 10000,
      websocketConnect: 5000,
    },
    endpoints: {
      historyCandles: '/candle-chart',
      singleCandle: '/single-candle',
      websocket: 'wss://api.fipulse.xyz/ws',
    },
  },
  {
    url: 'wss://api.fipulse.xyz/ws',
    reconnectDelay: 1000,
    maxReconnectAttempts: 5,
  },
  {
    maxCandles: 1000,
    autoScroll: true,
  }
);

// Set up event handlers
sdk.onChartUpdate((data) => {
  console.log('Chart updated:', data.candles.length, 'candles');
});

sdk.onTrade((trade) => {
  console.log('New trade:', trade);
});

sdk.onError((error) => {
  console.error('SDK error:', error);
});

// Initialize with a token ID
// Format: {chain_id}-{lowercase_token_address}
// Example: "1-2260fac5e5542a773aa44fbcfedf7c193bc2c599"
await sdk.initialize('1-2260fac5e5542a773aa44fbcfedf7c193bc2c599');

// Subscribe to real-time updates
sdk.subscribe();
```

## API Reference

### CryptoChartSDK

Main SDK class for managing chart data and real-time updates.

#### Constructor

```typescript
new CryptoChartSDK(
  apiConfig: ApiConfig,
  wsConfig: WebSocketConfig,
  chartConfig?: ChartConfig,
  httpClient?: HttpClient
)
```

#### Methods

- `initialize(tokenId: string, connectWebSocket?: boolean): Promise<void>` - Initialize SDK with a token ID
- `connectWebSocket(): void` - Connect to WebSocket manually
- `subscribe(tokenId?: string): void` - Subscribe to real-time data
- `unsubscribe(): void` - Unsubscribe from real-time data
- `getChartData(): ChartData` - Get current chart data
- `getSubscriptionStatus(): SubscriptionStatus` - Get WebSocket subscription status
- `updateChartConfig(config: Partial<ChartConfig>): void` - Update chart configuration
- `updateApiConfig(config: Partial<ApiConfig>): void` - Update API configuration
- `updateWebSocketConfig(config: Partial<WebSocketConfig>): void` - Update WebSocket configuration
- `cleanupOldData(olderThanHours?: number): void` - Manually clean up old data
- `destroy(): void` - Cleanup and disconnect

#### Event Handlers

- `onChartUpdate(callback: ChartUpdateCallback): void` - Called when chart data is updated
- `onTrade(callback: TradeCallback): void` - Called when a new trade is received
- `onError(callback: ErrorCallback): void` - Called when an error occurs
- `onConnectionChange(callback: ConnectionCallback): void` - Called when connection status changes

## Types

### Candle

```typescript
interface Candle {
  OpenPrice: number;
  ClosePrice: number;
  HighPrice: number;
  LowPrice: number;
  VolumeIn: number;
  VolumeOut: number;
  Timestamp: number; // seconds
  TransactionCount: number;
}
```

### RealTimeTrade

```typescript
interface RealTimeTrade {
  TradeTime: number;
  USD: number;
  Amount: number;
  Price: number;
}
```

### ChartData

```typescript
interface ChartData {
  candles: Candle[];
  lastUpdate: Date | null;
  isLoading: boolean;
  error: string | null;
}
```

## Framework Integration

### Angular

```typescript
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CryptoChartSDK, ApiService, AngularHttpClient } from '@fipulse/crypto-chart-sdk';

@Injectable({ providedIn: 'root' })
export class ChartService {
  private sdk: CryptoChartSDK;

  constructor(private http: HttpClient) {
    // Create Angular-specific HTTP client adapter
    const angularHttpClient: HttpClient = {
      get: async (url: string, options?: any) => {
        const response = await firstValueFrom(
          this.http.get(url, {
            params: options?.params,
            responseType: 'text',
            headers: options?.headers,
          })
        );
        return response;
      },
    };

    this.sdk = new CryptoChartSDK(
      apiConfig,
      wsConfig,
      chartConfig,
      angularHttpClient
    );
  }
}
```

### React

```typescript
import { useEffect, useState } from 'react';
import { CryptoChartSDK, ChartData } from '@fipulse/crypto-chart-sdk';

function useCryptoChart(tokenId: string) {
  const [chartData, setChartData] = useState<ChartData | null>(null);
  const [sdk] = useState(() => new CryptoChartSDK(apiConfig, wsConfig));

  useEffect(() => {
    sdk.onChartUpdate(setChartData);
    sdk.initialize(tokenId);

    return () => {
      sdk.destroy();
    };
  }, [tokenId]);

  return chartData;
}
```

## License

MIT