caishen

THS - Timeline History Services

RISE Framework Specification

Spec ID: 08
Version: 1.0
Document ID: caishen-rise-ths-v1.0
Last Updated: 2026-01-31

Creative Intent

What THS Enables Users to Create:

Desired Outcomes:

  1. Every strategy captures market context at creation time
  2. Historical snapshots can be queried and replayed
  3. Trading performance can be analyzed with full context
  4. Decision review supports continuous improvement

Core Components

THSSnapshotter

Central service for creating market state snapshots.

Behavior:

Process:

THS_Create_Snapshot:
  1. Receive snapshot request with POV and context
  2. Fetch current ChaosDataBuilder for POV
  3. Extract key chaos indicators (last N bars)
  4. Serialize to compact format (JSON/BSON)
  5. Store with TLID index
  6. Return snapshot ID

THSSnapshot Entity

THSSnapshot:
  # Identification
  - Id: Guid                    # Unique snapshot ID
  - Tlid: string                # Timeline ID (yyMMddHHmm)
  - CreatedAt: DateTime         # Snapshot creation time
  - CorrelationId: Guid         # Link to strategy/order
  
  # Context
  - POV: string                 # Point of View (EUR-USD_H4)
  - SnapshotType: SnapshotType  # STRATEGY_CREATED, ORDER_FILLED, etc.
  - Note: string                # Optional user note
  
  # Market State
  - CurrentBar: BarChaosItem    # Bar at snapshot time
  - RecentBars: BarChaosItem[]  # Last N bars for context
  - FractalLevels: FractalInfo  # Active fractal levels
  - AlligatorState: AlligatorSnapshot
  
  # Strategy Context (if applicable)
  - StrategyId: Guid?
  - BreakoutPrice: decimal?
  - Direction: string?          # "B" or "S"

SnapshotType Enum

SnapshotType:
  - STRATEGY_CREATED = 0        # When BDBO strategy created
  - STRATEGY_FILLED = 1         # When order executed
  - STRATEGY_CLOSED = 2         # When position closed
  - PRICE_BROKE_OUT = 3         # At breakout moment
  - MANUAL_CAPTURE = 4          # User-initiated snapshot
  - PERIODIC_AUTO = 5           # Scheduled snapshots

Snapshot Content

AlligatorSnapshot

AlligatorSnapshot:
  - Lips: decimal               # Current Lips value
  - Teeth: decimal              # Current Teeth value
  - Jaw: decimal                # Current Jaw value
  - MouthOpen: bool             # Are lines diverging?
  - NbBarsOpen: int             # Bars since mouth opened
  - Trend: string               # "UP", "DOWN", "SLEEPING"

FractalInfo

FractalInfo:
  - LastBuyFractal: decimal?    # Most recent buy fractal
  - LastBuyFractalTlid: string
  - LastSellFractal: decimal?   # Most recent sell fractal
  - LastSellFractalTlid: string
  - InitiatingFractal: decimal? # Fractal that triggered signal
  - InitiatingFractalTlid: string

Storage Interface

ITHSStorage

ITHSStorage:
  Create(snapshot: THSSnapshot) → Guid
  GetById(id: Guid) → THSSnapshot?
  GetByTlid(tlid: string) → THSSnapshot[]
  GetByPOV(pov: string, limit: int) → THSSnapshot[]
  GetByStrategy(strategyId: Guid) → THSSnapshot[]
  GetByDateRange(start: DateTime, end: DateTime) → THSSnapshot[]
  Delete(id: Guid) → bool

Storage Implementations


API Endpoints

REST API

POST /ths/snapshot
  Body: { pov: string, type: string, note?: string, strategyId?: string }
  Response: { id: string, tlid: string }

GET /ths/snapshot/:id
  Response: THSSnapshot (full)

GET /ths/snapshots?pov=EUR-USD_H4&limit=10
  Response: THSSnapshot[] (compact)

GET /ths/snapshots/strategy/:strategyId
  Response: THSSnapshot[]

DELETE /ths/snapshot/:id
  Response: { deleted: true }

CLI Tool

