Function trailingStop

  • Adjusts the trailing stop-loss distance for an active pending signal.

    CRITICAL: Always calculates from ORIGINAL SL, not from current trailing SL. This prevents error accumulation on repeated calls. Larger percentShift ABSORBS smaller one (updates only towards better protection).

    Updates the stop-loss distance by a percentage adjustment relative to the ORIGINAL SL distance. Negative percentShift tightens the SL (reduces distance, moves closer to entry). Positive percentShift loosens the SL (increases distance, moves away from entry).

    Absorption behavior:

    • First call: sets trailing SL unconditionally
    • Subsequent calls: updates only if new SL is BETTER (protects more profit)
    • For LONG: only accepts HIGHER SL (never moves down, closer to entry wins)
    • For SHORT: only accepts LOWER SL (never moves up, closer to entry wins)

    Automatically detects backtest/live mode from execution context.

    Parameters

    • symbol: string

      Trading pair symbol

    • percentShift: number

      Percentage adjustment to ORIGINAL SL distance (-100 to 100)

    • currentPrice: number

      Current market price to check for intrusion

    Returns Promise<boolean>

    Promise - true if trailing SL was set/updated, false if rejected (absorption/intrusion/conflict)

    import { trailingStop } from "backtest-kit";

    // LONG: entry=100, originalSL=90, distance=10%, currentPrice=102

    // First call: tighten by 5%
    const success1 = await trailingStop("BTCUSDT", -5, 102);
    // success1 = true, newDistance = 10% - 5% = 5%, newSL = 95

    // Second call: try weaker protection (smaller percentShift)
    const success2 = await trailingStop("BTCUSDT", -3, 102);
    // success2 = false (SKIPPED: newSL=97 < 95, worse protection, larger % absorbs smaller)

    // Third call: stronger protection (larger percentShift)
    const success3 = await trailingStop("BTCUSDT", -7, 102);
    // success3 = true (ACCEPTED: newDistance = 10% - 7% = 3%, newSL = 97 > 95, better protection)