у меня есть программа на js //Глобальный флаг, чтобы можно было остановить обновление…
- User
у меня есть программа на js
//Глобальный флаг, чтобы можно было остановить обновление let isUpdating = true;
document.getElementById('fetchButton').addEventListener('click', () => { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
// Устанавливаем флаг обновления в false и отправляем его в chrome.runtime isUpdating = false; chrome.runtime.sendMessage({ action: 'updateFlag', isUpdating }); chrome.scripting.executeScript({ target: { tabId: tabs[0].id }, func: async () => { console.log('Скрипт начал выполняться'); // Основная функция const processPositionsScript = async () => { // Получаем строки таблицы и пропускаем первые две const rows = Array.from(document.querySelectorAll('.by-table-row')).slice(2); // Пропускаем первые две строки let positions = rows.map((row, index) => { const cells = row.querySelectorAll('.by-table-cell'); const position = { index, orderPriceIV: cells[8]?.innerText.trim() || '', direction: cells[5]?.innerText.trim() || '', quantity: parseFloat(cells[9]?.innerText.trim()) || 0, orderPriceCell: cells[8], quantityCell: cells[9], askSize: parseFloat(cells[10]?.innerText.trim()) || 0, bidSize: parseFloat(cells[6]?.innerText.trim()) || 0, }; return position; }).filter(pos => pos.orderPriceIV && pos.direction); // Исключаем пустые записи console.log("Recycle position"); // Записываем информацию о позициях в sessionStorage positions.forEach((pos) => { if(sessionStorage.getItem(`quantity_${pos.index}`) === null) { const keyOrderPriceIV = `orderPriceIV_${pos.index}`; const keyQuantity = `quantity_${pos.index}`; console.log(`Записываю в sessionStorage: ${keyOrderPriceIV} = ${pos.orderPriceIV}`); console.log(`Записываю в sessionStorage: ${keyQuantity} = ${pos.quantity}`); sessionStorage.setItem(keyOrderPriceIV, pos.orderPriceIV); sessionStorage.setItem(keyQuantity, pos.quantity); } else console.log("Data has even") }); // Функция масштабирования количеств const scaleAllQuantities = () => { const groupedByOrderPrice = positions.reduce((acc, pos) => { if (!acc[pos.orderPriceIV]) acc[pos.orderPriceIV] = []; acc[pos.orderPriceIV].push(pos); return acc; }, {}); let scaleFactors = Object.values(groupedByOrderPrice).flatMap(group => { const buyGroup = group.filter(pos => pos.direction === 'Купить'); const sellGroup = group.filter(pos => pos.direction === 'Продать'); const calculateScale = (group, sizeKey) => { if (group.length === 0) return 1; const totalSize = group[0][sizeKey]; const totalQuantity = group.reduce((sum, pos) => sum + pos.quantity, 0); return totalQuantity > totalSize ? totalSize / totalQuantity : 1; }; return [ calculateScale(buyGroup, 'askSize'), calculateScale(sellGroup, 'bidSize'), ]; }); const minScaleFactor = Math.min(...scaleFactors, 1); console.log(`Минимальный коэффициент масштабирования: ${minScaleFactor * 100}%`); positions.forEach(pos => { pos.quantity *= minScaleFactor console.log("ORIGINAL: " + pos.quantity) pos.quantityCell.innerText = pos.quantity.toFixed(2); }); return minScaleFactor < 1; }; // Функция для обновления позиций const updatePositions = () => { positions.forEach(pos => { const cells = pos.quantityCell.parentElement.querySelectorAll('.by-table-cell'); Object.assign(pos, { orderPriceIV: cells[8]?.innerText.trim() || '', direction: cells[5]?.innerText.trim() || '', quantity: parseFloat(pos.quantityCell.innerText.trim()) || 0, askSize: parseFloat(cells[10]?.innerText.trim()) || 0, bidSize: parseFloat(cells[6]?.innerText.trim()) || 0, }); }); }; // Функция обработки позиций и нажатия кнопок const processAndClickButtons = async () => { // Пока есть позиции с количеством больше 0.001 while (positions.some(pos => pos.quantity >= 0.001)) { console.log('Обрабатываем позиции...'); positions.forEach(pos => { // Рассчитываем разницу между сохраненным и текущим количеством const diff = Math.abs(sessionStorage.getItem(`quantity_${pos.index}`) - pos.quantity); console.log("Index: " + pos.index + " Diff: " + diff + " SavedQuantity: " + sessionStorage.getItem(`quantity_${pos.index}`) + " NowQuantity: " + pos.quantity + " SavedOrderPrice " + sessionStorage.getItem(`orderPriceIV_${pos.index}`) + " OrderPrice " + pos.orderPriceIV + " askSIZE: " + pos.askSize + " bidSIZE: " + pos.bidSize ) // Проверяем, если разница между сохраненным количеством и текущим количеством меньше или равна размеру заявки if (diff <= (pos.direction === 'Купить' ? pos.askSize : pos.bidSize)) { // Если разница мала, позиция выполнена и количество становится 0 pos.quantity = 0; sessionStorage.setItem(`quantity_${pos.index}`, pos.quantity.toString()); } else { // Если разница велика, вычисляем новое количество, вычитая размер заявки const newQuantity = diff - (pos.direction === 'Купить' ? pos.askSize : pos.bidSize); // Обновляем количество на размер заявки (askSize для покупки, bidSize для продажи) 5% от текущей pos.quantity = (pos.direction === 'Купить' ? pos.askSize : pos.bidSize) * 0.95; sessionStorage.setItem(`quantity_${pos.index}`, newQuantity.toString()); } // Расчет новой цены с фактором случайной вариации const priceFactor = 1 + (Math.random() * 0.1 - 0.05); const getPrice = sessionStorage.getItem(`orderPriceIV_${pos.index}`) pos.orderPriceIV = (parseFloat(getPrice) * priceFactor).toFixed(2); // Обновляем цену и количество на странице pos.orderPriceCell.innerText = pos.orderPriceIV; pos.quantityCell.innerText = pos.quantity.toFixed(2); console.log("ASK: " + pos.askSize + " BID: " + pos.bidSize + " getQuantity: " + pos.quantity + " orderPrice " + pos.orderPriceIV) }); updatePositions(); await clickButtons(); } console.log('Все позиции обработаны.'); }; // Функция нажатия кнопок const clickButtons = async () => { const firstButton = document.querySelector('.by-button.by-builder-opr-btn.by-button--contained.by-button--xx-large.by-button--brand'); if (firstButton) firstButton.click(); await new Promise(resolve => setTimeout(resolve, 1000)); const secondButton = document.querySelector('.by-button.by-dialog__btn.by-button--contained.by-button--xx-large.by-button--brand'); if (secondButton) secondButton.click(); console.log("Все кнопки прожаты") }; // Запускаем обработку const requiresScaling = scaleAllQuantities(); if (requiresScaling) { await clickButtons(); await processAndClickButtons(); } else { await clickButtons(); console.log('Скрипт завершен без необходимости масштабирования.'); } // Меняем информацию о позициях в sessionStorage на null positions.forEach((pos) => { if(sessionStorage.getItem(`quantity_${pos.index}`) !== null) { const keyOrderPriceIV = `orderPriceIV_${pos.index}`; const keyQuantity = `quantity_${pos.index}`; console.log(`Записываю в sessionStorage: ${keyOrderPriceIV} = null`); console.log(`Записываю в sessionStorage: ${keyQuantity} = null`); sessionStorage.setItem(keyOrderPriceIV, null); sessionStorage.setItem(keyQuantity, null); } else console.log("Data has not recycle") }); }; await processPositionsScript(); }, }); // Устанавливаем флаг завершения обновления в true isUpdating = true; chrome.runtime.sendMessage({ action: 'updateFlag', isUpdating }); - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.