import requests import matplotlib.pyplot as plt import matplotlib.dates as mdates import os from datetime import datetime, timedelta import numpy as np import streamlit as st DISCORD_WEBHOOK_URL = st.secrets["DISCORD_WEBHOOK"] def get_crypto_prices(): end_time = datetime.utcnow() start_time = end_time - timedelta(hours=48) coins = { 'bitcoin': 'bitcoin', 'ethereum': 'ethereum', 'tether': 'tether', 'ripple': 'xrp' } prices = {} for coin, coin_id in coins.items(): url = f'https://api.coincap.io/v2/assets/{coin_id}/history' params = { 'interval': 'm15', 'start': int(start_time.timestamp() * 1000), 'end': int(end_time.timestamp() * 1000) } response = requests.get(url, params=params) if response.status_code == 200: data = response.json().get('data', []) prices[coin] = [[int(item['time']), float(item['priceUsd'])] for item in data] if data: prices[coin].append([int(end_time.timestamp() * 1000), float(data[-1]['priceUsd'])]) else: st.error(f"Erreur lors de la récupération des prix pour {coin}: {response.status_code}") return prices def create_graph(prices_history): fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(15, 10)) axs = axs.flatten() for ax, (coin, prices) in zip(axs, prices_history.items()): if prices: times, price_values = zip(*prices) times = [datetime.fromtimestamp(t / 1000) for t in times] ax.plot(times, price_values, label=coin.capitalize()) ax.set_title(f'Prix de {coin.upper()} sur les 48 dernières heures') ax.set_xlabel('Heures') ax.set_ylabel('Prix en USD') ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) ax.xaxis.set_major_locator(mdates.HourLocator(interval=2)) plt.setp(ax.xaxis.get_majorticklabels(), rotation=45) ax.set_ylim(0, 1.5 * max(price_values)) ax.grid() ax.legend() plt.tight_layout() plt.savefig('crypto_prices_rectangle.png') plt.close() def send_to_discord(prices, image_path): embed = { "content": "Mise à jour des prix des crypto-monnaies", "embeds": [{ "title": "Prix des Cryptomonnaies", "color": 0x00ff00, "fields": [{"name": coin.capitalize(), "value": f"${prices.get(coin, [{}])[-1][1]:.2f}" if prices.get(coin) else "N/A", "inline": True} for coin in prices.keys()] }] } with open(image_path, 'rb') as f: requests.post(DISCORD_WEBHOOK_URL, json=embed, files={"file": (image_path, f)}) def run_script(): prices = get_crypto_prices() st.write(f"Prix récupérés: {prices}") prices_history = {coin: prices.get(coin, []) for coin in ['bitcoin', 'ethereum', 'tether', 'ripple']} create_graph(prices_history) send_to_discord(prices, 'crypto_prices_rectangle.png') st.image('crypto_prices_rectangle.png') # Affichage des prix actuels sous chaque graphique st.write("### Prix actuel des crypto-monnaies :") for coin, prices in prices_history.items(): if prices: current_price = prices[-1][1] st.write(f"- {coin.capitalize()}: ${current_price:,.2f}") st.success("Graphique créé et envoyé à Discord!") st.title("Suivi des Prix des Cryptomonnaies") if 'page_loaded' not in st.session_state: st.session_state.page_loaded = True run_script() if st.button("Rafraîchir les prix et envoyer à Discord"): run_script()