OPEN-SOURCE SCRIPT

[GYTS-CE] Pattern Texture Codex (PTC)

507
Pattern Texture Codex (Community Edition)
🌸 Part of GoemonYae Trading System (GYTS) 🌸


🌸 --------- INTRODUCTION --------- 🌸

💮 What is the Pattern Texture Codex?

Standard technical analysis focuses on two dimensions: Amplitude (how far price moves) and Momentum (how fast price moves). The Pattern Texture Codex introduces a third: Structure (how price moves).

This indicator implements Permutation Entropy (PE), a complexity measure from dynamical systems theory that captures whether price evolves in structured patterns or chaotic noise. We call this "Market Texture":
  • 🫧 Smooth Texture (Low Entropy): Price evolves in ordered, predictable patterns. Trends are durable and causality is high. Momentum strategies favoured.
  • 🌵 Rough Texture (High Entropy): Price evolves chaotically. The market is noisy, trends are fragile. Mean reversion or defensive sizing recommended.


💮 Why Use This Indicator?

Most "entropy" indicators on TradingView fall into common traps:
  • Shannon entropy of price histograms — measures value distribution but ignores temporal sequence
  • Approximate Entropy (ApEn) — measures amplitude similarity with O(N²) computational cost
  • Volatility metrics labelled "entropy" — captures magnitude, not pattern structure
  • Mathematical errors — normalised values that don't form valid probability distributions
The Pattern Texture Codex provides true ordinal pattern analysis — it examines the sequence of price movements, not just their distribution or magnitude. A smooth uptrend and choppy consolidation may have identical volatility, but their texture is completely different.


สแนปชอต↑ Pattern Texture Codex with dynamic threshold bands. Rough Texture (high entropy) often indicates reversals, while Smooth Texture (low entropy) often precedes trend continuation.


🌸 --------- HOW IT WORKS --------- 🌸

💮 Core Concept: Ordinal Patterns

Instead of analysing raw price values, Permutation Entropy converts price into ordinal patterns — the relative ordering of consecutive data points.

For example, with embedding dimension D=3 (three points per pattern):
  • Pattern "012": first < second < third → ascending
  • Pattern "210": first > second > third → descending
  • Pattern "102": middle value smallest → valley shape
The indicator counts how often each pattern appears over a lookback window, then calculates the Shannon entropy of this distribution.

สแนปชอต↑ With D=3, three consecutive data points determine each pattern. Left: ascending pattern "012" (first point smallest, second middle, third greatest). Right: descending pattern "210" (first point greatest, second middle, third smallest).


💮 Calculation Overview

The normalised Permutation Entropy is computed as:

H = −∑ p(π) · ln(p(π)) / ln(D!)

Where:
• p(π) is the probability of each ordinal pattern π
• D is the embedding dimension (number of points per pattern)
• D! is the total possible patterns (e.g., 4! = 24 for D=4)

The result ranges from 0 to 1:
H → 0: One pattern dominates — highly structured, predictable
H → 1: All patterns equally likely — pure randomness

สแนปชอต↑ Full calculation example at D=3 showing the lowest entropy point (green vertical line). With 3!=6 possible patterns, the monotonic rising pattern "012" dominates while three other patterns occur only once. The frequency column feeds into the entropy contribution formula, yielding H(3)=1.039. Normalising produces 0.4019 — matching the indicator output exactly.


💮 Theoretical Background

Permutation Entropy has deep theoretical foundations. For piecewise monotone maps, it converges to the Kolmogorov-Sinai entropy — the fundamental measure of chaos in dynamical systems.

Key scientific properties:
Scale invariance — analyses rank orderings, invariant to monotonic transformations
Noise robustness — ordinal encoding naturally filters high-frequency noise
Computational efficiency — O(1) amortised per bar with lookup acceleration
Micro-structure sensitivity — captures specific sequence patterns, not just distribution


🌸 --------- KEY FEATURES --------- 🌸

💮 Lookup Table Acceleration

Standard PE requires sorting each embedding vector — O(D log D) operations per bar. This implementation uses precomputed transition tables from Unakafova & Keller (2013), reducing complexity to O(D) per bar.

The key insight: successive ordinal patterns in overlapping windows share (D−1) data points. Rather than recomputing from scratch, the algorithm derives the new pattern from the previous one using a single table lookup.
  • Enabled by default for Delay=1 and Dimension ∈ {3, 4, 5}
  • Falls back to standard calculation for D=2, D=6

💮 Flexible Threshold Modes

The indicator supports four independent threshold modes for both Smooth and Rough detection:
  • Static — Fixed threshold values you define
  • Dynamic — Adaptive bands based on entropy baseline ± standard deviation
  • Percentile — Threshold at Nth percentile of recent entropy history
  • Disabled — No threshold for that direction
You can mix modes: for example, Dynamic for Smooth detection while using Percentile for Rough detection.


🌸 --------- CONFIGURATION --------- 🌸

💮 General Settings

Source — Price series to analyse (default: close)
Smoothing Critical Period — Smoothing via 2-pole Ultimate Smoother (default: 0 = disabled). Reveals underlying texture by filtering entropy noise.


💮 Entropy Calculation
  • Dimension (D) — Points per ordinal pattern:
    • D=3: 6 patterns — fast, stable. Good for limited lookback.
    • D=4: 24 patterns — balanced, captures V-reversals. Recommended.
    • D=5: 120 patterns — sensitive, captures W/M patterns. Noisier.
    • D=6: 720 patterns — maximum sensitivity. No lookup acceleration.
  • Lookback — Estimation window size. Hard minimum: D × 5. Statistical recommendation: 5 × D! (e.g., 120 for D=4). Default: 100.
  • Delay (τ) — Stride between points in each pattern (default: 1). Change only for oversampled data.
  • Lookup Acceleration — Enables transition tables for D ∈ {3, 4, 5} with Delay=1.

