from modules import api, stream
from datetime import datetime, timedelta
import pprint
import time

def obtener_delta(opcion_chain):
    # Función para obtener el delta de las opciones
    calls_delta = [opcion['delta'] for strikes in opcion_chain['callExpDateMap'].values() for strike in strikes.values() for opcion in strike]
    puts_delta = [opcion['delta'] for strikes in opcion_chain['putExpDateMap'].values() for strike in strikes.values() for opcion in strike]
    return calls_delta, puts_delta

def filtrar_opciones(opciones_chain, delta_limite_call, delta_limite_put):
    calls = opciones_chain['callExpDateMap']
    puts = opciones_chain['putExpDateMap']
    
    call_cercano = None
    put_cercano = None
    
    for exp_date, strikes in calls.items():
        for strike, detalles in strikes.items():
            delta = detalles[0]['delta']
            if abs(delta - delta_limite_call) < 0.05:
                if call_cercano is None or abs(call_cercano[1] - delta_limite_call) > abs(delta - delta_limite_call):
                    call_cercano = (strike, delta)
                
    for exp_date, strikes in puts.items():
        for strike, detalles in strikes.items():
            delta = detalles[0]['delta']
            if abs(delta - delta_limite_put) < 0.05:
                if put_cercano is None or abs(put_cercano[1] - delta_limite_put) > abs(delta - delta_limite_put):
                    put_cercano = (strike, delta)
                
    return call_cercano, put_cercano

def main():
    symbol = "$SPX"
    from_date = "2024-05-31"
    to_date = "2024-05-31"
    totalStrikes = "30"
    options_chain=(api.options.chains(symbol,fromDate=from_date, toDate=to_date, strikeCount=totalStrikes).json()) 

    delta_limite_call = 0.1
    delta_limite_put = -0.1
    
    call_cercano, put_cercano = filtrar_opciones(options_chain, delta_limite_call, delta_limite_put)
    

    if call_cercano:
        print("Calls con delta cercano a {:.3f}:".format(delta_limite_call))
        print("Strike: {}, Delta: {:.3f}".format(call_cercano[0], call_cercano[1]))
    else:
        print("No se encontraron calls con el delta deseado.")
    
    if put_cercano:
        print("\nPuts con delta cercano a {:.3f}:".format(delta_limite_put))
        print("Strike: {}, Delta: {:.3f}".format(put_cercano[0], put_cercano[1]))
    else:
        print("\nNo se encontraron puts con el delta deseado.")

  

if __name__ == '__main__':
    print("Welcome to the unofficial Schwab api interface!\nGithub: https://github.com/tylerebowers/Schwab-API-Python")
    api.initialize()  # checks tokens & loads variables
    api.updateTokensAutomatic()  # starts thread to update tokens automatically
    #stream.startManual()  # start the stream manually
    main()  # call the user code above