← Blog
TelegramTradingAutomation

A Telegram market digest where the LLM cannot invent a number

A small Python bot that pulls public Binance futures data each morning, asks one cheap model call for a plain summary and sends both to Telegram.

Hakob Nahapetyan · 2026-10-28 · 9 min

Every morning I want the same facts about the coins I watch: price, the 24h move, volume and the funding rate on the perpetual future. A bot that posts a small table to Telegram at 07:00 beats opening an exchange tab.

The table is the product. The language model only adds three to five sentences on top of it. That order matters for the design: if the model is down, slow or wrong, the table still goes out. And the model never sees anything except the table, so it has nothing else to talk about.

This post is the whole build: one Python file of about 165 lines, the public Binance API, the Telegram Bot API and one call to Claude Haiku.

A Telegram chat where the bot types and then posts the morning digest with a note and a table of six coins

What the message looks like in Telegram as it arrives. The table is the real run from 2026-10-28 at 09:53 UTC. The note is an example of the format, written by hand.

What the bot does

  1. Fetch 24h tickers, funding rates and funding intervals from Binance USDT perpetual futures. No API key is needed for this data.
  2. Build a fixed-width text table for a short watchlist.
  3. Send the table to the model with a strict prompt and get a short note back.
  4. Check that every number in the note appears in the table. If one does not, drop the note.
  5. Post the note and the table to Telegram with sendMessage.

Here is a real table from a run on 2026-10-28 at 09:53 UTC. The six rows came back in 1.21 seconds.

coin        last   24h %   vol $M  funding %
BTC    81,448.30   +2.25    9,082  +0.0098/8h
ETH     2,369.35   +2.71    6,345  +0.0072/8h
SOL       102.78   +3.18    1,085  +0.0100/8h
BNB       753.84   +2.46      293  +0.0057/8h
XRP         1.33   +2.73      524  +0.0100/8h
DOGE      0.0804   +4.66      248  +0.0100/8h

The bot covers single coins. For spreads between related coins (two different coins that tend to move together) I use Hedgicore, built by Bonton AI, an AI quant company. This guide shows how I send Hedgicore alerts to the same Telegram chat through its API.

Step 1: a Telegram bot and your chat id

Open Telegram and message @BotFather. Send /newbot, pick a display name and a username that ends in bot. BotFather replies with a token that looks like 123456789:AA.... Anyone with it can post as your bot, so treat it like a password.

Telegram bots cannot message you first. Send your new bot any message, then open this URL in a browser with your token in it:

https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates

The reply holds "chat":{"id":...}. That number is your chat id. For a group, add the bot to the group, send a message there and read the id the same way. Group ids are negative.

Keep both values in environment variables, never in the code:

export TELEGRAM_BOT_TOKEN="123456789:AA..."
export TELEGRAM_CHAT_ID="123456789"
export ANTHROPIC_API_KEY="sk-ant-..."

Step 2: fetch the data with retries

Three public endpoints give everything. /fapi/v1/ticker/24hr returns price, change and quote volume for every perpetual. /fapi/v1/premiumIndex returns the last funding rate. /fapi/v1/fundingInfo lists the contracts whose funding interval differs from the usual 8 hours, so the table can say /4h when that is the case.

Asking for all symbols at once and filtering locally is three requests per run, whatever the watchlist size.

"""Morning market digest: public Binance futures data -> table -> one LLM summary -> Telegram."""
import html
import os
import re
import sys
import time
from datetime import datetime, timezone

import requests

WATCHLIST = ["BTCUSDT", "ETHUSDT", "SOLUSDT", "BNBUSDT", "XRPUSDT", "DOGEUSDT"]
FAPI = "https://fapi.binance.com"
MODEL = "claude-haiku-5-5"


def get_json(url, params=None, tries=4):
    """GET with retries and exponential backoff. Raises after the last try."""
    for attempt in range(tries):
        try:
            r = requests.get(url, params=params, timeout=10)
            if r.status_code == 429 or r.status_code >= 500:
                raise requests.HTTPError(f"HTTP {r.status_code}")
            r.raise_for_status()
            return r.json()
        except (requests.ConnectionError, requests.Timeout, requests.HTTPError) as e:
            if attempt == tries - 1:
                raise
            wait = 2 ** attempt
            print(f"retry {attempt + 1} after {wait}s: {e}", file=sys.stderr)
            time.sleep(wait)


def fetch_rows():
    tickers = {t["symbol"]: t for t in get_json(f"{FAPI}/fapi/v1/ticker/24hr")}
    premium = {p["symbol"]: p for p in get_json(f"{FAPI}/fapi/v1/premiumIndex")}
    # Most perps settle funding every 8h. fundingInfo lists the ones that differ.
    intervals = {f["symbol"]: f["fundingIntervalHours"]
                 for f in get_json(f"{FAPI}/fapi/v1/fundingInfo")}
    rows = []
    for sym in WATCHLIST:
        t, p = tickers.get(sym), premium.get(sym)
        if not t or not p:
            print(f"missing data for {sym}, skipped", file=sys.stderr)
            continue
        rows.append({
            "symbol": sym.replace("USDT", ""),
            "last": float(t["lastPrice"]),
            "chg_pct": float(t["priceChangePercent"]),
            "vol_musd": float(t["quoteVolume"]) / 1e6,
            "funding_pct": float(p["lastFundingRate"]) * 100,
            "funding_h": intervals.get(sym, 8),
        })
    return rows

