missbaj commited on
Commit
b42a644
·
verified ·
1 Parent(s): c16abe6
Files changed (1) hide show
  1. app.py +26 -171
app.py CHANGED
@@ -1,184 +1,39 @@
1
  import streamlit as st
2
  import requests
3
- import pandas as pd
4
- import plotly.graph_objs as go
5
  from datetime import datetime
6
- from requests.adapters import HTTPAdapter
7
- from requests.packages.urllib3.util.retry import Retry
8
 
9
- # Function to create a session with retry logic
10
- def create_session():
11
- session = requests.Session()
12
- retry = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
13
- adapter = HTTPAdapter(max_retries=retry)
14
- session.mount('http://', adapter)
15
- session.mount('https://', adapter)
16
- return session
17
-
18
- # Function to fetch historical price data from CoinGecko
19
- def fetch_historical_data(coin_id, from_timestamp, to_timestamp):
20
- url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart/range?vs_currency=usd&from={from_timestamp}&to={to_timestamp}"
21
- session = create_session()
22
- try:
23
- response = session.get(url)
24
- response.raise_for_status()
25
- data = response.json()
26
- prices = data.get('prices', [])
27
- if not prices:
28
- return "No historical data available for the selected date range."
29
- return prices
30
- except requests.RequestException as e:
31
- return f"Error fetching historical data: {e}"
32
-
33
- # Function to fetch current prices from CoinGecko
34
- def fetch_current_price(coin_id):
35
  url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd"
36
- session = create_session()
37
  try:
38
- response = session.get(url)
39
  response.raise_for_status()
40
  data = response.json()
41
- price = data.get(coin_id, {}).get('usd', 'N/A')
42
- return price
43
  except requests.RequestException as e:
44
- return f"Error fetching current price: {e}"
45
-
46
- # Function to convert dates to timestamps
47
- def date_to_timestamp(date_str):
48
- try:
49
- return int(pd.Timestamp(date_str).timestamp())
50
- except Exception as e:
51
- st.error(f"Error converting date to timestamp: {e}")
52
- return None
53
-
54
- # Function to plot historical prices using Plotly
55
- def plot_historical_prices(coin_name, from_date, to_date):
56
- from_timestamp = date_to_timestamp(from_date)
57
- to_timestamp = date_to_timestamp(to_date)
58
-
59
- if from_timestamp is None or to_timestamp is None:
60
- return "Invalid date format. Please ensure dates are in YYYY-MM-DD format."
61
-
62
- prices = fetch_historical_data(coin_name, from_timestamp, to_timestamp)
63
-
64
- if isinstance(prices, str): # Error message
65
- return prices
66
-
67
- try:
68
- df = pd.DataFrame(prices, columns=['timestamp', 'price'])
69
- df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
70
-
71
- fig = go.Figure()
72
- fig.add_trace(go.Scatter(x=df['date'], y=df['price'], mode='lines', name=coin_name))
73
- fig.update_layout(title=f'{coin_name.capitalize()} Prices from {from_date} to {to_date}', xaxis_title='Date', yaxis_title='Price (USD)')
74
- return fig
75
- except Exception as e:
76
- return f"Error plotting historical prices: {e}"
77
-
78
- # Function to provide TradingView widget HTML
79
- def tradingview_widget():
80
- return """
81
- <iframe
82
- src="https://www.tradingview.com/widgetembed/?frameElementId=tradingview_ea33b&symbol=BINANCE:BTCUSDT&interval=60"
83
- width="800"
84
- height="600"
85
- frameborder="0"
86
- allowtransparency="true"
87
- scrolling="no"
88
- allowfullscreen="true">
89
- </iframe>
90
- """
91
-
92
- # Functions for mocked analyses
93
- def analyze_order_book():
94
- return "Order book analysis: Buying pressure above, selling pressure below."
95
-
96
- def analyze_technicals():
97
- return "Technical analysis: Divergence detected, RSI showing overbought."
98
-
99
- def analyze_funding_rate():
100
- return "Funding rate: Higher on longs, suggesting bullish sentiment."
101
-
102
- def analyze_on_chain():
103
- return "On-chain analysis: Ichimoku cloud shows potential reversal."
104
 
105
- def analyze_news():
106
- return "News analysis: Positive sentiment with increasing institutional interest."
107
 
108
- def btc_analysis():
109
- order_book = analyze_order_book()
110
- technicals = analyze_technicals()
111
- funding_rate = analyze_funding_rate()
112
- on_chain = analyze_on_chain()
113
- news = analyze_news()
114
-
115
- return f"""
116
- {order_book}
117
- {technicals}
118
- {funding_rate}
119
- {on_chain}
120
- {news}
121
- """
122
 