# Create snapshot
ths-cli snapshot --pov EUR-USD_H4 --note "Pre-FDB buy setup"

# List recent snapshots
ths-cli list --pov EUR-USD_H4 --limit 10

# View snapshot
ths-cli view --id <snapshot-id>

# Export for review
ths-cli export --id <snapshot-id> --format json

Integration with SDS

When a BDBO strategy is created, THS automatically captures:

BDBO_Created → THS_Create_Snapshot(STRATEGY_CREATED)
  │
  ├── Market state at creation time
  ├── Fractal level that triggered signal
  ├── Alligator state (mouth open/closed)
  ├── AO/AC values and zones
  └── Link to strategy ID

When strategy state changes:

BDBO_StateChange → THS_Create_Snapshot(state-specific)
  │
  ├── PLACED → Capture order submission context
  ├── FILLED → Capture entry execution context
  ├── PRICE_BROKE_OUT → Capture breakout moment
  └── CLOSED → Capture exit context

Python Implementation Example

from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional, List
from uuid import UUID, uuid4
from enum import IntEnum
import json

class SnapshotType(IntEnum):
    STRATEGY_CREATED = 0
    STRATEGY_FILLED = 1
    STRATEGY_CLOSED = 2
    PRICE_BROKE_OUT = 3
    MANUAL_CAPTURE = 4
    PERIODIC_AUTO = 5

@dataclass
class AlligatorSnapshot:
    lips: float
    teeth: float
    jaw: float
    mouth_open: bool
    nb_bars_open: int
    trend: str

@dataclass
class FractalInfo:
    last_buy_fractal: Optional[float] = None
    last_buy_fractal_tlid: Optional[str] = None
    last_sell_fractal: Optional[float] = None
    last_sell_fractal_tlid: Optional[str] = None
    initiating_fractal: Optional[float] = None
    initiating_fractal_tlid: Optional[str] = None

@dataclass
class THSSnapshot:
    id: UUID = field(default_factory=uuid4)
    tlid: str = ""
    created_at: datetime = field(default_factory=datetime.utcnow)
    correlation_id: Optional[UUID] = None
    
    pov: str = ""
    snapshot_type: SnapshotType = SnapshotType.MANUAL_CAPTURE
    note: str = ""
    
    current_bar: dict = field(default_factory=dict)
    recent_bars: List[dict] = field(default_factory=list)
    fractal_levels: FractalInfo = field(default_factory=FractalInfo)
    alligator_state: AlligatorSnapshot = None
    
    strategy_id: Optional[UUID] = None
    breakout_price: Optional[float] = None
    direction: Optional[str] = None

class THSService:
    def __init__(self, storage: 'ITHSStorage'):
        self.storage = storage
    
    def create_snapshot(
        self,
        pov: str,
        cdb: 'ChaosDataBuilder',
        snapshot_type: SnapshotType = SnapshotType.MANUAL_CAPTURE,
        note: str = "",
        strategy_id: Optional[UUID] = None
    ) -> THSSnapshot:
        """Create a market state snapshot."""
        now = datetime.utcnow()
        tlid = now.strftime("%y%m%d%H%M")
        
        snapshot = THSSnapshot(
            tlid=tlid,
            pov=pov,
            snapshot_type=snapshot_type,
            note=note,
            strategy_id=strategy_id,
            current_bar=self._extract_bar(cdb.bars[-1]) if cdb.bars else {},
            recent_bars=[self._extract_bar(b) for b in cdb.bars[-20:]],
            fractal_levels=self._extract_fractals(cdb),
            alligator_state=self._extract_alligator(cdb)
        )
        
        self.storage.create(snapshot)
        return snapshot
    
    def _extract_bar(self, bar) -> dict:
        return {
            'tlid': bar.Tlid,
            'o': bar.Ask.O,
            'h': bar.Ask.H,
            'l': bar.Ask.L,
            'c': bar.Ask.C,
            'ao': bar.AO,
            'ac': bar.AC,
            'zone': bar.Zone
        }
    
    def _extract_fractals(self, cdb) -> FractalInfo:
        # Find most recent fractals from bars
        info = FractalInfo()
        for bar in reversed(cdb.bars):
            if bar.FractalBuy and not info.last_buy_fractal:
                info.last_buy_fractal = bar.FractalBuy
                info.last_buy_fractal_tlid = bar.Tlid
            if bar.FractalSell and not info.last_sell_fractal:
                info.last_sell_fractal = bar.FractalSell
                info.last_sell_fractal_tlid = bar.Tlid
            if info.last_buy_fractal and info.last_sell_fractal:
                break
        return info
    
    def _extract_alligator(self, cdb) -> AlligatorSnapshot:
        if not cdb.bars:
            return None
        bar = cdb.bars[-1]
        return AlligatorSnapshot(
            lips=bar.Lips,
            teeth=bar.Teeth,
            jaw=bar.Jaw,
            mouth_open=bar.Lips > bar.Teeth > bar.Jaw or bar.Lips < bar.Teeth < bar.Jaw,
            nb_bars_open=cdb.NbBarMouthIsOpen,
            trend=cdb.TrendLastWave
        )

