feat: add Prometheus, Grafana, and Tailscale monitoring stack

- Install Prometheus + Grafana via kube-prometheus-stack (ClusterIP only, no public ingress)
- Deploy Tailscale Operator for secure VPN access to internal services
- Add CNPG/PostgreSQL monitoring dashboards
- Add vLLM inference monitoring dashboards (tokens, latency, GPU)
- Add Cilium networking dashboards (policy, traffic, drops)
- Update infra-controllers staging kustomization to include all controllers
- Add monitoring-configs Flux sync for dashboard deployment
- Update README with monitoring architecture and access instructions
- Remove broken stale monitoring files (Azure Key Vault refs, wrong domains)

Access: kubectl port-forward or Tailscale VPN (replace auth key before deploy)
This commit is contained in:
Hermes Agent 2026-04-26 02:31:53 +00:00
commit 6183159974
37 changed files with 4207 additions and 212 deletions

View file

@ -0,0 +1,630 @@
---
apiVersion: v1
kind: ConfigMap
metadata:
name: dashboard-cilium
labels:
grafana_dashboard: "1"
annotations:
grafana_folder: Networking
data:
cilium-networking.json: |-
{
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": {
"type": "grafana",
"uid": "-- Grafana --"
},
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"description": "Cilium networking dashboard for monitoring network flows, policy denials, drops, and connectivity",
"editable": true,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"id": null,
"links": [],
"liveNow": false,
"panels": [
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 },
"id": 100,
"panels": [],
"title": "Network Traffic Overview",
"type": "row"
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "Total bytes received across the cluster",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "line",
"fillOpacity": 20,
"lineWidth": 2,
"showPoints": "never"
},
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] },
"unit": "bytes"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 1 },
"id": 1,
"options": {
"legend": { "calcs": ["mean", "max"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Network Received Bytes Total",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "rate(cilium_network_received_bytes_total[5m])",
"legendFormat": "{{namespace}} - {{pod}}",
"refId": "A"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "Total bytes sent across the cluster",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "line",
"fillOpacity": 20,
"lineWidth": 2,
"showPoints": "never"
},
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] },
"unit": "bytes"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 1 },
"id": 2,
"options": {
"legend": { "calcs": ["mean", "max"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Network Sent Bytes Total",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "rate(cilium_network_sent_bytes_total[5m])",
"legendFormat": "{{namespace}} - {{pod}}",
"refId": "A"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "Bandwidth received per namespace",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "line",
"fillOpacity": 20,
"lineWidth": 2,
"showPoints": "never"
},
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] },
"unit": "Bps"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 9 },
"id": 3,
"options": {
"legend": { "calcs": ["mean", "max"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Bandwidth Received Per Namespace",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "sum by (namespace) (rate(cilium_network_received_bytes_total[5m]))",
"legendFormat": "{{namespace}}",
"refId": "A"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "Bandwidth sent per namespace",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "line",
"fillOpacity": 20,
"lineWidth": 2,
"showPoints": "never"
},
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] },
"unit": "Bps"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 9 },
"id": 4,
"options": {
"legend": { "calcs": ["mean", "max"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Bandwidth Sent Per Namespace",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "sum by (namespace) (rate(cilium_network_sent_bytes_total[5m]))",
"legendFormat": "{{namespace}}",
"refId": "A"
}
]
},
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 17 },
"id": 200,
"panels": [],
"title": "Network Policy Enforcement",
"type": "row"
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "Policy L3/L4 denied connections",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "line",
"fillOpacity": 10,
"lineWidth": 2,
"showPoints": "never"
},
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null },
{ "color": "red", "value": 1 }
]
},
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 18 },
"id": 5,
"options": {
"legend": { "calcs": ["sum", "max"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Policy L3/L4 Denied Total",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "increase(cilium_policy_l3_l4_denied_total[5m])",
"legendFormat": "{{namespace}} - {{pod}}",
"refId": "A"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "Policy L3/L4 allowed connections",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "line",
"fillOpacity": 20,
"lineWidth": 2,
"showPoints": "never"
},
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] },
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 18 },
"id": 6,
"options": {
"legend": { "calcs": ["sum", "max"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Policy L3/L4 Allowed Total",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "increase(cilium_policy_l3_l4_allowed_total[5m])",
"legendFormat": "{{namespace}} - {{pod}}",
"refId": "A"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "Dropped packets by reason",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "bars",
"fillOpacity": 80,
"lineWidth": 1,
"showPoints": "never"
},
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null },
{ "color": "yellow", "value": 10 },
{ "color": "red", "value": 100 }
]
},
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 26 },
"id": 7,
"options": {
"legend": { "calcs": ["sum", "max"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Drop Total By Reason",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "increase(cilium_drop_total{reason!=\"\"}[5m])",
"legendFormat": "{{reason}}",
"refId": "A"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "Total drops across all reasons",
"fieldConfig": {
"defaults": {
"color": { "mode": "thresholds" },
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null },
{ "color": "yellow", "value": 50 },
{ "color": "red", "value": 200 }
]
},
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 26 },
"id": 8,
"options": {
"colorMode": "value",
"graphMode": "area",
"justifyMode": "auto",
"orientation": "auto",
"reduceOptions": { "calcs": ["sum"], "fields": "", "values": false },
"textMode": "auto"
},
"title": "Total Drops",
"type": "stat",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "sum(increase(cilium_drop_total[5m]))",
"legendFormat": "Total",
"refId": "A"
}
]
},
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 34 },
"id": 300,
"panels": [],
"title": "Service Connectivity & TCP",
"type": "row"
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "TCP connection count and duration",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "line",
"fillOpacity": 20,
"lineWidth": 2,
"showPoints": "never"
},
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] },
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 35 },
"id": 9,
"options": {
"legend": { "calcs": ["mean", "max"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "TCP Connection Count",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "rate(cilium_network_tcp_duration_seconds_count[5m])",
"legendFormat": "{{namespace}} - {{pod}}",
"refId": "A"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "TCP connection duration (latency)",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "line",
"fillOpacity": 20,
"lineWidth": 2,
"showPoints": "never"
},
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null },
{ "color": "yellow", "value": 0.1 },
{ "color": "red", "value": 0.5 }
]
},
"unit": "s"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 35 },
"id": 10,
"options": {
"legend": { "calcs": ["mean", "max", "p99"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "TCP Connection Duration (Latency)",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "rate(cilium_network_tcp_duration_seconds_sum[5m]) / rate(cilium_network_tcp_duration_seconds_count[5m])",
"legendFormat": "{{namespace}} - {{pod}}",
"refId": "A"
}
]
},
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 43 },
"id": 400,
"panels": [],
"title": "DNS Query Monitoring",
"type": "row"
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "DNS query rate from Cilium",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "line",
"fillOpacity": 20,
"lineWidth": 2,
"showPoints": "never"
},
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] },
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 44 },
"id": 11,
"options": {
"legend": { "calcs": ["sum", "max"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "DNS Query Rate",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "rate(cilium_dns_queries_total[5m])",
"legendFormat": "{{namespace}} - {{pod}}",
"refId": "A"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "DNS query errors from Cilium",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "bars",
"fillOpacity": 80,
"lineWidth": 1,
"showPoints": "never"
},
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null },
{ "color": "red", "value": 1 }
]
},
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 44 },
"id": 12,
"options": {
"legend": { "calcs": ["sum", "max"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "DNS Query Errors",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "rate(cilium_dns_queries_total{status=\"error\"}[5m])",
"legendFormat": "{{namespace}} - {{pod}}",
"refId": "A"
}
]
},
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 52 },
"id": 500,
"panels": [],
"title": "Load Balancer Metrics",
"type": "row"
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "Load balancer backend selection count",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "line",
"fillOpacity": 20,
"lineWidth": 2,
"showPoints": "never"
},
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] },
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 53 },
"id": 13,
"options": {
"legend": { "calcs": ["sum"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Load Balancer Backend Selections",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "rate(cilium_lb_backends_total[5m])",
"legendFormat": "{{type}} - {{address}}:{{port}}",
"refId": "A"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"description": "Service proxy TCP connections tracked by Cilium load balancer",
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"drawStyle": "line",
"fillOpacity": 20,
"lineWidth": 2,
"showPoints": "never"
},
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] },
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 53 },
"id": 14,
"options": {
"legend": { "calcs": ["sum", "max"], "displayMode": "table", "placement": "bottom" },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Service Proxy TCP Connections",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "prometheus", "uid": "$datasource" },
"expr": "rate(cilium_service_proxy_tcp_connections_total[5m])",
"legendFormat": "{{namespace}} - {{pod}}",
"refId": "A"
}
]
}
],
"refresh": "30s",
"schemaVersion": 39,
"tags": ["cilium", "networking", "kubernetes"],
"templating": {
"list": [
{
"current": {
"selected": false,
"text": "prometheus",
"value": "prometheus"
},
"hide": 2,
"includeAll": false,
"label": "Datasource",
"multi": false,
"name": "datasource",
"options": [],
"query": "prometheus",
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"type": "datasource"
}
]
},
"time": {
"from": "now-3h",
"to": "now"
},
"timepicker": {
"refresh_intervals": [
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
]
},
"timezone": "",
"title": "Cilium Networking Dashboard",
"uid": "cilium-networking-dashboard"
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,11 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- dashboards-cnpg.yaml
- dashboards-cilium.yaml
- dashboards-vllm.yaml
# NOTE: No Kubernetes dashboard ConfigMap is included here.
# kube-prometheus-stack (63.x) ships with built-in K8s cluster/node
# dashboards that are auto-imported. There is no need to duplicate them.

