OPEN-SOURCE SCRIPT
Updated Canuck Trading KAMA Strategy

Canuck Trading KAMA Strategy
OVERVIEW
Canuck Trading KAMA is a strategy around one core idea: trade the color, manage the exit. Kaufman's Adaptive Moving Average (KAMA) determines trend direction. A dual health system handles all exit decisions.
Two user inputs control the strategy: Trade Direction and Max Entry Distance.
Everything else auto-calibrates from price action.
CORE CONCEPTS
KAMA (Kaufman Adaptive Moving Average)
KAMA adjusts its speed using the Efficiency Ratio (ER). ER measures how
much of the price path is directional versus noise. Trending markets
produce a fast KAMA that tracks price closely. Choppy markets produce a
slow KAMA that barely moves. This is the foundation of all signals.
Fair Value Band (FVB)
The colored line on the chart. Green means KAMA is rising (bullish),
red means KAMA is falling (bearish), gray means choppy (neutral).
Entries follow the color. Exits are managed by the health system.
Deviation Bands
Upper and lower bands are calculated from the standard deviation of
price around KAMA over 20 bars, scaled by 2.0 standard deviations.
Bands tighten in trends and widen in chop. This replaces the old
fixed ATR bands and adapts automatically to any instrument.
ENTRY SIGNALS
Color Trend Entry
When KAMA turns green, a long entry fires if price is within the max
entry distance from KAMA (the proximity gate). When KAMA turns red,
a short entry fires under the same proximity rule. A color settle gate
blocks entries on the first bar of a direct red-to-green or green-to-red
flip. Two consecutive bars of the new color are required to confirm the
trend is real and not a one-bar chop spike.
In squeeze conditions (bands tight relative to their own average),
the proximity gate is bypassed entirely since price is naturally close
to KAMA during squeezes.
Gray Zone Entry
When KAMA is gray (neutral), entries can still fire if structural
confirmation is present. Gray longs require 2 or more gray bars,
a higher low (buyers defending), and price above KAMA. Gray shorts
require 2 or more gray bars, a lower high (sellers capping), and
price below KAMA. No proximity gate is applied to gray entries.
The health system and follow-through exit manage risk.
EXIT CHAIN
Exits are evaluated every bar in priority order. The first matching
condition triggers the exit.
1. Follow-Through
On the bar after entry, if price closes below the entry close (for
longs) or above the entry close (for shorts), the position is closed
immediately. This catches entries that fail to confirm on the next bar.
2. Health Exit
The dual health system scores the position from 0 to 6. If either
sub-score drops to 0, or the combined score falls to 1 or below,
the position is closed. A minimum holding period of 2 bars (3 in
high volatility) prevents premature exits on entry noise.
3. Gray Fade
During gray periods, if 2 or more consecutive bars show structural
deterioration (lower highs while long, higher lows while short),
the position is closed. The pullback is deepening, not stabilizing.
4. Gray Timeout
If a position remains in gray for longer than twice the average
color run length (minimum 6 bars), the position is closed. The
trend that justified the entry is likely over.
5. Direction Exit
A full color reversal closes the position. Green to red exits longs.
Red to green exits shorts. Gray pauses do not trigger this exit.
DUAL HEALTH SYSTEM
Two independent scores evaluate position quality from different angles.
KAMA Health (0-3)
C - Color: bar color supports the position direction
K - Slope: KAMA is still moving in the position's favor
D - Duration: the color run has not exceeded the average run length
Price Health (0-3)
S - Structure: higher lows for longs, lower highs for shorts
M - Momentum: efficiency ratio is rising (directional energy building)
V - Value: price on the favorable side of KAMA
The dashboard shows both scores with their individual factors. For example,
K2 CK. P1 ..V means KAMA health is 2 (Color and Slope passing, Duration
failing) and Price health is 1 (only Value passing).
VOLATILITY ADAPTATION
The strategy adapts to volatility regimes automatically.
Squeeze Detection
When bands are tight relative to their 20-bar average (ratio below 0.7),
the dashboard shows SQUEEZE. The proximity gate is bypassed for color
entries since sigma-normalization inflates distances unreliably in
tight-band conditions.
High Volatility
When bands are wide relative to their average (ratio above 1.3), the
dashboard shows HIGH-VOL. The minimum holding period extends from 2 to
3 bars to give trades more room in volatile conditions.
Chop Detection
When the smoothing constant falls below the geometric mean of its range,
KAMA enters gray (choppy). A rolling chop ratio tracks how many of the
last 10 bars were gray. Above 50 percent triggers the CHOP indicator
on the dashboard.
USER INPUTS
Trade Direction
Long, Short, or Both. Default: Long.
Controls which side of the market the strategy trades.
Max Entry Distance (sigma)
Default: 1.0. Range: 0.1 and up, step 0.1.
Maximum sigma-distance from KAMA for color trend entries. Lower values
require price to be closer to KAMA before entering. Higher values allow
entries further from fair value. Gray entries bypass this setting.
The effective distance is scaled inversely by band width ratio, so it
automatically tightens in volatile conditions and loosens in squeezes.
DASHBOARD
The dashboard displays 10 rows of live information.
Row 0 Canuck Trading KAMA v5.0 header
Row 1 Price - current close
Row 2 KAMA - fair value level, colored by trend
Row 3 Trend - BULLISH, BEARISH, or NEUTRAL
Row 4 Signal - current entry or exit signal with health score
Row 5 Position - LONG, SHORT, or FLAT
Row 6 P&L - open profit/loss with percentage
Row 7 ER - efficiency ratio with trend strength label
Row 8 Band - position within bands and volatility regime
Row 9 Health - dual health scores with factor breakdown
STRATEGY SETTINGS
Initial Capital: 100,000
Position Size: 10 percent of equity
Pyramiding: disabled (one position at a time)
Commission: 0.1 percent per trade
Slippage: 1 tick
Order Execution: process orders on close
Calculation: on bar close only
INTERNAL PARAMETERS
These values are fixed and proven through extensive testing. They are not
exposed as inputs to prevent over-optimization.
ER Length: 10 (Kaufman standard)
Fast Period: 2 (fastest smoothing in strong trends)
Slow Period: 30 (slowest smoothing in pure chop)
Deviation Length: 20 (band width lookback)
Band Multiplier: 2.0 (standard deviations for band width)
CHANGES FROM v3.2
- ATR bands replaced with self-tuning KAMA deviation bands
- Quality scoring system removed entirely
- Candle pattern detection removed entirely
- Gray zone intelligence replaced with structural confirmation entries
- Smart hold/verdict system replaced with dual health scoring
- Band profit-taking removed
- KAMA smoothing option removed (raw Kaufman behavior only)
- Sharp flip protection retained and enhanced with color settle gate
- Follow-through exit added (entry close confirmation)
- Gray fade exit added (structural deterioration detection)
- Gray timeout exit added (adaptive based on average run length)
- Dashboard reduced from 13 rows to 10
- Max Entry Distance added as configurable input
- Codebase reduced from 900+ lines to approximately 540 lines
DISCLAIMER
This strategy is provided for educational and informational purposes only.
It is not financial advice, and it does not constitute a recommendation to
buy, sell, or hold any security or financial instrument.
Past performance in backtesting does not guarantee future results. All
trading involves risk, including the potential loss of principal. You are
solely responsible for your own trading decisions.
The author makes no warranties regarding the accuracy, completeness, or
reliability of this strategy. Use it at your own risk. Always do your own
research and consult a qualified financial advisor before making investment
decisions.
This strategy uses simulated order execution with process_orders_on_close
enabled, which means backtest results assume fills at the closing price of
the signal bar. Live trading conditions including slippage, liquidity, and
execution delays may produce different results.
OVERVIEW
Canuck Trading KAMA is a strategy around one core idea: trade the color, manage the exit. Kaufman's Adaptive Moving Average (KAMA) determines trend direction. A dual health system handles all exit decisions.
Two user inputs control the strategy: Trade Direction and Max Entry Distance.
Everything else auto-calibrates from price action.
CORE CONCEPTS
KAMA (Kaufman Adaptive Moving Average)
KAMA adjusts its speed using the Efficiency Ratio (ER). ER measures how
much of the price path is directional versus noise. Trending markets
produce a fast KAMA that tracks price closely. Choppy markets produce a
slow KAMA that barely moves. This is the foundation of all signals.
Fair Value Band (FVB)
The colored line on the chart. Green means KAMA is rising (bullish),
red means KAMA is falling (bearish), gray means choppy (neutral).
Entries follow the color. Exits are managed by the health system.
Deviation Bands
Upper and lower bands are calculated from the standard deviation of
price around KAMA over 20 bars, scaled by 2.0 standard deviations.
Bands tighten in trends and widen in chop. This replaces the old
fixed ATR bands and adapts automatically to any instrument.
ENTRY SIGNALS
Color Trend Entry
When KAMA turns green, a long entry fires if price is within the max
entry distance from KAMA (the proximity gate). When KAMA turns red,
a short entry fires under the same proximity rule. A color settle gate
blocks entries on the first bar of a direct red-to-green or green-to-red
flip. Two consecutive bars of the new color are required to confirm the
trend is real and not a one-bar chop spike.
In squeeze conditions (bands tight relative to their own average),
the proximity gate is bypassed entirely since price is naturally close
to KAMA during squeezes.
Gray Zone Entry
When KAMA is gray (neutral), entries can still fire if structural
confirmation is present. Gray longs require 2 or more gray bars,
a higher low (buyers defending), and price above KAMA. Gray shorts
require 2 or more gray bars, a lower high (sellers capping), and
price below KAMA. No proximity gate is applied to gray entries.
The health system and follow-through exit manage risk.
EXIT CHAIN
Exits are evaluated every bar in priority order. The first matching
condition triggers the exit.
1. Follow-Through
On the bar after entry, if price closes below the entry close (for
longs) or above the entry close (for shorts), the position is closed
immediately. This catches entries that fail to confirm on the next bar.
2. Health Exit
The dual health system scores the position from 0 to 6. If either
sub-score drops to 0, or the combined score falls to 1 or below,
the position is closed. A minimum holding period of 2 bars (3 in
high volatility) prevents premature exits on entry noise.
3. Gray Fade
During gray periods, if 2 or more consecutive bars show structural
deterioration (lower highs while long, higher lows while short),
the position is closed. The pullback is deepening, not stabilizing.
4. Gray Timeout
If a position remains in gray for longer than twice the average
color run length (minimum 6 bars), the position is closed. The
trend that justified the entry is likely over.
5. Direction Exit
A full color reversal closes the position. Green to red exits longs.
Red to green exits shorts. Gray pauses do not trigger this exit.
DUAL HEALTH SYSTEM
Two independent scores evaluate position quality from different angles.
KAMA Health (0-3)
C - Color: bar color supports the position direction
K - Slope: KAMA is still moving in the position's favor
D - Duration: the color run has not exceeded the average run length
Price Health (0-3)
S - Structure: higher lows for longs, lower highs for shorts
M - Momentum: efficiency ratio is rising (directional energy building)
V - Value: price on the favorable side of KAMA
The dashboard shows both scores with their individual factors. For example,
K2 CK. P1 ..V means KAMA health is 2 (Color and Slope passing, Duration
failing) and Price health is 1 (only Value passing).
VOLATILITY ADAPTATION
The strategy adapts to volatility regimes automatically.
Squeeze Detection
When bands are tight relative to their 20-bar average (ratio below 0.7),
the dashboard shows SQUEEZE. The proximity gate is bypassed for color
entries since sigma-normalization inflates distances unreliably in
tight-band conditions.
High Volatility
When bands are wide relative to their average (ratio above 1.3), the
dashboard shows HIGH-VOL. The minimum holding period extends from 2 to
3 bars to give trades more room in volatile conditions.
Chop Detection
When the smoothing constant falls below the geometric mean of its range,
KAMA enters gray (choppy). A rolling chop ratio tracks how many of the
last 10 bars were gray. Above 50 percent triggers the CHOP indicator
on the dashboard.
USER INPUTS
Trade Direction
Long, Short, or Both. Default: Long.
Controls which side of the market the strategy trades.
Max Entry Distance (sigma)
Default: 1.0. Range: 0.1 and up, step 0.1.
Maximum sigma-distance from KAMA for color trend entries. Lower values
require price to be closer to KAMA before entering. Higher values allow
entries further from fair value. Gray entries bypass this setting.
The effective distance is scaled inversely by band width ratio, so it
automatically tightens in volatile conditions and loosens in squeezes.
DASHBOARD
The dashboard displays 10 rows of live information.
Row 0 Canuck Trading KAMA v5.0 header
Row 1 Price - current close
Row 2 KAMA - fair value level, colored by trend
Row 3 Trend - BULLISH, BEARISH, or NEUTRAL
Row 4 Signal - current entry or exit signal with health score
Row 5 Position - LONG, SHORT, or FLAT
Row 6 P&L - open profit/loss with percentage
Row 7 ER - efficiency ratio with trend strength label
Row 8 Band - position within bands and volatility regime
Row 9 Health - dual health scores with factor breakdown
STRATEGY SETTINGS
Initial Capital: 100,000
Position Size: 10 percent of equity
Pyramiding: disabled (one position at a time)
Commission: 0.1 percent per trade
Slippage: 1 tick
Order Execution: process orders on close
Calculation: on bar close only
INTERNAL PARAMETERS
These values are fixed and proven through extensive testing. They are not
exposed as inputs to prevent over-optimization.
ER Length: 10 (Kaufman standard)
Fast Period: 2 (fastest smoothing in strong trends)
Slow Period: 30 (slowest smoothing in pure chop)
Deviation Length: 20 (band width lookback)
Band Multiplier: 2.0 (standard deviations for band width)
CHANGES FROM v3.2
- ATR bands replaced with self-tuning KAMA deviation bands
- Quality scoring system removed entirely
- Candle pattern detection removed entirely
- Gray zone intelligence replaced with structural confirmation entries
- Smart hold/verdict system replaced with dual health scoring
- Band profit-taking removed
- KAMA smoothing option removed (raw Kaufman behavior only)
- Sharp flip protection retained and enhanced with color settle gate
- Follow-through exit added (entry close confirmation)
- Gray fade exit added (structural deterioration detection)
- Gray timeout exit added (adaptive based on average run length)
- Dashboard reduced from 13 rows to 10
- Max Entry Distance added as configurable input
- Codebase reduced from 900+ lines to approximately 540 lines
DISCLAIMER
This strategy is provided for educational and informational purposes only.
It is not financial advice, and it does not constitute a recommendation to
buy, sell, or hold any security or financial instrument.
Past performance in backtesting does not guarantee future results. All
trading involves risk, including the potential loss of principal. You are
solely responsible for your own trading decisions.
The author makes no warranties regarding the accuracy, completeness, or
reliability of this strategy. Use it at your own risk. Always do your own
research and consult a qualified financial advisor before making investment
decisions.
This strategy uses simulated order execution with process_orders_on_close
enabled, which means backtest results assume fills at the closing price of
the signal bar. Live trading conditions including slippage, liquidity, and
execution delays may produce different results.
Release Notes
OVERVIEWCT KAMA v7.0 focuses on three areas: fixing partial re-entry position sizing,
adding a band deviation gate for entries, and improving dashboard responsiveness
and clarity. No changes to the core KAMA engine or market state logic.
CHANGES
1. Partial Re-Entry Fix
Previous versions calculated the top-up quantity from equity using
math.floor (later math.round), which produced integer share counts.
On higher-priced instruments or fractional-qty markets (crypto, forex),
this consistently underestimated the target and produced a zero or
negative add quantity. The signal triangle appeared on the chart but
no order was placed.
The re-entry now captures the original filled position size on initial
entry and uses exact subtraction to compute the add quantity. No rounding
is involved. TradingView handles any lot-size constraints internally.
Additionally, the partial_long_taken / partial_short_taken flags now
only reset when the top-up order actually fires. Previously the flag
cleared unconditionally, meaning a failed top-up was never retried.
The flag now persists until a successful order, allowing the strategy
to retry on subsequent bars if the first attempt is blocked.
2. Band Deviation Gate
New configurable entry filter that prevents chasing extended moves.
When enabled, entries and partial re-entries are blocked if price is
more than the specified sigma distance from fair value (KAMA).
Two new inputs in the Strategy group:
- Band Deviation Gate (bool, default: on)
- Max Entry Deviation (float, default: 1.5 sigma)
The gate uses the existing dist_from_fv_norm calculation (normalized
distance from KAMA in units of kama_dev). It applies to all four
entry conditions: color_long, color_short, partial_reenter_long,
and partial_reenter_short.
Exits are not affected. Gray behaviour and color-flip exits operate
exactly as before regardless of the deviation gate setting.
3. Dashboard Responsiveness
Changed calc_on_every_tick from false to true. The dashboard now
updates on every tick as the candle forms rather than waiting for
bar close. Order execution is unaffected because process_orders_on_close
remains true.
4. Position Sizing in Dashboard
Row 5 (Position) now shows the full position breakdown when in a trade:
direction, quantity, dollar value, and percentage of equity.
Example: LONG 21 $10,080.00 (10.1%)
All values update live with the forming candle.
5. Dashboard Nomenclature Cleanup
Standardized all text across the dashboard:
- All signal text is now ALL CAPS for consistency
- All flat/no-data states use a single dash character
- Fixed Row 9 label from duplicate "Position" to "Dev"
- Row 9 distance highlight now uses the configured Max Entry Deviation
threshold instead of a hardcoded 1.5
Before: mixed casing (Color Ended, Resume Long, Partial Close, TREND LONG)
After: consistent caps (COLOR ENDED, RESUME LONG, PARTIAL CLOSE, TREND LONG)
Before: flat states varied (FLAT, dash, dash with text)
After: all flat states show a single dash
INPUTS
Strategy group:
Trade Direction Long / Short / Both (default: Long)
Gray Behaviour Hold / Exit / Partial (default: Hold)
Partial Close % on Gray 1-99% (default: 50%)
Band Deviation Gate on / off (default: on)
Max Entry Deviation 0.1-5.0 sigma (default: 1.5)
Style, Display, and Theme groups are unchanged from v6.x.
BEHAVIOUR SUMMARY
Entry: Color signal + deviation gate + direction filter
Re-entry: Partial flag + color return + deviation gate
Exit: Gray behaviour or color flip (deviation gate not involved)
Dashboard: Updates every tick, shows live position sizing
Release Notes
Replaced partial with a more advanced adaptive trading approach. Open-source script
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.
Open-source script
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.