agentleFS
SKE-LabsSKE-Labs/agent-trading-skills/skills/technical-strategies/market-regime-detection/SKILL.md

market-regime-detection

Skill17 starsChanged 4 months agoApache-2.0View on GitHub

Identify current market regime (trending, ranging, squeeze, or volatile) to select appropriate trading strategies. Uses only no-cost indicators (EMA slope, BB Width, ATR Ratio, Donchian) — avoids API-billed indicators like ADX/DMI/Supertrend.

2 other projects use a version of this, 1 of them edited.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 4 are distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use rolling percentiles or training-set thresholds.

    line 38
  2. Distinctive:

    Treat the setup as a testable hypothesis, not a prediction.

    line 127
  3. Distinctive:

    Use regime detection only when it improves the downstream strategy versus a no-regime baseline.

    line 135
  4. Distinctive:

    Treat transitional/uncertain states according to predeclared policy.

    line 136

≈ “Common” is an estimate: at least 1 in 5 of the 372,429 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Market Regime Detection

Regime labels summarize observable trend and volatility states. They are model outputs with uncertainty, not natural market categories; measure whether they add held-out value to the downstream strategy.

Regime Types

RegimeEMA Slope (50, 5-bar)BB WidthPrice Action
Trending UpPositive normalized slopeExpanding/steadyObjective HH/HL or directional-return state
Trending DownNegative normalized slopeExpanding/steadyObjective LH/LL or directional-return state
RangingNear-zero normalized slopeMiddle distributionOscillation under predeclared rule
SqueezeNear-zero normalized slopeLow percentile, optional BB inside KCRelative compression; direction unknown
Volatile / ChopSlope flipping run-to-runVery wideWhipsaws both directions

Detection Inputs (all in the free indicator whitelist)

EMA slope candidate — compute over a predeclared horizon and normalize by price or ATR:

ema50_slope_pct = (ema50[-1] - ema50[-5]) / ema50[-5] * 100

Derive positive, negative, and near-zero bands from training data or rolling historical percentiles for the instrument/timeframe; freeze them before evaluation.

BB Width = (bb_upper - bb_lower) / bb_middle * 100 — rolling-100-period percentile:

  • > 80th pctl → expansion, supports a trend read
  • < 20th pctl → squeeze candidate; no direction or imminent break is implied
  • mid-band → ranging

ATR Ratio = atr_14 / rolling_median(atr_14, 20): Use rolling percentiles or training-set thresholds; ATR ratio measures volatility, not whether price is trending or choppy.

BB Inside KC — if bb_lower > kc_lower AND bb_upper < kc_upper, the Bollinger band is inside the Keltner channel → compression. Pair with low BB Width to confirm squeeze.

Donchian Position — (close - donchian_lower) / (donchian_upper - donchian_lower):

  • near 0 or 1 with EMA slope agreeing → confirmed trend continuation
  • mid-band (0.4–0.6) with flat slope → ranging

Composite Classification

EMA SlopeBB WidthATR RatioBB-in-KCRegime
Outside trained near-zero bandExpandingElevated percentileNoTrending candidate
Inside trained near-zero bandLow percentileLow percentileYesSqueeze candidate
Inside trained near-zero bandMiddle percentileMiddle percentileNoRange candidate
Unstable signVery high percentileVery high percentileNoVolatile candidate
MixedMixedMixedMixedTransitional/uncertain

The table is a seed specification only. Do not count correlated inputs as independent agreement or map them directly to confidence/size. Calibrate a classifier, report posterior/calibration if available, otherwise report features plus classified, uncertain, or no trade.

Regime Change Signals

SignalMeaning
EMA50 5-bar slope crosses through ±0.15%Range → trend or trend → range pivot
BB Width expansion exceeds trained percentile/rateVolatility expansion; direction unknown
BB Width contracts to <20th pctl + BB inside KCSqueeze forming
ATR Ratio jumps above 1.5x off a low baseVol expansion, expect direction reveal
Price closes outside Donchian-20 boundaryBreakout from prior range

Strategy Selection Matrix

RegimeUse These SkillsAvoid
Trendingmoving-average-crossover, pullback-trading, fibonacci-trading, trailing-stopmean-reversion, range-trading
Rangingmean-reversion, bollinger-bands, supply-demand-zonesmomentum-trading, MA crossover
Squeezebreakout-trading (arm BOTH directions, wait for break)range-trading (about to break)
Volatile / Chopwider stops, smaller size, prefer to sit outall trend-following, all mean-reversion
Transitionaluse only strategies validated in this state or waituntested regime substitution

