"""趋势回调:补仓触达与有效保证金估算."""
from lib.strategy.strategy_trend_lib import trend_dca_level_reached, trend_effective_margin_capital


def test_trend_dca_short_monotonic_up_fills_missed_legs():
    """做空价升:旧逻辑需 last<level,价越过 0.3437 后 last 已高于该档则永不补仓."""
    direction = "short"
    levels = [0.3413, 0.3437, 0.346, 0.3483, 0.3507]
    pf = 0.353
    filled = [lv for lv in levels if trend_dca_level_reached(direction, pf, lv)]
    assert filled == levels


def test_trend_dca_short_not_before_first_level():
    direction = "short"
    assert not trend_dca_level_reached(direction, 0.336, 0.3413)
    assert trend_dca_level_reached(direction, 0.3413, 0.3413)


def test_trend_dca_long_mark_below_trigger():
    direction = "long"
    assert trend_dca_level_reached(direction, 0.344, 0.3465)
    assert not trend_dca_level_reached(direction, 0.347, 0.3465)


def test_trend_effective_margin_first_leg_only():
    plan = {
        "plan_margin_capital": 12.11,
        "target_order_amount": 359.0,
        "order_amount_open": 179.0,
        "first_order_amount": 179.0,
    }
    m = trend_effective_margin_capital(plan)
    assert abs(m - 12.11 * 179 / 359) < 0.01


def test_trend_effective_margin_full_position():
    plan = {
        "plan_margin_capital": 12.11,
        "target_order_amount": 359.0,
        "order_amount_open": 359.0,
    }
    assert trend_effective_margin_capital(plan) == 12.11
