CoolFace
Apppublic

ArcheanVision/Crypto_Agent_Signals_predict

sourceHugging Faceupdated 2y agoView on Hugging Face
10likes
app.py268 linesDownload Raw Back to root
1import os2from dotenv import load_dotenv3import streamlit as st4import pandas as pd5import plotly.express as px6import cloudscraper7import warnings8import logging9# Charger les variables d'environnement (si vous utilisez un .env localement)10load_dotenv()11API_KEY = os.environ.get("API_KEY")12headers = {13    "Authorization": f"Bearer {API_KEY}",14    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " 15                  "AppleWebKit/537.36 (KHTML, like Gecko) " 16                  "Chrome/115.0.0.0 Safari/537.36"17}18 19url = "https://archeanvision.com/api/signals/available"20 21# Create a cloudscraper instance22scraper = cloudscraper.create_scraper()  # This will handle Cloudflare challenges23response = scraper.get(url, headers=headers)24 25print(response.status_code)26print(response.text)27 28# Load environment variables from .env29load_dotenv()30 31# Suppress deprecation warnings about experimental query params functions32warnings.filterwarnings(33    "ignore", 34    message="Please replace `st.experimental_get_query_params` with `st.query_params`"35)36warnings.filterwarnings(37    "ignore", 38    message="Please replace `st.experimental_set_query_params` with `st.query_params`"39)40warnings.filterwarnings("ignore", category=DeprecationWarning)41 42# Adjust Streamlit loggers to show only errors43logging.getLogger("streamlit.deprecation").setLevel(logging.ERROR)44logging.getLogger("streamlit.runtime.scriptrunner").setLevel(logging.ERROR)45 46 47# ---------------------------- #48#         AUTO-REFRESH         #49# ---------------------------- #50st.set_page_config(51    page_title="Dashboard Auto-Refresh",52    layout="wide"53)54 55REFRESH_INTERVAL = 260  # seconds56st.markdown(f"<meta http-equiv='refresh' content='{REFRESH_INTERVAL}'>", unsafe_allow_html=True)57# ---------------------------- #58 59LOGO_IMAGE_URL = "https://archeanvision.com/assets/archeanvision.png"60st.sidebar.image(LOGO_IMAGE_URL, use_container_width=True, caption="ArcheanVision")61 62# Get the API key from environment variables (stored in .env or Hugging Face Secrets)63if not API_KEY:64    st.error("API_KEY is not set. Please add it to your environment (e.g. .env file or Hugging Face Secrets).")65    st.stop()66 67# --- Helper Functions Using cloudscraper ---68 69def get_active_markets_cloudscraper(api_key):70    """Retrieves the list of active markets using cloudscraper to bypass Cloudflare."""71    headers = {72        "Authorization": f"Bearer {api_key}",73        "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "74                       "AppleWebKit/537.36 (KHTML, like Gecko) "75                       "Chrome/115.0.0.0 Safari/537.36")76    }77    url = "https://archeanvision.com/api/signals/available"78    scraper = cloudscraper.create_scraper()79    response = scraper.get(url, headers=headers)80    response.raise_for_status()  # Raises an exception for HTTP errors81    return response.json()  # Assuming the endpoint returns JSON82 83def get_market_data_cloudscraper(api_key, market):84    """Retrieves market data for the given market using cloudscraper."""85    headers = {86        "Authorization": f"Bearer {api_key}",87        "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "88                       "AppleWebKit/537.36 (KHTML, like Gecko) "89                       "Chrome/115.0.0.0 Safari/537.36")90    }91    # Endpoint for market data (1,440 points ~ 24h); adjust as per API docs92    url = f"https://archeanvision.com/api/signals/{market}/data"93    scraper = cloudscraper.create_scraper()94    response = scraper.get(url, headers=headers)95    response.raise_for_status()96    return response.json()97 98def get_market_signals_cloudscraper(api_key, market):99    """Retrieves market signals for the given market using cloudscraper."""100    headers = {101        "Authorization": f"Bearer {api_key}",102        "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "103                       "AppleWebKit/537.36 (KHTML, like Gecko) "104                       "Chrome/115.0.0.0 Safari/537.36")105    }106    url = f"https://archeanvision.com/api/signals/{market}/signals"107    scraper = cloudscraper.create_scraper()108    response = scraper.get(url, headers=headers)109    response.raise_for_status()110    return response.json()111 112# --- End Helper Functions ---113 114def get_selected_market(market_list):115    """116    Retourne le marché sélectionné à partir des paramètres d'URL ou, par défaut, le premier élément.117    Met à jour le paramètre de l'URL si l'utilisateur choisit un marché différent.118    """119    # Récupère les paramètres sous forme de dictionnaire-like120    params = st.query_params121 122    # Récupérer le paramètre "market" ou définir la valeur par défaut123    default_market = params.get("market", market_list[0])124    # Si "market" est une liste (clé répétée), on prend le dernier (ou le premier) élément125    if isinstance(default_market, list):126        default_market = default_market[0]127 128    # Trouver l'index correspondant129    default_index = market_list.index(default_market) if default_market in market_list else 0130 131    # Affiche un menu déroulant pour choisir le marché132    selected = st.selectbox("Select a market:", market_list, index=default_index)133 134    # Si l'utilisateur choisit un marché différent, on met à jour le paramètre dans l'URL135    if selected != default_market:136        st.query_params.market = selected  # Mise à jour via la notation par attribut137        # Vous pouvez également faire : st.query_params["market"] = selected138 139    return selected140 141 142def main():143    st.title("Active AI Crypto Markets - ArcheanVision")144 145    st.markdown("""146    ### What is ArcheanVision?147    **ArcheanVision** is an autonomous multi-market trading agent.  148    It operates simultaneously on multiple crypto assets, monitoring price movements149    in real time and delivering **data** as well as **signals** (BUY, SELL, etc.)150    to automate and optimize decision-making.151    - **AI Agent**: Continuously analyzes crypto markets.  152    - **Multi-Market**: Manages multiple assets at once.  153    - **Live Data**: Access to streaming data feeds (SSE).  154    - **Buy/Sell Signals**: Generated in real-time to seize market opportunities.  155    Below is a dashboard showcasing the active markets, their 24h data 156    (1,440 most recent data points), and their associated signals.157    ---158    **Join our Discord as a beta tester** to help improve the agent and the system.  159    - Official platform: [https://archeanvision.com](https://archeanvision.com)  160    - Discord link: [https://discord.gg/k9xHuM7Jr8](https://discord.gg/k9xHuM7Jr8)161    """)162 163    # Retrieve active markets using cloudscraper164    try:165        active_markets = get_active_markets_cloudscraper(API_KEY)166    except Exception as e:167        st.error(f"Error fetching active markets: {e}")168        return169 170    if not active_markets:171        st.error("No active markets found through the API.")172        return173 174    # Expecting active_markets to be a list of market names, e.g. ["BTC", "ETH", ...]175    market_list = []176    if isinstance(active_markets, list):177        for item in active_markets:178            # Depending on the response structure, adjust accordingly.179            if isinstance(item, dict) and "market" in item:180                market_list.append(item["market"])181            elif isinstance(item, str):182                market_list.append(item)183            else:184                st.warning(f"Item missing 'market' key: {item}")185    else:186        st.error("The structure of 'active_markets' is not a list as expected.")187        return188 189    if not market_list:190        st.error("The market list is empty or 'market' keys not found.")191        return192 193    selected_market = get_selected_market(market_list)194    if not selected_market:195        st.error("No market selected.")196        return197 198    st.subheader(f"Selected Market: {selected_market}")199    st.write(f"Fetching data for **{selected_market}** ...")200 201    # Retrieve market data using cloudscraper202    try:203        market_data = get_market_data_cloudscraper(API_KEY, selected_market)204    except Exception as e:205        st.error(f"Error fetching market data for {selected_market}: {e}")206        return207 208    if not market_data:209        st.error(f"No data found for market {selected_market}.")210        return211 212    df = pd.DataFrame(market_data)213    if "close_time" in df.columns:214        df['close_time'] = pd.to_datetime(df['close_time'], unit='ms', errors='coerce')215    else:216        st.error("The 'close_time' column is missing from the retrieved data.")217        return218 219    st.write("### Market Data Overview")220    st.dataframe(df.head())221 222    required_cols = {"close", "last_predict_15m", "last_predict_1h"}223    if not required_cols.issubset(df.columns):224        st.error(225            f"The required columns {required_cols} are not all present. "226            f"Available columns: {list(df.columns)}"227        )228        return229 230    fig = px.line(231        df,232        x='close_time',233        y=['close', 'last_predict_15m', 'last_predict_1h'],234        title=f"{selected_market} : Close Price & Predictions",235        labels={236            'close_time': 'Time',237            'value': 'Price',238            'variable': 'Metric'239        }240    )241    st.plotly_chart(fig, use_container_width=True)242 243    st.write(f"### Signals for {selected_market}")244    try:245        signals = get_market_signals_cloudscraper(API_KEY, selected_market)246    except Exception as e:247        st.error(f"Error fetching signals for {selected_market}: {e}")248        return249 250    if not signals:251        st.warning(f"No signals found for market {selected_market}.")252    else:253        df_signals = pd.DataFrame(signals)254        if 'date' in df_signals.columns:255            df_signals['date'] = pd.to_datetime(df_signals['date'], unit='s', errors='coerce')256        for col in df_signals.columns:257            if df_signals[col].apply(lambda x: isinstance(x, dict)).any():258                df_signals[col] = df_signals[col].apply(lambda x: str(x) if isinstance(x, dict) else x)259        if 'date' in df_signals.columns:260            df_signals = df_signals.sort_values('date', ascending=False)261        st.write("Total number of signals:", len(df_signals))262        st.write("Preview of the last 4 signals:")263        st.dataframe(df_signals.head(4))264 265if __name__ == "__main__":266    main()267 268