const marginForOrders = 40; const cupDrawer = { clear: (ctx: CanvasRenderingContext2D,…
- User
const marginForOrders = 40;
const cupDrawer = { clear: (ctx: CanvasRenderingContext2D, size: CanvasSize) => { ctx.clearRect(0, 0, size.width, size.height); }, draw: ( ctx: CanvasRenderingContext2D, size: CanvasSize, dpiScale: number, bestBidPrice: number, bestAskPrice: number, maxVolume: number, pricePrecision: number, quantityPrecision: number, priceStep: number, zoom: number, rowCount: number, camera: number, cellHeight: number, zoomedBestMicroPrice: any, darkMode: boolean, volumeAsDollars: boolean, cup: {[key: number]: CupItem}, history: CupHistory, positions: Record<string, AccountPosition>, openOrders: Record<string, AccountOpenOrder>, symbol: string, ) => { const zoomedTickSize = priceStep * zoom; const startMicroPrice = camera + rowCount / 2 * zoomedTickSize - zoomedTickSize; const quantityDivider = Math.pow(10, quantityPrecision); const priceDivider = Math.pow(10, pricePrecision); const fullWidthAsMarginForOrders = size.width - (marginForOrders * dpiScale);
for (let index = 0; index <= rowCount; index++) { const microPrice = startMicroPrice - index * zoomedTickSize; if (microPrice < 0) continue; const item = cup[microPrice] || {}; let side = "undefined" !== typeof item?.bid ? "bid" : "undefined" !== typeof item?.ask ? "ask" : ""; if ("" === side || (!item?.bid && !item.ask)) { side = (microPrice >= (zoomedBestMicroPrice?.buy || zoomedBestMicroPrice?.sell || 0) ? "ask" : "bid"); } const historyItemAsk = history.ask[microPrice] || {}; const historyItemBid = history.bid[microPrice] || {}; let historyItem: CupHistoryItem; side === "ask" ? historyItem = historyItemAsk : historyItem = historyItemBid; const yPosition = cellHeight * index; const quantity = volumeAsDollars ? ((side === "bid" ? item?.bid || 0 : item?.ask || 0) / quantityDivider) * (microPrice / priceDivider) : (side === "bid" ? item?.bid || 0 : item?.ask || 0) / quantityDivider; const isBestPrice = cupTools.isBestPrice( side, microPrice, zoomedBestMicroPrice, ); if ((microPrice / zoomedTickSize) % 5 === 0) { ctx.beginPath(); ctx.strokeStyle = darkMode ? "#232425" : "#dddedf"; ctx.lineWidth = Math.max(1, dpiScale); ctx.moveTo((marginForOrders * dpiScale), yPosition); ctx.lineTo(size.width, yPosition); ctx.stroke(); } if (Object.keys(historyItem).length !== 0) { cupDrawer.drawHistoryTcks( ctx, historyItem.tcks, cupTools.microPriceToReal(microPrice, pricePrecision), quantity, side, maxVolume, isBestPrice, yPosition, cellHeight, fullWidthAsMarginForOrders, dpiScale, quantityDivider, darkMode ); } cupDrawer.drawCell( ctx, quantity, side, maxVolume, isBestPrice, yPosition, cellHeight, fullWidthAsMarginForOrders, dpiScale, darkMode ); if (isBestPrice) { cupDrawer.drawFill( ctx, quantity, side, maxVolume, yPosition, cellHeight, fullWidthAsMarginForOrders, dpiScale, darkMode ); } cupDrawer.drawPrice( ctx, cupTools.microPriceToReal(microPrice, pricePrecision), side, isBestPrice, yPosition, cellHeight, fullWidthAsMarginForOrders, dpiScale, darkMode ); cupDrawer.drawQuantity( ctx, cupTools.abbreviateNumber(quantity), side, isBestPrice, yPosition, cellHeight, fullWidthAsMarginForOrders, dpiScale, darkMode ); } if(openOrders) { let filteredOrders = Object.values(openOrders).filter(o => o.symbol === symbol); if(filteredOrders.length > 0) { filteredOrders.forEach(order => { return cupDrawer.drawOpenOrder( ctx, order, Object.keys(cup), priceDivider, cellHeight, dpiScale, darkMode ); }); } } if(positions && positions[symbol]) { const position = positions[symbol]; cupDrawer.drawPosition( ctx, position, priceDivider, Object.keys(cup), bestBidPrice, bestAskPrice, cellHeight, size, dpiScale, darkMode ); } - Assistant
- User
if (Object.keys(historyItem.tcks).length !== 0) { //TypeError: Cannot convert undefined or null to object
- Assistant
Этот TypeError возникает, потому что
historyItem.tcksравноundefinedилиnull, а не объекту, и попытка вызвать методObject.keys()на нем вызывает эту ошибку.Для исправления этой ошибки можно добавить проверку на
undefinedилиnull, прежде чем вызывать методObject.keys(). Например:if (historyItem.tcks && Object.keys(historyItem.tcks).length !== 0) { cupDrawer.drawHistoryTcks( ctx, historyItem.tcks, cupTools.microPriceToReal(microPrice, pricePrecision), quantity, side, maxVolume, isBestPrice, yPosition, cellHeight, fullWidthAsMarginForOrders, dpiScale, quantityDivider, darkMode ); }Таким образом, функция
cupDrawer.drawHistoryTcks()будет вызвана только тогда, когдаhistoryItem.tcksявляется объектом и имеет непустое количество ключей. - User
let side: "bid" | "ask" = item.bid !== undefined ? "bid" : item.ask !== undefined ? "ask" : ""; //Type '"bid" | "ask" | ""' is not assignable to type '"bid" | "ask"'. Type '""' is not assignable to type '"bid" | "ask"'.ts(2322) let side: "bid" | "ask"
- Assistant
Ошибка возникает из-за неправильного присвоения значения переменной
side, которая должна быть типа"bid" | "ask". В данный момент, вариант""также допускается.для исправления ошибки, можно добавить условие else в конце, чтобы присвоить переменной
"", если ниitem.bid, ниitem.askне определены.let side: "bid" | "ask" = item.bid !== undefined ? "bid" : item.ask !== undefined ? "ask" : ""; if (side === "bid" || side === "ask") { // continue with the rest of the code } else { side = ""; }Теперь
sideбудет иметь значение"bid","ask"или"". - User
let historyQuantityTotal: HistoryQuantityTotalType = { ask: 0, bid: 0, };
let sideExceeds;
Если объем асков или бидов перевешивает другую сторону в 3 раза и более, нужно возвращать тот, который превышает, иначе null
- Assistant
Для решения этой задачи можно использовать следующий подход:
// Вычисляем суммарный объем асков и бидов let historyQuantityTotal: HistoryQuantityTotalType = { ask: 0, bid: 0, }; // Вычисляем максимальный объем между асками и бидами let maxQuantity = Math.max(historyQuantityTotal.ask, historyQuantityTotal.bid); // Проверяем условие перевеса объема if ((maxQuantity / 3) >= historyQuantityTotal.ask || (maxQuantity / 3) >= historyQuantityTotal.bid) { // Определяем, какая сторона превышает объем и сохраняем значение в переменной sideExceeds sideExceeds = historyQuantityTotal.ask > historyQuantityTotal.bid ? "ask" : "bid"; } else { sideExceeds = null; } // Возвращаем значение sideExceeds return sideExceeds;В этом коде мы вычисляем суммарный объем асков и бидов в переменной
historyQuantityTotal. Затем мы находим максимальный объем между асками и бидами с помощьюMath.max(). После этого мы проверяем условие перевеса объема, где мы сравниваем максимальный объем со значением, равным трети этого объема. Если условие выполняется, то определяем, какая сторона превышает объем (если это аски, будет больше, если это биды, будет больше) и сохраняем значение в переменной . Если условие не выполняется, присваиваем переменной значение . В конце возвращаем значение .
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.