in html, get btcusdc futures 1m prices from binance public api between selected dates. then calculate moving average 99 and linear regression curve with window 19. then, calculate derivative of linear regression curve. i want that if derivative of linear regression goes from below zero to above zero and price is below moving average, a buy will start. but this will be a grid buy. grid spacing is 100. once buy is started, for every igrid spacing amount increase in price, a buy will happen. for selling all bought btc, price should go above moving average or price should fall 1 grid spacing from last bought point. also, for example grid buy started at 86500, and next btc bought at 85620 (since we check price every 1 minute, we cant buy exactly at 100 above), our next buy condition is not 86720, it is 86700. i mean buy prices for grid is set by first buy of grid. after a sell happened grid will wait for first start and again after buy started next buy prices will be set accordingly again. i have 100 usdc, simulate this trading strategy and draw total asset value to graph (also draw price, ma, regression and derivative too).
Assistant
Certainly! Below is a comprehensive Python script that will:
Fetch BTC/USDC futures 1-minute price data from Binance API between selected dates.
Calculate the 99-period moving average (MA99).
Calculate the 19-period linear regression curve and its derivative.
Simulate the specified grid trading strategy with an initial capital of 100 USDC.
Plot the total asset value over time along with the price, moving average, regression curve, and derivative.
The final output will be an interactive HTML file containing the graphs.
Please note: To run this script, you'll need to have Python installed along with the required libraries: requests, pandas, numpy, scipy, and plotly. You can install them using pip:
bash
pip install requests pandas numpy scipy plotly
Now, here's the code:
python
import requests
import pandas as pd
import numpy as np
from scipy.stats import linregress
import plotly.graph_objs as go
from plotly.offline import plot
from datetime import datetime, timedelta
import math
# Function to get historical klines from Binance API
def get_historical_klines(symbol, interval, start_str, end_str=None):
url = 'https://fapi.binance.com/fapi/v1/klines'
limit = 1500 # Max limit per request
data = []
start_ts = int(pd.to_datetime(start_str).timestamp() * 1000)
end_ts = int(pd.to_datetime(end_str).timestamp() * 1000) if end_str else None
while True:
params = {
'symbol': symbol,
'interval': interval,
'startTime': start_ts,
'limit': limit
}
if end_ts:
params['endTime'] = end_ts
response = requests.get(url, params=params)
temp_data = response.json()
if not temp_data:
break
data.extend(temp_data)
start_ts = temp_data[-1][0] + 1 # Move to next timestamp
if len(temp_data) < limit:
break
return data
# User-defined parameters
symbol = 'BTCUSDC'
interval = '1m'
start_date = '2023-09-01'
end_date = '2023-09-07'
initial_capital = 100 # USDC
grid_spacing = 100 # Price units
ma_window = 99
regression_window = 19
# Fetch data
print("Fetching data from Binance...")
klines = get_historical_klines(symbol, interval, start_date, end_date)
# Prepare DataFrame
columns = ['Open time', 'Open', 'High', 'Low', 'Close', 'Volume',
'Close time', 'Quote asset volume', 'Number of trades',
'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore']
df = pd.DataFrame(klines, columns=columns)
df['Open time'] = pd.to_datetime(df['Open time'], unit='ms')
df['Close time'] = pd.to_datetime(df['Close time'], unit='ms')
df[['Open', 'High', 'Low', 'Close']] = df[['Open', 'High', 'Low', 'Close']].astype(float)
df.set_index('Open time', inplace=True)
# Calculate Moving Average
df['MA'] = df['Close'].rolling(window=ma_window).mean()
# Calculate Linear Regression and its derivative
def calc_linear_regression(series, window):
slope_list = [np.nan]*len(series)
intercept_list = [np.nan]*len(series)
reg_line = [np.nan]*len(series)
for i in range(window-1, len(series)):
y = series.iloc[i-window+1:i+1]
x = np.arange(len(y))
slope, intercept, _, _, _ = linregress(x, y)
slope_list[i] = slope
intercept_list[i] = intercept
reg_line[i] = slope * (window-1) + intercept # Last point in the window
return reg_line, slope_list
print("Calculating regression and derivative...")
df['Reg_Line'], df['Derivative'] = calc_linear_regression(df['Close'], regression_window)
# Simulate Trading Strategy
print("Simulating trading strategy...")
usdc_balance = initial_capital
btc_balance = 0
total_asset_value = []
positions = []
grid_prices = []
for i in range(len(df)):
price = df['Close'].iloc[i]
ma = df['MA'].iloc[i]
reg_line = df['Reg_Line'].iloc[i]
derivative = df['Derivative'].iloc[i]
timestamp = df.index[i]
# Update total asset value
total_value = usdc_balance + btc_balance * price
total_asset_value.append(total_value)
# Check for signals only if necessary data is available
if np.isnan(ma) or np.isnan(derivative):
continue
# Conditions for starting a grid buy
if derivative >= 0 and df['Derivative'].shift(1).iloc[i-1] < 0 and price < ma and btc_balance == 0:
# Start grid buying
first_buy_price = price
usdc_to_spend = usdc_balance / 10 # Spending 10% of current balance per grid
btc_bought = usdc_to_spend / price
if usdc_balance >= usdc_to_spend:
usdc_balance -= usdc_to_spend
btc_balance += btc_bought
positions.append({
'Price': price,
'BTC': btc_bought,
'Timestamp': timestamp
})
# Set up grid prices
grid_prices = [first_buy_price + grid_spacing * n for n in range(1, int((ma - first_buy_price) / grid_spacing) + 1)]
else:
print("Insufficient USDC balance to start grid buying.")
continue
# Grid buying logic
if btc_balance > 0 and price >= grid_prices[0]:
usdc_to_spend = usdc_balance / 10 # Spending 10% of current balance per grid
btc_bought = usdc_to_spend / price
if usdc_balance >= usdc_to_spend:
usdc_balance -= usdc_to_spend
btc_balance += btc_bought
positions.append({
'Price': price,
'BTC': btc_bought,
'Timestamp': timestamp
})
# Remove this grid price and move to next
grid_prices.pop(0)
if not grid_prices:
# Recalculate grid prices based on new price
grid_prices = [price + grid_spacing * n for n in range(1, int((ma - price) / grid_spacing) + 1)]
else:
print("Insufficient USDC balance for grid buying.")
# Conditions for selling
if btc_balance > 0 and (price > ma or price <= positions[-1]['Price'] - grid_spacing):
# Sell all BTC
usdc_balance += btc_balance * price
btc_balance = 0
positions = []
grid_prices = []
continue
# Create DataFrame for total asset value
df_asset = df.iloc[ma_window-1:].copy()
df_asset['Total Asset Value'] = total_asset_value[ma_window-1:]
# Plotting
print("Plotting results...")
fig = go.Figure()
# Price trace
fig.add_trace(go.Scatter(x=df.index, y=df['Close'], mode='lines', name='Price'))
# Moving Average
fig.add_trace(go.Scatter(x=df.index, y=df['MA'], mode='lines', name='MA99'))
# Regression Line
fig.add_trace(go.Scatter(x=df.index, y=df['Reg_Line'], mode='lines', name='Regression Line'))
# Derivative
fig.add_trace(go.Scatter(x=df.index, y=df['Derivative'], mode='lines', name='Derivative', yaxis='y2'))
# Total Asset Value
fig.add_trace(go.Scatter(x=df_asset.index, y=df_asset['Total Asset Value'], mode='lines', name='Total Asset Value', yaxis='y3'))
# Layout
fig.update_layout(
title=f"Trading Strategy Simulation for {symbol}",
xaxis_title="Time",
yaxis_title="Price",
yaxis=dict(
title="Price",
side="left"
),
yaxis2=dict(
title="Derivative",
overlaying='y',
side='right',
showgrid=False
),
yaxis3=dict(
title="Total Asset Value",
anchor="free",
overlaying="y",
side="right",
position=1.15
),
legend=dict(
x=1.05,
y=1
),
width=1000,
height=600
)
# Save plot to HTML
plot(fig, filename='trading_strategy_simulation.html')
print("Simulation complete. The results have been plotted and saved to 'trading_strategy_simulation.html'.")
Explanation of the Code:
Data Fetching:
Fetches BTC/USDC futures 1-minute data from Binance between the specified dates.
The data includes open, high, low, close prices, and timestamps.
Calculations:
Calculates the 99-period moving average (MA99).
Calculates the 19-period linear regression line and its derivative (slope).
Trading Strategy Simulation:
Buy Conditions:
When the derivative of the regression line crosses from negative to positive.
The price is below the moving average.
Starts a grid buy with the first buy at the current price.
Grid spacing is set at intervals of 100 in price units above the first buy price.
Grid Buying:
For every grid spacing increase in price from the first buy price, a new buy is executed.
The grid prices are set based on the first buy price.
Only 10% of the current USDC balance is used per grid buy to manage risk.
Sell Conditions:
When the price goes above the moving average.
Or the price drops one grid spacing below the last bought price.
Sells all the accumulated BTC holdings.
Asset Value Tracking:
Keeps track of the total asset value over time (USDC balance + BTC holdings at current price).
Plotting:
Plots the price, moving average, regression line, derivative, and total asset value.
The derivative is plotted on a secondary y-axis.
The total asset value is plotted on another secondary y-axis.
The plot is saved as an interactive HTML file named trading_strategy_simulation.html.
How to View the Results:
Run the script in your Python environment.
Ensure that you have an active internet connection to fetch data from Binance.
After the script completes, it will generate an HTML file named trading_strategy_simulation.html.
Open this HTML file in a web browser to view the interactive plot.
Adjusting Parameters:
You can change the start_date and end_date variables to simulate different time periods.
Modify initial_capital to change the starting USDC balance.
Adjust grid_spacing, ma_window, and regression_window to see how different parameters affect the strategy.
Disclaimer: This simulation is for educational purposes only and does not constitute financial advice. Trading cryptocurrencies involves significant risk, and past performance is not indicative of future results.