Question: I am trying to render the level2 api in the chartjs. But unable to do it
I have kep the data in 2 variable bid, ask and trying to plot them against time.
code sandbox https://codesandbox.io/p/sandbox/dazzling-neumann-qjw7yv
API: https://docs.cdp.coinbase.com/exchange/docs/websocket-channels/#level2-channel
CODE
options={{
scales: {
x: {
type: "realtime",
realtime: {
onRefresh: (chart) => {
bids.forEach((bid) => {
chart.data.datasets[0].data.push({
x: bid.time,
y: bid.price,
});
});
asks.forEach((ask) => {
chart.data.datasets[1].data.push({
x: ask.time,
y: ask.price,
});
});
},
},
},
},
}}
After a little time spent on it, here is what I managed to do.
First, you create a table which will be populated with each new bid or ask, all via useEffect
.
const { bids, asks } = useWebSocket();
const [chartData, setChartData] = useState({ datasets: [] });
const [newBid, setnewBid] = useState([]);
const [newAsk, setnewAsk] = useState([]);
useEffect(() => {
bids.map((bid) => {
setnewBid([...newBid, { x: bid.time, y: bid.price }]);
});
}, [bids]);
useEffect(() => {
asks.map((ask) => {
setnewAsk([...newAsk, { x: ask.time, y: ask.price }]);
});
}, [asks]);
Second, you define your options.
const options = {
scales: {
y: {
display: true,
type: "linear",
position: "left",
suggestedMin: 0.245,
suggestedMax: 0.26,
},
x: {
display: true,
type: "realtime",
},
},
};
Third, you define your datasets.
const datasets = {
datasets: [
{
label: "Bids",
backgroundColor: "rgba(255, 99, 132, 0.5)",
borderColor: "rgb(255, 99, 132)",
fill: true,
data: newBid,
},
{
label: "Asks",
backgroundColor: "rgba(54, 162, 235, 0.5)",
borderColor: "rgb(54, 162, 235)",
cubicInterpolationMode: "monotone",
fill: true,
data: newAsk,
},
],
};
Finally you import everything into your graph.
return <Line data={datasets} options={options} />;
Thanks to this code, the two lines are displayed correctly, without the axes reacting strangely, and over time. The curves are not necessarily very beautiful, but it's an adjustment to see afterwards.