import nexustrade as nt


def create_long_strangle():
    asset = nt.stock_asset("SPY")
    return nt.portfolio(
        "Public SEO example - Long strangle",
        [
            nt.strategy(
                "Open Long strangle",
                ((nt.RSI(asset, 14, "Day") > nt.Value(60)) & (nt.OptionPositionCount("SPY", "call", "long", "strangle") == nt.Value(0))),
                nt.open_option(
                    builder=nt.options_builder(
                        legs=[
                            nt.leg(
                                option_type="call",
                                direction="long",
                                min_days_to_expiration=30,
                                max_days_to_expiration=45,
                                preference="nearest",
                                distance=5,
                                ratio=1
                            ),
                            nt.leg(
                                option_type="put",
                                direction="long",
                                min_days_to_expiration=30,
                                max_days_to_expiration=45,
                                preference="nearest",
                                distance=5,
                                ratio=1
                            )
                        ],
                        underlying_symbol="SPY",
                        spread_type="strangle"
                    ),
                    allocation={'type': 'contracts', 'amount': 1}
                )
            ),
            nt.strategy(
                "Close when signal invalidates",
                (nt.RSI(asset, 14, "Day") <= nt.Value(50)),
                nt.close_option(
                    underlyings=['SPY'],
                    spread_type="strangle",
                    close_scope="spread",
                    quantity={'type': 'all'}
                )
            ),
            nt.strategy(
                "Close at 14 DTE",
                (nt.Value(1) > nt.Value(0)),
                nt.close_option(
                    underlyings=['SPY'],
                    spread_type="strangle",
                    close_scope="spread",
                    quantity={'type': 'all'},
                    triggers=[nt.dte_trigger(max_dte=14)]
                )
            ),
        ],
        initial_value=10000,
        supports_fractional_shares=False,
        alerts_enabled=False,
        dividend_policy='cash',
    )


def backtest_long_strangle(client=None):
    client = client or nt.NexusTradeClient.from_environment()
    operation = client.create_backtest(
        nt.backtest(
            create_long_strangle(),
            start_date="2024-01-01", end_date="2024-12-31",
            interval="Day", baseline_symbol="SPY",
            initial_value=10000, generate_events=True,
            dividend_policy="cash",
            fee_config={"Stock": {"type": "percent", "amount": 0.1},
                        "Cryptocurrency": {"type": "percent", "amount": 0.7},
                        "Option": {"type": "dollars", "amount": 0.65}},
        ),
        idempotency_key="explore-long-strangle-2024-spy-v1",
    )
    return client.wait_for_backtest(operation["id"])


# Build locally: book = create_long_strangle()
# Run and inspect: completed = backtest_long_strangle(); print(completed["result"])