View file

@ -0,0 +1,21 @@
FROM python:3.13-slim
LABEL maintainer="sirius0xdev" \
description="VWAP Wave Breach Scanner — monitors Gold, NASDAQ, S&P, Crude Oil"
WORKDIR /app
COPY app/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app/scanner.py .
# Default scan interval: 120s (2 min), threshold: 2σ
ENV SCAN_INTERVAL_SEC=120 \
BREACH_THRESHOLD=2.0
# Health check: ensure process is alive
HEALTHCHECK --interval=60s --timeout=10s --retries=3 \
CMD ["python3", "-c", "import os; assert os.path.exists('/proc/1/fd/0')"]
CMD ["python3", "scanner.py"]

View file

@ -0,0 +1,3 @@
yfinance>=0.2.54
requests>=2.32
apscheduler>=3.10

View file

@ -0,0 +1,205 @@
#!/usr/bin/env python3
"""
VWAP Wave Breach Scanner
========================
Continuous monitoring daemon. Scans instruments on a schedule,
detects VWAP wave breaches, and pushes alerts via Telegram.
Environment variables:
TELEGRAM_BOT_TOKEN — Telegram Bot API token (required)
TELEGRAM_CHAT_ID — Chat ID to send alerts to (required)
SCAN_INTERVAL_SEC — Seconds between scans (default: 120)
BREACH_THRESHOLD — Sigma threshold for alerts (default: 2.0)
No LLM overhead — pure Python, ~20MB RAM.
"""
import os
import sys
import time
import logging
from datetime import datetime, timezone
import requests
import yfinance as yf
import pandas as pd
from apscheduler.schedulers.background import BlockingScheduler
# ── Config ──────────────────────────────────────────────────────────────────
TELEGRAM_BOT_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
TELEGRAM_CHAT_ID = os.environ["TELEGRAM_CHAT_ID"]
SCAN_INTERVAL_SEC = int(os.environ.get("SCAN_INTERVAL_SEC", "120"))
BREACH_THRESHOLD = float(os.environ.get("BREACH_THRESHOLD", "2.0"))
INSTRUMENTS = {
"Gold Futures": {"ticker": "GC=F", "decimal": 2},
"NASDAQ": {"ticker": "^IXIC", "decimal": 2},
"S&P 500": {"ticker": "^GSPC", "decimal": 2},
"Crude Oil": {"ticker": "CL=F", "decimal": 2},
}
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-5s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger(__name__)
# Track last alert state to prevent spam (no repeat within same threshold direction)
_last_alert = {}
# ── Telegram ────────────────────────────────────────────────────────────────
def send_telegram(message: str) -> bool:
"""Send a message via Telegram Bot API."""
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
payload = {
"chat_id": TELEGRAM_CHAT_ID,
"text": message,
"parse_mode": "Markdown",
"disable_web_page_preview": True,
}
try:
resp = requests.post(url, json=payload, timeout=10)
resp.raise_for_status()
log.info("Telegram alert sent: %s", message[:80])
return True
except Exception as e:
log.error("Telegram send failed: %s", e)
return False
# ── VWAP Calculation ────────────────────────────────────────────────────────
def compute_vwap(data: pd.DataFrame) -> dict | None:
"""Compute cumulative VWAP, σ, and deviation."""
df = data.copy()
df["typical"] = (df["High"] + df["Low"] + df["Close"]) / 3.0
df["tp_vol"] = df["typical"] * df["Volume"]
cum_tp_vol = df["tp_vol"].cumsum()
cum_vol = df["Volume"].cumsum().replace(0, 1)
df["cum_vwap"] = cum_tp_vol / cum_vol
df["deviation"] = df["typical"] - df["cum_vwap"]
df["cum_var"] = (df["deviation"] ** 2).cumsum() / cum_vol
df["sigma"] = df["cum_var"] ** 0.5
last = df.iloc[-1]
if last["sigma"] <= 0:
return None
return {
"price": last["Close"],
"vwap": last["cum_vwap"],
"sigma": last["sigma"],
"dev_sigmas": (last["Close"] - last["cum_vwap"]) / last["sigma"],
}
def fetch_data(ticker: str) -> pd.DataFrame:
"""Fetch recent intraday data via yfinance."""
try:
data = yf.Ticker(ticker).history(period="1d", interval="1m", auto_adjust=True)
except Exception:
data = pd.DataFrame()
if len(data) < 30:
data = yf.Ticker(ticker).history(period="5d", interval="1m", auto_adjust=True)
cutoff = pd.Timestamp.now(tz=data.index.tz) - pd.Timedelta(hours=24)
data = data[data.index >= cutoff]
return data
# ── Scanner ─────────────────────────────────────────────────────────────────
def run_scan() -> None:
"""Execute a full scan cycle and push any breaches."""
ts = datetime.now(timezone.utc).strftime("%H:%M:%S UTC")
log.info("── Scan %s ──", ts)
breaches = []
for name, cfg in INSTRUMENTS.items():
try:
data = fetch_data(cfg["ticker"])
if data.empty or len(data) < 20:
log.warning("SKIP %s — insufficient data (%d bars)", name, len(data))
continue
info = compute_vwap(data)
if info is None:
log.warning("SKIP %s — zero sigma", name)
continue
d = cfg["decimal"]
dev = info["dev_sigmas"]
log.info(" %-14s $%10.2f | VWAP $%10.2f | %+.2fσ", name, info["price"], info["vwap"], dev)
if abs(dev) >= BREACH_THRESHOLD:
# Prevent repeat spam: only alert if state changed
alert_key = f"{name}:{dev > 0}"
if _last_alert.get(alert_key) == "breach":
log.info(" → %s already in breach, skipping repeat", name)
continue
breaches.append((name, cfg["decimal"], dev, info["price"], info["vwap"], info["sigma"]))
_last_alert[alert_key] = "breach"
else:
_last_alert[f"{name}:True"] = "clean"
_last_alert[f"{name}:False"] = "clean"
except Exception as e:
log.error("ERROR %s: %s", name, e)
# Push alerts
for name, d, dev, price, vwap, sigma in breaches:
direction = "⬆️ UP" if dev > 0 else "⬇️ DOWN"
band_label = f"±{int(abs(dev))}σ"
severity = "🚨 **EXTREME**" if abs(dev) >= 3.0 else "⚡ **BREACH**"
msg = (
f"{severity} — VWAP Wave Alert\n\n"
f"**{name}** broke through **{band_label}** band\n"
f"Deviation: **{dev:+.2f}σ**\n"
f"Price: **${price:.{d}f}** | VWAP: **${vwap:.{d}f}**\n"
f"σ: ${sigma:.{d}f} | {direction}\n\n"
f"_at {ts}_"
)
send_telegram(msg)
# ── Main ────────────────────────────────────────────────────────────────────
def main() -> None:
log.info("=" * 60)
log.info(" VWAP Wave Breach Scanner")
log.info(" Interval: %d sec | Threshold: ±%.1fσ", SCAN_INTERVAL_SEC, BREACH_THRESHOLD)
log.info(" Telegram: @chat_id=%s", TELEGRAM_CHAT_ID)
log.info("=" * 60)
# Validate Telegram connectivity
send_telegram(
"🟢 *VWAP Breach Scanner* is online.\n"
f"Scanning every **{SCAN_INTERVAL_SEC}s** — threshold ±**{BREACH_THRESHOLD:.1f}σ**\n"
f"Monitoring: Gold, NASDAQ, S&P 500, Crude Oil"
)
scheduler = BlockingScheduler()
scheduler.add_job(run_scan, "interval", seconds=SCAN_INTERVAL_SEC, id="scan")
# Run immediately on start
run_scan()
log.info("Scanner running. Press Ctrl+C to stop.")
try:
scheduler.start()
except KeyboardInterrupt:
log.info("Shutting down...")
scheduler.shutdown()
if __name__ == "__main__":
main()

