sptrader-chart-lib
v2.0.20
Published
Professional financial charting library with real-time data, canvas primitives, and smooth transitions
Maintainers
Readme
SPTrader Chart Library
A professional financial charting library built on TradingView's Lightweight Charts with real-time data support, canvas-based primitives, and smooth transitions.
Features
- Real-time Data Integration: Connect to TimescaleDB or any REST API for historical data
- WebSocket Support: Real-time price updates with automatic reconnection
- Canvas Primitives: Native chart overlays (watermarks, countdown timers) drawn directly on canvas
- Smart Caching: Two-layer caching with browser HTTP cache and in-memory storage
- Smooth Transitions: Seamless timeframe switching with viewport preservation
- Auto Timeframe Switching: Automatically adjusts timeframe based on zoom level
- TypeScript: Full type safety and IntelliSense support
- React Integration: Built for React with hooks and state management
Installation
npm install sptrader-chart-lib
# or
yarn add sptrader-chart-libQuick Start
import { MarketChartPage, getHTTPDataProvider, chartDataCoordinator } from 'sptrader-chart-lib';
// Configure HTTP data provider (do this once at app startup)
getHTTPDataProvider({
baseUrl: 'https://your-api.com',
timeout: 30000
});
chartDataCoordinator.enableHTTP(true);
// Use the chart component
function App() {
return (
<MarketChartPage
symbol="EURUSD"
timeframe="1h"
enableTimeframeAutoSwitch={true}
/>
);
}Components
MarketDataChart
The main chart component with full features:
import { MarketDataChart } from 'sptrader-chart-lib';
<MarketDataChart
symbol="EURUSD" // Trading pair
timeframe="1h" // Initial timeframe
onTimeframeChange={(tf) => console.log('Timeframe changed to:', tf)}
enableTimeframeAutoSwitch={true} // Auto-switch based on zoom
/>Data Providers
HTTP Data Provider
Connect to any REST API for historical candle data:
import { getHTTPDataProvider } from 'sptrader-chart-lib';
// Configure once at app startup
getHTTPDataProvider({
baseUrl: 'https://api.example.com',
apiKey: 'your-api-key', // Optional
timeout: 30000 // Request timeout in ms
});Expected API response format:
[
{
"time": 1234567890,
"open": 1.0823,
"high": 1.0845,
"low": 1.0812,
"close": 1.0834
}
]WebSocket Provider
Real-time price updates via WebSocket:
import { WebSocketService } from 'sptrader-chart-lib';
const wsService = new WebSocketService({
url: 'wss://stream.example.com',
broker: 'yourbroker',
enableHeartbeat: true,
pingInterval: 30000,
pongTimeout: 5000
});
// Subscribe to a symbol
await wsService.subscribe('EURUSD');
// Listen for updates
wsService.onMessage((data) => {
console.log('Price update:', data);
});Canvas Primitives
Countdown Timer
Shows time remaining until next candle:
import { CountdownTimerPrimitive } from 'sptrader-chart-lib';
const timer = new CountdownTimerPrimitive({
timeframe: '1h',
position: 'bottom-right',
offset: { x: 10, y: 10 },
onNewCandleBoundary: (time) => {
console.log('New candle at:', time);
}
});
// Attach to chart series
candlestickSeries.attachPrimitive(timer);Timeframe Watermark
Displays current timeframe as a watermark:
import { TimeframeWatermarkPrimitive } from 'sptrader-chart-lib';
const watermark = new TimeframeWatermarkPrimitive({
timeframe: '4h',
opacity: 0.2,
fontSize: 72
});
candlestickSeries.attachPrimitive(watermark);State Management
Chart Store
Manages chart state with Zustand:
import { useChartStore } from 'sptrader-chart-lib';
function ChartControls() {
const { timeframe, setTimeframe, isLoading } = useChartStore();
return (
<select
value={timeframe}
onChange={(e) => setTimeframe(e.target.value)}
disabled={isLoading}
>
<option value="1m">1 Minute</option>
<option value="5m">5 Minutes</option>
<option value="1h">1 Hour</option>
<option value="4h">4 Hours</option>
</select>
);
}Trading Store
Symbol selection state management:
import { useTradingStore } from 'sptrader-chart-lib';
function SymbolSelector() {
const { selectedPair, setSelectedPair } = useTradingStore();
return (
<select value={selectedPair} onChange={(e) => setSelectedPair(e.target.value)}>
<option value="EURUSD">EUR/USD</option>
<option value="GBPUSD">GBP/USD</option>
</select>
);
}Hooks
useCountdownTimer
Hook for countdown functionality:
import { useCountdownTimer } from 'sptrader-chart-lib';
function CountdownDisplay({ timeframe }) {
const {
countdown,
countdownColor,
secondsRemaining,
isNearBoundary
} = useCountdownTimer(timeframe, {
onNewCandleBoundary: (time) => {
console.log('New candle!');
},
warningThreshold: 30,
criticalThreshold: 10
});
return (
<div style={{ color: countdownColor }}>
{countdown}
{isNearBoundary && <span> ⚠️</span>}
</div>
);
}usePlaceholderCandle
Creates placeholder candles for smooth real-time updates:
import { usePlaceholderCandle } from 'sptrader-chart-lib';
function Chart({ symbol, timeframe }) {
const { createPlaceholder, updatePlaceholder } = usePlaceholderCandle(
chartRef.current,
seriesRef.current,
timeframe
);
// Create placeholder for new candle
useEffect(() => {
const candleTime = calculateCandleTime(Date.now(), timeframe);
createPlaceholder(candleTime);
}, [timeframe]);
}Configuration
Chart Data Coordinator
Central data management:
import { chartDataCoordinator } from 'sptrader-chart-lib';
// Enable HTTP mode
chartDataCoordinator.enableHTTP(true);
// Set custom range for a symbol/timeframe
chartDataCoordinator.setDefaultRange('EURUSD', '1h', fromTime, toTime);
// Get symbol metadata
const metadata = await chartDataCoordinator.getSymbolMetadata('EURUSD');Timeframes
Available timeframes and their configurations:
import { TIMEFRAMES, TIMEFRAME_SECONDS, TIMEFRAME_LABELS } from 'sptrader-chart-lib';
// Available timeframes
TIMEFRAMES // ['1m', '5m', '15m', '1h', '4h', '12h', '1d', '1w']
// Seconds per timeframe
TIMEFRAME_SECONDS['1h'] // 3600
// Human-readable labels
TIMEFRAME_LABELS['1h'] // '1 Hour'API Requirements
Your backend API should implement these endpoints:
GET /api/candles
Query parameters:
symbol: Trading pair (e.g., "EURUSD")timeframe: Timeframe (e.g., "1h")from: Unix timestamp (start)to: Unix timestamp (end)
Response:
[
{
"time": 1234567890,
"open": 1.0823,
"high": 1.0845,
"low": 1.0812,
"close": 1.0834
}
]WebSocket Messages
Subscribe:
{
"type": "subscribe",
"symbol": "EURUSD"
}Price update:
{
"type": "price",
"symbol": "EURUSD",
"bid": 1.0823,
"ask": 1.0825,
"timestamp": 1234567890
}Browser Support
- Chrome/Edge 90+
- Firefox 88+
- Safari 14+
Performance
- Caching: Two-layer caching reduces API calls
- Virtualization: Only visible candles are rendered
- Canvas Primitives: Direct canvas drawing for overlays
- Debouncing: Smart request debouncing prevents API flooding
- Viewport Preservation: Maintains position during timeframe switches
TypeScript Support
Full TypeScript support with exported types:
import type {
Candle,
ChartData,
WebSocketConfig,
SymbolMetadata,
TimeframeType
} from 'sptrader-chart-lib';License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Support
For issues and questions, please use the GitHub issues page.