💮 Threshold Management
  • Rough/Smooth Mode — Static, Dynamic, Percentile, or Disabled for each threshold
  • Static Values — Fixed threshold when Static mode selected
  • Std Dev Multiplier — Band width for Dynamic mode (default: 2.0σ)
  • Baseline/Deviation Length — Lookback for Dynamic mode calculations
  • Percentile Settings — Lookback and percentile values for Percentile mode

💮 Visualisation & Alerts
  • Palette — Colour scheme (default: GYTS Purple)
  • Colouring Bars — Applies texture colours to chart candles
  • Dark Mode — Optimises colour intensity for dark backgrounds
  • Alerts — Triggers when entropy crosses above/below thresholds


🌸 --------- USAGE GUIDE --------- 🌸

💮 Getting Started

Apply the indicator with default settings:
• Dimension: 4 (balanced complexity, captures V-shaped reversals)
• Lookback: 100 (responsive; statistical ideal: ≥120 for 5× coverage)
• Smooth Threshold: Dynamic mode with 2.0σ multiplier

Observe how entropy rises during choppy consolidation and falls during clean trends.


💮 Interpretation

Entropy Value (0 to 1):
  • Below 0.6: Strong pattern dominance — highly ordered
  • 0.7–0.9: Normal complexity — typical market behaviour
  • Above 0.95: Near-random — patterns uniformly distributed

Transitions:
Watch for regime changes. When entropy rises sharply after a prolonged smooth period, the trend may be losing coherence. When entropy falls from elevated levels, a new trend may be establishing.


สแนปชอต↑ Texture transitions during a trend-to-consolidation regime change. During the uptrend, similar patterns (D=3) recur frequently and entropy decreases. As the market transitions to consolidation, entropy rises — signalling the trend is losing structure.


💮 Trading Applications
  • Trend Filtering — Only take trend-following signals during Smooth texture.
  • Mean Reversion Timing — Elevated entropy often precedes mean reversion.
  • Position Sizing — Reduce exposure during Rough texture.
  • Exit Management — Tighten stops when entropy rises during a position.

💮 Integration with GYTS Suite

The Pattern Texture Codex exports two signals:
  • PE Continuous — Raw entropy value (0 to 1)
  • PE Ternary — State signal (+1 = Rough, 0 = Neutral, −1 = Smooth)
These can be read by Flux Composer or used as filter conditions with Market Regime Detector.


🌸 --------- PARAMETER TUNING --------- 🌸

💮 Lookback Selection

Shorter lookbacks react faster but may produce unstable estimates:
  • 50–100: Responsive. Good for intraday regime detection.
  • 100–200: Balanced. Recommended for swing trading.
  • 200–500: Stable. Better for position trading or noisy instruments.
The indicator enforces a hard minimum of D × 5 to prevent meaningless output.


สแนปชอต↑ Three dimensions (D=3, D=4, D=5) with their academically recommended minimum lookback periods.


💮 Threshold Tuning

For Smooth Detection:
Dynamic mode with 2.0σ works well across most instruments. Lower multipliers (1.5σ) detect structure earlier but may false-trigger.

For Rough Detection:
Percentile mode at 90th percentile identifies only extreme chaos. Static threshold of 0.95+ focuses on near-random conditions.

Consider disabling Rough detection entirely if your strategy only cares about identifying structured trends.


สแนปชอต↑ The three threshold modes on the same PTC calculation. Both upper and lower thresholds are independently configurable.


🌸 --------- LIMITATIONS --------- 🌸
  • Amplitude Blindness — PE treats all patterns equally regardless of magnitude. A 0.1% drift and a 10% crash produce identical entropy if their ordinal patterns match.
  • Equal Values (Ties) — Handled via temporal tie-breaking (recent values rank higher), but heavily discretised data may produce edge-case behaviour.
  • Sample Size Requirements — Very short lookbacks (below D × 5) produce unreliable estimates. Statistical reliability improves with larger samples.
  • Not Predictive Alone — Low entropy indicates structure exists, not that the trend will continue. Combine with directional analysis for trading decisions.
  • Lag During Transitions — The sliding window approach introduces inherent lag when market texture changes.


🌸 --------- CREDITS --------- 🌸

💮 Academic Sources
  • Bandt, C., & Pompe, B. (2002). Permutation entropy: A natural complexity measure for time series. Physical Review Letters, 88(17), 174102. DOI
  • Unakafova, V., & Keller, K. (2013). Efficiently measuring complexity on the basis of real-world data. Entropy, 15(10), 4392-4415. DOI
  • Ehlers, J. F. (2024). The Ultimate Smoother. Technical Analysis of Stocks & Commodities, 2024-04. TASC

💮 Libraries Used

คำจำกัดสิทธิ์ความรับผิดชอบ

ข้อมูลและบทความไม่ได้มีวัตถุประสงค์เพื่อก่อให้เกิดกิจกรรมทางการเงิน, การลงทุน, การซื้อขาย, ข้อเสนอแนะ หรือคำแนะนำประเภทอื่น ๆ ที่ให้หรือรับรองโดย TradingView อ่านเพิ่มเติมใน ข้อกำหนดการใช้งาน