Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

in html, get btcusdc data between selected dates from binance public api in 1m.…

  1. User

    in html, get btcusdc data between selected dates from binance public api in 1m. calculate moving average 99, then calculate the slope of the moving average. then calculate the angle between horizontal and the slope of the the point (do this for every point, if slope is negative angle is negative), then normalize the angle between -1 and 1. also, calculate the absolute difference between price data and moving average. rule is that; if the normalized angle is between -0.3 and -1, and absolute difference is greater than 100, buy dca with that amount -1*[normalized_angle]*[abosolute_difference]/10 usdc. also, if the price crosses above the moving average, sell all bought btc.

  2. Assistant

    Certainly! Below is an HTML file that uses JavaScript to fetch BTC/USDC 1-minute interval data from Binance's public API between selected dates. It calculates the 99-period moving average, computes the slope and angle at each point, normalizes the angle between -1 and 1, calculates the absolute difference between the price and the moving average, and applies the trading rules you specified.

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>BTC/USDC Trading Strategy</title>
    </head>
    <body>
      <h1>BTC/USDC Trading Strategy Simulation</h1>
      <label for="startDate">Start Date (YYYY-MM-DD):</label>
      <input type="date" id="startDate" required>
      <br>
      <label for="endDate">End Date (YYYY-MM-DD):</label>
      <input type="date" id="endDate" required>
      <br>
      <button id="runButton">Run Strategy</button>
    
      <h2>Trading Log</h2>
      <pre id="log"></pre>
    
      <script>
        document.getElementById('runButton').addEventListener('click', runStrategy);
    
        async function runStrategy() {
          const logElement = document.getElementById('log');
          logElement.textContent = 'Fetching data...\n';
    
          const startDate = document.getElementById('startDate').value;
          const endDate = document.getElementById('endDate').value;
    
          if (!startDate || !endDate) {
            logElement.textContent += 'Please enter valid start and end dates.\n';
            return;
          }
    
          const startTime = new Date(startDate).getTime();
          const endTime = new Date(endDate).getTime();
    
          // Fetch data from Binance API
          const klines = await fetchKlines('BTCUSDC', '1m', startTime, endTime);
          if (!klines.length) {
            logElement.textContent += 'No data fetched. Please check the dates.\n';
            return;
          }
    
          logElement.textContent += 'Data fetched. Processing...\n';
    
          // Process data
          const prices = klines.map(k => parseFloat(k[4])); // Close prices
          const times = klines.map(k => k[0]);
    
          // Calculate 99-period moving average
          const ma99 = movingAverage(prices, 99);
    
          // Calculate slopes, angles, normalized angles, and absolute differences
          const slopes = [];
          const angles = [];
          const normalizedAngles = [];
          const absDiffs = [];
    
          for (let i = 1; i < ma99.length; i++) {
            const slope = ma99[i] - ma99[i - 1];
            slopes.push(slope);
    
            // Angle in radians
            const angleRad = Math.atan(slope);
    
            // Convert to degrees for interpretation (optional)
            const angleDeg = angleRad * (180 / Math.PI);
            angles.push(angleDeg);
    
            // Normalize angle between -1 and 1
            const normalizedAngle = angleDeg / 90; // Since arctangent outputs between -90 and 90 degrees
            normalizedAngles.push(normalizedAngle);
    
            const absDiff = Math.abs(prices[i + 98] - ma99[i]); // Offset by 98 due to MA99
            absDiffs.push(absDiff);
          }
    
          // Simulate trading
          let usdcBalance = 10000; // Starting USDC balance (for example)
          let btcBalance = 0;
          let boughtBtc = 0;
          let buyLog = [];
    
          for (let i = 0; i < normalizedAngles.length; i++) {
            const angle = normalizedAngles[i];
            const absDiff = absDiffs[i];
            const price = prices[i + 98];
            const ma = ma99[i];
    
            // Check buying condition
            if (angle >= -1 && angle <= -0.3 && absDiff > 100) {
              // Calculate amount to buy
              const amountUsdc = (-1 * angle * absDiff) / 10;
    
              if (usdcBalance >= amountUsdc) {
                const btcToBuy = amountUsdc / price;
                usdcBalance -= amountUsdc;
                btcBalance += btcToBuy;
                boughtBtc += btcToBuy;
    
                logElement.textContent += `Buy ${btcToBuy.toFixed(6)} BTC at $${price.toFixed(2)} on ${new Date(times[i + 98]).toLocaleString()}\n`;
              }
            }
    
            // Check selling condition
            if (price > ma && btcBalance > 0) {
              // Sell all bought BTC
              const amountUsdc = btcBalance * price;
              usdcBalance += amountUsdc;
              logElement.textContent += `Sell ${btcBalance.toFixed(6)} BTC at $${price.toFixed(2)} on ${new Date(times[i + 98]).toLocaleString()}\n`;
              btcBalance = 0;
            }
          }
    
          logElement.textContent += `\nFinal USDC Balance: $${usdcBalance.toFixed(2)}\n`;
          logElement.textContent += `Final BTC Balance: ${btcBalance.toFixed(6)} BTC\n`;
        }
    
        // Function to fetch klines from Binance API
        async function fetchKlines(symbol, interval, startTime, endTime) {
          const limit = 1000; // Maximum number of data points per request
          let klines = [];
          let fetchStartTime = startTime;
    
          try {
            while (fetchStartTime < endTime) {
              const url = `https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=${interval}&startTime=${fetchStartTime}&endTime=${endTime}&limit=${limit}`;
              const response = await fetch(url);
              const data = await response.json();
    
              if (data && data.length) {
                klines = klines.concat(data);
                fetchStartTime = data[data.length - 1][0] + 60000; // Move to next minute
              } else {
                break; // No more data
              }
            }
          } catch (error) {
            console.error('Error fetching data:', error);
          }
    
          return klines;
        }
    
        // Function to calculate moving average
        function movingAverage(data, period) {
          let ma = [];
          for (let i = 0; i <= data.length - period; i++) {
            const sum = data.slice(i, i + period).reduce((a, b) => a + b, 0);
            ma.push(sum / period);
          }
          return ma;
        }
      </script>
    </body>
    </html>
    

    Explanation:

    • The HTML code includes input fields for the user to select the start and end dates.
    • When the "Run Strategy" button is clicked, the runStrategy function is called.
    • runStrategy fetches BTC/USDC 1-minute interval data from Binance's public API between the selected dates.
    • It calculates the 99-period moving average (ma99) using the movingAverage function.
    • It computes the slope by taking the difference between consecutive moving average points.
    • The angle is calculated using Math.atan(slope), which returns the angle in radians.
    • The angle is converted to degrees and then normalized between -1 and 1 by dividing by 90.
    • The absolute difference between the current price and the moving average is calculated.
    • The trading rules are applied:
      • Buy Condition: If the normalized angle is between -1 and -0.3 and the absolute difference is greater than 100, it buys BTC with the amount (-1 * normalizedAngle * absDiff) / 10 USDC.
      • Sell Condition: If the price crosses above the moving average and there's BTC in the balance, it sells all bought BTC.
    • The trading actions and final balances are logged in the "Trading Log" section.

    Notes:

    • You need to run this code from a server or configure your browser to allow CORS requests to Binance's API.
    • The Binance API has rate limits. Fetching large amounts of data might require adjusting the limits or adding delays.
    • The fetchKlines function handles pagination by fetching data in chunks of 1000 data points until it reaches the end time.
    • Error handling is minimal; in a production environment, you should add more robust error checking.

    Disclaimer:

    • This code is for educational purposes and simulates the trading strategy based on historical data.
    • Trading cryptocurrencies involves risk, and past performance does not guarantee future results.
    • Always do thorough testing and consider consulting with a financial advisor before using any trading strategy with real funds.