The retry helper backs off 1, 2 then 4 seconds on timeouts, HTTP 429 and 5xx. A 4xx other than 429 raises at once, because retrying a bad request only burns time. A symbol missing from the response gets skipped with a note instead of failing the run.

Step 3: the table

A fixed-width table inside a Telegram <pre> block lines up on phones and desktop. Prices under 1 get four decimals.

def fmt_price(x):
    return f"{x:,.2f}" if x >= 1 else f"{x:.4f}"


def build_table(rows):
    lines = [f"{'coin':<5} {'last':>10} {'24h %':>7} {'vol $M':>8} {'funding %':>10}"]
    for r in rows:
        lines.append(
            f"{r['symbol']:<5} {fmt_price(r['last']):>10} {r['chg_pct']:>+7.2f} "
            f"{r['vol_musd']:>8,.0f} {r['funding_pct']:>+8.4f}/{r['funding_h']}h"
        )
    return "\n".join(lines)

Step 4: the prompt that keeps the model on the table

I wrote this so the model only sees the table. It gets no news, no history and no tools. The system prompt sets the rules:

SYSTEM = """You write a short morning note about crypto futures data.
Rules:
- Use only the numbers in the table. Do not add any other number, date or price.
- Describe what the table shows: biggest moves, volume, where funding is positive or negative.
- Funding: positive means longs pay shorts, negative means shorts pay longs. Say no more than that.
- No predictions, no advice, no words like buy, sell, bullish, bearish, should or expect.
- 3 to 5 plain sentences. No headings, no bullet points, no emoji."""


def summarize(table, client):
    """One LLM call. Returns (text, usage) or (None, reason) on any failure."""
    try:
        resp = client.messages.create(
            model=MODEL,
            max_tokens=600,
            thinking={"type": "disabled"},  # a short note needs no reasoning step
            output_config={"effort": "low"},
            system=SYSTEM,
            messages=[{"role": "user", "content": f"Table (Binance USDT perps, last 24h):\n{table}"}],
        )
    except Exception as e:  # network, auth, rate limit, outage: the table still goes out
        return None, f"model call failed: {type(e).__name__}"
    if resp.stop_reason != "end_turn":  # refusal or cut off at max_tokens
        return None, f"stop reason {resp.stop_reason}"
    text = next((b.text for b in resp.content if b.type == "text"), "").strip()
    if not text:
        return None, "empty model reply"
    return text, resp.usage

Some choices in there:

  • Banned words. "Buy", "sell", "bullish" and "expect" are the words that turn a description into a forecast. Naming them works better than a general "no advice" line.
  • Funding explained in one line. Positive funding means longs pay shorts. That is a fact about the contract. Anything past it is a guess, so the prompt stops there.
  • Thinking off, effort low. A short rewrite of six rows needs no reasoning step. Turning it off keeps output tokens small and predictable.
  • max_tokens=600. Far more than five sentences need. If the reply still hits the cap, the stop reason is max_tokens and the code treats it as a failure, because half a sentence is worse than none.
  • Any exception returns None. Network errors, a bad key, a rate limit or an outage all lead to the same place: the table goes out alone.

The Anthropic SDK already retries 429 and 5xx twice with backoff, so there is no retry loop around this call.

Step 5: check the numbers before sending

The model can still ignore a prompt, so the code checks the reply. Every number in the note has to appear somewhere in the table text. If the model writes "BTC near 250,000", the check finds 250000, the note is dropped and the table goes out alone.

NUM = re.compile(r"\d[\d,]*\.?\d*")


def numbers_not_in_table(summary, table):
    """Every number in the summary must appear in the table text."""
    known = {n.replace(",", "").rstrip(".") for n in NUM.findall(table)}
    known |= {k.lstrip("0") or "0" for k in known}
    found = [n.replace(",", "").rstrip(".") for n in NUM.findall(summary)]
    return [n for n in found if n not in known and n.lstrip("0") not in known]

This check is strict on purpose. If the model rounds 2.25 to "about 2%", the note is dropped too. I prefer losing a note now and then over sending one number that is not in the data.

Step 6: send to Telegram

def build_message(table, summary):
    stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    parts = [f"<b>Morning digest</b> {stamp}"]
    if summary:
        parts.append(html.escape(summary))
    parts.append(f"<pre>{html.escape(table)}</pre>")
    parts.append("Source: Binance USDT perpetuals, public API. Not advice.")
    return "\n\n".join(parts)


