Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,13 +5,15 @@ from datetime import datetime
|
|
5 |
import time
|
6 |
import csv
|
7 |
import threading
|
|
|
8 |
import os
|
9 |
-
|
10 |
|
11 |
-
# Hugging Face
|
12 |
-
HF_USERNAME = "abolfazle80"
|
13 |
-
REPO_NAME = "crypto_data"
|
14 |
-
CSV_FILENAME = "USDT.csv"
|
|
|
15 |
|
16 |
# Define the markets (cryptocurrencies to monitor)
|
17 |
markets = ['DOTUSDT', 'BTCUSDT', 'ADAUSDT', 'BNBUSDT', 'SUIUSDT', 'XRPUSDT']
|
@@ -19,27 +21,41 @@ markets = ['DOTUSDT', 'BTCUSDT', 'ADAUSDT', 'BNBUSDT', 'SUIUSDT', 'XRPUSDT']
|
|
19 |
# Initialize Hugging Face API
|
20 |
api = HfApi()
|
21 |
|
22 |
-
#
|
23 |
-
|
|
|
|
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
try:
|
30 |
-
hf_hub_download(
|
31 |
-
repo_id=f"{HF_USERNAME}/{REPO_NAME}",
|
32 |
-
filename=CSV_FILENAME,
|
33 |
-
repo_type="dataset",
|
34 |
-
local_dir=".", # Save in current directory
|
35 |
-
)
|
36 |
-
print("β
CSV downloaded successfully!")
|
37 |
-
except Exception as e:
|
38 |
-
print(f"β Download failed: {e}")
|
39 |
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
def upload_to_huggingface():
|
42 |
-
"""Uploads the CSV file to the Hugging Face dataset repo."""
|
43 |
try:
|
44 |
api.upload_file(
|
45 |
path_or_fileobj=CSV_FILENAME,
|
@@ -51,85 +67,64 @@ def upload_to_huggingface():
|
|
51 |
except Exception as e:
|
52 |
print(f"β Upload failed: {e}")
|
53 |
|
54 |
-
# Function to fetch
|
55 |
def fetch_data():
|
56 |
-
"""Fetches crypto data, appends to CSV, and uploads to Hugging Face."""
|
57 |
global loop_running
|
58 |
while loop_running:
|
59 |
try:
|
60 |
all_data = []
|
61 |
for market in markets:
|
62 |
crypto_data = get_crypto_price_from_coinex(market)
|
63 |
-
all_data += crypto_data
|
64 |
-
|
65 |
-
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Timestamp
|
66 |
-
all_data.append(timestamp) # Append timestamp to row
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
with open(CSV_FILENAME, "a", newline="") as file:
|
71 |
-
writer = csv.writer(file)
|
72 |
-
if not file_exists:
|
73 |
-
# Write header if the file was just created
|
74 |
-
header = [f"{m} Price" for m in markets] + [f"{m} Volume" for m in markets] + ["Timestamp"]
|
75 |
-
writer.writerow(header)
|
76 |
-
writer.writerow(all_data) # Append new row
|
77 |
|
78 |
-
|
|
|
79 |
|
80 |
-
#
|
81 |
-
|
|
|
|
|
82 |
|
83 |
-
|
84 |
-
|
85 |
-
print(f"β Error: {e}")
|
86 |
-
loop_running = False # Stop loop if error occurs
|
87 |
|
88 |
-
#
|
89 |
-
|
90 |
-
url = 'https://api.coinex.com/v1/market/ticker'
|
91 |
-
params = {'market': symbol}
|
92 |
|
93 |
-
|
94 |
-
response = requests.get(url, params=params)
|
95 |
-
response.raise_for_status() # Check for HTTP errors
|
96 |
-
data = response.json()
|
97 |
|
98 |
-
|
99 |
-
|
100 |
-
volume = data['data']['ticker']['vol']
|
101 |
-
return [price, volume] # Return as list
|
102 |
-
else:
|
103 |
-
return ["Symbol not found", "Symbol not found"]
|
104 |
-
except requests.exceptions.RequestException as e:
|
105 |
-
return ["Request error", "Request error"]
|
106 |
-
except ValueError as e:
|
107 |
-
return ["JSON decode error", "JSON decode error"]
|
108 |
|
109 |
-
#
|
110 |
-
|
|
|
|
|
111 |
|
112 |
-
#
|
113 |
-
|
114 |
|
115 |
-
# Start
|
116 |
if st.button("Start Fetching Data"):
|
117 |
if not loop_running:
|
118 |
loop_running = True
|
119 |
threading.Thread(target=fetch_data, daemon=True).start()
|
120 |
-
st.success("β
Started fetching
|
121 |
else:
|
122 |
-
st.warning("β οΈ
|
123 |
|
124 |
-
# Stop
|
125 |
if st.button("Stop Fetching Data"):
|
126 |
loop_running = False
|
127 |
st.success("π Stopped fetching data.")
|
128 |
|
129 |
-
# Show
|
130 |
-
st.
|
131 |
try:
|
132 |
df = pd.read_csv(CSV_FILENAME)
|
133 |
-
st.write(df.tail())
|
134 |
except Exception as e:
|
135 |
-
st.error(f"
|
|
|
5 |
import time
|
6 |
import csv
|
7 |
import threading
|
8 |
+
from huggingface_hub import HfApi
|
9 |
import os
|
10 |
+
import io
|
11 |
|
12 |
+
# Hugging Face Info
|
13 |
+
HF_USERNAME = "abolfazle80"
|
14 |
+
REPO_NAME = "crypto_data"
|
15 |
+
CSV_FILENAME = "USDT.csv"
|
16 |
+
HF_CSV_URL = f"https://huggingface.co/datasets/{HF_USERNAME}/{REPO_NAME}/resolve/main/{CSV_FILENAME}"
|
17 |
|
18 |
# Define the markets (cryptocurrencies to monitor)
|
19 |
markets = ['DOTUSDT', 'BTCUSDT', 'ADAUSDT', 'BNBUSDT', 'SUIUSDT', 'XRPUSDT']
|
|
|
21 |
# Initialize Hugging Face API
|
22 |
api = HfApi()
|
23 |
|
24 |
+
# Function to fetch data from CoinEx
|
25 |
+
def get_crypto_price_from_coinex(symbol):
|
26 |
+
url = 'https://api.coinex.com/v1/market/ticker'
|
27 |
+
params = {'market': symbol}
|
28 |
|
29 |
+
try:
|
30 |
+
response = requests.get(url, params=params)
|
31 |
+
response.raise_for_status()
|
32 |
+
data = response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
+
if 'data' in data:
|
35 |
+
price = data['data']['ticker']['last']
|
36 |
+
volume = data['data']['ticker']['vol']
|
37 |
+
return [price, volume]
|
38 |
+
else:
|
39 |
+
return ["Symbol not found", "Symbol not found"]
|
40 |
+
except Exception as e:
|
41 |
+
st.error(f"Error fetching data: {e}")
|
42 |
+
return ["Error", "Error"]
|
43 |
+
|
44 |
+
# Function to download existing CSV from Hugging Face
|
45 |
+
def download_existing_csv():
|
46 |
+
try:
|
47 |
+
response = requests.get(HF_CSV_URL)
|
48 |
+
response.raise_for_status()
|
49 |
+
|
50 |
+
csv_data = io.StringIO(response.text)
|
51 |
+
df = pd.read_csv(csv_data)
|
52 |
+
|
53 |
+
return df # Return existing DataFrame
|
54 |
+
except requests.exceptions.RequestException:
|
55 |
+
return pd.DataFrame() # Return empty DataFrame if file doesn't exist
|
56 |
+
|
57 |
+
# Function to upload the CSV back to Hugging Face
|
58 |
def upload_to_huggingface():
|
|
|
59 |
try:
|
60 |
api.upload_file(
|
61 |
path_or_fileobj=CSV_FILENAME,
|
|
|
67 |
except Exception as e:
|
68 |
print(f"β Upload failed: {e}")
|
69 |
|
70 |
+
# Function to fetch, append & update the CSV
|
71 |
def fetch_data():
|
|
|
72 |
global loop_running
|
73 |
while loop_running:
|
74 |
try:
|
75 |
all_data = []
|
76 |
for market in markets:
|
77 |
crypto_data = get_crypto_price_from_coinex(market)
|
78 |
+
all_data += crypto_data
|
|
|
|
|
|
|
79 |
|
80 |
+
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
81 |
+
all_data.append(timestamp)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
+
# Load existing data
|
84 |
+
df_existing = download_existing_csv()
|
85 |
|
86 |
+
# Convert new data to DataFrame
|
87 |
+
df_new = pd.DataFrame([all_data], columns=[f"{m} Price" for m in markets] +
|
88 |
+
[f"{m} Volume" for m in markets] +
|
89 |
+
["Timestamp"])
|
90 |
|
91 |
+
# Append new data to existing data
|
92 |
+
df_combined = pd.concat([df_existing, df_new], ignore_index=True)
|
|
|
|
|
93 |
|
94 |
+
# Save updated data to CSV
|
95 |
+
df_combined.to_csv(CSV_FILENAME, index=False)
|
|
|
|
|
96 |
|
97 |
+
print(f"β
{all_data} added to CSV and uploaded.")
|
|
|
|
|
|
|
98 |
|
99 |
+
# Upload to Hugging Face
|
100 |
+
upload_to_huggingface()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
|
102 |
+
time.sleep(1) # Fetch new data every second
|
103 |
+
except Exception as e:
|
104 |
+
st.error(f"An error occurred: {e}")
|
105 |
+
loop_running = False
|
106 |
|
107 |
+
# Streamlit UI
|
108 |
+
st.title("π Live Cryptocurrency Data Fetching")
|
109 |
|
110 |
+
# Start Fetching Button
|
111 |
if st.button("Start Fetching Data"):
|
112 |
if not loop_running:
|
113 |
loop_running = True
|
114 |
threading.Thread(target=fetch_data, daemon=True).start()
|
115 |
+
st.success("β
Started fetching and saving data.")
|
116 |
else:
|
117 |
+
st.warning("β οΈ Fetching is already running.")
|
118 |
|
119 |
+
# Stop Fetching Button
|
120 |
if st.button("Stop Fetching Data"):
|
121 |
loop_running = False
|
122 |
st.success("π Stopped fetching data.")
|
123 |
|
124 |
+
# Show Latest Data
|
125 |
+
st.text("π Latest Data from CSV:")
|
126 |
try:
|
127 |
df = pd.read_csv(CSV_FILENAME)
|
128 |
+
st.write(df.tail())
|
129 |
except Exception as e:
|
130 |
+
st.error(f"Error reading CSV: {e}")
|