import nexustrade as nt


def create_btc_trend_pullback():
    asset = nt.crypto_asset("BTC-USD")
    return nt.portfolio(
        "Public SEO crypto example - BTC trend pullback",
        [
            nt.strategy(
                "Enter BTC trend pullback",
                (((nt.Price(asset) > nt.SMA(asset, 200, "Day")) & (nt.RSI(asset, 14, "Day") < nt.Value(40))) & (nt.PositionValue(asset) == nt.Value(0))),
                nt.buy(asset, 95, "percent of buying power")
            ),
            nt.strategy(
                "Exit BTC trend pullback",
                (((nt.RSI(asset, 14, "Day") >= nt.Value(60)) | (nt.Price(asset) <= nt.SMA(asset, 200, "Day"))) & (nt.PositionValue(asset) > nt.Value(0))),
                nt.sell(asset, 100, "percent of current positions")
            ),
        ],
        initial_value=10000,
        supports_crypto=True,
        supports_fractional_shares=True,
        alerts_enabled=False,
        dividend_policy='cash',
    )


def backtest_btc_trend_pullback(client=None):
    client = client or nt.NexusTradeClient.from_environment()
    operation = client.create_backtest(
        nt.backtest(
            create_btc_trend_pullback(),
            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-btc-trend-pullback-2024-spy-v1",
    )
    return client.wait_for_backtest(operation["id"])


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