最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - highcharts stock-tools not working(next.js) - Stack Overflow

programmeradmin0浏览0评论

I was using highcharts in my next.js project and everything was fine. but suddenly I noticed the stock tools are not working. they are showing and I can select them but they are not working and they have no effect on chart???

"use client";
import React, { useEffect } from "react";
import { Sidebar } from "@/components/sidebar-component";
import { usePathname } from "next/navigation";
import Script from "next/script";
import { SelectSymbolComponent } from "@/components/select-symbol-component";
import { ModeToggle } from "@/components/theme-change-button";

import Highcharts from "highcharts";
import HighchartsStock from "highcharts/modules/stock";
import StockTools from "highcharts/modules/stock-tools";
import HighchartsIndicators from "highcharts/indicators/indicators";
import HighchartsStockTools from "highcharts/modules/stock-tools";
import HighchartsExporting from "highcharts/modules/exporting";
import "highcharts/css/stocktools/gui.css";
import { px } from "framer-motion";

HighchartsStock(Highcharts);
HighchartsIndicators(Highcharts);
HighchartsStockTools(Highcharts);
StockTools(Highcharts);
HighchartsExporting(Highcharts);

export default function () {
  const pathname = usePathname();

  return (
    <>
      <link
        rel="stylesheet"
        type="text/css"
        href=".css"
      />
      <link
        rel="stylesheet"
        type="text/css"
        href=".css"
      />
      <div className="flex flex-col h-screen w-full overflow-hidden">
        <div className="flex flex-grow overflow-hidden">
          <Sidebar />
          <div className="flex-1 overflow-hidden">
            <Chart currentPage={pathname} />
          </div>
        </div>
      </div>
      <div className="fixed right-5 bottom-4 z-50">
        <ModeToggle />
      </div>

      {/* Highcharts scripts */}
      <Script
        src=".js"
        strategy="afterInteractive"
      />
      <Script
        src=".js"
        strategy="afterInteractive"
      />
      <Script
        src=".js"
        strategy="afterInteractive"
      />
      <Script
        src=".js"
        strategy="afterInteractive"
      />
    </>
  );
}

const Chart = ({ currentPage }: { currentPage: string }) => {
  const pageTitle = currentPage.split("/").pop() || "Chart";

  useEffect(() => {
    const loadChart = async () => {
      const data = await fetch(
        ".json"
      ).then((response) => response.json());

      const yearChangePoints = findYearChangePoints(data);

      const ohlc: [number, number, number, number, number][] = [];
      const volume: [number, number][] = [];
      data.forEach((dataPoint: number[]) => {
        ohlc.push([
          dataPoint[0],
          dataPoint[1],
          dataPoint[2],
          dataPoint[3],
          dataPoint[4],
        ]);
        volume.push([dataPoint[0], dataPoint[5]]);
      });

      if (typeof Highcharts !== "undefined") {
        const chart = Highcharts.stockChart("container", {
          chart: {
            borderRadius: 10,
            backgroundColor: "#f0f0f0",
            height: "50%",
          },
          stockTools: {
            gui: {
              enabled: true,
              buttons: [
                "indicators",
                "separator",
                "simpleShapes",
                "lines",
                "crookedLines",
                "measure",
                "advanced",
                "toggleAnnotations",
                "separator",
                "verticalLabels",
                "flags",
                "separator",
                "zoomChange",
                "fullScreen",
                "typeChange",
                "separator",
                "currentPriceIndicator",
                "saveChart",
              ],
            },
          },
          yAxis: [
            { labels: { align: "left" }, resize: { enabled: true } },
            { labels: { align: "left" }, top: "80%", height: "20%", offset: 0 },
          ],
          xAxis: {
            plotLines: yearChangePoints.map((point) => ({
              color: "#000000",
              width: 1,
              value: point,
              label: {
                text: new Date(point).getFullYear().toString(),
                rotation: 90,
                align: "left",
                x: 10,
                style: { color: "#000000" },
              },
            })),
          },
          tooltip: {
            enabled: true,
            shared: true,
            formatter: function () {
              return `<b>${this.x}</b><br/>${this.points
                .map(
                  (point: any) =>
                    `<span style="color:${point.series.color}">●</span> ${
                      point.series.name
                    }: ${point.y}`
                )
                .join("<br/>")}`;
            },
          },
          series: [
            {
              type: "candlestick",
              id: "aapl-ohlc",
              name: "AAPL Stock Price",
              data: ohlc,
            },
            {
              type: "column",
              id: "aapl-volume",
              name: "AAPL Volume",
              data: volume,
              yAxis: 1,
            },
          ],
        });

        chart.reflow();
      }
    };

    loadChart();
  }, []);

  return (<div id="container" className="chart z-50 h-2" style={{ height: '1000px' }} />
  );
};



