An alert bot is only as good as its signature check
Hedgicore alerts from my own saved rule, sent to Telegram with a short journal note and the news from the hours before, in one Python file.
Hakob Nahapetyan · 2026-10-29 · 10 min
I already have a morning digest in Telegram for single coins and a news index that tags headlines by coin. The missing piece was pairs. I watch a few spreads between related coins in Hedgicore, built by Bonton AI, an AI quant company. I keep my own saved rules and alerts on them there. I wanted those alerts in the same Telegram chat, each with a two-line journal note and any news on those coins from the hours before.

Hedgicore app, from hedgicore.com.
Hedgicore has an API for this, and this post is also a guide to it. My script reads two things from it and receives one:
- A morning line for each pair on my watchlist, read with an API key.
- My alerts, sent to my server as signed webhooks.
Two things this bot never does. It never places an order: Hedgicore has no endpoint that trades, and no key scope allows it. And the model never decides anything. It writes a journal note from facts it is given.

The path of one alert. Nothing after step 1 places an order.
What the Hedgicore API gives you
The API gives your own scripts what the app shows you. Every request is a plain HTTPS call to https://api.hedgicore.com/api/v1/... with an API key. Answers are JSON, times are epoch milliseconds in UTC and the data changes when a bar closes, never inside a bar. Timeframes are 1m, 5m, 15m and 1h, on Binance USDT perpetual futures.
| What you get | Endpoint | Key scope |
|---|---|---|
| The pairs screener, ranked, with tags | GET /screener |
read:market |
| The coins in the universe | GET /universe |
read:market |
| One pair: score, last z-score, data quality | GET /pairs/{a}/{b}/summary |
read:market |
| One pair over time: spread and z-score per closed bar | GET /pairs/{a}/{b}/series |
read:market |
| The same, live, as server-sent events | GET /pairs/{a}/{b}/stream |
read:market |
| Price bars for one coin | GET /bars/{symbol} |
read:market |
| A backtest of the z-score bands rule, with your fee | POST /backtest |
run:backtest |
| Your saved strategies and their versions | GET and POST /strategies |
read:strategies, write:strategies |
| Your alerts, as a list or a live stream | GET /alerts, GET /alerts/stream |
read:alerts |
| Your alerts pushed to your server | signed webhook POST |
set up in the app |
The full reference is an OpenAPI document at GET /api/v1/openapi.json, so you can generate a client in any language.
Three things the API does not do, by design. It never places, changes or cancels an order: no scope allows it. A key cannot change account settings, billing, keys or webhooks; those need you signed in to the app. And the backtest results are modelled, with no real fills.

