Skip to content

Commit

Permalink
Add Telegram bot for notifications (#12)
Browse files Browse the repository at this point in the history
Related to #5

Implement Telegram bot for real-time notifications and analysis info.

* **main.py**
  - Import `telegram` and `telegram.ext` modules.
- Add `TELEGRAM_BOT_API_KEY` and `TELEGRAM_CHAT_ID` to required
environment variables.
  - Initialize `telegram.Bot` instance with `TELEGRAM_BOT_API_KEY`.
  - Update `Notifier` initialization to include `telegram_bot` instance.

* **.env**
- Add `TELEGRAM_BOT_API_KEY` and `TELEGRAM_CHAT_ID` environment
variables.

* **utils/notifier.py**
  - Import `telegram` and `telegram.ext` modules.
- Add `telegram_bot` and `telegram_chat_id` to `Notifier` class
initialization.
  - Implement `_send_telegram` method to send messages via Telegram bot.
  • Loading branch information
vishwamartur authored Nov 3, 2024
2 parents 1f5324d + 09c2353 commit 4feda1d
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
3 changes: 3 additions & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,6 @@ RECIPIENT_NUMBER=1234567890
LOG_FILE_PATH=logs/trading_bot.log
LOG_LEVEL=INFO

# Telegram Notifications
TELEGRAM_BOT_API_KEY=your_telegram_bot_api_key
TELEGRAM_CHAT_ID=your_telegram_chat_id
11 changes: 9 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,17 @@
from websocket.order_execution import OrderExecution
from utils.backtest import Backtester
from data.investment_banking_tracker import InvestmentBankingTracker
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Load environment variables and validate required keys
load_dotenv()
required_env_vars = [
"DHAN_API_KEY",
"DHAN_SECRET_KEY",
"CHATGPT_API_KEY"
"CHATGPT_API_KEY",
"TELEGRAM_BOT_API_KEY",
"TELEGRAM_CHAT_ID"
]
for var in required_env_vars:
if not os.getenv(var):
Expand All @@ -36,6 +40,9 @@
# Load and validate configuration settings
config = load_config()

# Initialize Telegram bot
telegram_bot = telegram.Bot(token=os.getenv("TELEGRAM_BOT_API_KEY"))

async def process_market_data(
data: Dict,
data_fetcher: DataFetcher,
Expand Down Expand Up @@ -109,7 +116,7 @@ async def main():
futures_strategy = FuturesStrategy(config["strategy"]["futures"])
options_strategy = OptionsStrategy(config["strategy"]["options"])
chatgpt_integration = ChatGPTIntegration(api_key=os.getenv("CHATGPT_API_KEY"))
notifier = Notifier(config["notifications"])
notifier = Notifier(config["notifications"], telegram_bot)
order_executor = OrderExecution(api_key=os.getenv("DHAN_API_KEY"))
investment_banking_tracker = InvestmentBankingTracker(config["investment_banking"])

Expand Down
14 changes: 11 additions & 3 deletions utils/notifier.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
import logging
from typing import Dict, Any
from datetime import datetime
import telegram
from telegram import Bot

class Notifier:
"""
Class for sending notifications and alerts about trading events.
"""

def __init__(self, config: Dict[str, Any]):
def __init__(self, config: Dict[str, Any], telegram_bot: Bot):
"""
Initialize notifier.
Args:
config: Dictionary containing notifier configuration parameters
telegram_bot: Initialized Telegram Bot instance
"""
self.config = config
self.logger = logging.getLogger(__name__)
self.telegram_bot = telegram_bot
self.telegram_chat_id = os.getenv("TELEGRAM_CHAT_ID")

def send_trade_notification(self, trade_data: Dict[str, Any]) -> None:
"""
Expand Down Expand Up @@ -88,5 +93,8 @@ def _send_slack(self, message: str) -> None:

def _send_telegram(self, message: str) -> None:
"""Send Telegram notification"""
# Telegram bot implementation
self.logger.debug("Telegram notification sent")
try:
self.telegram_bot.send_message(chat_id=self.telegram_chat_id, text=message)
self.logger.debug("Telegram notification sent")
except Exception as e:
self.logger.error(f"Failed to send Telegram notification: {str(e)}")

0 comments on commit 4feda1d

Please sign in to comment.