File size: 5,045 Bytes
f4d3c75
 
 
76b2ffc
e4ac995
5bd003e
7cce695
5bd003e
17ef819
5bd003e
 
 
 
 
 
 
 
 
 
 
 
17ef819
5bd003e
 
 
 
 
 
17ef819
 
e4ac995
5bd003e
 
 
 
 
 
 
 
 
17ef819
5bd003e
 
 
f4d3c75
 
76b2ffc
f4d3c75
 
 
 
 
 
 
 
 
 
 
 
 
17ef819
76b2ffc
5bd003e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76b2ffc
 
f4d3c75
76b2ffc
5bd003e
 
 
 
76b2ffc
5bd003e
 
76b2ffc
f4d3c75
e4ac995
 
17ef819
 
f4d3c75
 
 
17ef819
76b2ffc
 
 
 
 
 
 
 
 
f4d3c75
 
17ef819
 
 
 
 
 
 
 
 
 
 
 
5bd003e
17ef819
 
 
 
 
 
 
 
 
 
5bd003e
17ef819
 
 
 
76b2ffc
e4ac995
17ef819
 
e4ac995
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import gradio as gr
import requests
import pandas as pd
import plotly.graph_objects as go

# Define your CryptoCompare API key
API_KEY = 'c1e07b0b9a72b6f5ea096763a17a2a1eec7a925a10faadd615b2d152f208a98d'

# Function to fetch historical price data from CryptoCompare
def fetch_historical_data(coin_id, from_date, to_date):
    try:
        url = "https://min-api.cryptocompare.com/data/v2/histoday"
        params = {
            'fsym': coin_id,
            'tsym': 'USD',
            'limit': 2000,  # Maximum number of data points
            'toTs': pd.Timestamp(to_date).timestamp(),
            'api_key': API_KEY
        }
        response = requests.get(url, params=params)
        response.raise_for_status()
        data = response.json()
        df = pd.DataFrame(data['Data']['Data'])
        df['time'] = pd.to_datetime(df['time'], unit='s')
        df = df[['time', 'close']].rename(columns={'time': 'timestamp', 'close': 'price'})
        return df
    except Exception as e:
        return f"Error fetching historical data for {coin_id}: {e}"

# Function to fetch current prices from CryptoCompare
def fetch_current_price(coin_id):
    try:
        url = "https://min-api.cryptocompare.com/data/price"
        params = {
            'fsym': coin_id,
            'tsyms': 'USD',
            'api_key': API_KEY
        }
        response = requests.get(url, params=params)
        response.raise_for_status()
        data = response.json()
        return f"${data['USD']}"
    except Exception as e:
        return f"Error fetching current price for {coin_id}: {e}"

# Function to provide TradingView widget HTML
def get_tradingview_chart():
    widget_html = """
    <iframe
        src="https://www.tradingview.com/widgetembed/?frameElementId=tradingview_ea33b&symbol=BINANCE:BTCUSDT&interval=60"
        width="800"
        height="600"
        frameborder="0"
        allowtransparency="true"
        scrolling="no"
        allowfullscreen="true">
    </iframe>
    """
    return widget_html

# Function to fetch real-time trade data from CryptoCompare
def get_real_time_trade_data():
    try:
        return fetch_current_price('BTC')
    except Exception as e:
        return f"Error fetching real-time trade data: {e}"

# Function to plot historical prices using Plotly
def plot_historical_prices(coin_name, from_date, to_date):
    df = fetch_historical_data(coin_name, from_date, to_date)
    if isinstance(df, str):  # In case of error
        return df

    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df['timestamp'], y=df['price'], mode='lines', name=coin_name))
    fig.update_layout(title=f'{coin_name.capitalize()} Prices from {from_date} to {to_date}', xaxis_title='Date', yaxis_title='Price (USD)')
    return fig

# Function to analyze Bitcoin based on the prompt
def analyze_btc(prompt):
    """Analyze the prompt and provide information."""
    prompt = prompt.lower()
    if "price" in prompt:
        return f"Current Bitcoin price: {fetch_current_price('BTC')}"
    elif "trade data" in prompt:
        return get_real_time_trade_data()
    elif "chart" in prompt:
        return get_tradingview_chart()  # Use HTML component for TradingView chart
    return "Try asking about the Bitcoin price, real-time trade data, or TradingView chart."

# Gradio Interface Setup

# AI BTC Analysis Interface
btc_analysis_interface = gr.Interface(
    fn=analyze_btc, 
    inputs="text",
    outputs="html",  # Ensure output is HTML
    title="Bitcoin Analyzer",
    description="Ask about the current Bitcoin price, real-time trade data, or TradingView chart."
)

# TradingView Interface for live charts
tradingview_interface = gr.Interface(
    fn=get_tradingview_chart,
    inputs=[],
    outputs=gr.HTML(label="TradingView Chart"),
    title="Live TradingView Chart"
)

# Real-time Trade Data Interface
real_time_trade_interface = gr.Interface(
    fn=get_real_time_trade_data,
    inputs=[],
    outputs=gr.Textbox(label="Real-Time Trade Data"),
    title="Real-Time Cryptocurrency Trade Data"
)

# Price Chart Interface
crypto_price_chart_interface = gr.Interface(
    fn=plot_historical_prices,
    inputs=[
        gr.Dropdown(choices=['BTC'], label="Cryptocurrency"),
        gr.Textbox(value="2024-01-01", label="From Date (YYYY-MM-DD)"),
        gr.Textbox(value="2025-12-31", label="To Date (YYYY-MM-DD)")
    ],
    outputs=gr.Plot(label="Cryptocurrency Price Chart"),
    title="Cryptocurrency Price Chart (2024-2025)"
)

# Current Price Interface
current_price_interface = gr.Interface(
    fn=fetch_current_price,
    inputs=gr.Dropdown(choices=['BTC'], label="Cryptocurrency"),
    outputs=gr.Textbox(label="Current Price"),
    title="Current Cryptocurrency Price"
)

# Combining all interfaces into a single tabbed app
gr.TabbedInterface(
    [crypto_price_chart_interface, current_price_interface, real_time_trade_interface, btc_analysis_interface, tradingview_interface],
    tab_names=["Price Chart", "Current Price", "Real-Time Trade Data", "AI BTC Analysis", "TradingView Chart"]
).launch()