File size: 8,142 Bytes
5f20dc6 6a1b2b8 30ed22f 6a1b2b8 5f20dc6 287080e 513dcc9 8e261b5 513dcc9 8e261b5 287080e 5f20dc6 6a1b2b8 5f20dc6 660a7f5 5f20dc6 660a7f5 6a1b2b8 660a7f5 4f1b608 660a7f5 4f1b608 660a7f5 5f20dc6 23fe3b0 5f20dc6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | 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 ('<a href="https://charts.blindmonkeys.org/grid/symbol-chart?symbol='
+ _up.quote(s) + '">' + s + '</a>')
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"π’ <b>{stamp}</b>\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"π’ <b>Scan β {len(signals)} Buy Signal(s)</b>",
f"<i>Lookback: {scan_data.get('lookback_days', 20)}d Β· "
f"RSI: {scan_data.get('rsi_period', 14)} Β· "
f"Scanned: {scan_data.get('total_scanned', 0)}</i>",
"",
]
for r in signals:
lines.append(
f"β’ <b>{_sym_link(r['symbol'])}</b> β "
f"Z:<code>{r['zscore']}</code> | "
f"RSI:<code>{r['rsi']}</code> | "
f"Mom:<code>{r['momentum']}%</code> | "
f"Vol:<code>{r['volatility']}%</code>"
)
lines.append(f" Score: <b>{r['composite_score']}</b>")
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 = "π’ <b>Scan β " + str(len(signals)) + " Buy Signal(s)</b>"
else:
mode_label = str(mode).capitalize()
top = max(results, key=lambda x: x.get("composite_score", 0)) \
if results else None
header = ("π <b>" + mode_label + " Scan Complete: No coin met "
"the buy criteria.</b>")
# 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 <b>" + str(threshold) + "</b>"
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 <b>"
+ _sym_link(top.get("symbol", "?"))
+ "</b> with a score of <b>" + _sc_txt + "</b>")
# 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 <font color> (message
# would fail to send) β use a red-circle emoji instead.
header += '\n<b>Blocked by:</b>'
for _f in _fails:
header += ('\n β’ π΄ ' + _f)
except Exception:
pass
lines = [
header,
"<i>Mode: " + str(mode) + " Β· Scanned: " + str(total) + " Β· Lookback: "
+ str(scan_data.get("lookback_days", 20)) + "d</i>",
]
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(
"β’ <b>" + str(r.get("symbol", "?")) + "</b> β "
+ "Z:<code>" + str(r.get("zscore", "?")) + "</code> | "
+ "RSI:<code>" + str(r.get("rsi", "?")) + "</code> | "
+ "Mom:<code>" + str(r.get("momentum", "?")) + "%</code>"
)
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)
|