JavaScript Realtime Ticking Stock Charts

Connects to Binance Exchange to fetch historical data on 1-minute timeframe. Subscribes to WebSocket and listens to candles & trades. Candles are updated in realtime. You can zoom, pan the example or use tooltips. Large trades > $25,000 size are plotted as bubbles.

Fullscreen

Edit

 Edit

Docs

index.tsx

binanceRestClient.ts

ExampleDataProvider.ts

theme.ts

binanceSocketClient.ts

createCandlestickChart.ts

VolumePaletteProvider.ts

Copy to clipboard
Minimise
Fullscreen
1/**
2 * Defines a price bar with Open, High, Low, Close and Date encoded as number
3 */
4export type TPriceBar = {
5    date: number;
6    open: number;
7    high: number;
8    low: number;
9    close: number;
10    volume: number;
11};
12
13/**
14 * Parses JSON candles into TPriceBar array
15 * @param candles
16 */
17const parseCandles = (candles: any[]): TPriceBar[] => {
18    const priceBars: TPriceBar[] = [];
19
20    candles.forEach((candle: any) => {
21        const [timestamp, open, high, low, close, volume] = candle;
22        const openValue = parseFloat(open);
23        const highValue = parseFloat(high);
24        const lowValue = parseFloat(low);
25        const closeValue = parseFloat(close);
26        const volumeValue = parseFloat(volume);
27
28        priceBars.push({
29            date: timestamp / 1000,
30            open: openValue,
31            high: highValue,
32            low: lowValue,
33            close: closeValue,
34            volume: volumeValue,
35        });
36    });
37
38    return priceBars;
39};
40
41/**
42 * Fetches candles from Binance Rest API
43 */
44const getCandles = async (
45    symbol: string,
46    interval: string,
47    startTime?: Date,
48    endTime?: Date,
49    limit: number = 500,
50    binanceDomain = "us"
51): Promise<TPriceBar[]> => {
52    let url = `https://api.binance.${binanceDomain}/api/v3/klines?symbol=${symbol}&interval=${interval}`;
53    if (startTime) {
54        url += `&startTime=${startTime.getTime()}`;
55    }
56    if (endTime) {
57        url += `&endTime=${endTime.getTime()}`;
58    }
59    if (limit) {
60        url += `&limit=${limit}`;
61    }
62    try {
63        console.log(`SimpleBinanceClient: Fetching ${symbol} ${interval} from ${startTime} to ${endTime}`);
64        const response = await fetch(url);
65        const data = await response.json();
66        return parseCandles(data);
67    } catch (err) {
68        console.error(err);
69        return [];
70    }
71};
72
73export const simpleBinanceRestClient = {
74    getCandles,
75};
76

Realtime Ticking Stock Charts with JavaScript

Overview

This example demonstrates a high-performance financial chart that updates in realtime using JavaScript and the SciChart.js library. It connects to the Binance Exchange for both historical candle and live trade data, updating candlestick charts dynamically while highlighting significant trades.

Technical Implementation

The implementation establishes WebSocket connections via the websocket-ts library to fetch candle and trade streams from Binance. These streams are merged using RxJS operators such as combineLatest and scan, a technique explained in detail in Ultimate Guide to RxJS Join Operators. The streaming data is processed and transformed into updated candlestick data with custom logic, and the chart is rendered using SciChart.js components such as the FastCandlestickRenderableSeries as described in The Candlestick Series type. In addition, moving average filters are applied to the data series to smooth trends, as covered in the Moving Average Filter Documentation. For WebSocket communication, best practices outlined in Writing WebSocket client applications have been followed.

Features and Capabilities

The example offers several advanced features including realtime chart updates, dynamic switching between candlestick and OHLC series, and the visualization of large trades as bubbles. Custom palette providers dynamically color volume bars based on trade direction, which leverages the capabilities discussed in The PaletteProvider API. Axis animations are also implemented to smoothly adjust the visible range as new data arrives, ensuring an engaging user experience.

Integration and Best Practices

Developers can use this example as a blueprint for integrating live exchange data with SciChart.js in a JavaScript environment. The solution demonstrates the effective use of RxJS for managing realtime data subscriptions and handling stream merging to maintain performance. By employing WebSocket connections for direct market data integration and utilizing SciChart.js for rendering high-performance charts, the implementation adheres to best practices in both realtime data processing and graphical rendering. This approach is ideal for developers looking to build scalable, responsive financial applications with minimal overhead.

javascript Chart Examples & Demos

See Also: Financial Charts (9 Demos)

JavaScript Candlestick Chart | Online JavaScript Chart Examples

JavaScript Candlestick Chart

Discover how to create a JavaScript Candlestick Chart or Stock Chart using SciChart.js. For high Performance JavaScript Charts, get your free demo now.

JavaScript OHLC Chart | Javascript Charts | SciChart.js Demo

JavaScript OHLC Chart

Easily create JavaScript OHLC Chart or Stock Chart using feature-rich SciChart.js chart library. Supports custom colors. Get your free trial now.

NEW!
JavaScript Orderbook Heatmap | Javascript Charts | SciChart.js

JavaScript Orderbook Heatmap

Create a Javascript heatmap chart showing historical orderbook levels using the high performance SciChart.js chart library. Get free demo now.

JavaScript Multi-Pane Stock Chart using Subcharts | View JavaScript Charts

JavaScript Multi-Pane Stock Charts using Subcharts

Create a JavaScript Multi-Pane Candlestick / Stock Chart with indicator panels, synchronized zooming, panning and cursors. Get your free trial of SciChart.js now.

Tenor Curves Demo | Javascript Charts | SciChart.js Demo

Tenor Curves Demo

Demonstrating the capability of SciChart.js to create a composite 2D &amp; 3D Chart application. An example like this could be used to visualize Tenor curves in a financial setting, or other 2D/3D data combined on a single screen.

JavaScript Multi-Pane Stock Chart | View JavaScript Charts

JavaScript Multi-Pane Stock Charts using Sync Multi-Chart

Create a JavaScript Multi-Pane Candlestick / Stock Chart with indicator panels, synchronized zooming, panning and cursors. Get your free trial of SciChart.js now.

JavaScript Market Depth Chart | Javascript Charts | SciChart.js

JavaScript Market Depth Chart

Create a JavaScript Depth Chart, using the high performance SciChart.js chart library. Get free demo now.

JavaScript Chart Hoverable Buy Sell Marker Annotations

JavaScript Chart Hoverable Buy Sell Marker Annotations

Demonstrates how to place Buy/Sell arrow markers on a JavaScript Stock Chart using SciChart.js - Annotations API

JavaScript User Annotated Stock Chart | SciChart.js Demo

JavaScript User Annotated Stock Chart

This demo shows you how to create a <strong>{frameworkName} User Annotated Stock Chart</strong> using SciChart.js. Custom modifiers allow you to add lines and markers, then use the built in serialisation functions to save and reload the chart, including the data and all your custom annotations.

SciChart Ltd, 16 Beaufort Court, Admirals Way, Docklands, London, E14 9XL.