File size: 15,406 Bytes
50c47e7
4fa5f7f
 
d2b6644
4fa5f7f
d06e540
d2b6644
 
4fa5f7f
d2b6644
 
4fa5f7f
 
d2b6644
de3b5e4
3a806ce
cc0d816
3a806ce
c81174d
 
4fa5f7f
d2b6644
 
 
 
4fa5f7f
d2b6644
4fa5f7f
3a806ce
4fa5f7f
 
3a806ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d06e540
d2b6644
d06e540
 
d2b6644
d06e540
d2b6644
4fa5f7f
3a806ce
 
 
 
4fa5f7f
 
 
3a806ce
4fa5f7f
d2b6644
4fa5f7f
 
 
 
d2b6644
 
 
 
4fa5f7f
d06e540
 
d2b6644
d06e540
 
d2b6644
 
 
d06e540
d2b6644
d06e540
 
 
 
 
d2b6644
4fa5f7f
d2b6644
4fa5f7f
3a806ce
d2b6644
3a806ce
 
37a9b47
 
d2b6644
 
 
 
 
 
 
 
 
 
 
 
4fa5f7f
 
 
3a806ce
4fa5f7f
 
d2b6644
 
4fa5f7f
d06e540
4fa5f7f
d06e540
4fa5f7f
d06e540
4fa5f7f
d06e540
4fa5f7f
 
 
d2b6644
4fa5f7f
 
d2b6644
4fa5f7f
d2b6644
4fa5f7f
3a806ce
d2b6644
 
4fa5f7f
 
3a806ce
d2b6644
3a806ce
 
d2b6644
 
3a806ce
d2b6644
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a806ce
d2b6644
 
 
d06e540
3a806ce
d2b6644
3a806ce
 
d2b6644
 
 
 
 
 
 
3a806ce
d2b6644
 
 
 
 
 
 
 
3a806ce
 
 
 
d2b6644
 
 
 
 
 
 
 
 
 
d06e540
50c47e7
 
79b75fb
50c47e7
 
3a806ce
79b75fb
 
 
 
 
 
 
50c47e7
 
 
 
4fa5f7f
d06e540
d2b6644
 
d06e540
 
4fa5f7f
d2b6644
4fa5f7f
3a806ce
4fa5f7f
 
 
3a806ce
4fa5f7f
d2b6644
3a806ce
d2b6644
3a806ce
 
d2b6644
4fa5f7f
 
3a806ce
 
50c47e7
 
3a806ce
79b75fb
 
 
 
50c47e7
 
79b75fb
 
 
 
50c47e7
 
79b75fb
 
 
 
 
 
 
50c47e7
 
3a806ce
79b75fb
 
 
 
 
3a806ce
79b75fb
 
3a806ce
79b75fb
 
3a806ce
 
79b75fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a806ce
 
79b75fb
 
 
 
 
 
 
 
 
 
 
50c47e7
3a806ce
d06e540
d2b6644
3a806ce
d06e540
d2b6644
 
 
 
 
3a806ce
d2b6644
 
d06e540
 
d2b6644
d06e540
d2b6644
d06e540
 
d2b6644
d06e540
d2b6644
d06e540
 
d2b6644
3a806ce
d2b6644
 
 
 
 
 
 
 
 
3a806ce
d2b6644
d06e540
3a806ce
 
3e41048
 
 
 
 
 
3a806ce
3e41048
 
 
 
 
 
 
d2b6644
 
3e41048
 
 
d06e540
d2b6644
3e41048
 
 
3a806ce
3e41048
 
 
 
3a806ce
3e41048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2b6644
3a806ce
d2b6644
 
3e41048
 
d2b6644
 
3e41048
d06e540
3a806ce
50c47e7
 
 
 
 
 
 
 
 
4fa5f7f
 
 
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
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()