import requests
import pandas as pd
import matplotlib.pyplot as plt
import argparse

# Initialisation du parser
parser = argparse.ArgumentParser(description='Programme qui accepte des paramètres.')

# Ajout d'arguments
parser.add_argument('--crypto', type=str, help='nom de la crypto (BTC)')
parser.add_argument('--nb', type=int, help='nombre d\'élément du cumul')
parser.add_argument('--horizon', type=int, help='nombre d\'élément à lire')
parser.add_argument('--verbose', action='store_true', help='Mode verbeux')

# Parsing des arguments
args = parser.parse_args()

# Utilisation des arguments
print(f"Premier argument : {args.crypto}")
print(f"Deuxième argument : {args.nb}")
print(f"Troisième argument : {args.horizon}")

if args.verbose:
    print("Mode verbeux activé")

# Fetch the API data
url = "https://api.binance.com/api/v3/depth?symbol=" + args.crypto + "USDT&limit=" + str(args.horizon)
response = requests.get(url)
data = response.json()

# Extract bids and asks
bids = data['bids']
asks = data['asks']

# Prepare data for plotting
bid_amounts = [float(bid[0]) for bid in bids]
bid_volumes = [float(bid[1]) for bid in bids]

ask_amounts = [float(ask[0]) for ask in asks]
ask_volumes = [float(ask[1]) for ask in asks]

# Convert to pandas DataFrame to apply moving average
bid_df = pd.DataFrame({'amount': bid_amounts, 'volume': bid_volumes})
ask_df = pd.DataFrame({'amount': ask_amounts, 'volume': ask_volumes})

# Apply a rolling window to calculate a n-value simple moving average (SMA)
bid_df['volume_sma'] = bid_df['volume'].rolling(window=args.nb).mean()
ask_df['volume_sma'] = ask_df['volume'].rolling(window=args.nb).mean()

# Plot the data
plt.figure(figsize=(10, 6))

# Plot raw bids and asks
#plt.plot(bid_df['amount'], bid_df['volume'], label='Bids (Raw)', color='green', alpha=0.3)
#plt.plot(ask_df['amount'], ask_df['volume'], label='Asks (Raw)', color='red', alpha=0.3)

# Plot the moving average
plt.plot(bid_df['amount'], bid_df['volume_sma'], label='Bids (SMA)', color='darkgreen')
plt.plot(ask_df['amount'], ask_df['volume_sma'], label='Asks (SMA)', color='darkred')

plt.title(f"Order Book Depth: {args.crypto}/USDT (with n-value SMA)")
plt.xlabel('Price (USDT)')
plt.ylabel(f"Volume ({args.crypto})")
plt.legend()
plt.grid(True)
plt.show()