View file

@ -0,0 +1,5 @@
# ─── Config ─────────────────────────────────────────────────────────────────
# Edit these values. They will be injected into the deployment automatically.
SCAN_INTERVAL_SEC=120
BREACH_THRESHOLD=2.0

View file

@ -0,0 +1,70 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: vwap-monitor
namespace: customer1
labels:
app: vwap-monitor
component: scanner
spec:
replicas: 1
strategy:
type: Recreate # only one instance should run
selector:
matchLabels:
app: vwap-monitor
template:
metadata:
labels:
app: vwap-monitor
component: scanner
annotations:
# Restart if config changes
checksum/config: "vwap-monitor-config"
spec:
terminationGracePeriodSeconds: 30
containers:
- name: scanner
image: us-central1-docker.pkg.dev/devops-lab-cluster/customer1/vwap-monitor:latest
imagePullPolicy: Always
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
cpu: 250m
memory: 256Mi
envFrom:
- configMapRef:
name: vwap-monitor-config
env:
- name: TELEGRAM_BOT_TOKEN
valueFrom:
secretKeyRef:
name: vwap-monitor-secrets
key: telegram-bot-token
- name: TELEGRAM_CHAT_ID
valueFrom:
secretKeyRef:
name: vwap-monitor-secrets
key: telegram-chat-id
startupProbe:
exec:
command: ["/bin/sh", "-c", "python3 -c 'import scanner'"]
initialDelaySeconds: 10
periodSeconds: 10
failureThreshold: 3
livenessProbe:
exec:
command: ["/bin/sh", "-c", "kill -0 1"]
initialDelaySeconds: 30
periodSeconds: 60
---
apiVersion: v1
kind: ConfigMap
metadata:
name: vwap-monitor-config
namespace: customer1
data:
SCAN_INTERVAL_SEC: "120"
BREACH_THRESHOLD: "2.0"

