import os
import requests
def _creds():
token = os.environ.get("TELEGRAM_BOT_TOKEN", "")
chat = os.environ.get("TELEGRAM_CHAT_ID", "")
return token, chat
def _sym_link(sym):
"""Symbol as a clickable link to its 24h thumbnail chart."""
import urllib.parse as _up
s = str(sym)
return ('' + s + '')
def send_telegram_message(text: str) -> bool:
"""Send an HTML-formatted message to the configured Telegram chat."""
token, chat = _creds()
if not token or not chat:
print("โ ๏ธ Telegram not configured (missing TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID)")
return False
from datetime import datetime, timezone, timedelta
stamp = datetime.now(timezone(timedelta(hours=4))).strftime("%Y-%m-%d %H:%M:%S")
# Primary: Rich Message โ every line (stamp + body) rendered as an H2
# heading (~1.5ร normal text size, per Dean's request 2026-11-05);
# classic messages have no font-size markup.
lines = ["## ๐ข " + stamp]
for ln in text.split("\n"):
lines.append("## " + ln if ln.strip() else "")
try:
r = requests.post(f"https://api.telegram.org/bot{token}/sendRichMessage", json={
"chat_id": chat,
"rich_message": {"markdown": "\n".join(lines)},
}, timeout=15)
if r.status_code == 200:
return True
except Exception:
pass
# Fallback: classic bold stamp (previous behavior)
text = f"๐ข {stamp}\n{text}"
url = f"https://api.telegram.org/bot{token}/sendMessage"
try:
r = requests.post(url, json={
"chat_id": chat,
"text": text,
"parse_mode": "HTML",
"disable_web_page_preview": True,
}, timeout=10)
if r.status_code != 200:
print(f"โ Telegram error {r.status_code}: {r.text}")
return False
return True
except Exception as e:
print(f"โ Telegram send failed: {e}")
return False
def format_buy_signals(scan_data: dict) -> str:
"""Build a rich HTML message for coins that passed buy criteria."""
results = scan_data.get("results", [])
signals = [r for r in results if r.get("buy_signal")]
if not signals:
return ""
lines = [
f"๐ข Scan โ {len(signals)} Buy Signal(s)",
f"Lookback: {scan_data.get('lookback_days', 20)}d ยท "
f"RSI: {scan_data.get('rsi_period', 14)} ยท "
f"Scanned: {scan_data.get('total_scanned', 0)}",
"",
]
for r in signals:
lines.append(
f"โข {_sym_link(r['symbol'])} โ "
f"Z:{r['zscore']} | "
f"RSI:{r['rsi']} | "
f"Mom:{r['momentum']}% | "
f"Vol:{r['volatility']}%"
)
lines.append(f" Score: {r['composite_score']}")
return "\n".join(lines)
_CACHED_AUTO_OPEN = {"value": None, "ts": 0.0}
def format_scan_summary(scan_data: dict) -> str:
"""Build an HTML summary message for ANY scan (buy signals or not)."""
results = scan_data.get("results", [])
signals = [r for r in results if r.get("buy_signal")]
total = scan_data.get("total_scanned", len(results))
mode = scan_data.get("scan_mode", "conservative")
if signals:
header = "๐ข Scan โ " + str(len(signals)) + " Buy Signal(s)"
else:
mode_label = str(mode).capitalize()
top = max(results, key=lambda x: x.get("composite_score", 0)) \
if results else None
header = ("๐ " + mode_label + " Scan Complete: No coin met "
"the buy criteria.")
# The threshold shown is the auto-open value from the futures
# settings (fut_auto_open), fetched from the trader config and
# cached for 15 minutes (the trader scales to zero; its cold
# start can exceed a short timeout).
import time as _time
_now = _time.time()
if _now - _CACHED_AUTO_OPEN["ts"] > 900:
try:
import os as _os
import urllib.request as _ur2
import json as _json2
_turl = _os.environ.get(
"TRADER_URL",
"https://blind-monkeys-trader-353804379600.europe-west1.run.app")
with _ur2.urlopen(_turl.rstrip("/") + "/config", timeout=40) as _r:
_cfg = _json2.loads(_r.read().decode("utf-8"))
_val = _cfg.get("fut_auto_open")
if _val is not None:
_CACHED_AUTO_OPEN["value"] = _val
_CACHED_AUTO_OPEN["ts"] = _now
except Exception:
pass
threshold = _CACHED_AUTO_OPEN["value"]
if threshold is None:
threshold = 1
if threshold is not None:
header += "\nThe current score threshold is " + str(threshold) + ""
if top:
_sc = top.get("composite_score")
try:
_sc = float(_sc)
_sc_txt = ("NEGATIVE " + str(abs(_sc))) if _sc < 0 else str(_sc)
except (TypeError, ValueError):
_sc_txt = str(_sc)
header += ("\nHighest scoring coin was "
+ _sym_link(top.get("symbol", "?"))
+ " with a score of " + _sc_txt + "")
# report the actual blocking criterion for the top coin
_crit = {"conservative": {"zscore": -1.0, "momentum": 5.0,
"volatility": 8.0, "rsi": 70.0},
"risk": {"zscore": -1.5, "momentum": 10.0,
"volatility": 25.0, "rsi": 60.0}}.get(
str(mode).lower(), {})
try:
_fails = []
if float(top.get("zscore") or 0) >= _crit["zscore"]:
_fails.append("Z-score " + str(top.get("zscore")) + " (must be below " + str(_crit["zscore"]) + ")")
if float(top.get("momentum") or 0) <= _crit["momentum"]:
_fails.append("momentum " + str(top.get("momentum")) + " (must be above " + str(_crit["momentum"]) + ")")
if float(top.get("volatility") or 0) >= _crit["volatility"]:
_fails.append("volatility " + str(top.get("volatility")) + " (must be below " + str(_crit["volatility"]) + ")")
if float(top.get("rsi") or 0) >= _crit["rsi"]:
_fails.append("RSI " + str(top.get("rsi")) + " (must be below " + str(_crit["rsi"]) + ")")
if _fails:
# NOTE: Telegram does not support (message
# would fail to send) โ use a red-circle emoji instead.
header += '\nBlocked by:'
for _f in _fails:
header += ('\n โข ๐ด ' + _f)
except Exception:
pass
lines = [
header,
"Mode: " + str(mode) + " ยท Scanned: " + str(total) + " ยท Lookback: "
+ str(scan_data.get("lookback_days", 20)) + "d",
]
geo = scan_data.get("geo")
if geo and (geo.get("city") or geo.get("country")):
parts = [x for x in [geo.get("city"), geo.get("state"), geo.get("country")] if x]
lines.append("๐ " + ", ".join(parts))
lines.append("")
if signals:
for r in signals[:10]:
lines.append(
"โข " + str(r.get("symbol", "?")) + " โ "
+ "Z:" + str(r.get("zscore", "?")) + " | "
+ "RSI:" + str(r.get("rsi", "?")) + " | "
+ "Mom:" + str(r.get("momentum", "?")) + "%"
)
return "\n".join(lines)
def alert_on_buy_signals(scan_data: dict) -> bool:
"""Send a Telegram summary for every scan (buy signals or not)."""
text = format_scan_summary(scan_data)
return send_telegram_message(text)