config.py
BINANCE_API_KEY = 'your_binance_api_key' ALPHA_VANTAGE_API_KEY = 'your_alpha_vantage_api_key' YAHOO_FINANCE_API_KEY = 'your_yahoo_finance_api_key' TRADING_VIEW_API_KEY = 'your_trading_view_api_key' BINOMO_API_KEY = 'your_binomo_api_key' TELEGRAM_BOT_API_KEY = 'your_telegram_bot_api_key'
data_acquisition.py
import requests import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout from telegram.ext import Updater, CommandHandler
def fetch_binance_data(pair): url = f"https://api.binance.com/api/v3/klines?symbol={pair}&interval=1h" response = requests.get(url) data = response.json() df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore']) df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms') return df[['timestamp', 'open', 'high', 'low', 'close', 'volume']]
def fetch_alpha_vantage_data(pair): symbol = pair.split("USDT")[0] # Assuming pair like BTCUSDT url = f"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={symbol}&interval=60min&apikey={ALPHA_VANTAGE_API_KEY}" response = requests.get(url) data = response.json() time_series_key = 'Time Series (60min)' if time_series_key not in data: raise ValueError(f"Error fetching data from Alpha Vantage: {data}") df = pd.DataFrame(data[time_series_key]).T df.columns = ['open', 'high', 'low', 'close', 'volume'] df.index = pd.to_datetime(df.index) return df.reset_index().rename(columns={'index': 'timestamp'})
def fetch_yahoo_finance_data(pair): url = f"https://yfapi.net/v8/finance/chart/{pair}?interval=60m" headers = {'x-api-key': YAHOO_FINANCE_API_KEY} response = requests.get(url, headers=headers) data = response.json() timestamps = data['chart']['result'][0]['timestamp'] ohlc = data['chart']['result'][0]['indicators']['quote'][0] df = pd.DataFrame({ 'timestamp': pd.to_datetime(timestamps, unit='s'), 'open': ohlc['open'], 'high': ohlc['high'], 'low': ohlc['low'], 'close': ohlc['close'], 'volume': ohlc['volume'] }) return df
def fetch_trading_view_data(pair): # Placeholder for TradingView API data fetching raise NotImplementedError("TradingView API integration not implemented.")
def fetch_binomo_data(pair): # Placeholder for Binomo API data fetching raise NotImplementedError("Binomo API integration not implemented.")
def get_combined_data(pair): df_binance = fetch_binance_data(pair) df_alpha = fetch_alpha_vantage_data(pair) df_yahoo = fetch_yahoo_finance_data(pair) # Merge dataframes on timestamp df = pd.merge(df_binance, df_alpha, on='timestamp', suffixes=('_binance', '_alpha')) df = pd.merge(df, df_yahoo, on='timestamp', suffixes=('', '_yahoo')) # Drop any redundant columns or handle conflicts return df
def preprocess_data(df): df = df.dropna() scaler = StandardScaler() scaled_data = scaler.fit_transform(df[['open', 'high', 'low', 'close', 'volume']]) return scaled_data, scaler
def create_dataset(data, time_step=60): X, Y = [], [] for i in range(len(data) - time_step - 1): a = data[i:(i + time_step), :] X.append(a) Y.append(data[i + time_step, 3]) # Assuming 'close' price is the target return np.array(X), np.array(Y)
def build_model(input_shape): model = Sequential() model.add(LSTM(50, return_sequences=True, input_shape=input_shape)) model.add(LSTM(50, return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense(25)) model.add(Dense(1)) model.compile(optimizer='adam', loss='mean_squared_error') return model
def train_model(df): data, scaler = preprocess_data(df) X, Y = create_dataset(data) X_train, Y_train = X[:int(len(X) * 0.8)], Y[:int(len(Y) * 0.8)] X_val, Y_val = X[int(len(X) * 0.8):], Y[int(len(Y) * 0.8):] model = build_model((X_train.shape[1], X_train.shape[2])) model.fit(X_train, Y_train, validation_data=(X_val, Y_val), epochs=20, batch_size=32) return model, scaler
def generate_signal(pair): df = get_combined_data(pair) model, scaler = train_model(df) recent_data = df.tail(60).drop(columns=['timestamp']) scaled_recent_data = scaler.transform(recent_data) prediction = model.predict(np.expand_dims(scaled_recent_data, axis=0)) last_close = df['close'].iloc[-1] if prediction > last_close: return "Buy" else: return "Sell"
def start(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a trading bot, how can I help you today?")
def signal(update, context): pair = context.args[0] if context.args else 'BTCUSDT' try: trade_signal = generate_signal(pair) context.bot.send_message(chat_id=update.effective_chat.id, text=f"Trade Signal for {pair}: {trade_signal}") except Exception as e: context.bot.send_message(chat_id=update.effective_chat.id, text=f"Error: {e}")
def main(): updater = Updater(token=TELEGRAM_BOT_API_KEY, use_context=True) dispatcher = updater.dispatcher
start_handler = CommandHandler('start', start)
signal_handler = CommandHandler('signal', signal)
dispatcher.add_handler(start_handler)
dispatcher.add_handler(signal_handler)
updater.start_polling()
if name == 'main': main()