View file

@ -0,0 +1,41 @@
# ─── Kustomization ──────────────────────────────────────────────────────────
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: customer1
resources:
- secret.yaml
- deployment.yaml
configMapGenerator:
- name: vwap-monitor-config
envs:
- config.env
patches:
- patch: |-
apiVersion: apps/v1
kind: Deployment
metadata:
name: vwap-monitor
spec:
template:
spec:
containers:
- name: scanner
envFrom:
- configMapRef:
name: vwap-monitor-config
env:
- name: TELEGRAM_BOT_TOKEN
valueFrom:
secretKeyRef:
name: vwap-monitor-secrets
key: telegram-bot-token
- name: TELEGRAM_CHAT_ID
valueFrom:
secretKeyRef:
name: vwap-monitor-secrets
key: telegram-chat-id

View file

@ -0,0 +1,15 @@
# ─── Secret Template ────────────────────────────────────────────────────────
# Replace the values below before applying.
# Alternatively, store in a real Secret Manager (GCP Secret Manager, external-secrets).
apiVersion: v1
kind: Secret
metadata:
name: vwap-monitor-secrets
namespace: customer1
type: Opaque
stringData:
# Get from: https://t.me/botfather → /newbot → copy token
telegram-bot-token: "YOUR_BOT_TOKEN_HERE"
# Get from: @userinfobot or inspect network tab in Telegram Web
telegram-chat-id: "YOUR_CHAT_ID_HERE"