Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

import {useCallback, useEffect, useState} from "react"; import {ReadyState} from…

  1. 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)
    
    }
    
    1. В компоненте TradingCup запрашивается cup из useRustWsServer, сделать отрисовку канвас как в методах renderTrade renderTrades .

    2. renderTrade renderTrades то другой немного компонент с немного другими данными, нужно использовать его в TradingCup только с нашими данными type CupItem = { futures_price_micro: number; quantity: number; spot_quantity: number; side: string; };

    3. В методе renderTrade() показатели quantity и price_float перемножаются, чтобы получить объем в $. Нам это не нужно, будем выводить только quantity. Нужно все отрисовать в канвасе И использовать тоже самое соединение, что установлено в rustWsServer.ts обязательно везде typescript

  2. Assistant

    To implement the requirements mentioned:

    1. In the TradingCup component of the cup received from useRustWsServer, you need to render the canvas similar to the renderTrade and renderTrades methods.

    First, create a ref for the canvas and create the context for it in the TradingCup component. 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} />;
    };
    
    1. Since renderTrade and renderTrades methods use different data, you need to adapt them for the CupItem type.

    Create modified renderTrade and renderTrades functions 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
    }
    
    1. Ensure that the same WebSocket connection established in rustWsServer.ts is used, and utilize TypeScript throughout the code.

    As the WebSocket connection is already established and managed through the useRustWsServer hook, there is no need for additional modifications. The provided code snippets utilize TypeScript and should work as expected.

  3. User

    полностью напиши код, что где и как писать

  4. Assistant

    Here's the complete code for implementing the TradingCup component, along with the modified renderTrades and renderTrade functions.

    1. In your TradingCup.tsx file, 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
    }
    
    1. In your rustWsServer.ts file, make sure you export the CupItem type:
    export type CupItem = {
      futures_price_micro: number;
      quantity: number;
      spot_quantity: number;
      side: string;
    };
    

    With the provided code, the TradingCup component will render the canvas using the cup data from the useRustWsServer hook. The renderTrades and renderTrade functions 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 the renderTrade function, as it currently only contains a placeholder comment.

  5. User

    полностью напиши код

  6. Assistant

    Here's the full code for the TradingCup component with the rendering logic for the CupItem. Note that the styling and positioning of elements in the canvas may still need to be adjusted based on your requirements.

    1. Update the TradingCup.tsx file:
    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);
    }
    
    1. Make sure the CupItem type is exported in your rustWsServer.ts file:
    export type CupItem = {
      futures_price_float: number;
      price_micro: number;
      quantity: number;
      side: string;
    };
    

    This code provides a basic implementation of the TradingCup component, rendering the cup data from the useRustWsServer hook.

    The renderTrades function processes and renders the cup items in the canvas, and the renderTrade function 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.