API & Python

Build a Telegram Trading Signal Push Bot with Python

ClawDUX TeamMarch 28, 20265 min read0 views

Build a Telegram Trading Signal Push Bot with Python

Once your trading strategy generates signals, you need a way to receive them instantly. Telegram bots are free, fast, and work on every device.

Setup

  1. Message @BotFather on Telegram → /newbot → get your bot token
  2. Get your chat ID: message your bot, then visit https://api.telegram.org/bot<TOKEN>/getUpdates
bash
pip install python-telegram-bot aiohttp

The Signal Bot

python
import asyncio
from datetime import datetime
from typing import Optional
import aiohttp

class TradingSignalBot:
    def __init__(self, token: str, chat_id: str):
        self.token = token
        self.chat_id = chat_id
        self.base_url = f"https://api.telegram.org/bot{token}"
        self._session: Optional[aiohttp.ClientSession] = None
        self._message_count = 0
        self._last_reset = datetime.now()

    async def _get_session(self):
        if self._session is None or self._session.closed:
            self._session = aiohttp.ClientSession()
        return self._session

    async def _rate_check(self):
        """Telegram limits: 30 messages/second to same chat."""
        now = datetime.now()
        if (now - self._last_reset).seconds >= 1:
            self._message_count = 0
            self._last_reset = now
        if self._message_count >= 25:  # Leave buffer
            await asyncio.sleep(1)
            self._message_count = 0
        self._message_count += 1

    async def send(self, text: str, parse_mode: str = "HTML"):
        """Send a message with rate limiting."""
        await self._rate_check()
        session = await self._get_session()
        async with session.post(
            f"{self.base_url}/sendMessage",
            json={
                "chat_id": self.chat_id,
                "text": text,
                "parse_mode": parse_mode,
            }
        ) as resp:
            if resp.status != 200:
                print(f"Telegram error: {await resp.text()}")

    async def send_signal(
        self,
        symbol: str,
        side: str,
        price: float,
        reason: str,
        confidence: float = 0.0,
    ):
        """Send a formatted trading signal."""
        emoji = "🟢" if side == "BUY" else "🔴"
        conf_bar = "█" * int(confidence * 10) + "░" * (10 - int(confidence * 10))

        msg = (
            f"{emoji} <b>{side} Signal: {symbol}</b>\n"
            f"\n"
            f"Price: <code>${price:,.2f}</code>\n"
            f"Confidence: [{conf_bar}] {confidence:.0%}\n"
            f"Reason: {reason}\n"
            f"\n"
            f"<i>{datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}</i>"
        )
        await self.send(msg)

    async def send_pnl_update(
        self,
        daily_pnl: float,
        total_pnl: float,
        positions: list,
    ):
        """Send daily P&L summary."""
        pnl_emoji = "📈" if daily_pnl >= 0 else "📉"
        pos_lines = "\n".join(
            f"  {p['symbol']}: {p['pnl']:+.2f}%"
            for p in positions[:5]
        )

        msg = (
            f"{pnl_emoji} <b>Daily P&L Report</b>\n"
            f"\n"
            f"Today: <code>{daily_pnl:+.2f}%</code>\n"
            f"Total: <code>{total_pnl:+.2f}%</code>\n"
            f"\n"
            f"<b>Positions:</b>\n"
            f"<code>{pos_lines}</code>"
        )
        await self.send(msg)

    async def close(self):
        if self._session:
            await self._session.close()

# Usage
async def main():
    bot = TradingSignalBot(
        token="your_bot_token",
        chat_id="your_chat_id"
    )
    await bot.send_signal(
        symbol="BTC/USDT",
        side="BUY",
        price=67250.00,
        reason="SMA crossover + volume spike",
        confidence=0.75,
    )
    await bot.close()

# asyncio.run(main())

Real-time notifications are a critical component of any automated trading system. On ClawDUX, a similar notification pipeline powers real-time alerts for order confirmations, dispute updates, and strategy performance changes.

The core logic discussed in this article has been integrated into the ClawDUX API. Access ClawDUX-core for full permissions, or browse the marketplace to discover verified trading strategies.

#telegram#bot#signals#notifications#python

Related Articles