let cup: {[key: number]: CupItem} = {};
let history: CupHistory = {
  ask: {},
  bid: {},
};
let isSubscribed = false;
let pair = "";
let aggregation = 10;
let publisherTimeoutInMs = 40;
let publisherIntervalId: any = null;
let wsConnection: WebSocket|null = null;
let bestBidPrice = 0;
let bestAskPrice = 0;
let pricePrecision = 1;
let priceStep = 1;
let quantityPrecision = 1;
let maxVolume = 1;
let fixedMaxVolume = 0;
let volumeIsFixed = false;
let volumeAsDollars = false;
let cameras: {[key: string]: number} = {};
let cameraStep = 4;
let cameraIsBlocked = false;
let unblockCameraTimerId: any = null;
let port: MessagePort|null = null;
let rowsCount: number = 60;
let quantityDivider = 1;
let priceDivider = 1;
let diffModifier = 2;
let cameraGoToCenter = false;

const connectToWs = (callback: () => void) => {
  if (wsConnection) {
    callback();

    return;
  }

  wsConnection = new WebSocket(`${process.env.NEXT_PUBLIC_RUST_WS_SERVER}`);

  wsConnection.onopen = () => {
    if (null !== wsConnection) {
      callback();
    }
  };

  wsConnection.onmessage = async(message: MessageEvent) => {
    if (!message.data) return;

    const data = JSON.parse(message.data);

    if (!data?.commands || data.commands.length === 0) return;

    const exchangeInitial = data?.commands?.find((item: any) => "ExchangeInitial" in item);
    const update = data.commands.find((item: any) => "undefined" !== typeof item.Update);

    if (exchangeInitial) {
      cup = exchangeInitial.ExchangeInitial.rows;
      pricePrecision = exchangeInitial.ExchangeInitial.params.pricePrecision;
      priceStep = exchangeInitial.ExchangeInitial.params.priceStep;
      quantityPrecision = exchangeInitial.ExchangeInitial.params.quantityPrecision;
      quantityDivider = Math.pow(10, quantityPrecision);
      priceDivider = Math.pow(10, pricePrecision);
    }

    if (update) {
      const futuresUpdate = update.Update.find((item: any) => item?.pair?.substring(0, 2) === "FT");

      if (pair === futuresUpdate.pair.substring(3)) {
        bestBidPrice = futuresUpdate.spread.bid;
        bestAskPrice = futuresUpdate.spread.ask;

        if (cameras[pair] === 0) {
          cameras[pair] = bestBidPrice;
        }

        Object.keys(futuresUpdate.history.ask)
        // @ts-ignore
          .forEach((key: number) => {
            history.ask[key] = futuresUpdate.history.ask[key];
          });

        Object.keys(futuresUpdate.history.bid)
        // @ts-ignore
          .forEach((key: number) => {
            history.bid[key] = futuresUpdate.history.bid[key];
          });

        Object
          .keys(futuresUpdate.rows)
          // @ts-ignore
          .forEach((key: number) => {
            cup[key] = futuresUpdate.rows[key];
          });
      }
    }
  };
};

const publish = () => {
  if (!isSubscribed) return;

  if (!cameras[pair]) {
    cameras[pair] = 0;
  }

  const zoomedTickSize = priceStep * aggregation;
  const centerCupPosition = parseInt((Math.ceil(bestAskPrice / zoomedTickSize) * zoomedTickSize).toFixed(0));
  const rows: {[key: number]: CupItem} = {};
  const historyRows: CupHistory = {ask: {}, bid: {}};
  const timeModifier = parseInt((publisherTimeoutInMs / 40).toFixed(0));
  diffModifier = Math.max(
    diffModifier,
    parseInt(((Math.abs(centerCupPosition - cameras[pair]) / zoomedTickSize) / (rowsCount / 2)).toFixed(0))
  );
  const cameraTopLime = centerCupPosition + rowsCount * .3 * zoomedTickSize;
  const cameraBottomLine = centerCupPosition - rowsCount * .3 * zoomedTickSize;
  const cameraIsVisible = cameras[pair] < cameraTopLime && cameras[pair] > cameraBottomLine;

  if (!cameraIsVisible && cameras[pair] !== 0 && !cameraIsBlocked) {
    cameraGoToCenter = true;
  }

  if (cameraGoToCenter) {
    cameras[pair] = cameras[pair] > centerCupPosition
      ? Math.max(centerCupPosition, cameras[pair] - zoomedTickSize * timeModifier * diffModifier)
      : Math.min(centerCupPosition, cameras[pair] + zoomedTickSize * timeModifier * diffModifier);

    if (cameras[pair] === centerCupPosition) {
      cameraGoToCenter = false;
    }
  } else {
    diffModifier = 2;
  }

  const startMicroPrice = cameras[pair] + rowsCount / 2 * zoomedTickSize - zoomedTickSize;

  for (let index = 0; index <= rowsCount; index++) {
    const microPrice = startMicroPrice - index * zoomedTickSize;

    if (microPrice < 0) continue;

    rows[microPrice] = cup[microPrice] || {};
    const bid = rows[microPrice]?.bid;
    const ask = rows[microPrice]?.ask;

    maxVolume = volumeAsDollars
      ? Math.max(maxVolume, (ask || bid || 0) / quantityDivider * (microPrice / priceDivider))
      : Math.max(maxVolume, (ask || bid || 0) / quantityDivider);
  }

  const startHistoryMicroPrice = bestAskPrice + 10 * zoomedTickSize - zoomedTickSize;

  for (let index = 0; index < 20; index++) {
    const historyMicroPrice = startHistoryMicroPrice - index * zoomedTickSize;

    if (historyMicroPrice < 0) continue;

    if (index <= 10) {
      historyRows.ask[historyMicroPrice] = history.ask[historyMicroPrice];
    } else {
      historyRows.bid[historyMicroPrice] = history.bid[historyMicroPrice];
    }
  }

  port?.postMessage({type: "set_camera", value: cameras[pair]});

  postMessage({
    type: "update_cup",
    cup: rows,
    history: historyRows,
    camera: cameras[pair],
    aggregation,
    bestBidPrice,
    bestAskPrice,
    pricePrecision,
    priceStep,
    quantityPrecision,
    rowsCount,
    maxVolume: volumeIsFixed
      ? fixedMaxVolume
      : maxVolume,
    volumeAsDollars,
  });
};

const publisherStart = () => {
  if (publisherIntervalId) {
    clearInterval(publisherIntervalId);
  }

  publisherIntervalId = setInterval(publish, publisherTimeoutInMs);
};

const publisherStop = () => {
  if (publisherIntervalId) {
    clearInterval(publisherIntervalId);
  }
};
  if (data && data?.type === "subscribe") {
    pair = data.pair;
    aggregation = data.zoom;
    isSubscribed = true;
    cameras[pair] = 0;
    maxVolume = 0;
    cup = {};
    publisherStart();

    if (wsConnection?.readyState === 3) {
      wsConnection = null;
    }

    connectToWs(() => {
      if (null === wsConnection) return;

      wsConnection.send(JSON.stringify({
        "commands": [
          {
            commandType: "SUBSCRIBE_SYMBOL",
            exchange: `FT:${pair}`,
            aggregation: aggregation,
          },
        ],
      }));
    });
  }


придумай как можно оптимизировать