TypeScript Implementation Example

interface THSSnapshot {
  id: string;
  tlid: string;
  createdAt: Date;
  correlationId?: string;
  
  pov: string;
  snapshotType: SnapshotType;
  note?: string;
  
  currentBar: BarChaosItem;
  recentBars: BarChaosItem[];
  fractalLevels: FractalInfo;
  alligatorState: AlligatorSnapshot;
  
  strategyId?: string;
  breakoutPrice?: number;
  direction?: 'B' | 'S';
}

enum SnapshotType {
  STRATEGY_CREATED = 0,
  STRATEGY_FILLED = 1,
  STRATEGY_CLOSED = 2,
  PRICE_BROKE_OUT = 3,
  MANUAL_CAPTURE = 4,
  PERIODIC_AUTO = 5
}

class THSService {
  constructor(private storage: ITHSStorage) {}
  
  async createSnapshot(
    pov: string,
    cdb: ChaosDataBuilder,
    options: {
      type?: SnapshotType;
      note?: string;
      strategyId?: string;
    } = {}
  ): Promise<THSSnapshot> {
    const now = new Date();
    const tlid = formatTlid(now);
    
    const snapshot: THSSnapshot = {
      id: uuid(),
      tlid,
      createdAt: now,
      pov,
      snapshotType: options.type ?? SnapshotType.MANUAL_CAPTURE,
      note: options.note,
      strategyId: options.strategyId,
      currentBar: cdb.bars[cdb.bars.length - 1],
      recentBars: cdb.bars.slice(-20),
      fractalLevels: this.extractFractals(cdb),
      alligatorState: this.extractAlligator(cdb)
    };
    
    await this.storage.create(snapshot);
    return snapshot;
  }
}

Creative Advancement Scenarios

Scenario: Strategy Creation Snapshot

Desired Outcome: Complete market context captured when trader creates BDBO strategy

Current Reality: Trader identifies FDB buy on EUR/USD H4

Natural Progression:

  1. User creates BDBO strategy via UI
  2. SDS triggers THS snapshot request
  3. THS fetches current CDB for EUR-USD_H4
  4. Extracts: last 20 bars, fractal levels, Alligator state
  5. Links snapshot to new strategy ID
  6. Stores with TLID index

Resolution: Full market context preserved for future review

Scenario: Historical Trade Review

Desired Outcome: Trader reviews past trade with full context

Current Reality: Trader wants to analyze why trade failed

Natural Progression:

  1. User queries: ths-cli list --strategy <id>
  2. THS returns all snapshots for strategy lifecycle
  3. User views: creation, entry, exit snapshots
  4. Each snapshot shows exact market state
  5. Trader identifies what changed

Resolution: Learning opportunity from concrete historical data


Quality Criteria

Complete Context: Captures all relevant chaos indicators
Linked to Strategy: Correlates with SDS entities
Queryable: Supports multiple query patterns
Compact Storage: Efficient serialization
Reproducible: Enables replay of past scenarios