Skip to content

Commit

Permalink
Depth not updating continuously
Browse files Browse the repository at this point in the history
  • Loading branch information
prateekkumaroriginal committed Jun 28, 2024
1 parent cb397ca commit 01ac3c7
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 42 deletions.
29 changes: 14 additions & 15 deletions week-1/day-2/binance-frontend-realtime/app/components/MarketBar.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
"use client";
import { useEffect, useState } from "react";
import { Ticker } from "../utils/types";
import { Ticker as TickerType } from "../utils/types";
import { getTicker } from "../utils/httpClient";
import { SignalingManager } from "../utils/SignalingManager";

export const MarketBar = ({market}: {market: string}) => {
const [ticker, setTicker] = useState<Ticker | null>(null);
const [ticker, setTicker] = useState<TickerType | null>(null);

useEffect(() => {
getTicker(market).then(setTicker);
SignalingManager.getInstance().registerCallback("ticker", (data: Partial<Ticker>) => setTicker(prevTicker => ({
SignalingManager.getInstance().registerCallback("ticker", (data: Partial<TickerType>) => setTicker(prevTicker => ({
firstPrice: data?.firstPrice ?? prevTicker?.firstPrice ?? '',
high: data?.high ?? prevTicker?.high ?? '',
lastPrice: data?.lastPrice ?? prevTicker?.lastPrice ?? '',
Expand All @@ -20,15 +20,14 @@ export const MarketBar = ({market}: {market: string}) => {
symbol: data?.symbol ?? prevTicker?.symbol ?? '',
trades: data?.trades ?? prevTicker?.trades ?? '',
volume: data?.volume ?? prevTicker?.volume ?? '',
})), market);
})), `TICKER-${market}`);
SignalingManager.getInstance().sendMessage({"method":"SUBSCRIBE","params":[`ticker.${market}`]} );

return () => {
SignalingManager.getInstance().deRegisterCallback("ticker", market);
SignalingManager.getInstance().deRegisterCallback("ticker", `TICKER-${market}`);
SignalingManager.getInstance().sendMessage({"method":"UNSUBSCRIBE","params":[`ticker.${market}`]} );
}
}, [market])
//

return <div>
<div className="flex items-center flex-row relative w-full overflow-hidden border-b border-slate-800">
Expand All @@ -37,22 +36,22 @@ export const MarketBar = ({market}: {market: string}) => {
<div className="flex items-center flex-row space-x-8 pl-4">
<div className="flex flex-col h-full justify-center">
<p className={`font-medium tabular-nums text-greenText text-md text-green-500`}>${ticker?.lastPrice}</p>
<p className="font-medium text-sm text-sm tabular-nums">${ticker?.lastPrice}</p>
<p className="font-medium text-sm tabular-nums">${ticker?.lastPrice}</p>
</div>
<div className="flex flex-col">
<p className={`font-medium text-xs text-slate-400 text-sm`}>24H Change</p>
<p className={` text-sm font-medium tabular-nums leading-5 text-sm text-greenText ${Number(ticker?.priceChange) > 0 ? "text-green-500" : "text-red-500"}`}>{Number(ticker?.priceChange) > 0 ? "+" : ""} {ticker?.priceChange} {Number(ticker?.priceChangePercent)?.toFixed(2)}%</p></div><div className="flex flex-col">
<p className="font-medium text-xs text-slate-400 text-sm">24H High</p>
<p className="text-sm font-medium tabular-nums leading-5 text-sm ">{ticker?.high}</p>
<p className={`font-medium text-xs text-slate-400`}>24H Change</p>
<p className={` text-sm font-medium tabular-nums leading-5 text-greenText ${Number(ticker?.priceChange) > 0 ? "text-green-500" : "text-red-500"}`}>{Number(ticker?.priceChange) > 0 ? "+" : ""} {ticker?.priceChange} {Number(ticker?.priceChangePercent)?.toFixed(2)}%</p></div><div className="flex flex-col">
<p className="font-medium text-xs text-slate-400">24H High</p>
<p className="text-sm font-medium tabular-nums leading-5">{ticker?.high}</p>
</div>
<div className="flex flex-col">
<p className="font-medium text-xs text-slate-400 text-sm">24H Low</p>
<p className="text-sm font-medium tabular-nums leading-5 text-sm ">{ticker?.low}</p>
<p className="font-medium text-xs text-slate-400">24H Low</p>
<p className="text-sm font-medium tabular-nums leading-5">{ticker?.low}</p>
</div>
<button type="button" className="font-medium transition-opacity hover:opacity-80 hover:cursor-pointer text-base text-left" data-rac="">
<div className="flex flex-col">
<p className="font-medium text-xs text-slate-400 text-sm">24H Volume</p>
<p className="mt-1 text-sm font-medium tabular-nums leading-5 text-sm ">{ticker?.volume}
<p className="font-medium text-xs text-slate-400">24H Volume</p>
<p className="mt-1 text-sm font-medium tabular-nums leading-5">{ticker?.volume}
</p>
</div>
</button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
export const AskTable = ({ asks }: { asks: [string, string][] }) => {
let currentTotal = 0;
const relevantAsks = asks.slice(0, 15);
relevantAsks.reverse();
const asksWithTotal: [string, string, number][] = relevantAsks.map(([price, quantity]) => [price, quantity, currentTotal += Number(quantity)]);
const maxTotal = relevantAsks.reduce((acc, [_, quantity]) => acc + Number(quantity), 0);
asksWithTotal.reverse();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@

export const BidTable = ({ bids }: {bids: [string, string][]}) => {
let currentTotal = 0;
const relevantBids = bids.slice(0, 15);
let currentTotal = 0;
const relevantBids = bids.slice(-15);
relevantBids.reverse()
const bidsWithTotal: [string, string, number][] = relevantBids.map(([price, quantity]) => [price, quantity, currentTotal += Number(quantity)]);
const maxTotal = relevantBids.reduce((acc, [_, quantity]) => acc + Number(quantity), 0);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,62 @@ import { useEffect, useState } from "react";
import { getDepth, getKlines, getTicker, getTrades } from "../../utils/httpClient";
import { BidTable } from "./BidTable";
import { AskTable } from "./AskTable";
import { SignalingManager } from "@/app/utils/SignalingManager";
import { Depth as DepthType } from "@/app/utils/types";

export function Depth({ market }: {market: string}) {
export function Depth({ market }: { market: string }) {
const [bids, setBids] = useState<[string, string][]>();
const [asks, setAsks] = useState<[string, string][]>();
const [price, setPrice] = useState<string>();

useEffect(() => {
getDepth(market).then(d => {
setBids(d.bids.reverse());
setBids(d.bids);
setAsks(d.asks);
});

SignalingManager.getInstance().registerCallback("depth", (data: DepthType) => {
setBids(prevBids => {
const bidsAfterUpdate = [...(prevBids || [])];
for (let i = 0; i < bidsAfterUpdate.length - 1; i++) {
for (let j = 0; j < data?.bids.length - 1; j++) {
if (bidsAfterUpdate[i][0] == data.bids[j][0]) {
bidsAfterUpdate[i][0] = data.bids[j][0];
break;
}
}
}

return bidsAfterUpdate;
});

setAsks(prevAsks => {
const asksAfterUpdate = [...(prevAsks || [])];
for (let i = 0; i < asksAfterUpdate.length - 1; i++) {
for (let j = 0; j < data?.asks.length - 1; j++) {
if (asksAfterUpdate[i][0] == data.asks[j][0]) {
asksAfterUpdate[i][0] = data.asks[j][0];
break;
}
}
}

return asksAfterUpdate;
});
}, `DEPTH-${market}`);

SignalingManager.getInstance().sendMessage({ "method": "SUBSCRIBE", "params": [`depth.200ms.${market}`] });

getTicker(market).then(t => setPrice(t.lastPrice));
getTrades(market).then(t => setPrice(t[0].price));
// getKlines(market, "1h", 1640099200, 1640100800).then(t => setPrice(t[0].close));
}, [])


return () => {
SignalingManager.getInstance().deRegisterCallback("depth", `DEPTH-${market}`);
SignalingManager.getInstance().sendMessage({ "method": "UNSUBSCRIBE", "params": [`depth.200ms.${market}`] });
}
}, [market])

return <div>
<TableHeader />
{asks && <AskTable asks={asks} />}
Expand All @@ -31,8 +70,8 @@ export function Depth({ market }: {market: string}) {

function TableHeader() {
return <div className="flex justify-between text-xs">
<div className="text-white">Price</div>
<div className="text-slate-500">Size</div>
<div className="text-slate-500">Total</div>
</div>
<div className="text-white">Price</div>
<div className="text-slate-500">Size</div>
<div className="text-slate-500">Total</div>
</div>
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ export default function Page() {
<TradeView market={market as string} />
</div>
<div className="flex flex-col w-[250px] overflow-hidden">
<Depth market={market as string} />
<Depth market={market as string} />
</div>
</div>
</div>
<div className="w-[10px] flex-col border-slate-800 border-l"></div>
<div className="w-[1px] flex-col border-slate-800 border-l"></div>
<div>
<div className="flex flex-col w-[250px]">
<SwapUI market={market as string} />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Ticker } from "./types";
import { Depth, Ticker } from "./types";

export const BASE_URL = "wss://ws.backpack.exchange/"

Expand Down Expand Up @@ -42,14 +42,18 @@ export class SignalingManager {
}
console.log(newTicker);
callback(newTicker);
}
}
if (type === "depth") {
callback(message.data.data);
callback({ bids: message.data.b, asks: message.data.a });
}
});
}
}
}

