ArcheanVision commited on
Commit
0c6421d
·
verified ·
1 Parent(s): d9a70da

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -99
app.py CHANGED
@@ -20,6 +20,11 @@ print(response.status_code)
20
  print(response.text)
21
  import warnings
22
  import logging
 
 
 
 
 
23
 
24
  # Suppress deprecation warnings about experimental query params functions
25
  warnings.filterwarnings(
@@ -32,14 +37,14 @@ warnings.filterwarnings(
32
  )
33
  warnings.filterwarnings("ignore", category=DeprecationWarning)
34
 
35
- # Adjust the Streamlit loggers to only show errors
36
  logging.getLogger("streamlit.deprecation").setLevel(logging.ERROR)
37
  logging.getLogger("streamlit.runtime.scriptrunner").setLevel(logging.ERROR)
38
 
39
  import streamlit as st
40
  import pandas as pd
41
  import plotly.express as px
42
- from archeanvision import ArcheanVisionAPI
43
 
44
  # ---------------------------- #
45
  # AUTO-REFRESH #
@@ -49,49 +54,88 @@ st.set_page_config(
49
  layout="wide"
50
  )
51
 
52
- REFRESH_INTERVAL = 260 # 160 seconds
53
  st.markdown(f"<meta http-equiv='refresh' content='{REFRESH_INTERVAL}'>", unsafe_allow_html=True)
54
  # ---------------------------- #
55
 
56
  LOGO_IMAGE_URL = "https://archeanvision.com/assets/archeanvision.png"
57
  st.sidebar.image(LOGO_IMAGE_URL, use_container_width=True, caption="ArcheanVision")
58
 
59
- # Replace with your API key
60
- #API_KEY = "0be4b0d76de6cf65b81e0a2de91b137f432e5a66e6d0c622d73c4b83e613e948"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  def get_selected_market(market_list):
63
  """
64
  Returns the selected market from the URL query params or defaults to the first item.
65
- Also updates the query param if the user picks a different market from the dropdown.
66
 
67
- Using experimental_* methods for compatibility with older Streamlit versions (<1.25).
68
  """
69
- # 1. Read current query parameters (EXPERIMENTAL)
70
  params = st.experimental_get_query_params()
71
-
72
- # 2. Check if 'market' param is set; otherwise default to the first market
73
  if "market" in params:
74
  default_market = params["market"]
75
- # If it's a list, pick the first element
76
  if isinstance(default_market, list):
77
  default_market = default_market[0]
78
  else:
79
  default_market = market_list[0]
80
 
81
- # 3. Determine the index to use in the selectbox
82
  if default_market in market_list:
83
  default_index = market_list.index(default_market)
84
  else:
85
  default_index = 0
86
 
87
- # 4. Create the dropdown
88
  selected = st.selectbox("Select a market:", market_list, index=default_index)
89
-
90
- # 5. If user picks a new market, update URL param (EXPERIMENTAL)
91
  if selected != default_market:
92
- params["market"] = selected
93
- st.experimental_set_query_params(**params)
94
-
95
  return selected
96
 
97
  def main():
@@ -99,39 +143,38 @@ def main():
99
 
100
  st.markdown("""
101
  ### What is ArcheanVision?
102
-
103
  **ArcheanVision** is an autonomous multi-market trading agent.
104
  It operates simultaneously on multiple crypto assets, monitoring price movements
105
  in real time and delivering **data** as well as **signals** (BUY, SELL, etc.)
106
  to automate and optimize decision-making.
107
-
108
  - **AI Agent**: Continuously analyzes crypto markets.
109
  - **Multi-Market**: Manages multiple assets at once.
110
  - **Live Data**: Access to streaming data feeds (SSE).
111
  - **Buy/Sell Signals**: Generated in real-time to seize market opportunities.
112
-
113
  Below is a dashboard showcasing the active markets, their 24h data
114
  (1,440 most recent data points), and their associated signals.
115
-
116
  ---
117
  **Join our Discord as a beta tester** to help improve the agent and the system.
118
  - Official platform: [https://archeanvision.com](https://archeanvision.com)
119
  - Discord link: [https://discord.gg/k9xHuM7Jr8](https://discord.gg/k9xHuM7Jr8)
120
  """)
121
 
122
- # 1. Initialize the API
123
- api = ArcheanVisionAPI(api_key=API_KEY)
124
-
125
- # 2. Retrieve active markets
126
- active_markets = api.get_active_markets()
 
 
127
  if not active_markets:
128
  st.error("No active markets found through the API.")
129
  return
130
 
131
- # 3. Build a list of markets
132
  market_list = []
133
  if isinstance(active_markets, list):
134
  for item in active_markets:
 
135
  if isinstance(item, dict) and "market" in item:
136
  market_list.append(item["market"])
137
  elif isinstance(item, str):
@@ -141,83 +184,82 @@ def main():
141
  else:
142
  st.error("The structure of 'active_markets' is not a list as expected.")
143
  return
144
-
145
  if not market_list:
146
  st.error("The market list is empty or 'market' keys not found.")
147
  return
148
 
149
- # 4. Get the selected market from (experimental) query params or default
150
  selected_market = get_selected_market(market_list)
151
-
152
- if selected_market:
153
- st.subheader(f"Selected Market: {selected_market}")
154
- st.write(f"Fetching data for **{selected_market}** ...")
155
-
156
- # 5. Retrieve market data (1,440 points ~24h)
157
- market_data = api.get_market_data(selected_market)
158
- if not market_data:
159
- st.error(f"No data found for market {selected_market}.")
160
- return
161
-
162
- # 6. Convert to DataFrame & parse 'close_time'
163
- df = pd.DataFrame(market_data)
164
- if "close_time" in df.columns:
165
- df['close_time'] = pd.to_datetime(df['close_time'], unit='ms', errors='coerce')
166
- else:
167
- st.error("The 'close_time' column is missing from the retrieved data.")
168
- return
169
-
170
- st.write("### Market Data Overview")
171
- st.dataframe(df.head())
172
-
173
- # 7. Check columns before plotting
174
- required_cols = {"close", "last_predict_15m", "last_predict_1h"}
175
- if not required_cols.issubset(df.columns):
176
- st.error(
177
- f"The required columns {required_cols} are not all present. "
178
- f"Available columns: {list(df.columns)}"
179
- )
180
- return
181
-
182
- # 8. Create a Plotly line chart
183
- fig = px.line(
184
- df,
185
- x='close_time',
186
- y=['close', 'last_predict_15m', 'last_predict_1h'],
187
- title=f"{selected_market} : Close Price & Predictions",
188
- labels={
189
- 'close_time': 'Time',
190
- 'value': 'Price',
191
- 'variable': 'Metric'
192
- }
193
  )
194
- st.plotly_chart(fig, use_container_width=True)
195
-
196
- # 9. Retrieve & display signals for the selected market
197
- st.write(f"### Signals for {selected_market}")
198
- signals = api.get_market_signals(selected_market)
199
- if not signals:
200
- st.warning(f"No signals found for market {selected_market}.")
201
- else:
202
- df_signals = pd.DataFrame(signals)
203
-
204
- # Convert 'date' if present
205
- if 'date' in df_signals.columns:
206
- df_signals['date'] = pd.to_datetime(df_signals['date'], unit='ms', errors='coerce')
207
-
208
- # Fix Arrow errors for dict columns
209
- for col in df_signals.columns:
210
- if df_signals[col].apply(lambda x: isinstance(x, dict)).any():
211
- df_signals[col] = df_signals[col].apply(lambda x: str(x) if isinstance(x, dict) else x)
212
-
213
- # Sort signals by date descending if desired
214
- if 'date' in df_signals.columns:
215
- df_signals = df_signals.sort_values('date', ascending=False)
216
-
217
- st.write("Total number of signals:", len(df_signals))
218
- st.write("Preview of the last 4 signals:")
219
- st.dataframe(df_signals.head(4))
 
 
 
 
 
 
 
 
 
 
220
 
221
  if __name__ == "__main__":
222
  main()
223
-
 
20
  print(response.text)
21
  import warnings
22
  import logging
23
+ import os
24
+ from dotenv import load_dotenv
25
+
26
+ # Load environment variables from .env
27
+ load_dotenv()
28
 
29
  # Suppress deprecation warnings about experimental query params functions
30
  warnings.filterwarnings(
 
37
  )
38
  warnings.filterwarnings("ignore", category=DeprecationWarning)
39
 
40
+ # Adjust Streamlit loggers to show only errors
41
  logging.getLogger("streamlit.deprecation").setLevel(logging.ERROR)
42
  logging.getLogger("streamlit.runtime.scriptrunner").setLevel(logging.ERROR)
43
 
44
  import streamlit as st
45
  import pandas as pd
46
  import plotly.express as px
47
+ import cloudscraper
48
 
49
  # ---------------------------- #
50
  # AUTO-REFRESH #
 
54
  layout="wide"
55
  )
