# 0DTE levels: Today's SPY expiration: gamma regime, flip, walls, max pain and the expected range, ready to paste on a chart.
# https://apexvol.com/developers/recipes/zero-dte-levels
import os
import sys

import requests

# One token, any paid or trial plan: Account, then API Access.
TOKEN = os.environ.get("APEXVOL_API_TOKEN") or sys.exit("set APEXVOL_API_TOKEN")
BASE = os.environ.get("APEXVOL_API_URL", "https://apexvol.com") + "/api/mcp/data"
S = requests.Session()
S.headers["Authorization"] = f"Bearer {TOKEN}"


def get(path, **params):
    r = S.get(BASE + path, params=params, timeout=90)
    body = r.json()
    if not body.get("success"):
        sys.exit(f"{path}: HTTP {r.status_code}: {body.get('error')}")
    return body["data"]


d = get("/zero-dte/SPY", strikes_around=5)
lv = d.get("key_levels") or {}
m = d.get("metrics") or {}
reg = d.get("gamma_regime") or {}
fc = d.get("iv_forecast") or {}
hit = d.get("em_hit_rate") or {}

fmt = lambda v: f"{v:,.2f}" if isinstance(v, (int, float)) else "none"
print(f"SPY 0DTE {d.get('expiration')}  status {d.get('data_status')}")
print(f"gamma regime   {reg.get('regime')} (net {fmt(reg.get('total_net_gex'))})")
print(f"flip           {fmt(lv.get('gamma_flip'))}")
print(f"call wall      {fmt(lv.get('call_wall'))}")
print(f"put wall       {fmt(lv.get('put_wall'))}")
print(f"max pain       {fmt(lv.get('max_pain'))}")
print(f"expected range {fmt(lv.get('em_lower'))} to {fmt(lv.get('em_upper'))} ({m.get('expected_move')}% from the ATM straddle)")
print(f"ATM IV         {m.get('atm_iv')}%  put/call OI {m.get('put_call_ratio')}")
print(f"IV forecast    {fc.get('signal')}")
print(f"EM hit rate    {hit.get('hit_rate')}% over {hit.get('total_days')} days ({hit.get('assessment')})")
