import {useCallback, useEffect, useState} from "react"; import {ReadyState} from…
- User
import {useCallback, useEffect, useState} from "react"; import {ReadyState} from "../enums/readyState";
type CupItem = { futures_price_micro: number; quantity: number; spot_quantity: number; side: string; };
export interface BestMicroPrice { buy: number; sell: number; }
export function useRustWsServer() { const [connection, setConnection] = useState<WebSocket|null>(null); const [readyState, setReadyState] = useState(0); const [cup, setCup] = useState<Array>([]); const [bestMicroPrice, setBestMicroPrice] = useState<BestMicroPrice|null>(null); const [maxVolume, setMaxVolume] = useState(1);
function splitCupSides(rawData: {[key: number]: CupItem}): Array { const sellRecords = []; const buyRecords = []; let max = 0;
for (const value of Object.values(rawData)) { if (value.side === "Buy") { buyRecords.push(value); } else if (value.side === "Sell") { sellRecords.push(value); } if (value.quantity > max) { max = value.quantity; } } sellRecords.sort((a, b) => { return b.futures_price_micro - a.futures_price_micro; }); buyRecords.sort((a, b) => { return b.futures_price_micro - a.futures_price_micro; }); setMaxVolume(max); return [...sellRecords, ...buyRecords];}
const cupSubscribe = useCallback((symbol: string, camera: number, zoom: number, rowCount: number) => { if (null === connection || readyState !== ReadyState.OPEN) return;
connection.send(JSON.stringify({ "commands": [ { commandType: "SUBSCRIBE_SYMBOL", symbol, camera: Math.round(camera / zoom) * zoom, zoom, rowCount, }, ], }));}, [readyState]);
const cupUnsubscribe = useCallback((symbol: string) => { if (null === connection || readyState !== ReadyState.OPEN) return;
connection.send(JSON.stringify({ "commands": [ { commandType: "UNSUBSCRIBE_SYMBOL", symbol, }, ], }));}, [readyState]);
useEffect(() => { const url = process.env.NEXT_PUBLIC_RUST_WS_SERVER;
if (url) { const ws = new WebSocket(url); setConnection(ws); }}, []);
useEffect(() => { if (null !== connection) {
connection.onmessage = (message: MessageEvent) => { if (!message.data) return; const data = JSON.parse(message.data); if (!data?.commands || data.commands.length === 0) return; const domUpdate = data.commands.find((item: any) => "undefined" !== typeof item.SymbolDomUpdate); if (!domUpdate) return; setCup(splitCupSides(domUpdate.SymbolDomUpdate.dom_rows)); setBestMicroPrice({ buy: domUpdate.SymbolDomUpdate.best_prices_futures.best_ask_micro, sell: domUpdate.SymbolDomUpdate.best_prices_futures.best_bid_micro, }); }; connection.onopen = () => { setReadyState(ReadyState.OPEN); }; connection.onclose = () => { setReadyState(ReadyState.CLOSED); }; }}, [connection]);
return { readyState, cupSubscribe, cupUnsubscribe, cup, maxVolume, bestMicroPrice, }; }
import {BestMicroPrice, useRustWsServer} from "../../hooks/rustWsServer"; import {createContext, Reducer, useEffect, useReducer, useRef, useState} from "react"; import CupDrawer from "../CupDrawer/CupDrawer"; import {IconButton} from "@mui/material"; import {AddRounded, RemoveRounded} from "@mui/icons-material"; import {ReadyState} from "../../enums/readyState"; import {useSelector} from "react-redux"; import {AppState} from "../../store/store";
interface CupConfigSubscription { pair: string | null; zoom: number; camera: number; rowCount: number; }
export const CupControlsContext = createContext<{ cupControlsState: any; cupControlsDispatcher: any; }>({ cupControlsState: null, cupControlsDispatcher: null, });
const TradingCup = () => { const symbol = useSelector((state: AppState) => state.screenerSlice.symbol); const {cup, bestMicroPrice, maxVolume, readyState, cupSubscribe, cupUnsubscribe} = useRustWsServer(); const precision = useSelector((state: AppState) => state.binancePrecision.futures[symbol.toUpperCase()]); const tickSize = useSelector((state: AppState) => state.binanceTickSize.futures[symbol.toUpperCase()]); const [cupConfig, setCupConfig] = useState({ pair: null, zoom: 10, camera: 0, rowCount: 40, });
useEffect(() => { if (symbol) { setCupConfig({ ...cupConfig, pair: symbol.toUpperCase(), camera: 0, }); } }, [symbol]);
useEffect(() => { if (readyState === ReadyState.OPEN) { if (null !== cupConfig.pair) { cupSubscribe( cupConfig.pair, cupConfig.camera, cupConfig.zoom, cupConfig.rowCount, ); } }
return () => { if (cupConfig.pair != null) { cupUnsubscribe(cupConfig.pair); } };}, [ cupConfig.pair, cupConfig.camera, cupConfig.zoom, cupConfig.rowCount, readyState, ]); return ( <> </> ); };
export default TradingCup;
import {each, get, map, reduce, range, clamp, reverse} from 'lodash' import {ESide} from "../../interfaces/interfaces"; import {abbreviateNumber, blendColors, blendRGBColors, getRatio, shadeColor} from "../../utils/utils"; import { bubbleSize, clusterBg, clusterGreen, clusterRed, clustersCountUI, deepGreen, deepRed, lightGreen, lightRed, maxClusterWidth, minuteMs, rowHeight, timeFrame, visibleClustersCount } from "../../constants/consts";
export default class ClustersClientControllers { xWidthInMs = timeFrame * clustersCountUI DOMBorderOffset = 0 abnormalDensities = 200 clusters = [] currentMin = 0 tempCluster = {} tempCurrentMin totals = [] tempTotal = {}
root: ClientController canvasHeight = 0 canvasWidth = 0 tradesArr: any = [] public bestPrices: any = null clustersCtx orderFeedCtx public cameraPrice = null public zoom = 10 clusterCellWidth virtualServerTime = null tradesFilterBySymbol = {} constructor(root) { this.root = root window['clusters'] = this this.restoreClusterSettings() } renderTrades = () => { this.clearOrderFeed(); reduce(this.tradesArr, (prev, cur, index) => { this.renderTrade(prev, cur, this.tradesArr.length - (index as any)) prev = cur console.log(prev); return prev }) } clearOrderFeed = () => { this.orderFeedCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight) } renderTrade = (prev, item, index) => { //const anomalyQty = this.root.instruments[this.root.selectedSymbol].anomalies.anomaly_qty; console.log(item); //price_float : 0.4139 price_micro : 4139000 quantity : 6 side : "Buy" time : 1685607036920
//if (size < 1) return; const ctx = this.orderFeedCtx let xPos = (this.canvasWidth - (index * (bubbleSize * 1.5))) - bubbleSize; const offsetFromTop = this.root.tradingDriverController.upperPrice - item.price_micro; const y = ((offsetFromTop / this.root.tradingDriverController.getZoomedStepMicro()) - 1) * rowHeight const label = abbreviateNumber(item.quantity * item.price_float) const {width: textWidth} = ctx.measureText(label); const itemUsdt = item.quantity * item.price_float; const tradeFilter = this.getTradeFilterBySymbol(this.getSymbol()) const maxUsdtBubbleAmount = tradeFilter * 30; const maxPixelBubbleAmount = 35; const realBubbleSize = (itemUsdt / maxUsdtBubbleAmount) * maxPixelBubbleAmount const size = clamp(realBubbleSize, (textWidth/2)+3, maxPixelBubbleAmount) const bubbleX = xPos; const bubbleY = y + 8; ctx.beginPath(); let bigRatio = (realBubbleSize / maxPixelBubbleAmount) / 3; bigRatio = bigRatio > 0.95 ? 0.95 : bigRatio; ctx.fillStyle = item.side === "Sell" ? deepGreen.lighten(bigRatio).toString() : deepRed.lighten(bigRatio).toString() ctx.strokeStyle = 'black'; ctx.arc(xPos, bubbleY, size, 0, 2 * Math.PI) ctx.fill(); ctx.stroke(); ctx.fillStyle = "#FFFFFF" ctx.fillText(label, bubbleX - (textWidth / 2), (bubbleY + (rowHeight / 2)) - 2) }-
В компоненте TradingCup запрашивается cup из useRustWsServer, сделать отрисовку канвас как в методах renderTrade renderTrades .
-
renderTrade renderTrades то другой немного компонент с немного другими данными, нужно использовать его в TradingCup только с нашими данными type CupItem = { futures_price_micro: number; quantity: number; spot_quantity: number; side: string; };
-
В методе renderTrade() показатели quantity и price_float перемножаются, чтобы получить объем в $. Нам это не нужно, будем выводить только quantity. Нужно все отрисовать в канвасе И использовать тоже самое соединение, что установлено в rustWsServer.ts обязательно везде typescript
-
- Assistant
To implement the requirements mentioned:
- In the
TradingCupcomponent of thecupreceived fromuseRustWsServer, you need to render the canvas similar to therenderTradeandrenderTradesmethods.
First, create a ref for the canvas and create the context for it in the
TradingCupcomponent. Then, update the canvas when the cup data changes.import {useEffect, useRef} from "react"; const TradingCup = () => { const canvasRef = useRef<HTMLCanvasElement>(null); const orderFeedCtx = useRef<CanvasRenderingContext2D | null>(null); useEffect(() => { if (canvasRef.current) { orderFeedCtx.current = canvasRef.current.getContext("2d"); } }, []); useEffect(() => { if (orderFeedCtx.current && cup.length > 0) { // Clear the canvas and render the trades orderFeedCtx.current.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height); renderTrades(cup, orderFeedCtx.current); } }, [cup]); return <canvas ref={canvasRef} />; };- Since
renderTradeandrenderTradesmethods use different data, you need to adapt them for theCupItemtype.
Create modified
renderTradeandrenderTradesfunctions that take the cup data and context as arguments.type CupItem = { futures_price_micro: number; quantity: number; spot_quantity: number; side: string; }; function renderTrades(cup: CupItem[], ctx: CanvasRenderingContext2D) { // Process and render cup items in the canvas cup.forEach((item, index) => { renderTrade(item, ctx, index); }); } function renderTrade(item: CupItem, ctx: CanvasRenderingContext2D, index: number) { // Rendering logic for a single cup item // Note that the quantity and price_float are not multiplied since we only need to display the quantity }- Ensure that the same WebSocket connection established in
rustWsServer.tsis used, and utilize TypeScript throughout the code.
As the WebSocket connection is already established and managed through the
useRustWsServerhook, there is no need for additional modifications. The provided code snippets utilize TypeScript and should work as expected. - In the
- User
полностью напиши код, что где и как писать
- Assistant
Here's the complete code for implementing the
TradingCupcomponent, along with the modifiedrenderTradesandrenderTradefunctions.- In your
TradingCup.tsxfile, replace the existing code with the following:
import React, {useEffect, useRef} from "react"; import {useRustWsServer, CupItem} from "../../hooks/rustWsServer"; const TradingCup = () => { const {cup} = useRustWsServer(); const canvasRef = useRef<HTMLCanvasElement>(null); const orderFeedCtx = useRef<CanvasRenderingContext2D | null>(null); useEffect(() => { if (canvasRef.current) { orderFeedCtx.current = canvasRef.current.getContext("2d"); } }, []); useEffect(() => { if (orderFeedCtx.current && cup.length > 0) { // Clear the canvas and render the trades orderFeedCtx.current.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height); renderTrades(cup, orderFeedCtx.current); } }, [cup]); return <canvas ref={canvasRef} />; }; export default TradingCup; function renderTrades(cup: CupItem[], ctx: CanvasRenderingContext2D) { // Process and render cup items in the canvas cup.forEach((item, index) => { renderTrade(item, ctx, index); }); } function renderTrade(item: CupItem, ctx: CanvasRenderingContext2D, index: number) { // Rendering logic for a single cup item // Note that the quantity and price_float are not multiplied since we only need to display the quantity }- In your
rustWsServer.tsfile, make sure you export theCupItemtype:
export type CupItem = { futures_price_micro: number; quantity: number; spot_quantity: number; side: string; };With the provided code, the
TradingCupcomponent will render the canvas using the cup data from theuseRustWsServerhook. TherenderTradesandrenderTradefunctions will process and render the cup items in the canvas. Note that you may still need to implement the rendering logic for a single cup item inside therenderTradefunction, as it currently only contains a placeholder comment. - In your
- User
полностью напиши код
- Assistant
Here's the full code for the
TradingCupcomponent with the rendering logic for theCupItem. Note that the styling and positioning of elements in the canvas may still need to be adjusted based on your requirements.- Update the
TradingCup.tsxfile:
import React, { useEffect, useRef } from "react"; import { useRustWsServer, CupItem } from "../../hooks/rustWsServer"; const TradingCup = () => { const { cup } = useRustWsServer(); const canvasRef = useRef<HTMLCanvasElement>(null); const orderFeedCtx = useRef<CanvasRenderingContext2D | null>(null); const canvasWidth = 600; const canvasHeight = 400; useEffect(() => { if (canvasRef.current) { canvasRef.current.width = canvasWidth; canvasRef.current.height = canvasHeight; orderFeedCtx.current = canvasRef.current.getContext("2d"); } }, []); useEffect(() => { if (orderFeedCtx.current && cup.length > 0) { // Clear the canvas and render the trades orderFeedCtx.current.clearRect(0, 0, canvasWidth, canvasHeight); renderTrades(cup, orderFeedCtx.current); } }, [cup]); return <canvas ref={canvasRef} />; }; export default TradingCup; function renderTrades(cup: CupItem[], ctx: CanvasRenderingContext2D) { // Process and render cup items in the canvas cup.forEach((item, index) => { renderTrade(item, ctx, index); }); } function renderTrade(item: CupItem, ctx: CanvasRenderingContext2D, index: number) { // Rendering logic for a single cup item const bubbleSize = 20; const rowHeight = 50; const label = item.quantity.toString(); const textWidth = ctx.measureText(label).width; const xPos = (index % 2 === 0) ? 10 : 310; const yPos = Math.floor(index / 2) * rowHeight + 20; ctx.fillStyle = item.side === "Buy" ? "green" : "red"; ctx.fillRect(xPos, yPos, bubbleSize, bubbleSize); ctx.fillStyle = "#FFFFFF"; ctx.fillText(label, xPos + (bubbleSize - textWidth) / 2, yPos + (bubbleSize / 2) + 5); }- Make sure the
CupItemtype is exported in yourrustWsServer.tsfile:
export type CupItem = { futures_price_float: number; price_micro: number; quantity: number; side: string; };This code provides a basic implementation of the
TradingCupcomponent, rendering the cup data from theuseRustWsServerhook.The
renderTradesfunction processes and renders the cup items in the canvas, and therenderTradefunction contains the rendering logic for a single cup item. This includes displaying the quantity as a label in the square bubble, with a green background for Buy items and a red background for Sell items. Note that the styling and positioning of the elements may be adjusted to suit your requirements. - Update the
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.