def send_telegram(text, token, chat_id, tries=3):
    url = f"https://api.telegram.org/bot{token}/sendMessage"
    payload = {"chat_id": chat_id, "text": text[:4096], "parse_mode": "HTML"}
    for attempt in range(tries):
        try:
            r = requests.post(url, json=payload, timeout=10)
            data = r.json()
            if data.get("ok"):
                return True
            # 4xx means a bad token or chat id: retrying will not help
            if 400 <= r.status_code < 500 and r.status_code != 429:
                print(f"telegram error {r.status_code}: {data.get('description')}", file=sys.stderr)
                return False
        except (requests.ConnectionError, requests.Timeout, ValueError) as e:
            print(f"telegram attempt {attempt + 1} failed: {e}", file=sys.stderr)
        time.sleep(2 ** attempt)
    return False


def make_client():
    import anthropic
    return anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment


def run(client=None, dry_run=False):
    rows = fetch_rows()
    table = build_table(rows)
    summary, info = summarize(table, client or make_client())
    if summary:
        bad = numbers_not_in_table(summary, table)
        if bad:
            print(f"summary dropped, numbers not in table: {bad}", file=sys.stderr)
            summary, info = None, "summary had numbers not in the table"
    if not summary:
        print(f"sending table only ({info})", file=sys.stderr)
    msg = build_message(table, summary)
    if dry_run:
        print(msg)
        return msg
    ok = send_telegram(msg, os.environ["TELEGRAM_BOT_TOKEN"], os.environ["TELEGRAM_CHAT_ID"])
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    run(dry_run="--dry-run" in sys.argv)

build_message escapes the model text for HTML mode, so a stray < cannot break the message. send_telegram retries network errors and 429, but stops at once on 400, 401 or 403. Those mean a wrong token or chat id. The script exits with code 1 when sending fails, so cron mail or your monitoring can see it.

An example of the finished message format (the summary sentence below is written by hand to show the layout, it is not model output):

Morning digest 2026-10-28 09:53 UTC

All six coins rose over 24h. DOGE moved the most at +4.66% and BTC had the
highest volume at 9,082 $M. Funding was positive on every row, so longs paid
shorts.

coin        last   24h %   vol $M  funding %
BTC    81,448.30   +2.25    9,082  +0.0098/8h
...

Source: Binance USDT perpetuals, public API. Not advice.

The morning digest in a Telegram chat: a bold title with the time, three sentences of notes and the table of six coins

The same message in Telegram, built from the real table of 2026-10-28 at 09:53 UTC. The note is an example of the format, not model output.

Testing without an API key

I tested the data steps on real Binance data. For the model step I used a small fake client with the same messages.create shape. It replies with a sentence built from the first row of the table it is sent, so the number check sees real numbers.

class FakeClient:
    """Mimics client.messages.create and returns a canned reply."""
    def __init__(self, text=None, error=None, reply_fn=None):
        self.text, self.error, self.reply_fn, self.calls = text, error, reply_fn, []
        self.messages = self

    def create(self, **kwargs):
        self.calls.append(kwargs)
        if self.error:
            raise self.error
        text = self.reply_fn(kwargs) if self.reply_fn else self.text
        return SimpleNamespace(
            stop_reason="end_turn",
            content=[SimpleNamespace(type="text", text=text)],
            usage=SimpleNamespace(input_tokens=0, output_tokens=0),
        )

The test file runs six checks: a note quoting table numbers passes, a note with 250,000 is caught, a full dry run includes the note, a model exception still sends the table, an invented number drops the note and a fake Telegram token returns False after a real 401 from Telegram. All six passed on 2026-10-28.

Terminal output of the test run: a table of six coins, three dry run messages, a dropped note, a 401 from Telegram and all tests passed

Real output of test_digest.py on 2026-10-28 at 10:44 UTC, so the prices differ from the table above. The bodies of the three dry run messages are cut for space.

Scheduling

Cron does not load your shell profile, so put the three variables in a file only you can read and load it in the cron line:

chmod 600 ~/digest/digest.env
crontab -e
# 07:00 server time every day
0 7 * * * cd ~/digest && set -a && . ./digest.env && set +a && ./venv/bin/python digest.py >> digest.log 2>&1

digest.env holds the three export lines from step 1. Cron runs in the server time zone. Check it with date.

Cost of one run

The system prompt and the table together are about 880 characters. At roughly 4 characters per token that is about 220 input tokens. A five sentence reply is around 100 to 150 tokens, and max_tokens caps it at 600.

At Claude Haiku 5.5 prices ($0.10 per million input tokens, $0.50 per million output tokens), one run costs about $0.0001. Even at the 600 token cap it is about $0.0003, which is under one cent a month for a daily digest. These token counts are estimates from text length. The real ones are in resp.usage after your first live run, so log them.

Run it yourself

mkdir digest && cd digest
python3 -m venv venv
./venv/bin/pip install anthropic requests
# save digest.py from this post, then:
export TELEGRAM_BOT_TOKEN="..." TELEGRAM_CHAT_ID="..." ANTHROPIC_API_KEY="..."
./venv/bin/python digest.py --dry-run   # prints the message, sends nothing
./venv/bin/python digest.py             # sends to Telegram

Change WATCHLIST to your own symbols. Any USDT perpetual on Binance works.

If you want a bot like this built for your team, with your data sources and your channels, write to me.

Have finance work that eats hours?

Tell me how it is done today and who does it. I will say whether automation is the right fix.

Get in touch

More from the blog