import os
import logging
import pandas as pd
import pandas_ta as ta
import yfinance as yf
import alpaca_trade_api as tradeapi
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes
# --- Configuration ---
# Replace these with your actual keys and tokens
TELEGRAM_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"
ALPACA_API_KEY = "YOUR_ALPACA_API_KEY_ID"
ALPACA_SECRET_KEY = "YOUR_ALPACA_SECRET_KEY"
ALPACA_PAPER = True # Set to False for live trading, True for paper trading
# The stock/asset you want to trade
TRADE_SYMBOL = 'SPY'
# The timeframe for your analysis (e.g., '1d' for daily, '1h' for hourly)
TIMEFRAME = '1d'
# Your strategy parameters
FAST_MA_PERIOD = 10
SLOW_MA_PERIOD = 30
# --- Setup Logging (Good practice) ---
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# --- Alpaca API Connection ---
api = tradeapi.REST(ALPACA_API_KEY, ALPACA_SECRET_KEY, base_url='https://paper-api.alpaca.markets' if ALPACA_PAPER else 'https://api.alpaca.markets')
# --- Trading Logic (The "Brain") ---
def check_for_signal():
"""
Checks for a trading signal based on a moving average crossover strategy.
Returns "BUY", "SELL", or "HOLD".
"""
try:
# Get historical data using yfinance
data = yf.download(TRADE_SYMBOL, period="2mo", interval=TIMEFRAME)
if data.empty:
logger.error(f"No data downloaded for {TRADE_SYMBOL}")
return "HOLD"
# Calculate moving averages using pandas-ta
data.ta.sma(length=FAST_MA_PERIOD, append=True)
data.ta.sma(length=SLOW_MA_PERIOD, append=True)
# Get the last two data points
last_row = data.iloc[-1]
prev_row = data.iloc[-2]
# Naming columns for clarity (e.g., SMA_10, SMA_30)
fast_ma_col = f'SMA_{FAST_MA_PERIOD}'
slow_ma_col = f'SMA_{SLOW_MA_PERIOD}'
# Check for crossover condition
# Buy signal: Fast MA crosses ABOVE Slow MA
if prev_row[fast_ma_col] < prev_row[slow_ma_col] and last_row[fast_ma_col] > last_row[slow_ma_col]:
return "BUY"
# Sell signal (optional, for this example we only focus on buy)
# if prev_row[fast_ma_col] > prev_row[slow_ma_col] and last_row[fast_ma_col] < last_row[slow_ma_col]:
# return "SELL"
return "HOLD"
except Exception as e:
logger.error(f"Error in signal generation: {e}")
return "HOLD"
# --- Telegram Bot Functions ---
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Sends a welcome message when the /start command is issued."""
await update.message.reply_text('Hello! I am your trading bot. I will periodically check for signals. Use /checknow to manually check for a signal.')
async def check_signal_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Manually checks for a signal and sends it to the user."""
chat_id = update.effective_chat.id
await send_signal_if_found(context, chat_id)
async def send_signal_if_found(context: ContextTypes.DEFAULT_TYPE, chat_id: int):
"""The core function that checks for a signal and sends a message with buttons."""
signal = check_for_signal()
if signal == "BUY":
logger.info(f"BUY signal found for {TRADE_SYMBOL}")
# Create interactive buttons
keyboard = [
[
InlineKeyboardButton("✅ Confirm Buy (1 share)", callback_data=f'BUY_{TRADE_SYMBOL}_1'),
InlineKeyboardButton("❌ Ignore", callback_data='IGNORE'),
]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.send_message(
chat_id=chat_id,
text=f"🚨 *BUY Signal Detected* 🚨\n\n*Symbol:* {TRADE_SYMBOL}\n*Strategy:* Moving Average Crossover\n\nDo you want to execute this trade?",
reply_markup=reply_markup,
parse_mode='Markdown'
)
elif signal == "SELL":
# You can implement sell logic similarly if needed
logger.info(f"SELL signal found for {TRADE_SYMBOL}")
# await context.bot.send_message(chat_id=chat_id, text=f"SELL Signal Detected for {TRADE_SYMBOL}")
else: # HOLD
logger.info(f"No signal (HOLD) for {TRADE_SYMBOL}")
# Optionally, send a "no signal" message for manual checks
if 'message' in context.job.data: # Check if it was a manual command
await context.bot.send_message(chat_id=chat_id, text=f"No trading signal for {TRADE_SYMBOL} at the moment.")
async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Parses the CallbackQuery and reacts to the button press."""
query = update.callback_query
await query.answer() # Acknowledge the button press
action, symbol, quantity = query.data.split('_')
if action == "BUY":
try:
logger.info(f"User confirmed BUY for {quantity} share(s) of {symbol}")
# Place the trade using the Alpaca API
order = api.submit_order(
symbol=symbol,
qty=int(quantity),
side='buy',
type='market',
time_in_force='gtc' # Good 'til canceled
)
logger.info(f"Order submitted: {order.id}")
await query.edit_message_text(text=f"✅ Trade Executed!\n\nSymbol: {symbol}\nQuantity: {quantity}\nOrder ID: {order.id}")
except Exception as e:
logger.error(f"Failed to execute trade: {e}")
await query.edit_message_text(text=f"❌ Error executing trade: {e}")
elif action == "IGNORE":
await query.edit_message_text(text="Trade ignored. No action taken.")
async def periodic_check(context: ContextTypes.DEFAULT_TYPE) -> None:
"""A function that the job queue will call periodically."""
job = context.job
await send_signal_if_found(context, job.chat_id)
def main() -> None:
"""Start the bot."""
application = Application.builder().token(TELEGRAM_TOKEN).build()
# Get the user's chat ID for periodic checks (a bit of a workaround)
# The bot needs to be started by the user first.
# A more robust solution involves a database to store chat_ids.
chat_id = None # You need to get your chat_id. You can find it by talking to @userinfobot on Telegram
if not chat_id:
print("WARNING: Please set your chat_id to enable periodic checks.")
print("Talk to @userinfobot on Telegram to get your ID.")
# Command handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("checknow", check_signal_command))
# Callback query handler for buttons
application.add_handler(CallbackQueryHandler(button_handler))
# Add a job to the queue for periodic checks (e.g., every 4 hours)
if chat_id:
application.job_queue.run_repeating(periodic_check, interval=14400, first=10, chat_id=chat_id)
# Start the Bot
application.run_polling()
if __name__ == '__main__':
main()