const calcTrade = (kLineList: KLineData[]): BarTradeEntity[] => { return…
- User
const calcTrade = (kLineList: KLineData[]): BarTradeEntity[] => { return bigOrders.map((order) => { let positionX: number = 0;
for (let bar = 0; bar < kLineList.length; bar++) { const kLine = kLineList[bar];
if (order.timestamp <= kLine.timestamp) {
if (positionX === 0) { positionX = bar - 1; }
break; } }
return { id: order.id, timestamp: order.timestamp, price: order.price, positionX, }; }); };
Здесь нужно в начале запустить один отдельный цикл по KLineList, который создаст объект, где ключами будут timestamp, а значениями bar.
В этом же цикле найти шаг между двумя timestamp.
Затем запустить второй цикл уже по bigOrders. Для расчета positionX нужно будет расчитать существующий timestamp и получить значение из объекта первого цикла.
Для расчета существующего timestamp нужно: Math.ceil(order.timestamp / timestampStep) * timestampStep
- Assistant
const calcTrade = (kLineList: KLineData[]): BarTradeEntity[] => { // Create an object mapping timestamps to bars const timestampToBarObj = {}; for (let bar = 0; bar < kLineList.length; bar++) { const kLine = kLineList[bar]; timestampToBarObj[kLine.timestamp] = bar; }
// Find the step between two timestamps const timestampStep = Math.ceil((kLineList[kLineList.length - 1].timestamp - kLineList[0].timestamp) / (kLineList.length - 1));
// Generate bar trade entities return bigOrders.map((order) => { let positionX: number = 0;
// Calculate the existing timestamp const existingTimestamp = Math.ceil(order.timestamp / timestampStep) * timestampStep; // Get the bar corresponding to the existing timestamp if (timestampToBarObj[existingTimestamp]) { positionX = timestampToBarObj[existingTimestamp] - 1; } return { id: order.id, timestamp: order.timestamp, price: order.price, positionX, };}); };
- User
drawTimestamp: ( ctx: CanvasRenderingContext2D, timestamp: number, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, theme: Theme, ) => { ctx.beginPath(); const currentTime = new Date().getTime();
const timeInSeconds = (currentTime - timestamp) / 1000; ctx.textBaseline = "middle"; ctx.font = `${tableIndicatorOptions().font.weight} ${tableIndicatorOptions().font.sizePx * dpiScale}px ${tableIndicatorOptions().font.family}`; ctx.textAlign = "right"; ctx.fillStyle = tableIndicatorOptions().font.color; ctx.fillText( `${timeInSeconds.toFixed(0)}`, (fullWidth * .8) - (tableIndicatorOptions().cell.paddingX * dpiScale), yPosition + cellHeight / 2, ); ctx.fill();},
нужно поправить формат отображения времени. Если больше 60 секунд, то отображать время минута и секунда, к примеру 1.07. если меньше 60 секунд отображать только секунда 5, 28 и т.д
- Assistant
drawTimestamp: ( ctx: CanvasRenderingContext2D, timestamp: number, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, theme: Theme, ) => { ctx.beginPath(); const currentTime = new Date().getTime();
const timeInSeconds = Math.floor((currentTime - timestamp) / 1000);
ctx.textBaseline = "middle"; ctx.font =
${tableIndicatorOptions().font.weight} ${tableIndicatorOptions().font.sizePx * dpiScale}px ${tableIndicatorOptions().font.family}; ctx.textAlign = "right"; ctx.fillStyle = tableIndicatorOptions().font.color;let formattedTime: string; if (timeInSeconds >= 60) { const minutes = Math.floor(timeInSeconds / 60); const seconds = timeInSeconds % 60; formattedTime =
${minutes}.${seconds.toString().padStart(2, "0")}; } else { formattedTime = timeInSeconds.toString(); }ctx.fillText( formattedTime, (fullWidth * .8) - (tableIndicatorOptions().cell.paddingX * dpiScale), yPosition + cellHeight / 2, ); ctx.fill(); },
- User
сделай это с помощью библиотеки day.js
- Assistant
import dayjs from 'dayjs';
drawTimestamp: ( ctx: CanvasRenderingContext2D, timestamp: number, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, theme: Theme, ) => { ctx.beginPath(); const currentTime = new Date().getTime();
const timeInSeconds = Math.floor((currentTime - timestamp) / 1000);
const duration = dayjs.duration(timeInSeconds, 'seconds'); let formattedTime: string;
if (duration.asMinutes() >= 1) { formattedTime =
${Math.floor(duration.asMinutes())}.${duration.seconds().toString().padStart(2, "0")}; } else { formattedTime = duration.seconds().toString(); }ctx.textBaseline = "middle"; ctx.font =
${tableIndicatorOptions().font.weight} ${tableIndicatorOptions().font.sizePx * dpiScale}px ${tableIndicatorOptions().font.family}; ctx.textAlign = "right"; ctx.fillStyle = tableIndicatorOptions().font.color;ctx.fillText( formattedTime, (fullWidth * .8) - (tableIndicatorOptions().cell.paddingX * dpiScale), yPosition + cellHeight / 2, ); ctx.fill(); },
- User
переписать формат времени на 00:06.24 через day.js
- Assistant
import dayjs from 'dayjs'; import duration from 'dayjs/plugin/duration';
// Extend dayjs with the duration plugin dayjs.extend(duration);
drawTimestamp: ( ctx: CanvasRenderingContext2D, timestamp: number, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, theme: Theme, ) => { ctx.beginPath(); const currentTime = new Date().getTime();
const timeInSeconds = Math.floor((currentTime - timestamp) / 1000);
const duration = dayjs.duration(timeInSeconds, 'seconds');
const formattedTime = dayjs.utc(duration.asMilliseconds()).format('mm:ss.SS');
ctx.textBaseline = "middle"; ctx.font =
${tableIndicatorOptions().font.weight} ${tableIndicatorOptions().font.sizePx * dpiScale}px ${tableIndicatorOptions().font.family}; ctx.textAlign = "right"; ctx.fillStyle = tableIndicatorOptions().font.color;ctx.fillText( formattedTime, (fullWidth * .8) - (tableIndicatorOptions().cell.paddingX * dpiScale), yPosition + cellHeight / 2, ); ctx.fill(); },
- User
import React, {useCallback, useEffect, useRef, useState} from "react"; import { init, dispose, Chart, DomPosition, IndicatorFigureStylesCallbackData, Indicator, IndicatorStyle, KLineData, utils, ActionType, Overlay, OverlayEvent, Nullable, YAxisType, } from "klinecharts";
export const CandleChart = ({ candles, uniqueId, symbolName, }: CandleChartProps) => { const chart = useRef<ExtendedChart|null>(null); const paneId = useRef(""); const [figureId, setFigureId] = useState(""); const ref = useRef(null); return (<> <Box ref={ref} id={
chart-${uniqueId}} width={!showToolbar ? "calc(100% - 5px)" : screenerPage ? "calc(100% - 5px)" : "calc(100% - 55px)"} height="100%" position="relative" > </>); };как мне в этой библиотеке достать данные которые отображаются на оси y - yAxis
- Assistant
import React, { useCallback, useEffect, useRef, useState } from "react"; import { init, dispose, Chart, DomPosition, IndicatorFigureStylesCallbackData, Indicator, IndicatorStyle, KLineData, utils, ActionType, Overlay, OverlayEvent, Nullable, YAxisType, } from "klinecharts";
export const CandleChart = ({ candles, uniqueId, symbolName, }: CandleChartProps) => { const chart = useRef<ExtendedChart | null>(null); const paneId = useRef(""); const [figureId, setFigureId] = useState(""); const ref = useRef(null);
useEffect(() => { if (ref.current) { // Initialize the chart chart.current = init(ref.current); // Set the chart data chart.current.setData(candles); // Render the chart chart.current.render(); }
return () => { // Dispose the chart when component unmounts if (chart.current) { chart.current.dispose(); } };}, []);
const getYAxisData = useCallback(() => { if (chart.current) { // Get the Y-axis data const yData = chart.current.getYAxisData(); console.log("Y-axis data:", yData); } }, []);
- User
- Assistant
Измените тип useRef на ExtendedChart или Chart:
const chart = useRef<Chart | null>(null);Затем при вызове методов или свойств из chart.current, удостоверьтесь, что они доступны в интерфейсе Chart или ExtendedChart.
- User
как мне в этой библиотеке достать данные которые отображаются на оси y - yAxis !!!
- Assistant
Для получения данных, которые отображаются на оси Y (yAxis), вы можете использовать метод
getYAxisDataиз объектаchart.current. Этот метод возвращает массив данных оси Y.const yAxisData = chart.current?.getYAxisData(); console.log(yAxisData);Обратите внимание, что
chart.currentможет бытьnull, поэтому мы используем оператор опциональной цепочки?., чтобы избежать ошибок, еслиchart.currentотсутствует.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.