# LongPort Python SDK via execute_code — reliable pattern
# Use this instead of terminal + source ~/.bashrc for Python SDK calls.
# The execute_code sandbox inherits LONGPORT_* env vars, so Config.from_env() works.
#
# Pitfalls:
#   - execute_code sandbox does NOT inherit bashrc; LONGPORT_* must already be in
#     the host env (they are, from ~/.bashrc on this system).
#   - If Config.from_env() throws "missing environment variable", the sandbox
#     couldn't find the var. Fall back to reading from bashrc via subprocess.
#   - Decimal fields (market_cap, last_done, etc.) need float() conversion.
#   - candlesticks() returns list sorted oldest-first; [-1] is latest.
#   - adjust_type is required for candlesticks: use openapi.AdjustType.NoAdjust
#     for raw data or openapi.AdjustType.ForwardAdjust for adjusted.

import os

# Safety net: if LONGPORT_* not in sandbox env, load from bashrc
if not os.environ.get("LONGPORT_APP_KEY"):
    import subprocess
    result = subprocess.run(
        ["bash", "-c", "source ~/.bashrc && env"],
        capture_output=True, text=True
    )
    for line in result.stdout.split("\n"):
        if "=" in line and "LONGPORT_" in line:
            key, val = line.split("=", 1)
            os.environ[key] = val

from longport import openapi

config = openapi.Config.from_env()
ctx = openapi.QuoteContext(config=config)

# --- Quote ---
resp = ctx.quote(["AAPL.US"])
q = resp[0]
print(f"Latest: {float(q.last_done)}, Open: {float(q.open)}, High: {float(q.high)}, Low: {float(q.low)}")

# --- Candlesticks (daily, 30 bars) ---
candles = ctx.candlesticks("AAPL.US", openapi.Period.Day, 30, openapi.AdjustType.NoAdjust)
first_close = float(candles[0].close)
last_close = float(candles[-1].close)
change_pct = (last_close - first_close) / first_close * 100
print(f"30d change: {first_close} -> {last_close} ({change_pct:+.2f}%)")