56
 
57
+ REFRESH_INTERVAL = 260 # seconds
58
  st.markdown(f"<meta http-equiv='refresh' content='{REFRESH_INTERVAL}'>", unsafe_allow_html=True)
59
  # ---------------------------- #
60
 
61
  LOGO_IMAGE_URL = "https://archeanvision.com/assets/archeanvision.png"
62
  st.sidebar.image(LOGO_IMAGE_URL, use_container_width=True, caption="ArcheanVision")
63
 
64
+ # Get the API key from environment variables (stored in .env or Hugging Face Secrets)
65
+ if not API_KEY:
66
+ st.error("API_KEY is not set. Please add it to your environment (e.g. .env file or Hugging Face Secrets).")
67
+ st.stop()
68
+
69
+ # --- Helper Functions Using cloudscraper ---
70
+
71
+ def get_active_markets_cloudscraper(api_key):
72
+ """Retrieves the list of active markets using cloudscraper to bypass Cloudflare."""
73
+ headers = {
74
+ "Authorization": f"Bearer {api_key}",
75
+ "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
76
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
77
+ "Chrome/115.0.0.0 Safari/537.36")
78
+ }
79
+ url = "https://archeanvision.com/api/signals/available"
80
+ scraper = cloudscraper.create_scraper()
81
+ response = scraper.get(url, headers=headers)
82
+ response.raise_for_status() # Raises an exception for HTTP errors
83
+ return response.json() # Assuming the endpoint returns JSON
84
+
85
+ def get_market_data_cloudscraper(api_key, market):
86
+ """Retrieves market data for the given market using cloudscraper."""
87
+ headers = {
88
+ "Authorization": f"Bearer {api_key}",
89
+ "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
90
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
91
+ "Chrome/115.0.0.0 Safari/537.36")
92
+ }
93
+ # Endpoint for market data (1,440 points ~ 24h); adjust as per API docs
94
+ url = f"https://archeanvision.com/api/signals/{market}/data"
95
+ scraper = cloudscraper.create_scraper()
96
+ response = scraper.get(url, headers=headers)
97
+ response.raise_for_status()
98
+ return response.json()
99
+
100
+ def get_market_signals_cloudscraper(api_key, market):
101
+ """Retrieves market signals for the given market using cloudscraper."""
102
+ headers = {
103
+ "Authorization": f"Bearer {api_key}",
104
+ "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
105
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
106
+ "Chrome/115.0.0.0 Safari/537.36")
107
+ }
108
+ url = f"https://archeanvision.com/api/signals/{market}/signals"
109
+ scraper = cloudscraper.create_scraper()
110
+ response = scraper.get(url, headers=headers)
111
+ response.raise_for_status()
112
+ return response.json()
113
+
114
+ # --- End Helper Functions ---
115
 
