Building a Live Signal Pipeline
WebSocket feeds, real-time signal generation, Telegram and Discord alerting, scheduling with cron, and moving from backtest to live signals.
From Thrive on YouTube
Watch the matching Thrive video
Daily and Weekly Loss Limits: Building Circuit Breakers Into Your Trading
Part of Trading Journal and Performance Review. Education only. Not financial advice.
Moving from Backtest to Live
A profitable backtest is the starting line, not the finish line. The gap between backtested returns and live results is where most quant traders fail. Live execution introduces latency, partial fills, slippage, exchange downtime, network failures, and the psychological pressure of real money. Building a reliable signal pipeline closes that gap by automating the repeatable parts and leaving you to make only the high-level decisions.
WebSocket Connections for Real-Time Data
WebSockets maintain a persistent connection to the exchange, streaming price updates as they happen instead of polling at intervals. For signal generation, you need the latest price the moment it arrives, not 30 seconds later on a polling cycle.
1import ccxt.pro as ccxtpro2import asyncio34async def watch_ohlcv(symbol='BTC/USDT', timeframe='5m'):5 exchange = ccxtpro.binance({'enableRateLimit': True})67 while True:8 try:9 candles = await exchange.watch_ohlcv(symbol, timeframe)10 latest = candles[-1]11 timestamp, o, h, l, c, v = latest12 print(f"{symbol} | Close: {c} | Volume: {v:.2f}")13 # Feed into signal generation here14 except Exception as e:15 print(f"Error: {e}")16 await asyncio.sleep(5)1718asyncio.run(watch_ohlcv())Signal Generation Loop
The signal loop receives new data, updates indicators, checks entry/exit conditions, and emits signals. State management is critical. You need to track your current position, entry price, and indicator values between candle updates.
1import pandas as pd2from collections import deque34class SignalEngine:5 def __init__(self, fast_period=20, slow_period=50):6 self.fast_period = fast_period7 self.slow_period = slow_period8 self.closes = deque(maxlen=slow_period + 10)9 self.position = None # None, 'long', or 'short'10 self.entry_price = None1112 def update(self, close_price):13 self.closes.append(close_price)14 if len(self.closes) < self.slow_period:15 return None1617 closes = pd.Series(list(self.closes))18 fast_ma = closes.rolling(self.fast_period).mean().iloc[-1]19 slow_ma = closes.rolling(self.slow_period).mean().iloc[-1]20 prev_fast = closes.rolling(self.fast_period).mean().iloc[-2]21 prev_slow = closes.rolling(self.slow_period).mean().iloc[-2]2223 # Crossover detection24 if prev_fast <= prev_slow and fast_ma > slow_ma:25 if self.position != 'long':26 self.position = 'long'27 self.entry_price = close_price28 return 'BUY'2930 elif prev_fast >= prev_slow and fast_ma < slow_ma:31 if self.position == 'long':32 self.position = None33 return 'SELL'3435 return NoneTelegram Bot for Alerts
Telegram bots are the simplest way to receive real-time alerts on your phone. Create a bot through BotFather, get the token, and send messages to yourself or a group chat whenever your signal engine fires.
1import requests23class TelegramAlert:4 def __init__(self, bot_token, chat_id):5 self.url = f"https://api.telegram.org/bot{bot_token}/sendMessage"6 self.chat_id = chat_id78 def send(self, message):9 payload = {'chat_id': self.chat_id, 'text': message, 'parse_mode': 'HTML'}10 try:11 requests.post(self.url, json=payload, timeout=10)12 except Exception as e:13 print(f"Telegram error: {e}")1415# Usage16alert = TelegramAlert('YOUR_BOT_TOKEN', 'YOUR_CHAT_ID')17alert.send('<b>BUY Signal</b>\nBTC/USDT at $67,450\n20/50 SMA Crossover')Scheduling and Monitoring
For strategies on longer timeframes (4h, daily), you do not need a persistent WebSocket connection. Use APScheduler or a system cron job to run your signal check at the close of each candle.
1from apscheduler.schedulers.blocking import BlockingScheduler2import logging34logging.basicConfig(level=logging.INFO, filename='signals.log')56engine = SignalEngine()7alert = TelegramAlert('TOKEN', 'CHAT_ID')89def check_signal():10 price = fetch_latest_close('BTC/USDT')11 signal = engine.update(price)12 if signal:13 msg = f"{signal} BTC/USDT at ${price:,.2f}"14 alert.send(msg)15 logging.info(msg)16 else:17 logging.info(f"No signal. BTC at ${price:,.2f}")1819scheduler = BlockingScheduler()20scheduler.add_job(check_signal, 'cron', hour='*/4', minute=1)21scheduler.start()Paper trade before you risk real money
Put this lesson to work
Free on Thrive, no account needed.