#!/usr/bin/env python3
"""Offline arithmetic on selected public quote values captured 2026-12-02.

No network, credentials, account access or order functionality. This is an
illustration of USD binary quote handling, not a universal future API schema.
"""
from decimal import Decimal, InvalidOperation

QUOTE = {
    'bestBid': {'value':'0.3390','currency':'USD'},
    'bestAsk': {'value':'0.3400','currency':'USD'},
    'currentPx': {'value':'0.3395','currency':'USD'},
    'longQuote': {'value':'0.3400','currency':'USD'},
    'shortQuote': {'value':'0.661','currency':'USD'},
    'state': 'MARKET_STATE_OPEN',
}

def usd_binary_price(field):
    if not isinstance(field, dict) or field.get('currency') != 'USD':
        raise ValueError('Expected a USD quote object')
    raw = field.get('value')
    if isinstance(raw, bool) or not isinstance(raw, (str, int, float, Decimal)):
        raise ValueError('Expected a decimal value; zero is valid, missing is not')
    try:
        value = Decimal(str(raw))
    except InvalidOperation as exc:
        raise ValueError('Malformed decimal') from exc
    if not value.is_finite() or not Decimal(0) <= value <= Decimal(1):
        raise ValueError('This example expects a finite binary USD price in [0,1]')
    return value

def main():
    bid, ask = usd_binary_price(QUOTE['bestBid']), usd_binary_price(QUOTE['bestAsk'])
    spread = ask - bid
    midpoint = (ask + bid)/2
    quote_sum = usd_binary_price(QUOTE['longQuote']) + usd_binary_price(QUOTE['shortQuote'])
    assert spread == Decimal('0.0010') and midpoint == Decimal('0.3395')
    assert quote_sum == Decimal('1.0010')
    assert midpoint == usd_binary_price(QUOTE['currentPx'])  # This snapshot only.
    assert usd_binary_price({'value':'0','currency':'USD'}) == 0
    for bad in [None,{}, {'value':None,'currency':'USD'}, {'value':True,'currency':'USD'},
                {'value':'NaN','currency':'USD'}, {'value':'Infinity','currency':'USD'},
                {'value':'-0.1','currency':'USD'}, {'value':'1.1','currency':'USD'},
                {'value':'0.5','currency':'EUR'}]:
        try: usd_binary_price(bad)
        except ValueError: pass
        else: raise AssertionError('Malformed or out-of-scope example was accepted')
    print(f'Spread: {spread} USD = {spread*100} cents')
    print(f'Arithmetic midpoint: {midpoint} USD; matched currentPx in this one snapshot')
    print(f'Long/short quote sum: {quote_sum} USD; do not normalize quote fields')
    print('State retained as OPEN; no resolution inferred from a price field.')
    print('Valid zero retained; missing, malformed and out-of-scope quotes rejected.')

if __name__ == '__main__':
    main()