116
  def get_selected_market(market_list):
117
  """
118
  Returns the selected market from the URL query params or defaults to the first item.
119
+ Also updates the query parameter if the user picks a different market from the dropdown.
120
 
121
+ (Uses experimental methods for compatibility with older Streamlit versions.)
122
  """
 
123
  params = st.experimental_get_query_params()
 
 
124
  if "market" in params:
125
  default_market = params["market"]
 
126
  if isinstance(default_market, list):
127
  default_market = default_market[0]
128
  else:
129
  default_market = market_list[0]
130
 
 
131
  if default_market in market_list:
132
  default_index = market_list.index(default_market)
133
  else:
134
  default_index = 0
135
 
 
136
  selected = st.selectbox("Select a market:", market_list, index=default_index)
 
 
137
  if selected != default_market:
138
+ st.experimental_set_query_params(market=selected)
 
 
139
  return selected
140
 
141
  def main():
 
143
 
144
  st.markdown("""
145
  ### What is ArcheanVision?
 
146
  **ArcheanVision** is an autonomous multi-market trading agent.
147
  It operates simultaneously on multiple crypto assets, monitoring price movements
148
  in real time and delivering **data** as well as **signals** (BUY, SELL, etc.)
149
  to automate and optimize decision-making.
 
150
  - **AI Agent**: Continuously analyzes crypto markets.
151
  - **Multi-Market**: Manages multiple assets at once.
152
  - **Live Data**: Access to streaming data feeds (SSE).
153
  - **Buy/Sell Signals**: Generated in real-time to seize market opportunities.
 
154
  Below is a dashboard showcasing the active markets, their 24h data
155
  (1,440 most recent data points), and their associated signals.
 
156
  ---
157
  **Join our Discord as a beta tester** to help improve the agent and the system.
158
  - Official platform: [https://archeanvision.com](https://archeanvision.com)
159
  - Discord link: [https://discord.gg/k9xHuM7Jr8](https://discord.gg/k9xHuM7Jr8)
160
  """)
