API Reference

class swingtrend.Swing(symbol: str | None = None, retrace_threshold_pct: float | None = 5.0, sideways_threshold: int = 20, minimum_bar_count: int = 40, on_breakout: OnBreakout | None = None, on_reversal: OnReversal | None = None, debug=False)

Detect trend direction, swing structure, and market state from OHLC data.

The Swing class processes price data sequentially to identify:

  • Trend direction (UP or DOWN)

  • Swing highs (SPH) and swing lows (SPL)

  • Breaks of structure (BOS)

  • Change of Character (CoCh) levels

  • Sideways / range-bound conditions

The class supports optional callbacks for breakout and reversal events and can generate plot-ready line data for visualization.

Parameters:
  • symbol (str or None) – Optional instrument symbol. This value may be overridden when calling Swing.run().

  • retrace_threshold_pct (float or None) – Minimum retracement percentage required to validate a Change of Character (CoCh). If None, all retracements qualify.

  • sideways_threshold (int) – Number of bars after which price action is considered sideways if no new swing forms.

  • minimum_bar_count (int) – Minimum number of bars required before the trend is considered stable.

  • on_breakout (OnBreakout or None) – Optional callback invoked on break of structure.

  • on_reversal (OnReversal or None) – Optional callback invoked on trend reversal.

  • debug (bool) – Enable debug-level logging.

identify(date, high: float, low: float, close: float) None

Process a single OHLC bar and update swing state.

This method must be called sequentially in time order.

Parameters:
  • date (datetime) – Datetime of the price bar.

  • high (float) – High price of the bar.

  • low (float) – Low price of the bar.

  • close (float) – Closing price of the bar.

pack() dict

Serialize the current state of the instance.

Loggers and callbacks are excluded. dataframe references are set to None.

Attributes containing date/time-like objects (e.g. datetime, date, pandas Timestamp) are included as-is and are not converted to strings.

Returns:

Serializable state dictionary.

Return type:

dict

reset() None

Reset all internal state.

Used when switching symbols or restarting analysis.

run(sym: str, df, plot_lines=False, add_series=False)

Process an OHLC DataFrame and evaluate market structure.

Iterates sequentially through the DataFrame and updates internal swing and trend state.

Parameters:
  • sym (str) – Instrument symbol. Overrides the symbol value provided during Swing initialization.

  • df (pandas.DataFrame) – OHLC data indexed by datetime.

  • plot_lines (bool) – If True, record CoCh levels for plotting.

  • add_series (bool) – If True, append TREND and IS_SIDEWAYS columns to the DataFrame.

unpack(data: dict) None

Restore internal state from serialized data.

The input dictionary is expected to be produced by pack().

No type coercion or validation is performed during unpacking.

In particular, date/time-like objects (e.g. datetime, date, pandas Timestamp) are assigned as-is and are not parsed or reconverted from string representations.

Parameters:

data (dict) – Dictionary produced by pack().

property bars_since: int

Number of bars since the last swing high or swing low.

Added in version 2.0.0.

property is_sideways: bool

Added in version 2.0.0.

Is the instrument range bound or in a sideways trend?

The instrument is considered sideways, if the number of bars since the last SPH or SPL was formed exceeds Swing.sideways_threshold

Note swing.trend can be UP or DOWN and still be sideways. The trend changes only on breakout or reversal.

If a breakout or trend reversal occurs, the bar count is reset to 0, until a new SPH or SPL is formed.

Type:

bool

property is_trend_stable: bool

Determine whether the market is range-bound.

A market is considered sideways if the number of bars since the last swing point exceeds sideways_threshold.

Added in version 2.0.0.

property leg_count: int

Number of completed swing legs in the current trend.

  • Reset to zero on trend reversal

  • Incremented on each break of structure

Added in version 2.0.1.

property retrace_threshold_pct: float | None

Retrace threshold percent. Minimum retracement required to qualify a Change of Character (CoCh) level.

Setter:

Sets the retrace threshold percent

Type:

float or None

Swing Class Properties

on_reversal: Callable or None

A optional function or class method that is called when a trend reversal occurs.

Swing.on_reversal has the below signature:

def on_reversal(cls: Swing, date, close: float, reversal_level: float)

Parameters:

cls - The Swing class instance which provides access to all its properties and methods.

date - The bar date on which the reversal occured.

close - The closing price of the reversal bar.

reversal_level - The coc price level that was broken.

on_breakout: Callable or None

A optional function or class method that is called when a Break of Structure (BOS) or breakout/breakdown occurs.

Swing.on_breakout has the below signature.

def on_breakout(cls: Swing, date, close: float, breakout_level: float)

Parameters:

cls - The Swing class instance which provides access to all its properties and methods.

date - The bar date on which the breakout occured.

close - The closing price of the breakout bar.

breakout_level - The breakout price or SPH/SPL level that was broken.

symbol: str or None

The current symbol name if passed during Swing.run.

df: pandas.DataFrame or None

pandas.DataFrame if passed during Swing.run.

trend: str or None

The current trend as UP or DOWN. Set to None, if too few candles were supplied.

sph: float or None

The current swing point high. Set to None, if trend is Down or sph not yet formed.

spl: float or None

The current swing point low. Set to None, if trend is UP or spl not yet formed.

coc: float or None

Change of Character. It represents the trend reversal level. If trend is None, coc is None.

high: float or None

The highest price reached within the current structure. Reset to None, when SPL is formed or a trend reversal has occured.

low: float or None

The lowest price reached within the current structure. Reset to None, when SPH is formed or a trend reversal has occured.

Note regarding dates

Swing class does not perform any datetime operations.

All properties below are based on the input type. If you passed a str or timestamp or datetime, the same type is returned for the properties.

sph_dt: datetime or None

Date of SPH candle formation.

spl_dt: datetime or None

Date of SPL candle formation.

coc_dt: datetime or None

Date of coc candle.

low_dt: datetime or None

Candle date with lowest price in the current structure.

high_dt: datetime or None

Candle date with highest price in the current structure.