import csv
from binance.client import Client
from datetime import datetime, timedelta

# Replace with your Binance API key and secret
api_key = 'WFIEaBuUafZ9ldAiMHLZ4Z1qHdVnpoDUVZM8MughMf6zmbSqGx5pEmQFBJysjwFp'  # Optional for public data
api_secret = 'C9HtmLk7fBCidyJI2lPtUbYhj4T0FdmJ0NE0LLipFiwUSR7euf1TEzJblEx1O6oA'  # Optional for public data

# Initialize the Binance client
client = Client(api_key, api_secret)

def get_top_traded_coins(limit=20):
    """Get the top traded coins by volume."""
    tickers = client.get_ticker()
    # Sort by quote volume (most traded)
    sorted_tickers = sorted(tickers, key=lambda x: float(x['quoteVolume']), reverse=True)
    # Extract the top 'limit' coins
    top_coins = [ticker['symbol'] for ticker in sorted_tickers[:limit]]
    return top_coins

def get_historical_prices(symbol, days=30):
    """Get historical prices for a symbol over the last 'days' days."""
    end_time = datetime.now()
    start_time = end_time - timedelta(days=days)
    klines = client.get_historical_klines(symbol, Client.KLINE_INTERVAL_1DAY, start_time.strftime("%d %b, %Y"), end_time.strftime("%d %b, %Y"))
    # Extract closing prices
    prices = [float(kline[4]) for kline in klines]
    return prices

def save_to_csv(data, days, filename='crypto_prices.csv'):
    """Save the data to a CSV file."""
    with open(filename, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['Symbol'] + [f'Day {i+1}' for i in range(days)])
        for symbol, prices in data.items():
            writer.writerow([symbol] + prices)

def main():
    # Get the top 20 traded coins
    top_coins = get_top_traded_coins(20)
    
    # Fetch historical prices for each coin
    crypto_prices = {}
    for coin in top_coins:
        print(f"Fetching prices for {coin}...")
        prices = get_historical_prices(coin, 60)
        crypto_prices[coin] = prices
    
    # Save the data to a CSV file
    save_to_csv(crypto_prices, 60)
    print("Data saved to crypto_prices.csv")

if __name__ == "__main__":
    main()