NODE SERVER PRIVATE BOT

Hi everybody,
I am trying to setup own binance private bot got help from Chat GPT to run on Windows 10 Pro.
After spend long time the bot works. But not buy coin from Binance. Bot shows that coin bought but when I check my account trade History the coin not bought.

Nod Server installed, and main page is html but under the directory created many files order forom Chat GPT.

It seems that a javascript file manage everything and some codes in html file also javascript connected to main bot file (bot.js)
I need a simple bot. trading spot market and buy and sell market price only.
I try to setup a bot shows me the coins prices started gain up 1% and in 15 minutes continue to price up.

I would like add my main file (bot.js) and I’ll appreciated if any expert wish to help me free.
Here is code: "// Maintain a set of already fetched symbols and bought coins
const fetchedSymbols = new Set();
const boughtCoins = new Map(); // Map to store bought coins and their bought prices

// Function to check if the coin name is valid
function isValidCoinName(coinName) {
return coinName.endsWith(“USDT”) && !/(BTC|ETH|BNB|USDC|BETH|BUSD|BULL|DOWN|UP)/.test(coinName);
}

// Function to shuffle an array
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i–) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}

// Function to fetch historical price data
async function fetchHistoricalPrice(symbol, interval, limit) {
const response = await fetch(https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=${interval}&limit=${limit});
const data = await response.json();
return data;
}

// Function to fetch coins for a specific row
async function fetchCoinsForRow(row) {
const symbolCell = row.querySelector(‘.coinSymbol’);
const priceCell = row.querySelector(‘.priceNow’);
const priceUpCell = row.querySelector(‘.priceUp’);
const change24hCell = row.querySelector(‘.change24H’);
const change7dCell = row.querySelector(‘.change7D’);
const boughtCell = row.querySelector(‘.coinBought’);
const boughtPriceCell = row.querySelector(‘.boughtPrice’);
const amountCell = row.querySelector(‘.amount’);
const changePercentCell = row.querySelector(‘.changePercent’);
const profitCell = row.querySelector(‘.profit’);

try {
    const response = await fetch("https://api.binance.com/api/v3/ticker/24hr");
    if (!response.ok) {
        throw new Error(`Failed to fetch coin data: ${response.statusText}`);
    }
    const data = await response.json();

    // Filter coins based on criteria
    let filteredCoins = data.filter(coin => {
        const priceChangePercent = parseFloat(coin.priceChangePercent);
        const isValidName = isValidCoinName(coin.symbol);
        const price = parseFloat(coin.lastPrice);
        return isValidName && price < 3 && priceChangePercent >= 1 && priceChangePercent <= 2;
    });

    if (filteredCoins.length === 0) {
        throw new Error("No suitable coins found");
    }

    // Remove symbols that have already been fetched
    filteredCoins = filteredCoins.filter(coin => !fetchedSymbols.has(coin.symbol));

    if (filteredCoins.length === 0) {
        throw new Error("No new suitable coins found");
    }

    // Shuffle the filtered coins array to ensure randomness
    filteredCoins = shuffleArray(filteredCoins);

    // Select the first coin from the shuffled array
    const coin = filteredCoins[0];

    // Fetch historical prices for 5-15 minutes and 7 days

const symbol = coin.symbol;
const [fiveMinuteData, oneDayData, sevenDayData] = await Promise.all([
fetchHistoricalPrice(symbol, ‘5m’, 3), // Last three 5-minute intervals
fetchHistoricalPrice(symbol, ‘1d’, 1), // Last 1-day interval
fetchHistoricalPrice(symbol, ‘1w’, 1) // Last 1-week interval
]);

// Calculate PRICE UP (5-15 mins) %
const price15MinutesAgo = parseFloat(fiveMinuteData[0][1]); // Open price of the first 5-minute interval
const currentPrice = parseFloat(coin.lastPrice);
const priceUpPercent = ((currentPrice - price15MinutesAgo) / price15MinutesAgo * 100).toFixed(2);

// CHANGE (24H)
const priceChangePercent24h = parseFloat(coin.priceChangePercent).toFixed(2);

// Calculate CHANGE (7D)
const price7DaysAgo = parseFloat(sevenDayData[0][1]); // Open price of the 7-day interval
const priceChangePercent7d = ((currentPrice - price7DaysAgo) / price7DaysAgo * 100).toFixed(2);

// Update table row with fetched coin data
symbolCell.textContent = coin.symbol;
priceCell.textContent = coin.lastPrice;
priceUpCell.textContent = priceUpPercent + “%”;
change24hCell.textContent = priceChangePercent24h + “%”;
change7dCell.textContent = priceChangePercent7d + “%”;

// Show Buy button only if the coin is not already bought
if (!boughtCoins.has(coin.symbol)) {
row.querySelector(“.buyButton”).style.display = “inline-block”;
}

    // Add the fetched symbol to the set of already fetched symbols
    fetchedSymbols.add(coin.symbol);
} catch (error) {
    console.error("Error fetching coins:", error);
}

}