Hedgicore app, from hedgicore.com.
How to get access
The API is in early developer access, which is how I have it. When it opens, every Hedgicore account creates its own keys in the app under Settings, API keys. The Free plan can read market data, strategies and alerts. Pro and above can also save strategies and run backtests. Webhooks need Pro+ or above. Rate limits start at 60 requests a minute per key on Free.
To ask for early developer access now, write to info@hedgicore.com and say what you want to build.
What you need
- A Hedgicore account and an API key (see above). This bot uses webhooks, so it needs Pro+ or above.
- A Telegram bot token and a chat id. The digest post shows how to get both in two minutes.
- Optional: an Anthropic API key for the journal note, and the
news.dbfile from the news index post. Without them you still get the alerts. - Python 3.10 or newer,
requestsandanthropic.
Step 1: a key with the fewest scopes
In the Hedgicore app, open Settings, then API keys, then Create key. Pick only read:market and read:alerts. This bot reads market data and alerts, so it should not hold a key that can save strategies or run backtests. The key starts with hck_live_ and is shown once.
Keep it in an environment variable, never in the code:
export HEDGICORE_API_KEY=hck_live_...
export HEDGICORE_WEBHOOK_SECRET=whsec_...
export TELEGRAM_BOT_TOKEN=...
export TELEGRAM_CHAT_ID=...
export ANTHROPIC_API_KEY=... # optional
The API takes the key in an Authorization: Bearer header. Requests are not signed, so the key over HTTPS is the whole credential. Treat it like a password and give each script its own key, so you can revoke one without breaking the rest.
Step 2: the morning watchlist
The pair summary endpoint gives the last z-score, the screener score and a data quality flag for one pair. Three pairs, three calls, once a morning.
import hashlib
import hmac
import json
import os
import queue
import sqlite3
import sys
import threading
import time
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
API = os.environ.get("HEDGICORE_API_URL", "https://api.hedgicore.com")
MODEL = "claude-haiku-5-5"
WATCHLIST = [("ETHUSDT", "BTCUSDT"), ("SOLUSDT", "AVAXUSDT"), ("LINKUSDT", "DOTUSDT")]
# ---------- reading the API ----------
def hc_get(path, params=None, tries=4):
headers = {"Authorization": f"Bearer {os.environ['HEDGICORE_API_KEY']}"}
for attempt in range(tries):
r = requests.get(f"{API}{path}", params=params, headers=headers, timeout=15)
if r.status_code in (429, 503):
time.sleep(int(r.headers.get("Retry-After", 2 ** attempt)))
continue
r.raise_for_status()
return r.json()
raise RuntimeError(f"{path}: still limited after {tries} tries")
def watchlist_lines(pairs=WATCHLIST, tf="1h"):
lines = []
for a, b in pairs:
s = hc_get(f"/api/v1/pairs/{a}/{b}/summary", {"tf": tf})
flag = "" if s["dataQuality"] == "ok" and not s["stale"] else " (check data)"
lines.append(f"{s['pair']:<20} z {s['zLast']:+.2f} score {s['score']:>3}{flag}")
return lines
Two details matter here. First, the API answers 429 with a Retry-After header when you go over the per-minute limit, and 503 when it is busy. The loop waits as told and tries again. Second, the data changes only when a bar closes. Asking every few seconds gets you the same answer and spends your daily request budget, so ask once per bar at most.
I flag a pair when dataQuality is not ok or the answer is stale. A number from a feed with a gap should not look the same as a clean one in my chat.
A line looks like this (from the published response sample in the Hedgicore docs, not a live call):
BTCUSDT|ETHUSDT z -1.04 score 69
Step 3: receiving alerts safely
This is the part that matters. A webhook receiver is a public address on the internet. Anyone who finds it can post to it. If the bot believes every POST, anyone can put fake alerts in my chat.
Hedgicore signs every delivery. The signed text is the timestamp, a dot, the alert's sequence number, a dot and the raw body. The key is the whsec_ secret from Settings, Webhooks. The receiver recomputes the signature and refuses the delivery when it does not match or when the timestamp is more than five minutes from the server clock. The five-minute rule stops someone from replaying an old delivery they captured.
def verify(secret, headers, body, now=None):
ts = headers.get("X-Hedgicore-Timestamp", "")
seq = headers.get("X-Hedgicore-Seq", "")
got = headers.get("X-Hedgicore-Signature", "")
if not ts.isdigit() or abs((now or time.time()) - int(ts)) > 300:
return False
mac = hmac.new(secret.encode(), f"{ts}.{seq}.".encode() + body, hashlib.sha256)
return hmac.compare_digest("sha256=" + mac.hexdigest(), got)
Three rules from the Hedgicore docs shape the rest:
- Answer within 5 seconds. The receiver answers
204as soon as the signature checks, then does the slow work (the model call, Telegram) on a worker thread. A model call can take longer than five seconds, and a slow answer counts as a failed delivery. - Expect repeats. A failed delivery is tried again after 1, 5, 30 and 120 seconds, so the same alert can arrive twice. I store the
X-Hedgicore-Event-Idin SQLite with a primary key. The second insert fails and the repeat is skipped. - No redirects. A
3xxcounts as a failure, so point the webhook at the final address.
def connect(path="desk.db"):
db = sqlite3.connect(path, check_same_thread=False)
db.execute("""CREATE TABLE IF NOT EXISTS alerts (
id TEXT PRIMARY KEY, received_utc TEXT NOT NULL, body TEXT NOT NULL,
journal TEXT)""")
return db
def first_time(db, event_id, body):
"""True the first time we see this id. Hedgicore can deliver an alert twice."""
try:
with db:
db.execute("INSERT INTO alerts (id, received_utc, body) VALUES (?, ?, ?)",
(event_id, datetime.now(timezone.utc).isoformat(), body.decode()))
return True
except sqlite3.IntegrityError:
return False
def make_handler(secret, db, jobs):
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length", "0")))
if not verify(secret, self.headers, body):
self.send_response(401)
self.end_headers()
return
self.send_response(204) # answer inside 5 seconds, work after
self.end_headers()
event_id = self.headers["X-Hedgicore-Event-Id"]
if first_time(db, event_id, body):
jobs.put(json.loads(body))
def log_message(self, *args):
pass
return Handler
Comparing signatures with hmac.compare_digest instead of == matters too. A plain comparison can stop at the first wrong character, and the time that takes leaks how much of a forged signature was right.
Step 4: from alert to message
An alert is a decision of my own saved rule at a closed bar: enter long, enter short or exit, with the reason as one of a fixed set of phrases. Exits carry the modelled gross result of the trade. The message says "modelled gross" because that is what it is: before fees and funding, with no real fills.
def alert_text(a):
when = datetime.fromtimestamp(a["barCloseTs"] / 1000, timezone.utc).strftime("%H:%M UTC")
head = f"{a['pair']} {a['tf']} {a['kind'].replace('_', ' ')} at the {when} close"
lines = [head, a["reason"]]
if a.get("buy") or a.get("sell"):
lines.append(f"buy {', '.join(a.get('buy') or []) or '-'} sell {', '.join(a.get('sell') or []) or '-'}")
if a.get("pnlPctGross") is not None:
lines.append(f"modelled gross result {a['pnlPctGross']:+.2f}%")
if a.get("late"):
lines.append("late: decided more than one bar after the close")
return "\n".join(lines)

