To accomplish your goal of analyzing BTCUSDC 1-minute price data from Binance and visualizing the results, you can follow these steps. Below is a guide that outlines how to fetch the data, perform the calculations, and plot the results using Python. This method leverages Python's powerful data processing libraries and can generate interactive HTML plots.
Note: Directly accessing Binance API via client-side JavaScript in an HTML file is not feasible due to CORS (Cross-Origin Resource Sharing) policy restrictions enforced by Binance. Instead, we can use Python to fetch and process the data, then output the results to an HTML file.
1. Fetch BTCUSDC 1-Minute Price Data from Binance API
Binance provides a public API endpoint to retrieve historical candlestick data (klines). We'll use Python's requests library to fetch the data.
import requests
import pandas as pd
# Function to convert date string to milliseconds
def date_to_milliseconds(date_str):
import datetime
epoch = datetime.datetime.strptime(date_str, "%d %m %Y")
milliseconds = int(epoch.timestamp() * 1000)
return milliseconds
# Set the start and end dates (default: 1 Nov 2024 to 5 Nov 2024)
start_str = '1 11 2024'
end_str = '5 11 2024'
# Convert dates to milliseconds
start_ts = date_to_milliseconds(start_str)
end_ts = date_to_milliseconds(end_str)
# Binance API endpoint
url = 'https://api.binance.com/api/v3/klines'
# Parameters for the API request
params = {
'symbol': 'BTCUSDC',
'interval': '1m',
'startTime': start_ts,
'endTime': end_ts,
'limit': 1000 # Maximum limit per request
}
# Fetch data
response = requests.get(url, params=params)
data = response.json()
# Check for errors
if 'code' in data:
print(f"Error fetching data: {data['msg']}")
exit()
# Create a DataFrame
df = pd.DataFrame(data, columns=[
'OpenTime', 'Open', 'High', 'Low', 'Close', 'Volume',
'CloseTime', 'QuoteAssetVolume', 'NumberOfTrades',
'TakerBuyBaseAssetVolume', 'TakerBuyQuoteAssetVolume', 'Ignore'
])
# Convert relevant columns to numeric types
df['Close'] = df['Close'].astype(float)
df['OpenTime'] = pd.to_datetime(df['OpenTime'], unit='ms')
Note: Since the dates provided are in the future and data may not be available, ensure to use dates within the available data range from Binance.
2. Calculate the Moving Average (MA99)
We'll compute the 99-period moving average of the closing prices.
# Calculate MA99
df['MA99'] = df['Close'].rolling(window=99).mean()
3. Calculate the Sum Between Price Curve and MA99 Curve with Window 99
We calculate the difference between the price and MA99. If the price is below MA99, the difference will be negative. Then, we compute the rolling sum over a window of 99 periods.
# Difference between price and MA99
df['Difference'] = df['Close'] - df['MA99']
# Rolling sum with window 99
df['Sum'] = df['Difference'].rolling(window=99).sum()
4. Find the Derivative of the Sum Curve
The derivative (rate of change) of the sum curve is calculated using the diff() function.
# Derivative of the sum curve
df['Derivative'] = df['Sum'].diff()
5. Plot the Results
We'll use Plotly to create interactive plots and output them to an HTML file.
import plotly.graph_objs as go
from plotly.subplots import make_subplots
# Create subplots
fig = make_subplots(rows=4, cols=1, shared_xaxes=True,
vertical_spacing=0.02,
subplot_titles=('Price and MA99', 'Sum between Price and MA99', 'Derivative of Sum'))
# Plot Actual Price and MA99
fig.add_trace(go.Scatter(x=df['OpenTime'], y=df['Close'], name='Price'), row=1, col=1)
fig.add_trace(go.Scatter(x=df['OpenTime'], y=df['MA99'], name='MA99'), row=1, col=1)
# Plot Sum
fig.add_trace(go.Scatter(x=df['OpenTime'], y=df['Sum'], name='Sum'), row=2, col=1)
# Plot Derivative of Sum
fig.add_trace(go.Scatter(x=df['OpenTime'], y=df['Derivative'], name='Derivative of Sum'), row=3, col=1)
# Update layout
fig.update_layout(height=900, width=1000, title_text="BTCUSDC Analysis")
# Output to HTML file
fig.write_html("btc_analysis.html")
print("Plot saved to btc_analysis.html")
Open the btc_analysis.html file in your web browser to view the interactive plots.
Final Notes
-
Data Availability: Ensure that the dates you use are within the range of available data from Binance. If you use future dates or dates too far in the past, the API may return errors or empty datasets.
-
API Limitations: Binance API has rate limits and maximum data per request. For larger datasets, you may need to implement pagination by making multiple requests and concatenating the results.
-
Environment Setup: Make sure you have the required Python libraries installed:
pip install requests pandas plotly
-
Customization: You can customize the plots, add more analyses, or adjust window sizes according to your needs.
By following these steps, you'll be able to fetch the required data, perform the necessary calculations, and visualize the results, all outputted to an HTML file for easy viewing and sharing.