caishen

BITT - Timeline Services

RISE Framework Specification

Spec ID: 06
Version: 1.0
Document ID: caishen-rise-bitt-v1.0
Last Updated: 2025-01-31

Creative Intent

What BITT Enables Users to Create:

Desired Outcomes:

  1. Users can navigate to any historical point in time
  2. Chart states are reproducible from timeline data
  3. Strategy events are correlated with market timelines
  4. Historical analysis and backtesting is enabled

Core Concepts

Timeline

A Timeline is a sequence of time-indexed data points for a specific POV (Point of View). Each point contains:

TLID (Timeline ID)

Unique identifier format: yyMMddHHmm

Example: 2501311430 = January 31, 2025, 14:30


Core Components

BITTService

Primary service for timeline operations.

Behavior:

BITTDataModel

Data model for timeline persistence.

Behavior:

StrategyTimelineItem

Timeline entry linked to strategy events.

Behavior:


Service Contracts

IBITTService

Interface IBITTService:

  Method CreateTimelineEntry:
    Input:
      - pov: string
      - cdb: ChaosDataBuilderDTO
      - correlationId: Guid (optional)
    Output: TimelineEntryResponse
    Behavior: Creates new timeline entry with CDB snapshot

  Method GetTimelineRange:
    Input:
      - pov: string
      - startDate: DateTime
      - endDate: DateTime
    Output: List<TimelineEntry>
    Behavior: Returns timeline entries within date range

  Method GetTimelineByTlid:
    Input:
      - pov: string
      - tlid: string
    Output: TimelineEntry
    Behavior: Returns single timeline entry by TLID

  Method GetStrategyTimeline:
    Input:
      - strategyIdug: Guid
    Output: List<StrategyTimelineItem>
    Behavior: Returns timeline entries for strategy

  Method GetLatestTimelineEntry:
    Input:
      - pov: string
    Output: TimelineEntry
    Behavior: Returns most recent timeline entry

Data Entities

TimelineEntry

TimelineEntry:
  - Tlid: string                    # Timeline ID (yyMMddHHmm)
  - Pov: string                     # "EUR-USD_H4"
  - Dt: DateTime                    # Entry timestamp
  - CorrelationId: Guid            # Related data group
  
  # Market State
  - TrendLastWave: string          # "UP" or "DOWN"
  - IsDiverging: bool              # Divergence detected
  - AODirection: int               # AO trend direction
  - ACDirection: int               # AC trend direction
  
  # Reference
  - CdbSnapshotPath: string        # Path to CDB JSON file
  - StrategyCount: int             # Active strategies for POV

StrategyTimelineItem

StrategyTimelineItem:
  - Idug: Guid                     # Item ID
  - StrategyIdug: Guid             # Parent strategy
  - Tlid: string                   # Timeline reference
  - Dt: DateTime                   # Event timestamp
  
  # Event Data
  - EventType: string              # "Created", "Updated", "StateChanged"
  - PreviousState: string
  - NewState: string
  - BreakoutPrice: double
  - CurrentPrice: double
  
  # Market Context
  - AO: double
  - AC: double
  - Zone: int
  
  # Snapshot
  - CdbSnapshotPath: string

TimelineItem

TimelineItem:
  - Id: Guid
  - Pov: string
  - Tlid: string
  - Dt: DateTime
  - CdbCorrelationId: Guid
  - Note: string
  - Tags: List<string>

Creative Advancement Scenarios

Scenario 1: Create Timeline Snapshot

Creative Advancement Scenario: Snapshot Current Market State

Desired Outcome: Timeline entry preserving current CDB

Current Reality: New CDB generated for POV

Natural Progression Steps:
  1. CDB generation completes for EUR/USD H4
  2. BITT creates TimelineEntry with TLID
  3. CDB saved as JSON to snapshot directory
  4. Entry metadata stored in database
  5. Entry correlationId linked to any active strategies

Achieved Outcome: Market state preserved for future reference

Supporting Features: BITTService.CreateTimelineEntry

Scenario 2: Navigate Historical Timeline

Creative Advancement Scenario: Review Past Market State

Desired Outcome: View chart as it appeared on specific date

Current Reality: User wants to analyze past decision

Natural Progression Steps:
  1. User selects date/time in timeline navigator
  2. GetTimelineByTlid retrieves entry for closest TLID
  3. CDB snapshot loaded from JSON file
  4. Chart rendered with historical data
  5. User analyzes market state at that time

Achieved Outcome: User sees historical chart state

Supporting Features: Timeline UI, CDB playback

Scenario 3: Strategy Event Timeline

Creative Advancement Scenario: Review Strategy History

Desired Outcome: Complete timeline of strategy lifecycle

Current Reality: Completed strategy needs review

Natural Progression Steps:
  1. User selects strategy by IDUG
  2. GetStrategyTimeline retrieves all events
  3. Timeline displays state changes with timestamps
  4. Each event links to CDB snapshot
  5. User can click to view market state at each event

Achieved Outcome: Full strategy audit trail

Supporting Features: StrategyTimelineItem linkage

Data Flow

┌─────────────────┐
│   ADSService    │
│   (CDB Gen)     │
└────────┬────────┘
         │ OnCDBCreated
         ▼
┌─────────────────┐
│   BITTService   │
│                 │
│ CreateTimeline  │
│     Entry       │
└────────┬────────┘
         │
    ┌────┴────┐
    │         │
    ▼         ▼