123
- # Function to fetch real-time trade data from CoinGecko
124
- def fetch_real_time_trade_data(coin_id):
125
- url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart?vs_currency=usd&days=1"
126
- session = create_session()
127
- try:
128
- response = session.get(url)
129
- response.raise_for_status()
130
- data = response.json()
131
- prices = data.get('prices', [])
132
- if prices:
133
- return prices[-1] # Latest price data
134
- return "No real-time data available"
135
- except requests.RequestException as e:
136
- return f"Error fetching real-time trade data: {e}"
137
-
138
- # Streamlit App Layout
139
- st.title("Cryptocurrency Dashboard")
140
-
141
- # Dropdown for selecting cryptocurrency
142
- top_100_cryptos = [
143
- 'bitcoin', 'ethereum', 'binancecoin', 'ripple', 'solana', 'cardano', 'dogecoin', 'polygon', 'polkadot', 'tron',
144
- # Add more top coins as necessary
145
- ]
146
-
147
- selected_crypto = st.sidebar.selectbox("Select Cryptocurrency", top_100_cryptos)
148
-
149
- # Tabs for different functionalities
150
- tab = st.sidebar.radio("Choose a Tab", ["Price Chart", "Current Price", "Real-Time Trade Data", "AI BTC Analysis", "TradingView Chart"])
151
-
152
- if tab == "Price Chart":
153
- st.header("Cryptocurrency Price Chart")
154
- from_date = st.date_input("From Date", value=pd.Timestamp("2024-01-01"))
155
- to_date = st.date_input("To Date", value=pd.Timestamp("2025-12-31"))
156
-
157
- if st.button("Plot Chart"):
158
- fig = plot_historical_prices(selected_crypto, from_date, to_date)
159
- if isinstance(fig, str): # Error message
160
- st.error(fig)
161
- else:
162
- st.plotly_chart(fig)
163
-
164
- elif tab == "Current Price":
165
- st.header("Current Cryptocurrency Price")
166
- price = fetch_current_price(selected_crypto)
167
- st.write(f"The current price of {selected_crypto.capitalize()} is: ${price}")
168
-
169
- elif tab == "Real-Time Trade Data":
170
- st.header("Real-Time Cryptocurrency Trade Data")
171
- data = fetch_real_time_trade_data(selected_crypto)
172
- if isinstance(data, str): # Error message
173
- st.error(data)
174
  else:
175
- st.write(f"The latest trading data for {selected_crypto.capitalize()} is: ${data[1]}")
176
-
177
- elif tab == "AI BTC Analysis":
178
- st.header("AI-Powered BTC Analysis")
179
- analysis = btc_analysis()
180
- st.write(analysis)
181
-
182
- elif tab == "TradingView Chart":
183
- st.header("Live TradingView Chart")
184
- st.markdown(tradingview_widget(), unsafe_allow_html=True)
 
 
1
  import streamlit as st
2
  import requests
3
+ import time
 
4
  from datetime import datetime
 
 
5
 
6
+ # Function to fetch real-time data from CoinGecko
7
+ def fetch_real_time_data(coin_id):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd"
 
9
  try:
10
+ response = requests.get(url)
11
  response.raise_for_status()
12
  data = response.json()
13
+ return data
 
14
  except requests.RequestException as e:
15
+ return {"error": str(e)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ # Streamlit app
18
+ st.title("Real-Time Cryptocurrency Data")
19
 
20
+ # Input for selecting cryptocurrency
21
+ coin = st.selectbox("Select Cryptocurrency", ["bitcoin", "ethereum", "binancecoin"])
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Button to fetch data
24
+ if st.button("Fetch Data"):
25
+ data = fetch_real_time_data(coin)
26
+ if "error" in data:
27
+ st.error(f"Error: {data['error']}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  else:
29
+ st.write(f"The current price of {coin.capitalize()} is: ${data[coin]['usd']}")
30
+
31
+ # Periodic updates
32
+ st.write("Updating data every 5 minutes...")
33
+ while True:
34
+ data = fetch_real_time_data(coin)
35
+ if "error" in data:
36
+ st.error(f"Error: {data['error']}")
37
+ else:
38
+ st.write(f"Last updated at {datetime.now()}: The current price of {coin.capitalize()} is: ${data[coin]['usd']}")
39
+ time.sleep(300) # Update every 5 minutes