function findYearChangePoints(data: [number, number][]): number[] {
  const yearChangePoints: number[] = [];
  let currentYear = new Date(data[0][0]).getFullYear();

  for (let i = 1; i < data.length; i++) {
    const date = new Date(data[i][0]);
    if (date.getFullYear() !== currentYear) {
      yearChangePoints.push(data[i][0]);
      currentYear = date.getFullYear();
    }
  }

  return yearChangePoints;
}

and I don't know what to try I was trying anything checking of the js and css files are loaded correctly or what changing functions and code asking ai like chatgpt and others but they didn't help at all just made the code worse...so if you know or can guess what's the problem please help thank you

I was using highcharts in my next.js project and everything was fine. but suddenly I noticed the stock tools are not working. they are showing and I can select them but they are not working and they have no effect on chart???

"use client";
import React, { useEffect } from "react";
import { Sidebar } from "@/components/sidebar-component";
import { usePathname } from "next/navigation";
import Script from "next/script";
import { SelectSymbolComponent } from "@/components/select-symbol-component";
import { ModeToggle } from "@/components/theme-change-button";

import Highcharts from "highcharts";
import HighchartsStock from "highcharts/modules/stock";
import StockTools from "highcharts/modules/stock-tools";
import HighchartsIndicators from "highcharts/indicators/indicators";
import HighchartsStockTools from "highcharts/modules/stock-tools";
import HighchartsExporting from "highcharts/modules/exporting";
import "highcharts/css/stocktools/gui.css";
import { px } from "framer-motion";

HighchartsStock(Highcharts);
HighchartsIndicators(Highcharts);
HighchartsStockTools(Highcharts);
StockTools(Highcharts);
HighchartsExporting(Highcharts);

export default function () {
  const pathname = usePathname();

  return (
    <>
      <link
        rel="stylesheet"
        type="text/css"
        href="https://code.highcharts/css/stocktools/gui.css"
      />
      <link
        rel="stylesheet"
        type="text/css"
        href="https://code.highcharts/css/annotations/popup.css"
      />
      <div className="flex flex-col h-screen w-full overflow-hidden">
        <div className="flex flex-grow overflow-hidden">
          <Sidebar />
          <div className="flex-1 overflow-hidden">
            <Chart currentPage={pathname} />
          </div>
        </div>
      </div>
      <div className="fixed right-5 bottom-4 z-50">
        <ModeToggle />
      </div>

      {/* Highcharts scripts */}
      <Script
        src="https://code.highcharts/stock/highstock.js"
        strategy="afterInteractive"
      />
      <Script
        src="https://code.highcharts/modules/stock-tools.js"
        strategy="afterInteractive"
      />
      <Script
        src="https://code.highcharts/modules/drag-panes.js"
        strategy="afterInteractive"
      />
      <Script
        src="https://code.highcharts/modules/full-screen.js"
        strategy="afterInteractive"
      />
    </>
  );
}

