Skip to main content

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

Watch the series
Daily and Weekly Loss Limits: Building Circuit Breakers Into Your Trading

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.

python-Real-time WebSocket feed
1import ccxt.pro as ccxtpro
2import asyncio
3
4async def watch_ohlcv(symbol='BTC/USDT', timeframe='5m'):
5 exchange = ccxtpro.binance({'enableRateLimit': True})
6
7 while True:
8 try:
9 candles = await exchange.watch_ohlcv(symbol, timeframe)
10 latest = candles[-1]
11 timestamp, o, h, l, c, v = latest
12 print(f"{symbol} | Close: {c} | Volume: {v:.2f}")
13 # Feed into signal generation here
14 except Exception as e:
15 print(f"Error: {e}")
16 await asyncio.sleep(5)
17
18asyncio.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.

python-Signal generation engine
1import pandas as pd
2from collections import deque
3
4class SignalEngine:
5 def __init__(self, fast_period=20, slow_period=50):
6 self.fast_period = fast_period
7 self.slow_period = slow_period
8 self.closes = deque(maxlen=slow_period + 10)
9 self.position = None # None, 'long', or 'short'
10 self.entry_price = None
11
12 def update(self, close_price):
13 self.closes.append(close_price)
14 if len(self.closes) < self.slow_period:
15 return None
16
17 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]
22
23 # Crossover detection
24 if prev_fast <= prev_slow and fast_ma > slow_ma:
25 if self.position != 'long':
26 self.position = 'long'
27 self.entry_price = close_price
28 return 'BUY'
29
30 elif prev_fast >= prev_slow and fast_ma < slow_ma:
31 if self.position == 'long':
32 self.position = None
33 return 'SELL'
34
35 return None

Telegram 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.

python-Telegram alert integration
1import requests
2
3class 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_id
7
8 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}")
14
15# Usage
16alert = 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.

python-Scheduled signal checks
1from apscheduler.schedulers.blocking import BlockingScheduler
2import logging
3
4logging.basicConfig(level=logging.INFO, filename='signals.log')
5
6engine = SignalEngine()
7alert = TelegramAlert('TOKEN', 'CHAT_ID')
8
9def 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}")
18
19scheduler = BlockingScheduler()
20scheduler.add_job(check_signal, 'cron', hour='*/4', minute=1)
21scheduler.start()

Paper trade before you risk real money

Run your pipeline for at least 2–4 weeks in paper-trade mode: logging signals and tracking hypothetical P&L without executing real trades. Compare signal-to-live performance against your backtest expectations. If there is a significant gap, debug the pipeline before deploying capital. The most expensive bugs are the ones you find with real money.

Put this lesson to work

Free on Thrive, no account needed.