public static getInstance(signalingServerUrl?: string) {
if (!this.instance) {
if (!this.instance) {
this.instance = new SignalingManager(signalingServerUrl);
}
return this.instance;
Expand Down
20 changes: 9 additions & 11 deletions week-1/day-2/binance-frontend/app/components/TradeView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function TradeView({
const init = async () => {
let klineData: KLine[] = [];
try {
klineData = await getKlines(market, "1h", Math.floor((new Date().getTime() - 1000 * 60 * 60 * 24 * 7) / 1000), Math.floor(new Date().getTime() / 1000));
klineData = await getKlines(market, "1h", Math.floor((new Date().getTime() - 1000 * 60 * 60 * 24 * 7) / 1000), Math.floor(new Date().getTime() / 1000));
} catch (e) { }

if (chartRef) {
Expand All @@ -24,21 +24,19 @@ export function TradeView({
}
const chartManager = new ChartManager(
chartRef.current,
[
...klineData?.map((x) => ({
close: parseFloat(x.close),
high: parseFloat(x.high),
low: parseFloat(x.low),
open: parseFloat(x.open),
timestamp: new Date(x.end),
})),
].sort((x, y) => (x.timestamp < y.timestamp ? -1 : 1)) || [],
klineData?.map((x) => ({
close: parseFloat(x.close),
high: parseFloat(x.high),
low: parseFloat(x.low),
open: parseFloat(x.open),
timestamp: new Date(x.end),
})).sort((x, y) => (x.timestamp < y.timestamp ? -1 : 1)) || [],
{
background: "#0e0f14",
color: "white",
}
);
//@ts-ignore
// @ts-ignore
chartManagerRef.current = chartManager;
}
};
Expand Down

0 comments on commit 01ac3c7

Please sign in to comment.