const Chart = ({ currentPage }: { currentPage: string }) => {
  const pageTitle = currentPage.split("/").pop() || "Chart";

  useEffect(() => {
    const loadChart = async () => {
      const data = await fetch(
        "https://demo-live-data.highcharts/aapl-ohlcv.json"
      ).then((response) => response.json());

      const yearChangePoints = findYearChangePoints(data);

      const ohlc: [number, number, number, number, number][] = [];
      const volume: [number, number][] = [];
      data.forEach((dataPoint: number[]) => {
        ohlc.push([
          dataPoint[0],
          dataPoint[1],
          dataPoint[2],
          dataPoint[3],
          dataPoint[4],
        ]);
        volume.push([dataPoint[0], dataPoint[5]]);
      });

      if (typeof Highcharts !== "undefined") {
        const chart = Highcharts.stockChart("container", {
          chart: {
            borderRadius: 10,
            backgroundColor: "#f0f0f0",
            height: "50%",
          },
          stockTools: {
            gui: {
              enabled: true,
              buttons: [
                "indicators",
                "separator",
                "simpleShapes",
                "lines",
                "crookedLines",
                "measure",
                "advanced",
                "toggleAnnotations",
                "separator",
                "verticalLabels",
                "flags",
                "separator",
                "zoomChange",
                "fullScreen",
                "typeChange",
                "separator",
                "currentPriceIndicator",
                "saveChart",
              ],
            },
          },
          yAxis: [
            { labels: { align: "left" }, resize: { enabled: true } },
            { labels: { align: "left" }, top: "80%", height: "20%", offset: 0 },
          ],
          xAxis: {
            plotLines: yearChangePoints.map((point) => ({
              color: "#000000",
              width: 1,
              value: point,
              label: {
                text: new Date(point).getFullYear().toString(),
                rotation: 90,
                align: "left",
                x: 10,
                style: { color: "#000000" },
              },
            })),
          },
          tooltip: {
            enabled: true,
            shared: true,
            formatter: function () {
              return `<b>${this.x}</b><br/>${this.points
                .map(
                  (point: any) =>
                    `<span style="color:${point.series.color}">●</span> ${
                      point.series.name
                    }: ${point.y}`
                )
                .join("<br/>")}`;
            },
          },
          series: [
            {
              type: "candlestick",
              id: "aapl-ohlc",
              name: "AAPL Stock Price",
              data: ohlc,
            },
            {
              type: "column",
              id: "aapl-volume",
              name: "AAPL Volume",
              data: volume,
              yAxis: 1,
            },
          ],
        });

        chart.reflow();
      }
    };

    loadChart();
  }, []);

  return (<div id="container" className="chart z-50 h-2" style={{ height: '1000px' }} />
  );
};



function findYearChangePoints(data: [number, number][]): number[] {
  const yearChangePoints: number[] = [];
  let currentYear = new Date(data[0][0]).getFullYear();

  for (let i = 1; i < data.length; i++) {
    const date = new Date(data[i][0]);
    if (date.getFullYear() !== currentYear) {
      yearChangePoints.push(data[i][0]);
      currentYear = date.getFullYear();
    }
  }

  return yearChangePoints;
}

and I don't know what to try I was trying anything checking of the js and css files are loaded correctly or what changing functions and code asking ai like chatgpt and others but they didn't help at all just made the code worse...so if you know or can guess what's the problem please help thank you

Share Improve this question edited Nov 21, 2024 at 21:43 Amir mohammad Sedaghat nia asked Nov 20, 2024 at 0:16 Amir mohammad Sedaghat niaAmir mohammad Sedaghat nia 116 bronze badges 6
  • Please reproduce this problem in an online editor I could work on. Feel free to use this demo as a basic template: stackblitz/edit/react-4ded5d?file=index.js – Dominik Chudy Commented Nov 20, 2024 at 9:01
  • @dominik-chudy I made a public repo for that you can try it using github/AMSN81/highhcharts_stock. I tried to add the repo to stackblitz but it had some weird bugs which I didn't have when I tried it in my localhost and sorry that I couldn't use an online editor. – Amir mohammad Sedaghat nia Commented Nov 20, 2024 at 12:24
  • @DominikChudy you can also try it using: stackblitz/~/github/AMSN81/highhcharts_stock?file=app/… – Amir mohammad Sedaghat nia Commented Nov 20, 2024 at 21:38
  • Unfortunately I'm getting an error: Module not found: Can't resolve 'highcharts' Still I found an interesting topic on HC forum about stocktools in next.js that might be really helpful to you, check it out here: highcharts/forum/viewtopic.php?t=46006 – Dominik Chudy Commented Nov 21, 2024 at 15:13
  • @DominikChudy actually it works. I checked it and it shows some errors but if you wait it will show up. personally waited for about 1~2 minutes and it showed up in stackblitz. – Amir mohammad Sedaghat nia Commented Nov 21, 2024 at 20:44
 |  Show 1 more comment

1 Answer 1

Reset to default 0

UPDATE it's fixed I fot to place
<script src="https://code.highcharts/modules/annotations-advanced.js"></script>

发布评论

评论列表(0)

  1. 暂无评论