"""Monitor SHFE.au9999 5-minute moving averages and print alerts on completed bars.

Usage:
    export EXSDK_TOKEN="YOUR_TOKEN"
    python ma_alert.py
"""

import math
import os
import time
from exsdk import ExApi

TOKEN = os.environ.get("EXSDK_TOKEN", "YOUR_TOKEN")
SYMBOL = os.environ.get("EXSDK_SYMBOL", "SHFE.au9999")
PERIOD = "5m"
FAST_WINDOW = 5
SLOW_WINDOW = 20


def main() -> None:
    with ExApi(token=TOKEN) as api:
        quote = api.watch_quote(SYMBOL)
        bars = api.watch_kline(SYMBOL, PERIOD, data_length=200)

        initial = bars.data()
        initial_valid = initial.loc[initial["timestamp"] > 0]
        last_processed = (
            int(initial_valid.iloc[-2]["timestamp"]) if len(initial_valid) >= 2 else 0
        )
        print(f"正在监控 {SYMBOL} ({PERIOD}) 均线信号，按 Ctrl+C 停止...")

        while True:
            if not api.wait_update(deadline=time.time() + 10):
                continue

            if quote.is_changing("last_price"):
                q = quote.data()
                if q.timestamp > 0 and math.isfinite(q.last_price):
                    target = f" (当前标的 {q.underlying_symbol})" if q.underlying_symbol else ""
                    print(f"[行情] {q.symbol}{target} 最新价: {q.last_price}")

            if not bars.is_changing(["timestamp", "close"]):
                continue

            frame = bars.data()
            valid = frame.loc[frame["timestamp"] > 0]
            completed = valid.iloc[:-1]
            if len(completed) < SLOW_WINDOW + 1:
                continue

            latest_ts = int(completed.iloc[-1]["timestamp"])
            if latest_ts <= last_processed:
                continue

            closes = completed["close"]
            fast_ma = closes.rolling(FAST_WINDOW).mean()
            slow_ma = closes.rolling(SLOW_WINDOW).mean()

            prev_fast, curr_fast = fast_ma.iloc[-2], fast_ma.iloc[-1]
            prev_slow, curr_slow = slow_ma.iloc[-2], slow_ma.iloc[-1]
            close_price = closes.iloc[-1]

            if all(math.isfinite(v) for v in (prev_fast, curr_fast, prev_slow, curr_slow, close_price)):
                if prev_fast <= prev_slow and curr_fast > curr_slow:
                    print(
                        f"[信号] {SYMBOL} {PERIOD} MA{FAST_WINDOW} 上穿 MA{SLOW_WINDOW} | "
                        f"收盘价 {close_price:.2f} | MA{FAST_WINDOW}={curr_fast:.2f} MA{SLOW_WINDOW}={curr_slow:.2f}"
                    )
                elif prev_fast >= prev_slow and curr_fast < curr_slow:
                    print(
                        f"[信号] {SYMBOL} {PERIOD} MA{FAST_WINDOW} 下穿 MA{SLOW_WINDOW} | "
                        f"收盘价 {close_price:.2f} | MA{FAST_WINDOW}={curr_fast:.2f} MA{SLOW_WINDOW}={curr_slow:.2f}"
                    )

            last_processed = latest_ts


if __name__ == "__main__":
    main()