An example alert, built by alert_text from the test alert. The journal line is the test placeholder, not model output.
The news before the alert, and a bug my test caught
The journal note gets the alert and up to five headlines tagged with either coin in the six hours before the bar closed. The headlines come from the news index, which already stores a coin tag per story.
My first version of this query had a lower time bound and no upper bound. On a live system that means an alert from 09:00 could get a 09:30 headline in its journal, a story that came after the decision. In a journal you reread later, that is worse than no news at all: it makes the decision look informed by something it never saw. A test with one headline before the close and one after it caught it. The fix is the second time bound:
def recent_headlines(a, news_db="news.db", hours=6):
"""Headlines tagged with either coin in the hours before the bar closed, none after it."""
if not os.path.exists(news_db) or not a.get("pair"):
return []
coins = [c.removesuffix("USDT") for c in a["pair"].split("|")]
close = datetime.fromtimestamp(a["barCloseTs"] / 1000, timezone.utc)
since = datetime.fromtimestamp(a["barCloseTs"] / 1000 - hours * 3600, timezone.utc)
q = f"""SELECT h.published_utc, h.title FROM headlines h JOIN tags t ON t.story_id = h.story_id
WHERE t.asset IN ({','.join('?' * len(coins))}) AND h.published_utc >= ? AND h.published_utc <= ?
GROUP BY h.story_id ORDER BY h.published_utc DESC LIMIT 5"""
with sqlite3.connect(news_db) as n:
return [f"{t[11:16]} {title}" for t, title in n.execute(q, (*coins, since.isoformat(), close.isoformat()))]
The journal prompt is short and strict. Facts in, two or three plain sentences out, no predictions, no advice:
JOURNAL_PROMPT = """You keep a trading journal for a person who uses alerts from their own rule.
Write two or three plain sentences for the entry below.
Use only the facts given. Do not predict prices. Do not give advice.
If there are no headlines, say that no news was found for these coins in the last hours."""
def journal_line(client, alert, headlines):
facts = alert_text(alert) + "\n\nHeadlines:\n" + ("\n".join(headlines) or "none")
try:
resp = client.messages.create(
model=MODEL, max_tokens=300, system=JOURNAL_PROMPT,
messages=[{"role": "user", "content": facts}])
return "".join(b.text for b in resp.content if b.type == "text").strip() or None
except Exception as e:
print(f"journal skipped: {e}", file=sys.stderr)
return None
If the model call fails, journal_line returns None and the alert goes to Telegram without a note. The alert matters more than the note.
Step 5: running it
def send_telegram(text, token, chat_id):
r = requests.post(f"https://api.telegram.org/bot{token}/sendMessage",
json={"chat_id": chat_id, "text": text}, timeout=15)
return r.ok
def handle(event, db, client, send):
if event["type"] != "alert":
send(f"Hedgicore test delivery {event['id']}: signature checked")
return
a = event["data"]
journal = journal_line(client, a, recent_headlines(a)) if client else None
with db:
db.execute("UPDATE alerts SET journal = ? WHERE id = ?", (journal, event["id"]))
send(alert_text(a) + (f"\n\n{journal}" if journal else ""))
def worker(jobs, db, client, send):
while True:
event = jobs.get()
try:
handle(event, db, client, send)
except Exception as e:
print(f"alert {event.get('id')} failed: {e}", file=sys.stderr)
def serve(port=8787):
db, jobs = connect(), queue.Queue()
client = None
if os.environ.get("ANTHROPIC_API_KEY"):
import anthropic
client = anthropic.Anthropic()
token, chat = os.environ["TELEGRAM_BOT_TOKEN"], os.environ["TELEGRAM_CHAT_ID"]
send = lambda text: send_telegram(text, token, chat)
threading.Thread(target=worker, args=(jobs, db, client, send), daemon=True).start()
handler = make_handler(os.environ["HEDGICORE_WEBHOOK_SECRET"], db, jobs)
print(f"listening on 127.0.0.1:{port}")
HTTPServer(("127.0.0.1", port), handler).serve_forever()
if __name__ == "__main__":
if sys.argv[1:] == ["watchlist"]:
print("\n".join(watchlist_lines()))
elif sys.argv[1:] == ["serve"]:
serve()
else:
print(__doc__)
The receiver listens on 127.0.0.1:8787. Hedgicore needs a public https:// address, so put it behind something that terminates TLS: Caddy or nginx on a small server, or a tunnel such as Cloudflare Tunnel. Then add the address in Settings, Webhooks, press Send test and check that your chat gets "test delivery ... signature checked". Then turn the webhook on for a saved strategy in its alert settings.
The Hedgicore app shows every delivery and what your endpoint answered, which is the first place to look when nothing arrives.
How I tested it
13 checks, all passing, with no real keys:
- The watchlist code against a local fake API that serves the published pair summary sample and answers
429on the first call. It retries, sends the bearer key and builds the line. - The Python signature against the
opensslrecipe in the Hedgicore docs, on the same bytes. They match. - A good signature accepted, a changed body refused, a delivery six minutes old refused.
- The receiver over real HTTP:
204for a signed delivery,204and no second job for the repeat,401for a bad signature. - The headline window: the headline before the close is in, the one after it is out.
- With a fake model client: the model sees the alert and the headline, the Telegram text is built and the journal is stored. With a model client that raises, the alert still goes out.

Real run of test_alert_desk.py on 2026-10-28 at 10:43 UTC. The line journal skipped: down is printed during the last check.
What the data can and cannot tell you
These are the limits Hedgicore states in its own docs, and they hold for this bot too:
- Alerts come after a bar closes, never inside a bar. A 1h alert for the 09:00 close arrives after 09:00.
- Results are modelled, with no real fills. Fees, slippage and funding can turn a modelled gain into a real loss.
- When Binance has no data for a bar, there is no decision for that bar. You get a note instead.
- An alert tells you what your own rule says. It is not advice. Trading involves risk.
Run it yourself
python -m venv venv && . venv/bin/activate
pip install requests anthropic
# set the variables from step 1
python alert_desk.py watchlist # once each morning, or from cron
python alert_desk.py serve # keep running, behind your https address
Change WATCHLIST at the top of the file to your own pairs. The whole file is about 200 lines.
If you want something like this for your own trading desk or group, built on the tools you already use, write to me.