// Function to handle fetch button click
async function handleFetchButtonClick(row) {
try {
await fetchCoinsForRow(row);
} catch (error) {
console.error(“Error handling fetch button click:”, error);
}
}

// Function to handle buy button click
async function handleBuyButtonClick(row) {
try {
// Extract necessary information from the row
const symbol = row.querySelector(‘.coinSymbol’).textContent;
const investment = parseFloat(row.querySelector(‘.investment’).value);
const priceNow = parseFloat(row.querySelector(‘.priceNow’).textContent);

    // Calculate the quantity of the coin to buy based on the investment amount and current price
    const quantity = (investment / priceNow).toFixed(6); // Ensuring quantity has 6 decimal places

    // Send a request to your proxy server to place a buy order
    const response = await fetch('https://localhost:8443/api/order', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-mbx-apikey': 'API_KEY' // Replace with your actual API key
        },
        body: JSON.stringify({
            symbol: symbol,
            side: 'BUY',
            type: 'MARKET',
            quantity: quantity,
            timestamp: Date.now(),
            recvWindow: 5000
        })
    });

    const data = await response.json();
    console.log('Buy order response:', data);

    // Check if the order was successful
    if (response.ok) {
        // Update the UI to reflect the purchase
        row.querySelector('.coinBought').textContent = 'Yes';
        row.querySelector('.boughtPrice').textContent = priceNow;
        row.querySelector('.amount').textContent = quantity;
        row.querySelector('.buyButton').classList.add('hidden');
        row.querySelector('.sellButton').classList.remove('hidden');

        // Store the bought coin and its price
        boughtCoins.set(symbol, priceNow);

        // Setup WebSocket connection to get live price updates for the bought coin
        setupWebSocketForRow(row, symbol);

    } else {
        throw new Error(`Failed to place buy order: ${data.msg}`);
    }
} catch (error) {
    console.error('Error handling buy button click:', error);
}

}

// Function to setup WebSocket connection for live price updates
function setupWebSocketForRow(row, symbol) {
const ws = new WebSocket(wss://stream.binance.com:9443/ws/${symbol.toLowerCase()}@trade);

ws.onmessage = (event) => {
    const message = JSON.parse(event.data);
    const priceNow = parseFloat(message.p);

    // Update the PRICE NOW column
    row.querySelector('.priceNow').textContent = priceNow;

    // Calculate and update CHANGE % and PROFIT
    const boughtPrice = parseFloat(row.querySelector('.boughtPrice').textContent);
    const amount = parseFloat(row.querySelector('.amount').textContent);
    const percentChange = (((priceNow - boughtPrice) / boughtPrice) * 100).toFixed(2);
    const profit = ((priceNow - boughtPrice) * amount).toFixed(2);

    row.querySelector('.changePercent').textContent = percentChange + "%";
    row.querySelector('.profit').textContent = profit;
};

ws.onerror = (error) => {
    console.error(`WebSocket error for ${symbol}:`, error);
};

ws.onclose = () => {
    console.log(`WebSocket connection closed for ${symbol}`);
};

}
"