Workflow

  1. Pull indicators (get_indicators returns one indicator per call — fetch each separately):
    get_indicators(indicator_code="ema_50",      symbol=<symbol>, exchange=<exchange>, interval=<interval>, count=120)
    get_indicators(indicator_code="bbands",      symbol=<symbol>, exchange=<exchange>, interval=<interval>, count=120)
    get_indicators(indicator_code="atr_14",      symbol=<symbol>, exchange=<exchange>, interval=<interval>, count=120)
    get_indicators(indicator_code="keltner_20",  symbol=<symbol>, exchange=<exchange>, interval=<interval>, count=120)
    get_indicators(indicator_code="donchian_20", symbol=<symbol>, exchange=<exchange>, interval=<interval>, count=120)
  2. Compute the four inputs in one execute block:
    execute python3 -c "
    import numpy as np
    ema50 = [<ema50 array>]
    bb_lower, bb_upper, bb_middle = [<...>], [<...>], [<...>]
    kc_lower, kc_upper = [<...>], [<...>]
    atr = [<atr_14 array>]
    don_lo, don_hi = [<...>], [<...>]
    close = [<...>]
    
    slope_pct = (ema50[-1] - ema50[-5]) / ema50[-5] * 100
    bb_width  = [(u - l) / m * 100 for u, l, m in zip(bb_upper, bb_lower, bb_middle)]
    bb_width_pctl = sum(1 for w in bb_width if w <= bb_width[-1]) / len(bb_width) * 100
    atr_ratio = atr[-1] / np.median(atr[-20:])
    bb_in_kc  = bb_lower[-1] > kc_lower[-1] and bb_upper[-1] < kc_upper[-1]
    don_pos   = (close[-1] - don_lo[-1]) / (don_hi[-1] - don_lo[-1])
    
    print(f'slope_pct={slope_pct:.3f} bb_width_pctl={bb_width_pctl:.1f} atr_ratio={atr_ratio:.2f} bb_in_kc={bb_in_kc} don_pos={don_pos:.2f}')
    "
  3. Classify using thresholds frozen from training data. Report label, uncertainty, numeric inputs, data window, and which downstream strategies have validated conditional results.
  4. Visualize (optional, only if user-facing report needs it):
    draw_chart_analysis(action="create", drawing={
        "type": "highlight",
        "points": [
            {"time": <regime_start>, "price": <candle_high>},
            {"time": <current_time>, "price": <candle_low>}
        ],
        "options": {"text": "TRENDING bullish (EMA50 slope +0.84%)"}
    })

Evidence and Validation

  • Treat the setup as a testable hypothesis, not a prediction. Define thresholds, entry, invalidation, and exit before evaluating outcomes.
  • Calibrate on the same instrument, venue, session, and timeframe. Use closed candles and a held-out or walk-forward sample; record every variant tried.
  • Include spread, fees, slippage, borrow or funding, partial fills, and latency. Reject the setup when net expectancy is not positive or depends on one narrow parameter.
  • Return observed inputs, missing data, cost assumptions, entry, invalidation, exit, and a valid, watch, or no-trade status.
  • Research basis: Ang & Bekaert supports regime-dependent volatility and correlation, while backtest-overfitting research cautions against selecting thresholds after repeated trials.

Key Rules

  • Use regime detection only when it improves the downstream strategy versus a no-regime baseline.
  • Treat transitional/uncertain states according to predeclared policy; never map them to arbitrary size.
  • The inputs are correlated; feature count does not prove accuracy or reduce false calls.
  • Model higher/lower-timeframe conflicts explicitly; the higher timeframe does not automatically override.
  • Compute EMA slope via execute; do NOT call ADX / DMI / Supertrend (API-billed, not in the free whitelist)

Related Skills

  • multi-timeframe-analysis — regime on HTF sets context; MTF refines entries within the regime
  • bollinger-bands — BB Width is a key detection input; BB strategies adapt to detected regime
  • trailing-stop — trail method per regime (TRENDING: Donchian/chandelier; RANGING: structural; SQUEEZE: don't enter)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.