How do you set up a Telegram bot that only sends demo reports, without exposing its token (the key that controls the bot)?
This post creates the bot with BotFather, finds the chat_id through
getUpdates, and sends a test message with a token read from an environment
variable. Then it gives every report a state, so a signal never reads like an
order and an order never reads like a fill. The easy mistake: pasting the
token into a prompt, committed code or a screenshot. Whoever has the token
controls the bot.
Terms used below:
- Bot token: the bot’s credential. Keep it like a password; never put it in a prompt or a screenshot.
chat_id: the ID of the chat that receives the messages.okanddescription: the fields in every Telegram Bot API answer.ok=falsemeans it failed, even when your code raised no error.- State: where an event stands, from signal only to confirmed by the demo account.
Where the token lives
Open the official BotFather (@BotFather, with the verified mark), send
/newbot and follow the steps. Keep this bot separate from the morning-report
bot in the trading-day post, so system reports never mix with other messages.
Store the token in local configuration that’s never committed; prompts only
ever see a placeholder. Send /start to the bot and check the target chat.
Then a script sends a fixed test message and reads the HTTP answer, ok and
description. On a permission or chat error, stop; don’t retry in a loop.
| Never | Where it belongs |
|---|---|
| Pasted into a prompt for Claude or Codex | Environment variable TELEGRAM_BOT_TOKEN |
| In committed source code | A secret manager, passed in only at run time |
| In a public Pine script or a screenshot | Prompts use a placeholder |
| Printed in a log inside a URL |
Whoever has the token can use everything the bot can do. Example code only needs a placeholder; it never needs the real token.
Setting it up
- In Telegram, open @BotFather, send
/newbot, give a display name and a username ending inbot, and copy the token it returns. - Store it as a Windows user environment variable through the dialog: Start
→ “environment” → Edit environment variables for your account → User
variables → New…, name
TELEGRAM_BOT_TOKEN. Not with a PowerShell command, which leaves the token in the command history. On macOS, anexportline in~/.zshrc. - Open a chat with the new bot and press Start. Bots can’t start a conversation; without this, the first send fails.
- Open a new PowerShell window so it sees the variable, and find the
chat_id. - Add
TELEGRAM_CHAT_IDthe same way, open a new window, and send the test message.
The notifier, src/notifier.py. It uses only Python’s standard library, sends
plain text, makes one attempt per message, and never prints the URL, which
contains the token:
# src/notifier.py: send DEMO status reports to one Telegram chat. Sends only: reads no commands, connects to no broker.
# .venv\Scripts\python src\notifier.py chats print the chat_id of chats that messaged the bot (run once)
# .venv\Scripts\python src\notifier.py test send one fixed test message and print Telegram's answer
# .venv\Scripts\python src\notifier.py preview print sample reports for each state; sends nothing
import json, os, sys, urllib.error, urllib.parse, urllib.request
from datetime import datetime, timezone
VERSION = "notifier-v1"
API = "https://api.telegram.org/bot{token}/{method}" # never print this once filled in
NEXT = {None: {"SIGNAL_ONLY", "RECEIVED"},
"RECEIVED": {"VALIDATED", "REJECTED"},
"VALIDATED": {"REQUESTED", "REJECTED"},
"REQUESTED": {"CONFIRMED", "REJECTED", "UNKNOWN"},
"UNKNOWN": {"CONFIRMED", "REJECTED"}, # only after reconciling with the demo account
"SIGNAL_ONLY": set(), "CONFIRMED": set(), "REJECTED": set()}
NEEDED = ("event_id", "rule_version", "symbol", "timeframe", "bar_close_utc", "state")
def check_transition(previous, new):
if new not in NEXT.get(previous, set()):
raise ValueError(f"{previous} -> {new} is not allowed")
def format_report(e, now=None):
missing = [k for k in NEEDED if not e.get(k)]
if missing:
raise ValueError(f"missing {', '.join(missing)}")
state = e["state"]
if state == "CONFIRMED" and not all(e.get(k) for k in ("ticket", "quantity", "fill_price")):
raise ValueError("CONFIRMED needs ticket, quantity and fill_price from the demo account")
detail = {"SIGNAL_ONLY": "signal only: no order sent",
"RECEIVED": "received, not checked yet",
"VALIDATED": "passed the checks, not sent yet",
"REQUESTED": "request sent to the demo account, no answer yet",
"CONFIRMED": f"demo confirmed ticket {e.get('ticket')}: {e.get('quantity')} lot at {e.get('fill_price')}",
"REJECTED": f"rejected: {e.get('reason', 'no reason given')}",
"UNKNOWN": "no confirmation (timeout?): reconcile with the demo account before any retry"}[state]
now = now or datetime.now(timezone.utc)
return "\n".join([f"DEMO | {state}",
f"event {e['event_id']} | rule {e['rule_version']}",
f"{e['symbol']} {e['timeframe']} | bar close {e['bar_close_utc']} UTC",
detail,
f"sent {now:%Y-%m-%d %H:%M:%S} UTC by {VERSION}"])
def redact(text, token):
return text.replace(token, "<token>") if token else text
def call(method, data, token, opener=urllib.request.urlopen):
"""One attempt, no retry loop. Returns Telegram's JSON, or {'ok': False, ...} on any failure."""
url = API.format(token=token, method=method)
body = urllib.parse.urlencode(data).encode()
try:
with opener(urllib.request.Request(url, data=body), timeout=10) as r:
return json.loads(r.read())
except urllib.error.HTTPError as err: # 4xx/5xx: Telegram still sends ok/description
try:
return json.loads(err.read())
except ValueError:
return {"ok": False, "error_code": err.code, "description": "no JSON in the answer"}
except (urllib.error.URLError, TimeoutError, OSError) as err: # the message may contain the url
return {"ok": False, "error_code": None, "description": redact(f"{type(err).__name__}: {err}", token)}
def env(name):
value = os.environ.get(name, "")
if not value:
sys.exit(f"Missing environment variable {name}")
return value
def send(text, opener=urllib.request.urlopen):
token, chat = env("TELEGRAM_BOT_TOKEN"), env("TELEGRAM_CHAT_ID")
res = call("sendMessage", {"chat_id": chat, "text": text}, token, opener)
if res.get("ok"):
print(f"ok=true | message_id {res['result']['message_id']}")
return True
print(f"ok=false | {res.get('error_code')} {redact(str(res.get('description')), token)}")
return False
SAMPLES = [
dict(event_id="xau-brk-v2-2026-12-03T15:00Z", rule_version="xau-brk-v2", symbol="XAUUSD", timeframe="H1",
bar_close_utc="2026-12-03 15:00", state="SIGNAL_ONLY"),
dict(event_id="xau-brk-v2-2026-12-03T16:00Z", rule_version="xau-brk-v2", symbol="XAUUSD", timeframe="H1",
bar_close_utc="2026-12-03 16:00", state="UNKNOWN"),
dict(event_id="xau-brk-v2-2026-12-03T16:00Z", rule_version="xau-brk-v2", symbol="XAUUSD", timeframe="H1",
bar_close_utc="2026-12-03 16:00", state="CONFIRMED", ticket="5012345", quantity="0.05", fill_price="4198.62"),
]
if __name__ == "__main__":
cmd = sys.argv[1] if len(sys.argv) > 1 else ""
if cmd == "chats":
res = call("getUpdates", {}, env("TELEGRAM_BOT_TOKEN"))
if not res.get("ok"):
sys.exit(f"ok=false | {res.get('error_code')} {res.get('description')}")
for u in res["result"]:
chat = (u.get("message") or {}).get("chat")
if chat:
print("chat_id:", chat["id"], "| type:", chat.get("type"), "| name:", chat.get("first_name") or chat.get("title"))
if not res["result"]:
print("No updates: message the bot (Start), then run again within 24 hours.")
elif cmd == "test":
ok = send(f"DEMO | test connection | {datetime.now(timezone.utc):%Y-%m-%d %H:%M} UTC | {VERSION}")
sys.exit(0 if ok else 1)
elif cmd == "preview":
sent = [datetime(2026, 12, 3, *t, tzinfo=timezone.utc) for t in ((15, 0, 7), (16, 0, 19), (16, 1, 34))]
print("\n\n".join(format_report(e, t) for e, t in zip(SAMPLES, sent)))
try:
format_report(dict(SAMPLES[2], ticket=""), sent[2])
except ValueError as err:
print(f"\nrefused: {err}")
else:
sys.exit("usage: notifier.py chats | test | preview")In Windows PowerShell, from C:\trade-system-lab:
notepad src\notifier.py
$env:TELEGRAM_BOT_TOKEN.Length
.venv\Scripts\python src\notifier.py chats
.venv\Scripts\python src\notifier.py testThe Length line prints how long the token is, not the token. chats prints
chat_id: 123456789 | type: private | name: …; nothing printed means nobody
has messaged the bot in the last 24 hours, so press Start and run it again.
test sends one line like DEMO | test connection | 2026-12-03 14:02 UTC | notifier-v1 and prints Telegram’s answer.
Then break it on purpose, in a window you close afterwards. The wrong values only live in that window; your stored variables don’t change:
$env:TELEGRAM_BOT_TOKEN = "123456:wrong"
.venv\Scripts\python src\notifier.py test
exit| It prints | Cause | Fix |
|---|---|---|
ok=true | message_id 42 |
Delivered | Check it arrived in the right chat |
ok=false | 401 Unauthorized |
Wrong or revoked token | Get it again from BotFather; if it leaked, revoke it and create a new one |
ok=false | 400 Bad Request: chat not found |
Wrong chat_id, or you never pressed Start |
Press Start, run chats again |
ok=false | 403 Forbidden: bot was blocked by the user |
You blocked the bot | Unblock it |
ok=false | 429 Too Many Requests: retry after … |
Burst sending, usually a loop bug | Wait that many seconds and fix the loop |
ok=false | 403 no JSON in the answer |
Something between you and Telegram answered (a proxy or firewall), not Telegram | Check the network; on a locked-down work network, ask for api.telegram.org |
ok=false | None URLError: … |
Network down; the token in the message is replaced by <token> |
Check the network and retry once, by hand |
The first report needs the right labels
- A fixed message first, before any backtest data is connected.
- Check it’s the right bot and your own separate target chat.
- Send one message labelled DEMO, with the time in UTC and a version.
- Read the success or failure Telegram returns; “the code didn’t throw” isn’t success.
- Never log the token; mask sensitive identifiers when you share your work.
| Step | What |
|---|---|
| 1 | BotFather |
| 2 | Your own token |
| 3 | Target chat |
| 4 | A DEMO message |
Worked example: a report has to tell a signal from an order
The first report carries only: DEMO, event_id, rule_version, symbol,
timeframe, bar close in UTC, and the state SIGNAL_ONLY. No API key, no account
number. If sending fails, fix the reporting on its own; never resend a trade
to see whether a message comes through.
| Line | Content | Why |
|---|---|---|
| 1 | DEMO and the state | The label is on every message |
| 2 | event_id · rule_version |
Traces back to the event and the rule version |
| 3 | Symbol · timeframe · bar close UTC | Which candle, in UTC |
| 4 | What the state means | SIGNAL_ONLY: a signal, no order |
| Never | API key, account number |
Once demo execution is added, the state moves RECEIVED → VALIDATED →
REQUESTED → CONFIRMED, or REJECTED, or UNKNOWN. Say “filled” only when the
demo account confirms the ticket, quantity and price. A timeout after a
request doesn’t prove the order didn’t fill; reconcile the state before any
retry. check_transition enforces the order: SIGNAL_ONLY never becomes
CONFIRMED, and UNKNOWN can only become CONFIRMED or REJECTED after you’ve
checked the demo account.
| Gate | Question | If not |
|---|---|---|
| Input | A demo order request was sent (REQUESTED) | |
| 1 | An answer came back, no timeout? | Report UNKNOWN; reconcile before any retry |
| 2 | Did the demo confirm a ticket? | Report REJECTED or UNKNOWN, never filled |
| 3 | Are the filled quantity and price confirmed? | Don’t say filled yet |
| Passed | Report CONFIRMED with ticket, quantity and price |
.venv\Scripts\python src\notifier.py preview prints what each state looks
like and sends nothing (made-up ticket and price):
DEMO | SIGNAL_ONLY
event xau-brk-v2-2026-12-03T15:00Z | rule xau-brk-v2
XAUUSD H1 | bar close 2026-12-03 15:00 UTC
signal only: no order sent
sent 2026-12-03 15:00:07 UTC by notifier-v1
DEMO | UNKNOWN
event xau-brk-v2-2026-12-03T16:00Z | rule xau-brk-v2
XAUUSD H1 | bar close 2026-12-03 16:00 UTC
no confirmation (timeout?): reconcile with the demo account before any retry
sent 2026-12-03 16:00:19 UTC by notifier-v1
DEMO | CONFIRMED
event xau-brk-v2-2026-12-03T16:00Z | rule xau-brk-v2
XAUUSD H1 | bar close 2026-12-03 16:00 UTC
demo confirmed ticket 5012345: 0.05 lot at 4198.62
sent 2026-12-03 16:01:34 UTC by notifier-v1
refused: CONFIRMED needs ticket, quantity and fill_price from the demo accountThe tests, tests/test_notifier.py, use a fake Telegram, so they need no
network and no token:
# tests/test_notifier.py: no network. A fake opener stands in for Telegram.
import io, json, urllib.error
import pytest
from src.notifier import call, check_transition, format_report, send, SAMPLES
TOKEN = "000000:fake-token-for-tests"
def test_confirmed_needs_ticket_quantity_and_price():
with pytest.raises(ValueError, match="CONFIRMED needs"):
format_report(dict(SAMPLES[2], fill_price=""))
def test_states_move_in_order():
check_transition("REQUESTED", "UNKNOWN")
check_transition("UNKNOWN", "CONFIRMED")
for prev, new in [("SIGNAL_ONLY", "CONFIRMED"), ("RECEIVED", "CONFIRMED"), ("CONFIRMED", "REQUESTED")]:
with pytest.raises(ValueError):
check_transition(prev, new)
def test_ok_false_is_a_failure_and_the_token_is_never_printed(monkeypatch, capsys):
def opener(req, timeout):
body = io.BytesIO(json.dumps({"ok": False, "error_code": 401, "description": "Unauthorized"}).encode())
raise urllib.error.HTTPError(req.full_url, 401, "Unauthorized", {}, body)
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", TOKEN)
monkeypatch.setenv("TELEGRAM_CHAT_ID", "123")
assert send("DEMO | test", opener) is False
out = capsys.readouterr().out
assert "ok=false | 401 Unauthorized" in out and TOKEN not in out
def test_network_error_hides_the_url():
def opener(req, timeout):
raise urllib.error.URLError(f"failed to reach {req.full_url}")
res = call("sendMessage", {"chat_id": 1, "text": "x"}, TOKEN, opener)
assert res["ok"] is False and TOKEN not in res["description"] and "<token>" in res["description"]Run .venv\Scripts\python -m pytest -q tests; you should see 4 passed.
The token sits in secret configuration on the machine that sends, never in public Pine, screenshots or prompts. Check the target chat with a harmless message, keep identifying details out of the content, and guard against spam and endless retries. A Telegram report that arrives quickly only proves the reporting path works; it says nothing about whether the system has an edge.
Try it: a send-only notifier
Write an example Python notifier that only sends a test message through the Telegram Bot API sendMessage. Read the current official Telegram documentation. Read `TELEGRAM_BOT_TOKEN` and `TELEGRAM_CHAT_ID` from environment variables; don't put a realistic-looking sample token or chat id in the source, don't print a URL containing the token to the log, don't send account data. Add a timeout and handle HTTP errors and answers with `ok=false`; the test message only says "test connection". Before running anything, explain each install and run command for a beginner on [WINDOWS/MAC/LINUX]. Don't connect to a broker and don't send orders.Fill the [brackets] with your own details. Never paste passwords, API keys or tokens into a prompt, and check whatever the AI returns on the demo account before relying on it.
The order to work in:
- Open @BotFather →
/newbot; name the bot, keep the token to yourself, and never give it to Claude or Codex. - Open the new bot’s chat → Start or
/start; run the localgetUpdatesscript to find the rightchat_idfor the test chat. - Call
sendMessagewith the token andchat_idread from environment variables; check it returnsok=true, and try a wrong token and a wrongchat_idto see the error handling. - Reports carry the time zone and the demo state; never send a balance, personal details or a secret.
Key takeaways
- The first report: DEMO,
event_id,rule_version, symbol, timeframe, bar close in UTC, and the state SIGNAL_ONLY (a signal, nothing else). - Demo order states: received, validated, requested, then confirmed, rejected or unknown; say “filled” only when the demo account confirms it.
- Read
ok=trueorok=falsein the answer, not just “no error”; test a wrong token and a wrongchat_id, and never retry in an endless loop.
Comments