abolfazle80 commited on
Commit
e9303eb
·
verified ·
1 Parent(s): f1ae916

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -22
app.py CHANGED
@@ -2,9 +2,12 @@ import streamlit as st
2
  import requests
3
  import pandas as pd
4
  from datetime import datetime
 
 
5
 
6
  # Define the markets (cryptocurrencies to monitor)
7
  markets = ['DOTUSDT', 'BTCUSDT', 'ADAUSDT', 'BNBUSDT', 'SUIUSDT', 'XRPUSDT']
 
8
 
9
  # Function to get price and volume data from CoinEx
10
  def get_crypto_price_from_coinex(symbol):
@@ -29,26 +32,77 @@ def get_crypto_price_from_coinex(symbol):
29
  st.error(f"JSON decode error: {e}")
30
  return ["JSON decode error", "JSON decode error"]
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  # Streamlit UI elements
33
- st.title("Live Cryptocurrency Data")
34
-
35
- # Create a button to fetch the data
36
- if st.button("Fetch Live Data"):
37
- # Create a list to store data for all markets
38
- all_data = []
39
-
40
- # Fetch data for each market
41
- for market in markets:
42
- crypto_data = get_crypto_price_from_coinex(market)
43
- all_data.append([market, crypto_data[0], crypto_data[1]]) # [market, price, volume]
44
-
45
- # Convert the data into a DataFrame for easier display
46
- df = pd.DataFrame(all_data, columns=["Market", "Price (USDT)", "Volume (24h)"])
47
- df['Timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Add a timestamp column
48
-
49
- # Display the table
50
- st.write(df)
51
-
52
- # To update the page every 30 seconds to show live data:
53
- st.text("Refreshing data every 30 seconds...")
54
- st.experimental_rerun() # Automatically rerun the app to update the data every 30 seconds
 
 
 
2
  import requests
3
  import pandas as pd
4
  from datetime import datetime
5
+ import time
6
+ import threading
7
 
8
  # Define the markets (cryptocurrencies to monitor)
9
  markets = ['DOTUSDT', 'BTCUSDT', 'ADAUSDT', 'BNBUSDT', 'SUIUSDT', 'XRPUSDT']
10
+ filename = 'USDT.csv'
11
 
12
  # Function to get price and volume data from CoinEx
13
  def get_crypto_price_from_coinex(symbol):
 
32
  st.error(f"JSON decode error: {e}")
33
  return ["JSON decode error", "JSON decode error"]
34
 
35
+ # Initialize a flag to control the loop
36
+ loop_running = False
37
+
38
+ # Check if the file exists and write the header if it doesn't
39
+ file_exists = False
40
+ try:
41
+ with open(filename, 'r') as file:
42
+ file_exists = True
43
+ except FileNotFoundError:
44
+ file_exists = False
45
+
46
+ if not file_exists:
47
+ with open(filename, 'w', newline='') as file:
48
+ writer = csv.writer(file)
49
+ # Write header: price and volume for all cryptos in markets list, with a timestamp
50
+ header = []
51
+ for market in markets:
52
+ header.append(f'{market} Price')
53
+ header.append(f'{market} Volume')
54
+ header.append('Timestamp') # Add timestamp to the end
55
+ writer.writerow(header)
56
+
57
+ # Function to fetch data in a loop
58
+ def fetch_data():
59
+ global loop_running
60
+ while loop_running:
61
+ try:
62
+ all_data = []
63
+ for market in markets:
64
+ crypto_data = get_crypto_price_from_coinex(market)
65
+ all_data += crypto_data # Add price and volume to the list
66
+
67
+ timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Get the current timestamp
68
+ all_data.append(timestamp) # Add the timestamp to the data list
69
+
70
+ # Append the data to the CSV file
71
+ with open(filename, 'a', newline='') as file:
72
+ writer = csv.writer(file)
73
+ writer.writerow(all_data)
74
+
75
+ # Print confirmation to console
76
+ print(f'{all_data} data added')
77
+
78
+ # Sleep for 1 second before the next iteration
79
+ time.sleep(1)
80
+ except Exception as e:
81
+ st.error(f"An error occurred: {e}")
82
+ loop_running = False # Stop the loop in case of an error
83
+
84
  # Streamlit UI elements
85
+ st.title("Live Cryptocurrency Data with Start/Stop Loop")
86
+
87
+ # Button to start the loop
88
+ if st.button("Start Fetching Data"):
89
+ if not loop_running:
90
+ loop_running = True
91
+ # Run the fetch data function in a separate thread so it doesn't block the Streamlit UI
92
+ threading.Thread(target=fetch_data, daemon=True).start()
93
+ st.success("Started fetching data and saving it to CSV.")
94
+ else:
95
+ st.warning("Data fetching is already running.")
96
+
97
+ # Button to stop the loop
98
+ if st.button("Stop Fetching Data"):
99
+ loop_running = False
100
+ st.success("Stopped fetching data.")
101
+
102
+ # Display the latest data from the CSV (if available)
103
+ st.text("Latest Data from CSV:")
104
+ try:
105
+ df = pd.read_csv(filename)
106
+ st.write(df.tail()) # Show the last few rows of the CSV
107
+ except Exception as e:
108
+ st.error(f"Error reading the CSV: {e}")