┌───────┐ ┌───────┐
│  SQL  │ │ JSON  │
│ Meta- │ │  CDB  │
│ data  │ │Snapshots│
└───────┘ └───────┘

TLID Generation

Algorithm GenerateTlid(datetime):
  Return datetime.ToString("yyMMddHHmm")
  
Example:
  DateTime: 2025-01-31 14:30:00
  TLID: "2501311430"

TLID Parsing

Algorithm ParseTlid(tlid):
  year = 2000 + int(tlid[0:2])
  month = int(tlid[2:4])
  day = int(tlid[4:6])
  hour = int(tlid[6:8])
  minute = int(tlid[8:10])
  Return DateTime(year, month, day, hour, minute)

MCD (Market Charting Data) Form

The BITT module includes a WinForms application for timeline visualization:

Form220221

Behavior:

KomodiaForm

Behavior:


Implementation Notes for Python/TypeScript

Python Implementation

from dataclasses import dataclass
from datetime import datetime
from uuid import UUID, uuid4
from typing import List, Optional
import json
from pathlib import Path

def generate_tlid(dt: datetime) -> str:
    """Generate timeline ID from datetime"""
    return dt.strftime("%y%m%d%H%M")

def parse_tlid(tlid: str) -> datetime:
    """Parse timeline ID to datetime"""
    return datetime.strptime(tlid, "%y%m%d%H%M")

@dataclass
class TimelineEntry:
    tlid: str
    pov: str
    dt: datetime
    correlation_id: Optional[UUID] = None
    trend_last_wave: str = ""
    is_diverging: bool = False
    cdb_snapshot_path: str = ""

@dataclass
class StrategyTimelineItem:
    idug: UUID
    strategy_idug: UUID
    tlid: str
    dt: datetime
    event_type: str
    previous_state: str = ""
    new_state: str = ""
    breakout_price: float = 0.0
    current_price: float = 0.0

class BITTService:
    def __init__(self, snapshot_dir: str = "./snapshots"):
        self.snapshot_dir = Path(snapshot_dir)
        self.snapshot_dir.mkdir(exist_ok=True)
    
    async def create_timeline_entry(
        self,
        pov: str,
        cdb: dict,
        correlation_id: Optional[UUID] = None
    ) -> TimelineEntry:
        """Create new timeline entry with CDB snapshot"""
        dt = datetime.now()
        tlid = generate_tlid(dt)
        
        # Save CDB snapshot
        snapshot_path = self.snapshot_dir / f"{pov}_{tlid}.json"
        with open(snapshot_path, 'w') as f:
            json.dump(cdb, f)
        
        entry = TimelineEntry(
            tlid=tlid,
            pov=pov,
            dt=dt,
            correlation_id=correlation_id,
            cdb_snapshot_path=str(snapshot_path)
        )
        
        return entry
    
    async def get_timeline_range(
        self,
        pov: str,
        start_date: datetime,
        end_date: datetime
    ) -> List[TimelineEntry]:
        """Get timeline entries within date range"""
        pass
    
    async def get_strategy_timeline(
        self,
        strategy_idug: UUID
    ) -> List[StrategyTimelineItem]:
        """Get timeline entries for strategy"""
        pass

TypeScript Implementation

interface TimelineEntry {
  tlid: string;
  pov: string;
  dt: Date;
  correlationId?: string;
  trendLastWave: string;
  isDiverging: boolean;
  cdbSnapshotPath: string;
}

interface StrategyTimelineItem {
  idug: string;
  strategyIdug: string;
  tlid: string;
  dt: Date;
  eventType: string;
  previousState: string;
  newState: string;
  breakoutPrice: number;
  currentPrice: number;
}

function generateTlid(date: Date): string {
  const y = date.getFullYear().toString().slice(2);
  const m = (date.getMonth() + 1).toString().padStart(2, '0');
  const d = date.getDate().toString().padStart(2, '0');
  const h = date.getHours().toString().padStart(2, '0');
  const min = date.getMinutes().toString().padStart(2, '0');
  return `${y}${m}${d}${h}${min}`;
}

function parseTlid(tlid: string): Date {
  const year = 2000 + parseInt(tlid.slice(0, 2));
  const month = parseInt(tlid.slice(2, 4)) - 1;
  const day = parseInt(tlid.slice(4, 6));
  const hour = parseInt(tlid.slice(6, 8));
  const minute = parseInt(tlid.slice(8, 10));
  return new Date(year, month, day, hour, minute);
}

class BITTService {
  private snapshotDir: string;
  
  constructor(snapshotDir = './snapshots') {
    this.snapshotDir = snapshotDir;
  }
  
  async createTimelineEntry(
    pov: string,
    cdb: ChaosDataBuilder,
    correlationId?: string
  ): Promise<TimelineEntry> {
    const dt = new Date();
    const tlid = generateTlid(dt);
    
    // Save CDB snapshot
    const snapshotPath = `${this.snapshotDir}/${pov}_${tlid}.json`;
    // fs.writeFileSync(snapshotPath, JSON.stringify(cdb));
    
    return {
      tlid,
      pov,
      dt,
      correlationId,
      trendLastWave: cdb.trendLastWave,
      isDiverging: false,
      cdbSnapshotPath: snapshotPath
    };
  }
  
  async getTimelineRange(
    pov: string,
    startDate: Date,
    endDate: Date
  ): Promise<TimelineEntry[]> {
    // Implementation
    return [];
  }
}