react typescript, klinechart charting library. You need to access market data as here…
- User
react typescript, klinechart charting library. You need to access market data as here https://www.binance.com/ru/futures/DOGEUSDT here is my code import React, {useState, useEffect, ChangeEvent} from “react”; import { Badge, Box, Button, ButtonGroup, Chip, CircularProgress, Grid, Icon, IconButton, Skeleton, TextField, Typography } from “@mui/material”; import ArrowUpwardRoundedIcon from ‘@mui/icons-material/ArrowUpwardRounded’; import ArrowDownwardRoundedIcon from ‘@mui/icons-material/ArrowDownwardRounded’; import {useAuthContext} from “…/…/AuthProvider/AuthProvider”; import FormatPrice from “…/…/Common/FormatPrice”; import {Order, readCandlesByTrade, readOrderByTrade, Trade, updateTrade} from “…/…/…/actions/cicap-diary-trades”; import DataTable from “…/…/DataTable/DataTable”; import {useSnackbar} from “notistack”; import {CandleChart} from “…/CandleChart/CandleChart”; import {TradeEntity} from “…/CandleChart/CandleChart.props”; import {FormattedNumber} from “react-intl”; import ImageIcon from “next/image”; import {createTradeImage, deleteTradeImage, tradeImagesCollection, TradeImage} from “…/…/…/actions/cicap-diary-trades-images”;
const timezoneOffset = new Date().getTimezoneOffset() * 60;
interface SideTypeProps { order: Order; }
const SideType = ({order}: SideTypeProps) => { let label = ‘’; let color = ‘default’; const icon = order?.side && ‘sell’ === order.side ? ArrowDownwardRoundedIcon : ArrowUpwardRoundedIcon;
switch (order?.type) { case ‘limit’: label = ‘L’; color = ‘success’ break; case ‘market’: label = ‘M’; color = ‘warning’ break; case ‘stop_market’: label = ‘F’; color = ‘primary’ break; }
return <> <Badge badgeContent={label} // @ts-ignore color={color}
interface CandlePrice { timestamp: number; open: number; high: number; low: number; close: number; volume: number; }
interface TradeDetailsProps { tradeId: string; defaultChartInterval: string; }
const TradeDetails = ({tradeId, defaultChartInterval}: TradeDetailsProps) => { const [trade, setTrade] = useState<{orders: Array, data: Trade} | undefined>(undefined); const [orders, setOrders] = useState<Array>([]); const [chartInterval, setChartInterval] = useState(defaultChartInterval); const [waiting, setWaiting] = useState(false); const [candleData, setCandleData] = useState<Array>([]); const [images, setImages] = useState<Array>([]); const [imageIdDeletion, setImageIdDeletion] = useState<string|null>(null);
const {diaryToken} = useAuthContext(); const [description, setDescription] = useState(‘’); const [conclusion, setConclusion] = useState(‘’); const [videoLink, setVideoLink] = useState(‘’); const {enqueueSnackbar} = useSnackbar(); const ref = React.createRef();
const fetchTrade = () => { if (!tradeId || !diaryToken) { return; }
setWaiting(true); readOrderByTrade(tradeId, diaryToken) .then(data => { setWaiting(false); if (!data) return;
const newOrders: Array = [];
data.orders.forEach(order => { const timestamp = Math.floor(order.msTimestamp) - timezoneOffset;
newOrders.push({ time: timestamp, position: order.side, value: parseFloat(order.price), }); });
setTrade(data); setOrders(newOrders); }); }
return <> <Box sx={{pr: 2}}> { trade?.data.id && candleData ? (<> </>) : (<> </>) }
</> }
import React, {useEffect, useRef, useState} from “react”; import { init, dispose, Chart, DeepPartial, IndicatorFigureStylesCallbackData, Indicator, IndicatorStyle, KLineData, utils, } from “klinecharts”; import {CandleChartProps} from “./CandleChart.props”; import CandleChartToolbar from “./CandleChartToolbar”; import {Style} from “util”; import {Box, Icon, IconButton, Stack} from “@mui/material”; import getMinutesTickSizeByInterval from “./utils/getMinutesTickSizeByInterval.util”; import drawTrade from “./utils/drawTrade.util”; import drawTradeLines from “./utils/drawTradeLines.util”; import {BasketIcon, ScreenIcon} from “…/…/icons”; import {FullScreen, useFullScreenHandle} from “react-full-screen”;;
interface Vol { volume?: number }
export const CandleChart = ({ images, candles, tradeId, orders, interval, openPrice, closePrice, pricePrecision, quantityPrecision, createImage }: CandleChartProps) => { console.log(candles);
const chart = useRef<Chart|null>(); const paneId = useRef(“”); const [figureId, setFigureId] = useState(“”) const ref = useRef(null); const handle = useFullScreenHandle();
useEffect(() => { chart.current = init(chart-${tradeId}, {styles: chartStyles});
return () => dispose(chart-${tradeId}); }, [tradeId]);
useEffect(() => { const onWindowResize = () => chart.current?.resize(); window.addEventListener(“resize”, onWindowResize);
return () => window.removeEventListener(“resize”, onWindowResize); }, []);
useEffect(() => { chart.current?.applyNewData(candles); chart.current?.overrideIndicator({ name: “VOL”, shortName: “Объем”, calcParams: [], figures: [ { key: “volume”, title: “”, type: “bar”, baseValue: 0, styles: (data: IndicatorFigureStylesCallbackData, indicator: Indicator, defaultStyles: IndicatorStyle) => { const kLineData = data.current.kLineData as KLineData let color: string if (kLineData.close > kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].upColor”, (defaultStyles.bars)[0].upColor) as string } else if (kLineData.close < kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].downColor”, (defaultStyles.bars)[0].downColor) as string } else { color = utils.formatValue(indicator.styles, “bars[0].noChangeColor”, (defaultStyles.bars)[0].noChangeColor) as string } return { color } } } ] }, paneId.current); chart.current?.createIndicator(“VOL”, false, { id: paneId.current }); chart.current?.setPriceVolumePrecision(+pricePrecision, +quantityPrecision); }, [candles]);
useEffect(() => { if (!orders || orders.length === 0 || candles.length === 0) return;
const minTime = orders[0].time; const maxTime = orders[orders.length - 1].time; const needleTime = minTime + (maxTime - minTime) / 2;
chart.current?.scrollToTimestamp(needleTime + 45 * getMinutesTickSizeByInterval(interval) * 60 * 1000); drawTrade(chart, paneId, orders, interval); if (openPrice && closePrice) { let openTime = Infinity; let closeTime = -Infinity;
orders.forEach(order => { if (openTime > order.time) { openTime = order.time; }
if (closeTime < order.time) { closeTime = order.time; } });
drawTradeLines( chart, openPrice, openTime, closePrice, closeTime, orders[0].position, paneId, pricePrecision, quantityPrecision, ); } }, [orders, candles, tradeId]); return (<> <Stack direction=“row” height={!handle.active ? 550 : “100%”} width=“100%”> <Box ref={ref} id={chart-${tradeId}} width=“calc(100% - 55px)” height={!handle.active ? 550 : “100%”} sx={{ borderLeft: “1px solid #ddd” }}
{ figureId.length > 0 && <Stack sx={{ backgroundColor: “#CBD4E3”, borderRadius: 1, position: “absolute”, zIndex: 10, right: 80, top: 30, border: “1px solid #697669”, }} spacing={2}
<IconButton sx={{ borderRadius: 1 }} onClick={removeFigure}> } </>); }
In those transactions where there is no closed order, you need to display real-time candles on the chart and calculate the percentage at the current price. This is necessary so that you can follow the transaction in real time. It is necessary that the chart reflects the current situation on the market, as here https://www.binance.com/ru/futures/DOGEUSDT
- Assistant
To display real-time candles on the chart, you need to subscribe to the Binance API Websocket and listen for candlestick updates for the desired symbol and interval. You can then update the chart with the new data received from the Websocket.
First, install the
binance-api-nodepackage using:npm install binance-api-nodeNext, import the Binance package and update the
TradeDetailscomponent:// Import Binance library import Binance from 'binance-api-node' // ... // In the TradeDetails component const fetchTrade = () => { // ... // Close the previous Websocket connection if exists if (ws.current) { ws.current(); } // Create a Binance client const client = Binance() // Subscribe to candlestick updates for the desired symbol and interval ws.current = client.ws.candles(trade?.data.symbol, chartInterval, (candle) => { // Update the chart with the new candle data const newCandleData = { timestamp: candle.startTime, open: parseFloat(candle.open), high: parseFloat(candle.high), low: parseFloat(candle.low), close: parseFloat(candle.close), volume: parseFloat(candle.volume), }; setCandleData((prevData) => [...prevData.slice(-1)[0].timestamp !== newCandleData.timestamp ? prevData : prevData.slice(0, -1), newCandleData]); }); }; // Use a ref to store the Websocket cleanup function const ws = useRef(null); // Add a cleanup function in useEffect to close the Websocket (optional) useEffect(() => { return () => { if (ws.current) { ws.current(); } }; }, []); // Call fetchTrade when chartInterval changes useEffect(() => { fetchTrade(); }, [chartInterval]);This will update the chart with real-time candles for the selected symbol and interval. Note that this implementation may not be fully optimized, but it should give you an idea of integrating the WebSocket into your current solution.
To calculate the percentage at the current price, you can listen to the trade updates for the symbol and calculate the percentage based on the last price:
const [lastPrice, setLastPrice] = useState(null); // Subscribe to trade updates for the desired symbol ws.current = client.ws.trades(trade?.data.symbol, (trade) => { setLastPrice(parseFloat(trade.price)); }); // Calculate the percentage based on the last price const percentage = lastPrice && trade?.data.openPrice ? (((lastPrice / trade.data.openPrice) - 1) * 100).toFixed(2) : null; // Display the percentage {percentage && <p>Current Percentage: {percentage}%</p>}By following the above steps, your chart should reflect the current situation in the market, as shown in the Binance link you provided.
- User
react typescript, klinechart charting library. You need to access market data as here https://www.binance.com/ru/futures/DOGEUSDT here is my code import React, {useState, useEffect, ChangeEvent} from “react”; import { Badge, Box, Button, ButtonGroup, Chip, CircularProgress, Grid, Icon, IconButton, Skeleton, TextField, Typography } from “@mui/material”; import ArrowUpwardRoundedIcon from ‘@mui/icons-material/ArrowUpwardRounded’; import ArrowDownwardRoundedIcon from ‘@mui/icons-material/ArrowDownwardRounded’; import {useAuthContext} from “…/…/AuthProvider/AuthProvider”; import FormatPrice from “…/…/Common/FormatPrice”; import {Order, readCandlesByTrade, readOrderByTrade, Trade, updateTrade} from “…/…/…/actions/cicap-diary-trades”; import DataTable from “…/…/DataTable/DataTable”; import {useSnackbar} from “notistack”; import {CandleChart} from “…/CandleChart/CandleChart”; import {TradeEntity} from “…/CandleChart/CandleChart.props”; import {FormattedNumber} from “react-intl”; import ImageIcon from “next/image”; import {createTradeImage, deleteTradeImage, tradeImagesCollection, TradeImage} from “…/…/…/actions/cicap-diary-trades-images”;
const timezoneOffset = new Date().getTimezoneOffset() * 60;
interface SideTypeProps { order: Order; }
const SideType = ({order}: SideTypeProps) => { let label = ‘’; let color = ‘default’; const icon = order?.side && ‘sell’ === order.side ? ArrowDownwardRoundedIcon : ArrowUpwardRoundedIcon;
switch (order?.type) { case ‘limit’: label = ‘L’; color = ‘success’ break; case ‘market’: label = ‘M’; color = ‘warning’ break; case ‘stop_market’: label = ‘F’; color = ‘primary’ break; }
return <> <Badge badgeContent={label} // @ts-ignore color={color}
interface CandlePrice { timestamp: number; open: number; high: number; low: number; close: number; volume: number; }
interface TradeDetailsProps { tradeId: string; defaultChartInterval: string; }
const TradeDetails = ({tradeId, defaultChartInterval}: TradeDetailsProps) => { const [trade, setTrade] = useState<{orders: Array, data: Trade} | undefined>(undefined); const [orders, setOrders] = useState<Array>([]); const [chartInterval, setChartInterval] = useState(defaultChartInterval); const [waiting, setWaiting] = useState(false); const [candleData, setCandleData] = useState<Array>([]); const [images, setImages] = useState<Array>([]); const [imageIdDeletion, setImageIdDeletion] = useState<string|null>(null);
const {diaryToken} = useAuthContext(); const [description, setDescription] = useState(‘’); const [conclusion, setConclusion] = useState(‘’); const [videoLink, setVideoLink] = useState(‘’); const {enqueueSnackbar} = useSnackbar(); const ref = React.createRef();
const fetchTrade = () => { if (!tradeId || !diaryToken) { return; }
setWaiting(true); readOrderByTrade(tradeId, diaryToken) .then(data => { setWaiting(false); if (!data) return;
const newOrders: Array = [];
data.orders.forEach(order => { const timestamp = Math.floor(order.msTimestamp) - timezoneOffset;
newOrders.push({ time: timestamp, position: order.side, value: parseFloat(order.price), }); });
setTrade(data); setOrders(newOrders); }); }
return <> <Box sx={{pr: 2}}> { trade?.data.id && candleData ? (<> </>) : (<> </>) }
</> }
import React, {useEffect, useRef, useState} from “react”; import { init, dispose, Chart, DeepPartial, IndicatorFigureStylesCallbackData, Indicator, IndicatorStyle, KLineData, utils, } from “klinecharts”; import {CandleChartProps} from “./CandleChart.props”; import CandleChartToolbar from “./CandleChartToolbar”; import {Style} from “util”; import {Box, Icon, IconButton, Stack} from “@mui/material”; import getMinutesTickSizeByInterval from “./utils/getMinutesTickSizeByInterval.util”; import drawTrade from “./utils/drawTrade.util”; import drawTradeLines from “./utils/drawTradeLines.util”; import {BasketIcon, ScreenIcon} from “…/…/icons”; import {FullScreen, useFullScreenHandle} from “react-full-screen”;;
interface Vol { volume?: number }
export const CandleChart = ({ images, candles, tradeId, orders, interval, openPrice, closePrice, pricePrecision, quantityPrecision, createImage }: CandleChartProps) => { console.log(candles);
const chart = useRef<Chart|null>(); const paneId = useRef(“”); const [figureId, setFigureId] = useState(“”) const ref = useRef(null); const handle = useFullScreenHandle();
useEffect(() => { chart.current = init(chart-{tradeId}, {styles: chartStyles});
return () => dispose(chart-{tradeId}); }, [tradeId]);
useEffect(() => { const onWindowResize = () => chart.current?.resize(); window.addEventListener(“resize”, onWindowResize);
return () => window.removeEventListener(“resize”, onWindowResize); }, []);
useEffect(() => { chart.current?.applyNewData(candles); chart.current?.overrideIndicator({ name: “VOL”, shortName: “Объем”, calcParams: [], figures: [ { key: “volume”, title: “”, type: “bar”, baseValue: 0, styles: (data: IndicatorFigureStylesCallbackData, indicator: Indicator, defaultStyles: IndicatorStyle) => { const kLineData = data.current.kLineData as KLineData let color: string if (kLineData.close > kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].upColor”, (defaultStyles.bars)[0].upColor) as string } else if (kLineData.close < kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].downColor”, (defaultStyles.bars)[0].downColor) as string } else { color = utils.formatValue(indicator.styles, “bars[0].noChangeColor”, (defaultStyles.bars)[0].noChangeColor) as string } return { color } } } ] }, paneId.current); chart.current?.createIndicator(“VOL”, false, { id: paneId.current }); chart.current?.setPriceVolumePrecision(+pricePrecision, +quantityPrecision); }, [candles]);
useEffect(() => { if (!orders || orders.length === 0 || candles.length === 0) return;
const minTime = orders[0].time; const maxTime = orders[orders.length - 1].time; const needleTime = minTime + (maxTime - minTime) / 2;
chart.current?.scrollToTimestamp(needleTime + 45 * getMinutesTickSizeByInterval(interval) * 60 * 1000); drawTrade(chart, paneId, orders, interval); if (openPrice && closePrice) { let openTime = Infinity; let closeTime = -Infinity;
orders.forEach(order => { if (openTime > order.time) { openTime = order.time; }
if (closeTime < order.time) { closeTime = order.time; } });
drawTradeLines( chart, openPrice, openTime, closePrice, closeTime, orders[0].position, paneId, pricePrecision, quantityPrecision, ); } }, [orders, candles, tradeId]); return (<> <Stack direction=“row” height={!handle.active ? 550 : “100%”} width=“100%”> <Box ref={ref} id={chart-${tradeId}} width=“calc(100% - 55px)” height={!handle.active ? 550 : “100%”} sx={{ borderLeft: “1px solid #ddd” }}
{ figureId.length > 0 && <Stack sx={{ backgroundColor: “#CBD4E3”, borderRadius: 1, position: “absolute”, zIndex: 10, right: 80, top: 30, border: “1px solid #697669”, }} spacing={2}
<IconButton sx={{ borderRadius: 1 }} onClick={removeFigure}> } </>); }
In those transactions where there is no closed order, you need to display real-time candles on the chart and calculate the percentage at the current price. This is necessary so that you can follow the transaction in real time. It is necessary that the chart reflects the current situation on the market, as here https://www.binance.com/ru/futures/DOGEUSDT import { Options, WebSocketHook, JsonValue } from './types'; export declare const useWebSocket: <T extends JsonValue | null = JsonValue | null>(url: string | (() => string | Promise) | null, options?: Options, connect?: boolean) => WebSocketHook<T, MessageEvent | null>; useWebSocket
- Assistant
To use a WebSocket hook with React, you can create a custom hook that manages the WebSocket connection and updates the state with real-time data. Here's an example of a custom
useWebSockethook for your project:import { useState, useEffect, useRef } from "react"; const useWebSocket = (url, onMessage) => { const [socket, setSocket] = useState(null); const socketRef = useRef(null); useEffect(() => { if (url && typeof onMessage === 'function') { const ws = new WebSocket(url); setSocket(ws); socketRef.current = ws; ws.addEventListener('message', onMessage); ws.onopen = () => console.log("Socket opened", ws); ws.onclose = () => console.log("Socket closed", ws); ws.onerror = (error) => console.log("Socket error", error); } return () => { if (socketRef.current) { socketRef.current.close(); } }; }, [url, onMessage]); return [socket]; }; export default useWebSocket;To use this
useWebSockethook with the Binance WebSocket API, first import the hook, and then update theTradeDetailscomponent as follows:- Replace this line:
const client = Binance();With this line:
const binanceUrl = `wss://stream.binance.com:9443/ws/${trade?.data.symbol.toLowerCase()}@kline_${chartInterval}`;You may need to append "usdt" to the symbol, for example
${trade?.data.symbol.toLowerCase()}usdt.-
Remove the lines of code that set up and close the WebSocket connection.
-
Replace the
wsref with the following:
const [socket] = useWebSocket(binanceUrl, (event) => { const data = JSON.parse(event.data); const candle = data.k; // Extract the candle data from the event const newCandleData = { timestamp: candle.t, open: parseFloat(candle.o), high: parseFloat(candle.h), low: parseFloat(candle.l), close: parseFloat(candle.c), volume: parseFloat(candle.v), }; setCandleData((prevData) => [...prevData.slice(-1)[0].timestamp !== newCandleData.timestamp ? prevData : prevData.slice(0, -1), newCandleData]); });This will create a WebSocket connection to the Binance API and update the chart with real-time candlestick data. The hook will automatically close the WebSocket connection when the component is unmounted or the
binanceUrlchanges.Remember that this example may not be fully optimized, but it should give you an idea for using the WebSocket hook in your project.