Spaces:
Build error
Build error
File size: 3,649 Bytes
2e7bf75 cc81aa8 2e7bf75 bea6f61 2e7bf75 cc81aa8 2e7bf75 cc81aa8 2e7bf75 cc81aa8 2e7bf75 4710116 2e7bf75 81431a5 2e7bf75 81431a5 38c0eeb c29801f 81431a5 2e7bf75 81431a5 4710116 bea6f61 4710116 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | 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()
|