у меня есть расширение для google на JS manifest { "manifestversion": 3, "name": "Info…
- User
у меня есть расширение для google на JS manifest { "manifest_version": 3, "name": "Info Extractor", "version": "1.0", "action": { "default_popup": "popup.html", "default_icon": "icons/icon128.png" }, "permissions": ["activeTab", "scripting"], "background": { "service_worker": "background.js" } } background function updateData() { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { if (tabs.length === 0) return; // Нет активной вкладки chrome.scripting.executeScript({ target: { tabId: tabs[0].id }, func: () => { document.querySelectorAll('.by-table-row').forEach((row) => { const cells = row.querySelectorAll('.by-table-cell'); const orderPriceCell = cells[8]; if (cells[5].innerText === 'Купить' && cells[11]) { orderPriceCell.innerText = cells[11].innerText; // Ставим "Цену предложения" } else if (cells[5].innerText === 'Продать' && cells[7]) { orderPriceCell.innerText = cells[7].innerText; // Ставим "Цену спроса" } }); }, }); }); } // Запускаем обновление данных каждую секунду setInterval(updateData, 500); popup Отправить в книгу ордеров. Click Original Button Введите новое значение Обновить значение popup document.getElementById('fetchButton').addEventListener('click', () => { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { chrome.scripting.executeScript({ target: { tabId: tabs[0].id }, func: () => { console.log('Скрипт начал выполняться'); // Получаем все строки таблицы const rows = Array.from(document.querySelectorAll('.by-table-row')); let positions = []; // Пропускаем первые две строки rows.forEach((row, index) => { if (index < 2) return; const cells = row.querySelectorAll('.by-table-cell'); const orderPriceIV = cells[8]?.innerText.trim(); const direction = cells[5]?.innerText.trim(); const quantityCell = cells[9]; // Ссылка на DOM элемент для quantity const quantity = parseFloat(quantityCell.innerText.trim()) || 0; const askSize = parseFloat(cells[10]?.innerText.trim(), 10) || 0; const bidSize = parseFloat(cells[6]?.innerText.trim(), 10) || 0; if (orderPriceIV && direction) { let position = { orderPriceIV, direction, quantity, quantityCell, // Сохраняем ссылку на DOM элемент askSize, bidSize, }; positions.push(position); } }); console.log('Собранные позиции:', positions); // Функция для изменения количества по минимальному коэффициенту const scaleAllQuantities = (positions) => { let scaleFactors = []; // Группируем позиции по цене ордера const groupedByOrderPrice = positions.reduce((acc, position) => { if (!acc[position.orderPriceIV]) { acc[position.orderPriceIV] = []; } acc[position.orderPriceIV].push(position); return acc; }, {}); Object.keys(groupedByOrderPrice).forEach((orderPrice) => { const group = groupedByOrderPrice[orderPrice]; console.log(
Группа для цены ${orderPrice}:, group); const buyGroup = group.filter(pos => pos.direction === 'Купить'); const sellGroup = group.filter(pos => pos.direction === 'Продать'); // Вычисляем коэффициенты масштабирования для каждой группы if (buyGroup.length > 0) { const totalAskSize = buyGroup[0].askSize; // Предполагаем одинаковый размер аска для всех в группе const totalQuantity = buyGroup.reduce((sum, pos) => sum + pos.quantity, 0); if (totalQuantity > totalAskSize) { scaleFactors.push(totalAskSize / totalQuantity); } } if (sellGroup.length > 0) { const totalBidSize = sellGroup[0].bidSize; // Предполагаем одинаковый размер бида для всех в группе const totalQuantity = sellGroup.reduce((sum, pos) => sum + pos.quantity, 0); if (totalQuantity > totalBidSize) { scaleFactors.push(totalBidSize / totalQuantity); } } }); // Находим минимальный коэффициент масштабирования const minScaleFactor = Math.min(...scaleFactors, 1); console.log(); // Применяем минимальный коэффициент масштабирования ко всем позициям positions.forEach(pos => { const newQuantity = pos.quantity * minScaleFactor; pos.quantity = newQuantity; pos.quantityCell.innerText = newQuantity.toFixed(2); // Обновляем текст элемента на странице }); return minScaleFactor < 1; }; // Вызов функции scaleAllQuantities и контроль выполнения let requiredScaling = scaleAllQuantities(positions); if (!requiredScaling) { console.log('Все условия выполнены, продолжаем выполнение скрипта.'); const firstButton = document.querySelector('.by-button.by-builder-opr-btn.by-button--contained.by-button--xx-large.by-button--brand'); if (firstButton) { firstButton.click(); setTimeout(() => { const secondButton = document.querySelector('.by-button.by-dialog__btn.by-button--contained.by-button--xx-large.by-button--brand'); if (secondButton) { secondButton.click(); } else { console.log('Вторая кнопка не найдена'); } }, 1000); } else { console.log('Первая кнопка не найдена'); } } else { console.log('Количество в позициях было изменено для соответствия доступным размерам.'); // Выполнить программу, нажатие кнопок const firstButton = document.querySelector('.by-button.by-builder-opr-btn.by-button--contained.by-button--xx-large.by-button--brand'); if (firstButton) { firstButton.click(); setTimeout(() => { const secondButton = document.querySelector('.by-button.by-dialog__btn.by-button--contained.by-button--xx-large.by-button--brand'); if (secondButton) { secondButton.click(); } else { console.log('Вторая кнопка не найдена'); } }, 1000); } else { console.log('Первая кнопка не найдена'); } } } }); }); }); document.getElementById('simulateButton').addEventListener('click', () => { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { chrome.scripting.executeScript({ target: { tabId: tabs[0].id }, func: () => { const button = document.querySelector('.by-button.by-builder-opr-btn.by-button--contained.by-button--xx-large.by-button--primary'); if (button) { button.click(); // Симулируем нажатие на кнопку } } }); }); }); document.getElementById('updateValueButton').addEventListener('click', () => { const newValue = document.getElementById('newValue').value; chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { chrome.scripting.executeScript({ target: { tabId: tabs[0].id }, func: (value) => { const element = document.querySelector('.pb-position-editor.pb-position-editor-qty-containner'); if (element) { element.innerText = value; // Обновляем текст элемента } }, args: [newValue] // Передаем новое значение }); }); }); function updateData() { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { chrome.scripting.executeScript({ target: { tabId: tabs[0].id }, func: () => { let data = []; document.querySelectorAll('.by-table-row').forEach((row) => { const cells = row.querySelectorAll('.by-table-cell'); let rowData = { modeledPositions: cells[0] ? cells[0].innerText : '--', leverage: cells[1] ? cells[1].innerText : '--', expiration: cells[2] ? cells[2].innerText : '--', strikePrice: cells[3] ? cells[3].innerText : '--', type: cells[4] ? cells[4].innerText : '--', direction: cells[5] ? cells[5].innerText : '--', bidSize: cells[6] ? cells[6].innerText : '--', bidPriceIV: cells[7] ? cells[7].innerText : '--', orderPriceIV: cells[8] ? cells[8].innerText : '--', quantity: cells[9] ? cells[9].innerText : '--', askSize: cells[10] ? cells[10].innerText : '--', askPriceIV: cells[11] ? cells[11].innerText : '--', pnl: cells[12] ? cells[12].innerText : '--', delta: cells[13] ? cells[13].innerText : '--', gamma: cells[14] ? cells[14].innerText : '--', vega: cells[15] ? cells[15].innerText : '--', theta: cells[16] ? cells[16].innerText : '--', action: cells[17] ? cells[17].innerText : '--' }; // Логика для обновления "Цены ордера" в зависимости от "Направления" const orderPriceCell = cells[8]; if (rowData.direction === 'Купить' && cells[11]) { orderPriceCell.innerText = cells[11].innerText; // Ставим "Цену предложения" } else if (rowData.direction === 'Продать' && cells[7]) { orderPriceCell.innerText = cells[7].innerText; // Ставим "Цену спроса" } data.push(rowData); }); return data; }, }, (results) => { if (results && results[0]) { let data = results[0].result; let dataDiv = document.getElementById('data'); // Очистить предыдущие данные dataDiv.innerHTML = ''; // Создаем таблицу let table = document.createElement('table'); data.forEach(rowData => { let row = document.createElement('tr'); let columns = [ 'modeledPositions', 'leverage', 'expiration', 'strikePrice', 'type', 'direction', 'bidSize', 'bidPriceIV', 'orderPriceIV', 'quantity', 'askSize', 'askPriceIV', 'pnl', 'delta', 'gamma', 'vega', 'theta', 'action' ]; columns.forEach(key => { let cell = document.createElement('td'); cell.innerText = rowData[key]; row.appendChild(cell); }); table.appendChild(row); }); dataDiv.appendChild(table); } }); }); } setInterval(updateData, 500); мне нужно что бы если после нажатия кнопки Отправить в книгу ордеров было изменено количество quantity после должна произойти докупка до того момента пока количество quantity не дойдет до того что было указано мной в начале - Assistant
- User
напиши полный код после исправлений
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.