import requests import streamlit as st import numpy as np import pandas as pd import plotly.graph_objs as go import plotly.express as px import yfinance as yf import mplfinance as mpf import tensorflow as tf from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout from prophet import Prophet import pandas_ta as ta import os # API Keys ALPHA_VANTAGE_API_KEY = os.getenv('1E7BEZ2T6N3YKN1H') CRYPTOCOMPARE_API_KEY = os.getenv('060a0d950fb96512f174c57fee1150fefb221c28e7aebc564a9ce8bc43762e6d') class AdvancedTradingPredictor: def __init__(self, symbol): self.symbol = symbol self.risk_tolerance = 0.02 def fetch_historical_data(self, period='1y', interval='1h'): """ Fetch comprehensive historical trading data using Alpha Vantage and CryptoCompare """ try: # Fetch data from Alpha Vantage alpha_url = f"https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_DAILY&symbol={self.symbol}&market=USD&apikey={ALPHA_VANTAGE_API_KEY}" alpha_response = requests.get(alpha_url) alpha_data = alpha_response.json() # Fetch data from CryptoCompare crypto_url = f"https://min-api.cryptocompare.com/data/v2/histoday?fsym={self.symbol}&tsym=USD&limit=1000&api_key={CRYPTOCOMPARE_API_KEY}" crypto_response = requests.get(crypto_url) crypto_data = crypto_response.json() # Combine data alpha_df = pd.DataFrame(alpha_data['Time Series (Digital Currency Daily)']).T crypto_df = pd.DataFrame(crypto_data['Data']['Data']) # Process and merge data # (Add your data processing logic here) return combined_df except Exception as e: st.error(f"Data Fetch Error: {e}") return None def prepare_lstm_data(self, data): """ Prepare data for LSTM model """ # Use Close prices prices = data['Close'].values.reshape(-1, 1) # Normalize scaler = MinMaxScaler(feature_range=(0, 1)) scaled_prices = scaler.fit_transform(prices) # Create sequences X, y = [], [] look_back = 60 for i in range(len(scaled_prices) - look_back): X.append(scaled_prices[i:i+look_back]) y.append(scaled_prices[i+look_back]) X, y = np.array(X), np.array(y) X = X.reshape((X.shape[0], X.shape[1], 1)) return X, y, scaler def build_lstm_model(self, input_shape): """ Build advanced LSTM model """ model = Sequential([ LSTM(100, return_sequences=True, input_shape=input_shape), Dropout(0.3), LSTM(50, return_sequences=False), Dropout(0.2), Dense(50, activation='relu'), Dense(1) ]) model.compile(optimizer='adam', loss='mean_squared_error') return model def prophet_forecast(self, data): """ Use Prophet for time series forecasting """ prophet_data = data[['Close']].reset_index() prophet_data.columns = ['ds', 'y'] # Remove timezone information prophet_data['ds'] = prophet_data['ds'].dt.tz_localize(None) model = Prophet( seasonality_mode='multiplicative', yearly_seasonality=True, weekly_seasonality=True, daily_seasonality=True ) model.fit(prophet_data) future = model.make_future_dataframe(periods=30) forecast = model.predict(future) return forecast def generate_trading_signals(self, predictions): """ Generate advanced trading signals using technical indicators """ signals = [] for i in range(1, len(predictions)): change_percent = ((predictions[i] - predictions[i-1]) / predictions[i-1]) * 100 if change_percent > 2: signals.append('Strong Buy') elif change_percent > 1: signals.append('Weak Buy') elif change_percent < -2: signals.append('Strong Sell') elif change_percent < -1: signals.append('Weak Sell') else: signals.append('Hold') return signals def predict_prices(self): """ Comprehensive price prediction """ # Fetch historical data data = self.fetch_historical_data() if data is None: return None # LSTM Prediction X, y, scaler = self.prepare_lstm_data(data) # Split data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # Build and train model model = self.build_lstm_model((X_train.shape[1], 1)) early_stop = tf.keras.callbacks.EarlyStopping( monitor='val_loss', patience=10, restore_best_weights=True ) model.fit( X_train, y_train, epochs=100, batch_size=32, validation_split=0.2, callbacks=[early_stop], verbose=0 ) # Predict predictions = model.predict(X_test) predictions = scaler.inverse_transform(predictions) actual = scaler.inverse_transform(y_test) # Prophet Forecast prophet_forecast = self.prophet_forecast(data) # Trading Signals trading_signals = self.generate_trading_signals(predictions.flatten()) return { 'lstm_predictions': predictions.flatten(), 'actual_prices': actual.flatten(), 'prophet_forecast': prophet_forecast, 'trading_signals': trading_signals, 'current_price': data['Close'].iloc[-1] } def create_candlestick_chart(data): """ Create interactive candlestick chart """ fig = go.Figure(data=[go.Candlestick( x=data.index, open=data['Open'], high=data['High'], low=data['Low'], close=data['Close'] )]) fig.update_layout( title='Candlestick Chart', xaxis_title='Date', yaxis_title='Price', template='plotly_dark' ) return fig def get_ton_usd_price(): """ Fetch real-time TON/USD price using yfinance """ try: # Using yfinance to get TON price ton_ticker = yf.Ticker("TON-USD") ton_data = ton_ticker.history(period='1d') if not ton_data.empty: return ton_data['Close'].iloc[-1] else: st.warning("Could not fetch latest TON price") return None except Exception as e: st.error(f"Could not fetch TON price: {e}") return None def main(): st.set_page_config( page_title="Advanced Trading Prediction", page_icon="📈", layout="wide" ) st.title("🚀 Advanced Trading Prediction AI") # Sidebar Configuration st.sidebar.header("Trading Configuration") trading_symbol = st.sidebar.selectbox( "Select Trading Pair", ["BTCUSDT", "ETHUSDT", "BNBUSDT", "ADAUSDT", "TONUSDT"] # Added TONUSDT ) # Initialize Predictor predictor = AdvancedTradingPredictor(trading_symbol) # Fetch Predictions predictions = predictor.predict_prices() if predictions: # Fetch TON/USD Price ton_usd_price = get_ton_usd_price() # Create metrics container st.subheader("🔹 TON (Toncoin) Trading Analysis") metrics_container = st.container() col1, col2, col3 = metrics_container.columns(3) with col1: st.metric( "Current TON/USD", f"${ton_usd_price:.4f}" if ton_usd_price else "Unavailable" ) with col2: predicted_change = ((predictions['lstm_predictions'][-1] - ton_usd_price) / ton_usd_price * 100) if ton_usd_price else None st.metric( "Predicted TON/USD", f"${predictions['lstm_predictions'][-1]:.4f}", f"{predicted_change:+.2f}%" if predicted_change is not None else None, delta_color="normal" ) with col3: volume = predictor.fetch_historical_data(period='1d')['Volume'].iloc[-1] if ton_usd_price else None st.metric( "24h Volume", f"{volume:,.0f} TON" if volume is not None else "Unavailable" ) # Add trading recommendations st.subheader("📊 Trading Recommendations") # Calculate key levels if ton_usd_price: current_price = ton_usd_price support_level = current_price * 0.95 # 5% below current price resistance_level = current_price * 1.05 # 5% above current price levels_col1, levels_col2 = st.columns(2) with levels_col1: st.markdown("#### Key Price Levels") st.markdown(f"- **Support Level**: ${support_level:.4f}") st.markdown(f"- **Current Price**: ${current_price:.4f}") st.markdown(f"- **Resistance Level**: ${resistance_level:.4f}") with levels_col2: st.markdown("#### Suggested Trading Ranges") st.markdown(f"- **Conservative Stop Loss**: ${current_price * 0.97:.4f}") st.markdown(f"- **Aggressive Stop Loss**: ${current_price * 0.95:.4f}") st.markdown(f"- **Conservative Take Profit**: ${current_price * 1.03:.4f}") st.markdown(f"- **Aggressive Take Profit**: ${current_price * 1.05:.4f}") # Add market sentiment latest_signals = predictions['trading_signals'][-5:] # Get last 5 signals bullish_count = sum(1 for signal in latest_signals if 'Buy' in signal) bearish_count = sum(1 for signal in latest_signals if 'Sell' in signal) sentiment = "Bullish" if bullish_count > bearish_count else "Bearish" if bearish_count > bullish_count else "Neutral" st.subheader("🎯 Market Sentiment") st.markdown(f""" - **Current Sentiment**: {sentiment} - **Signal Strength**: {'Strong' if abs(bullish_count - bearish_count) >= 3 else 'Moderate' if abs(bullish_count - bearish_count) >= 2 else 'Weak'} - **Recommendation**: {'Consider Long Positions' if sentiment == 'Bullish' else 'Consider Short Positions' if sentiment == 'Bearish' else 'Wait for Clearer Signals'} """) # Create Layout col1, col2 = st.columns(2) # Candlestick Chart with col1: st.subheader("Price Movement") historical_data = predictor.fetch_historical_data() candlestick_chart = create_candlestick_chart(historical_data) st.plotly_chart(candlestick_chart) # Predictions Visualization with col2: st.subheader("Price Predictions") fig = go.Figure() fig.add_trace(go.Scatter( y=predictions['actual_prices'], mode='lines', name='Actual Prices' )) fig.add_trace(go.Scatter( y=predictions['lstm_predictions'], mode='lines', name='LSTM Predictions' )) st.plotly_chart(fig) # Trading Signals st.subheader("Trading Signals") signal_counts = pd.Series(predictions['trading_signals']).value_counts() signal_chart = px.pie( values=signal_counts.values, names=signal_counts.index, title="Trading Signal Distribution" ) st.plotly_chart(signal_chart) # Current Price & Risk Management st.subheader("Risk Management") current_price = predictions['current_price'] # Advanced Risk Calculation volatility = np.std(predictions['actual_prices']) risk_multiplier = 1 + (volatility / current_price) stop_loss = current_price * (1 - (0.02 * risk_multiplier)) take_profit = current_price * (1 + (0.05 * risk_multiplier)) # Risk Level Classification if volatility < current_price * 0.02: risk_level = "Low" elif volatility < current_price * 0.05: risk_level = "Moderate" else: risk_level = "High" col1, col2 = st.columns(2) with col1: st.metric("Current Price", f"${current_price:.4f}") st.metric("Stop Loss", f"${stop_loss:.4f}") st.metric("Volatility", f"{volatility:.4f}") with col2: st.metric("Take Profit", f"${take_profit:.4f}") st.metric("Risk Level", risk_level) # Future Price Projection st.subheader("Future Price Projection") prophet_forecast = predictions['prophet_forecast'] future_prices = prophet_forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']] # Create Forecast Visualization forecast_fig = go.Figure() forecast_fig.add_trace(go.Scatter( x=future_prices['ds'], y=future_prices['yhat'], mode='lines', name='Predicted Price', line=dict(color='blue') )) forecast_fig.add_trace(go.Scatter( x=future_prices['ds'], y=future_prices['yhat_upper'], mode='lines', name='Upper Bound', line=dict(color='green', dash='dot') )) forecast_fig.add_trace(go.Scatter( x=future_prices['ds'], y=future_prices['yhat_lower'], mode='lines', name='Lower Bound', line=dict(color='red', dash='dot') )) st.plotly_chart(forecast_fig) # Comprehensive Warning st.warning(""" ⚠️ Trading Disclaimer: - Predictions are probabilistic, NOT guaranteed - Cryptocurrency markets are highly volatile - Always conduct personal research - Risk only what you can afford to lose - Consult financial advisors before making decisions """) # Add a informative section about TON st.markdown("### 💡 About TON (Toncoin)") st.markdown(""" TON (The Open Network) is a high-performance blockchain designed for mass adoption: - **Fast Transactions**: Up to 100,000 transactions per second - **Low Fees**: Minimal transaction costs - **Developed by Telegram**: Initial concept by Telegram's founder Pavel Durov - **Decentralized**: Community-driven blockchain platform - **Smart Contract Support**: Enables complex decentralized applications """) if __name__ == "__main__": main()