161
 
162
+ # Retrieve active markets using cloudscraper
163
+ try:
164
+ active_markets = get_active_markets_cloudscraper(API_KEY)
165
+ except Exception as e:
166
+ st.error(f"Error fetching active markets: {e}")
167
+ return
168
+
169
  if not active_markets:
170
  st.error("No active markets found through the API.")
171
  return
172
 
173
+ # Expecting active_markets to be a list of market names, e.g. ["BTC", "ETH", ...]
174
  market_list = []
175
  if isinstance(active_markets, list):
176
  for item in active_markets:
177
+ # Depending on the response structure, adjust accordingly.
178
  if isinstance(item, dict) and "market" in item:
179
  market_list.append(item["market"])
180
  elif isinstance(item, str):
 
184
  else:
185
  st.error("The structure of 'active_markets' is not a list as expected.")
186
  return
187
+
188
  if not market_list:
189
  st.error("The market list is empty or 'market' keys not found.")
190
  return
191
 
 
192
  selected_market = get_selected_market(market_list)
193
+ if not selected_market:
194
+ st.error("No market selected.")
195
+ return
196
+
197
+ st.subheader(f"Selected Market: {selected_market}")
198
+ st.write(f"Fetching data for **{selected_market}** ...")
199
+
200
+ # Retrieve market data using cloudscraper
201
+ try:
202
+ market_data = get_market_data_cloudscraper(API_KEY, selected_market)
203
+ except Exception as e:
204
+ st.error(f"Error fetching market data for {selected_market}: {e}")
205
+ return
206
+
207
+ if not market_data:
208
+ st.error(f"No data found for market {selected_market}.")
209
+ return
210
+
211
+ df = pd.DataFrame(market_data)
212
+ if "close_time" in df.columns:
213
+ df['close_time'] = pd.to_datetime(df['close_time'], unit='ms', errors='coerce')
214
+ else:
215
+ st.error("The 'close_time' column is missing from the retrieved data.")
216
+ return
217
+
218
+ st.write("### Market Data Overview")
219
+ st.dataframe(df.head())
220
+
221
+ required_cols = {"close", "last_predict_15m", "last_predict_1h"}
222
+ if not required_cols.issubset(df.columns):
223
+ st.error(
224
+ f"The required columns {required_cols} are not all present. "
225
+ f"Available columns: {list(df.columns)}"
 
 
 
 
 
 
 
 
 
226
  )
227
+ return
228
+
229
+ fig = px.line(
230
+ df,
231
+ x='close_time',
232
+ y=['close', 'last_predict_15m', 'last_predict_1h'],
233
+ title=f"{selected_market} : Close Price & Predictions",
234
+ labels={
235
+ 'close_time': 'Time',
236
+ 'value': 'Price',
237
+ 'variable': 'Metric'
238
+ }
239
+ )
240
+ st.plotly_chart(fig, use_container_width=True)
241
+
242
+ st.write(f"### Signals for {selected_market}")
243
+ try:
244
+ signals = get_market_signals_cloudscraper(API_KEY, selected_market)
245
+ except Exception as e:
246
+ st.error(f"Error fetching signals for {selected_market}: {e}")
247
+ return
248
+
249
+ if not signals:
250
+ st.warning(f"No signals found for market {selected_market}.")
251
+ else:
252
+ df_signals = pd.DataFrame(signals)
253
+ if 'date' in df_signals.columns:
254
+ df_signals['date'] = pd.to_datetime(df_signals['date'], unit='ms', errors='coerce')
255
+ for col in df_signals.columns:
256
+ if df_signals[col].apply(lambda x: isinstance(x, dict)).any():
257
+ df_signals[col] = df_signals[col].apply(lambda x: str(x) if isinstance(x, dict) else x)
258
+ if 'date' in df_signals.columns:
259
+ df_signals = df_signals.sort_values('date', ascending=False)
260
+ st.write("Total number of signals:", len(df_signals))
261
+ st.write("Preview of the last 4 signals:")
262
+ st.dataframe(df_signals.head(4))
263
 
264
  if __name__ == "__main__":
265
  main()