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. if the starting usdc is 500, draw a chart for profit and loss.

  2. Assistant

    Sure! I can help you build an HTML page with JavaScript that fetches BTCUSDC (which I'll assume you meant BTCUSDT, as BTCUSDC is less common) data from Binance's public API, performs the calculations you've described, executes the trading strategy, and then plots the profit and loss over time.

    Below is a step-by-step implementation:

    1. Fetch Historical Data from Binance API
    2. Calculate the 99-point Moving Average (MA99)
    3. Compute the Slope of the Moving Average
    4. Calculate the Angle between the Slope and Horizontal Axis
    5. Normalize the Angle between -1 and 1
    6. Calculate the Absolute Difference between Price Data and Moving Average
    7. Implement the Trading Strategy
    8. Simulate Trades and Calculate Profit and Loss
    9. Plot the Profit and Loss Chart

    Let's go through each step, and then I'll provide the full HTML and JavaScript code.


    1. Fetch Historical Data from Binance API

    We'll use the Binance Kline/Candlestick Data endpoint to fetch historical 1-minute BTCUSDT data between selected dates.

    API Endpoint:

    https://api.binance.com/api/v3/klines
    

    Parameters:

    • symbol: Trading pair symbol (e.g., BTCUSDT)
    • interval: Data interval (e.g., 1m for 1 minute)
    • startTime: Start time in milliseconds
    • endTime: End time in milliseconds

    2. Calculate the 99-point Moving Average (MA99)

    For each price point, calculate the average of the previous 99 closing prices.


    3. Compute the Slope of the Moving Average

    For each point in MA99, calculate the slope by taking the difference between the current MA99 value and the previous one.


    4. Calculate the Angle between the Slope and Horizontal Axis

    Use the arctangent function to calculate the angle:

    angle = Math.atan(slope);
    

    5. Normalize the Angle between -1 and 1

    Normalize the angle to be between -1 and 1:

    normalizedAngle = angle / (Math.PI / 2); // Since arctangent's range is (-π/2, π/2)
    

    6. Calculate the Absolute Difference between Price Data and Moving Average

    For each point, compute:

    absoluteDifference = Math.abs(price - movingAverage);
    

    7. Implement the Trading Strategy

    • Buy Rule:
      • If normalizedAngle is between -0.3 and -1 and absoluteDifference is greater than 100, then:
        • Buy BTC worth: amount = -1 * normalizedAngle * absoluteDifference / 10 USDC
    • Sell Rule:
      • If the price crosses above the moving average, sell all bought BTC.

    8. Simulate Trades and Calculate Profit and Loss

    Keep track of:

    • Available USDC balance
    • BTC holdings
    • Profit and loss over time

    9. Plot the Profit and Loss Chart

    Use a charting library like Chart.js or Google Charts to plot the profit and loss over time.


    Now, let's put it all together.


    Full HTML and JavaScript Code

    Create an index.html file and include the following code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>BTCUSDT Trading Simulator</title>
      <style>
        body {
          font-family: Arial, sans-serif;
        }
        #chart-container {
          width: 100%;
          height: 500px;
        }
      </style>
    </head>
    <body>
    
    <h1>BTCUSDT Trading Simulator</h1>
    
    <label for="startDate">Start Date and Time (UTC):</label>
    <input type="datetime-local" id="startDate" value="2023-01-01T00:00">
    <br><br>
    <label for="endDate">End Date and Time (UTC):</label>
    <input type="datetime-local" id="endDate" value="2023-01-02T00:00">
    <br><br>
    <button id="startButton">Start Simulation</button>
    
    <h2>Profit and Loss Chart</h2>
    <canvas id="profitLossChart"></canvas>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
    document.getElementById('startButton').addEventListener('click', async () => {
      // Clear existing chart
      if (window.profitLossChart) {
        window.profitLossChart.destroy();
      }
    
      // Get selected dates
      const startDateInput = document.getElementById('startDate').value;
      const endDateInput = document.getElementById('endDate').value;
      const startTime = new Date(startDateInput).getTime();
      const endTime = new Date(endDateInput).getTime();
    
      // Fetch data from Binance API
      const candles = await fetchCandles('BTCUSDT', '1m', startTime, endTime);
    
      // Process data
      const closingPrices = candles.map(c => parseFloat(c[4])); // Close prices
      const timestamps = candles.map(c => c[0]); // Open time
    
      // Calculate MA99
      const ma99 = calculateMA(closingPrices, 99);
    
      // Calculate slope, angle, normalized angle, and absolute difference
      const slopes = [];
      const angles = [];
      const normalizedAngles = [];
      const absoluteDifferences = [];
    
      for (let i = 1; i < ma99.length; i++) {
        const slope = ma99[i] - ma99[i - 1];
        slopes.push(slope);
    
        const angle = Math.atan(slope);
        angles.push(angle);
    
        const normalizedAngle = angle / (Math.PI / 2); // Normalize between -1 and 1
        normalizedAngles.push(normalizedAngle);
    
        const price = closingPrices[i + 98]; // Adjust index because of MA99 lag
        const movingAverage = ma99[i];
        const absoluteDifference = Math.abs(price - movingAverage);
        absoluteDifferences.push(absoluteDifference);
      }
    
      // Implement trading strategy
      let usdcBalance = 500; // Starting USDC
      let btcHoldings = 0;
      let profitLoss = [];
      let totalInvested = 0;
      let tradeTimestamps = [];
    
      for (let i = 0; i < normalizedAngles.length; i++) {
        const normAngle = normalizedAngles[i];
        const absDiff = absoluteDifferences[i];
        const price = closingPrices[i + 99]; // Adjust for MA99 and slopes lag
    
        // Buy condition
        if (normAngle >= -1 && normAngle <= -0.3 && absDiff > 100) {
          const amountToInvest = (-1 * normAngle * absDiff) / 10; // Amount in USDC
          const investAmount = Math.min(amountToInvest, usdcBalance); // Can't spend more than we have
          if (investAmount > 0) {
            const btcPurchased = investAmount / price;
            btcHoldings += btcPurchased;
            usdcBalance -= investAmount;
            totalInvested += investAmount;
          }
        }
    
        // Sell condition
        const priceBelowMA = closingPrices[i + 99 - 1] <= ma99[i]; // Previous price
        const priceAboveMA = price > ma99[i]; // Current price
        if (btcHoldings > 0 && priceBelowMA && priceAboveMA) {
          // Sell all BTC
          const sellAmount = btcHoldings * price;
          usdcBalance += sellAmount;
          btcHoldings = 0;
          totalInvested = 0;
        }
    
        // Calculate current total value
        const currentValue = usdcBalance + btcHoldings * price;
        profitLoss.push(currentValue);
        tradeTimestamps.push(timestamps[i + 99]);
      }
    
      // Convert timestamps to readable dates
      const dates = tradeTimestamps.map(ts => new Date(ts).toLocaleString());
    
      // Plot profit and loss
      const ctx = document.getElementById('profitLossChart').getContext('2d');
      window.profitLossChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: dates,
          datasets: [{
            label: 'Portfolio Value (USDC)',
            data: profitLoss,
            borderColor: 'green',
            fill: false,
          }]
        },
        options: {
          scales: {
            x: {
              display: false // Hide x-axis labels for clarity
            }
          }
        }
      });
    });
    
    // Function to fetch candle data
    async function fetchCandles(symbol, interval, startTime, endTime) {
      const limit = 1000; // Max limit per Binance API
      let data = [];
      let fetchTime = startTime;
    
      while (fetchTime < endTime) {
        const url = `https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=${interval}&startTime=${fetchTime}&endTime=${endTime}&limit=${limit}`;
        const response = await fetch(url);
        const json = await response.json();
    
        if (json.length === 0) {
          break;
        }
    
        data = data.concat(json);
        fetchTime = json[json.length - 1][0] + 60000; // Move to next minute after the last fetched candle
        if (json.length < limit) {
          break;
        }
      }
      return data;
    }
    
    // Function to calculate Moving Average
    function calculateMA(prices, windowSize) {
      const ma = [];
    
      for (let i = 0; i <= prices.length - windowSize; i++) {
        const window = prices.slice(i, i + windowSize);
        const sum = window.reduce((acc, val) => acc + val, 0);
        ma.push(sum / windowSize);
      }
      return ma;
    }
    </script>
    </body>
    </html>
    

    Instructions to Run the Code

    1. Save the Code:

      Save the above HTML code into a file named index.html.

    2. Open in a Browser:

      Open index.html in your web browser (e.g., Chrome, Firefox).

    3. Select Dates:

      • Use the date and time pickers to select your desired start and end dates.
      • Ensure the date range is reasonable (e.g., a few days), as fetching too much data may overwhelm the browser due to API rate limits.
    4. Start Simulation:

      Click the Start Simulation button to begin fetching data and running the simulation.

    5. View Profit and Loss Chart:

      After a short wait, the profit and loss chart will be displayed, showing how the portfolio value changes over time according to the trading strategy.


    Notes and Considerations

    • API Rate Limits:

      • Binance API has rate limits. Be cautious with the amount of data you request.
      • If you encounter errors fetching data, try reducing the date range.
    • Data Lag Due to MA99 Calculation:

      • The Moving Average calculation introduces a lag of 99 data points.
      • Adjustments are made in the indices when accessing price and MA arrays to align the data correctly.
    • Trading Strategy Variables:

      • usdcBalance: Starts at 500 USDC.
      • btcHoldings: Tracks the amount of BTC held.
      • profitLoss: Array storing the total portfolio value (USDC + BTC value in USDC) over time.
    • Chart Display:

      • The x-axis labels are hidden for clarity, but you can adjust the options in the Chart.js configuration to show them.
      • The timestamps are converted to readable date strings for plotting.
    • JavaScript Libraries:

      • Chart.js: Used for plotting the profit and loss chart.
      • Fetch API: Used to make HTTP requests to the Binance API.

    Understanding the Trading Strategy Implementation

    • Buying BTC:

      When the conditions are met, the script calculates the amount to invest in BTC:

      const amountToInvest = (-1 * normAngle * absDiff) / 10;
      
      • This amount is adjusted to ensure we don't invest more USDC than we have available.
    • Selling BTC:

      • The script checks if the price crosses above the moving average.
      • All BTC holdings are sold at the current price.

    Extending the Code

    • Error Handling:

      • Add try-catch blocks to handle any network or data errors.
      • Inform the user if there's an issue fetching data.
    • Data Visualization:

      • Add additional charts to visualize BTC price, moving average, and trading signals.
      • Highlight buy and sell points on the price chart.
    • Parameter Inputs:

      • Allow the user to adjust parameters like moving average window size, angle thresholds, and difference thresholds.
    • Performance Metrics:

      • Calculate and display metrics like total return, number of trades, and average profit per trade.

    Disclaimer

    • This simulation is for educational purposes and does not constitute financial advice.
    • Past performance is not indicative of future results.
    • Trading cryptocurrencies involves significant risk of loss.