caishen

SDS - Strategic Data Services

RISE Framework Specification

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

Creative Intent

What SDS Enables Users to Create:

Desired Outcomes:

  1. Users can create fractal breakout strategies with defined entry levels
  2. Strategies automatically advance through states based on price action
  3. Complete order history is maintained for review
  4. Active strategies are monitored and managed across all POVs

Core Concepts

BDBO Strategy

A BDBO Strategy represents a fractal breakout trading opportunity:

Strategy States (Simplified View)

Created → Placed → (EntryOrderCanceled) → Filled → Closed
                 → (PriceBrokeOut)
                 → (Deactivated)

Strategy States (Full FSM — extracted from BOBDBOStrategiesFsm.cs)

The actual state machine has 14 states organized hierarchically:

BOBDBOStrategiesStateEnum:
  - Instanciated = 0          # Initial construction
  - Idle = 1                  # Awaiting activation
  - Active = 2                # Parent state (composite)
    ├─ Active_Created = 3           # Strategy defined, not yet monitoring
    ├─ Active_WaitingBreakout = 4   # Monitoring price for breakout level
    ├─ Active_WaitingSignal = 5     # Price broke out, awaiting valid FDB signal
    └─ Active_WaitingEntering = 6   # Valid signal found, awaiting order fill
  - Innactive = 7             # Parent state (composite)
    ├─ Innactive_Completed = 8              # Strategy lifecycle complete (success)
    ├─ Innactive_MaxTradeCreatedReached = 9  # MaxTC exceeded
    ├─ Innactive_MaxEntryCreatedReached = 10 # MaxEOC exceeded
    ├─ Innactive_MaxPeriodUntilInvalidReached = 11  # MaxPUI exceeded
    └─ Innactive_StrategyFaulted = 12       # Error state
  - End = 13                  # Terminal state

Full FSM Events

Events (BOBDBOStrategiesEventEnum):
  - StrategyUpdateStarting          # Pre-update hook
  - StrategyUpdateCompleted         # Post-update hook
  - StrategyStatusChanged           # Generic status change
  - StrategyCreationInitialized     # Strategy first created
  - StrategyBrokeOutPriceReached    # Price crossed breakout level
  - StrategyValidSignalFound        # Valid FDB signal detected
  - StrategyEntryOrderInvalidated   # Entry order was invalidated
  - StrategyCompleted               # Successful completion
  - StrategyPUIReached              # Max periods exceeded
  - StrategyFailed                  # Error/fault occurred

Full FSM Transitions

Instanciated ──[init]──→ Idle
Idle ──[StrategyCreationInitialized]──→ Active_Created
Active_Created ──[activate]──→ Active_WaitingBreakout
Active_WaitingBreakout ──[StrategyBrokeOutPriceReached]──→ Active_WaitingSignal
Active_WaitingSignal ──[StrategyValidSignalFound]──→ Active_WaitingEntering
Active_WaitingEntering ──[StrategyCompleted]──→ Innactive_Completed
Active_WaitingEntering ──[StrategyEntryOrderInvalidated]──→ Active_WaitingSignal
Active_* ──[StrategyPUIReached]──→ Innactive_MaxPeriodUntilInvalidReached
Active_* ──[StrategyFailed]──→ Innactive_StrategyFaulted
Active_* ──[MaxTradesReached]──→ Innactive_MaxTradeCreatedReached
Active_* ──[MaxEntriesReached]──→ Innactive_MaxEntryCreatedReached
Innactive_* ──[cleanup]──→ End

WaitingEntry Sub-FSM (BOBDBO__SS_WaitingEntryFsm.cs)

When in Active_WaitingEntering, a nested state machine manages entry lifecycle:

BOBDBO__SS_WaitingEntryStateEnum:
  - Instanciated = 0
  - Idle = 1
  - Running = 2 (composite)
    ├─ Running_Initializing = 3     # Preparing entry order
    ├─ Running_Active = 4           # Order placed, awaiting fill
    ├─ Running_Invalid = 5          # Order invalidated
    ├─ Running_Trading = 6          # Order filled, trade active
    └─ Running_FailedTrade = 7      # Trade failed
  - End = 8

Events:
  - BOBDBO__SS_WaitingEntryInitialized
  - EntrySignalActive(OrderID, Msg)     # Order placed at broker
  - EntrySignalInvalid(OrderID, Msg)    # Order rejected/invalid
  - TradingNow(OrderID, TradeID, PnlPips)  # Order filled
  - TradingFailed                        # Trade execution failed

Event Args Pattern (C# Heritage)

Each event carries typed args with a unique eventIdug for tracking:

EntrySignalActiveEventArgs:
  - OrderID: string
  - Msg: string
  - eventIdug: "23b09cca-2db9-4cba-8e3c-1bf9b1266749"

Core Components

SDSService

The primary service interface for strategy operations.

Behavior:

Layout: Contains BDBOStrategyService, THSComponent

BDBOStrategyService

Internal business logic for BDBO strategy management.

Behavior:

BDBOStrategy Entity

Core entity representing a breakout strategy.

Behavior:


Service Contracts

ISDSService

Interface ISDSService:

  Method CreateBdboStrategy:
    Input: CreateBDBOStrategyRequest
      - BdboStrategyDto: BDBOStrategyDto
    Output: CreateBDBOStrategyResponse
      - BdboStrategyDto: BDBOStrategyDto
      - Success: bool
    Behavior: Creates new strategy, saves THS snapshot

  Method GetBdboStrategy:
    Input: GetBDBOStrategyRequest
      - Idug: string (GUID)
    Output: GetBDBOStrategyResponse
      - BdboStrategyDto: BDBOStrategyDto
    Behavior: Retrieves single strategy by ID

  Method GetBdboStrategyList:
    Input: GetBDBOStrategyListRequest
      - InstrumentFilter: string
      - TimeframeFilter: string
      - OnlyActive: bool
    Output: GetBDBOStrategyListResponse
      - BdboStrategies: Dictionary<string, BDBOStrategyDto>
    Behavior: Returns filtered list of strategies

  Method GetBdboStrategySummaryList:
    Input: GetBDBOStrategyListRequest
    Output: GetBDBOStrategySummaryListResponse
      - BdboStrategiesSummary: Dictionary<string, BDBOStrategySummaryDto>
    Behavior: Returns lightweight summary list

  Method UpdateBdboStrategy:
    Input: UpdateBDBOStrategyRequest
      - BdboStrategyDto: BDBOStrategyDto
    Output: UpdateBDBOStrategyResponse
    Behavior: Updates strategy, saves THS snapshot

  Method DeleteStrategy:
    Input: GenericRequest
      - Idug: Guid
    Output: GenericResponse
    Behavior: Removes strategy from database

  Method ChangeStrategyActiveState:
    Input: GenericActiveRequest
      - Idug: Guid
      - Active: bool
    Output: GenericResponse
    Behavior: Toggles strategy active/inactive

  Method GetBdboStrategyOrderHistory:
    Input: GetBDBOStrategyOrderHistoryRequest
      - Idug: string
    Output: GetBDBOStrategyOrderHistoryResponse
      - Histories: Dictionary<string, vBDBOStrategyOrderingHistory>
    Behavior: Returns order history for strategy

  Method GetPovPriorityList:
    Input: GenericRequest
    Output: PovListResponse
      - Povs: List<string>
    Behavior: Returns list of POVs with active strategies

  Method HasStrategy:
    Input: PovRequest
      - Instrument: string
      - Timeframe: string
    Output: GenericBooleanResponse
    Behavior: Checks if POV has active strategies

  Method AddCancelOrderRequest:
    Input: BDBOCancelOrderRequestDto
    Output: GenericBooleanResponse
    Behavior: Records order cancellation request

  Method AddCancelOrderResponse:
    Input: BDBOCancelOrderResponseDto
    Output: GenericBooleanResponse
    Behavior: Records order cancellation response

Data Entities

BDBOStrategy

BDBOStrategy:
  # Identification
  - Idug: Guid                    # Unique identifier
  - CorrelationId: Guid           # Related strategy group
  
  # Core Properties
  - Instrument: string            # "EUR/USD"
  - Timeframe: string             # "H4"
  - BreakoutPrice: double         # Entry trigger price
  - BuySell: string               # "B" or "S"
  - Active: bool                  # Is monitoring enabled
  
  # State Management
  - StateName: string             # Current state name
  - StateId: int                  # State enum value
  - Status: int                   # Numeric status code
  
  # Timestamps
  - Dt: DateTime                  # Creation timestamp
  - DtModified: DateTime          # Last modification
  - DtFirstAction: DateTime       # First state change
  
  # Risk Management
  - MPR: int                      # Max pip risk (default: 120)
  - MaxPUI: int                   # Max periods until invalid (default: 1000)
  - DP: double                    # Deactivation price
  
  # Order Tracking
  - CEOC: int                     # Count entry orders canceled
  - MaxEOC: int                   # Max entry order cancellations (default: 5)
  - CTC: int                      # Count trades created
  - MaxTC: int                    # Max trade count (default: 3)
  - CFT: int                      # Count failed trades
  
  # Validation
  - DiValid: int                  # Divergence validation (-1, 0, 1)
  - VCP: int                      # Validation control pattern
  
  # Twin Trade
  - TT: bool                      # Twin trade enabled
  - TTO: int                      # Twin trade option
  - K: int                        # Multiplier (default: 1)
  
  # Exit Strategy
  - ExitStrategyTargetPrice: double
  - ExitStrategyType: int         # 1 = default
  
  # Metadata
  - Meta: string                  # Additional JSON data
  - Note: string                  # User notes
  - IsNew: bool                   # Unsaved flag

BDBOStrategyStateEnum

BDBOStrategyStateEnum:
  - Created = 0
  - Placed = 1
  - EntryOrderCanceled = 2
  - Filled = 3
  - Closed = 4
  - PriceBrokeOut = 5
  - Deactivated = 6

vBDBOStrategyOrderingHistory

vBDBOStrategyOrderingHistory:
  - Idug: Guid
  - StrategyIdug: Guid            # Parent strategy
  - OrderType: string             # "Entry", "Exit", "Cancel"
  - OrderId: string               # External order ID
  - Price: double
  - Quantity: double
  - Dt: DateTime
  - Status: string
  - Message: string

State Machine

Strategy Lifecycle (Simplified)

                    ┌─────────────┐
                    │   Created   │
                    │   (State 0) │
                    └──────┬──────┘
                           │ PlaceOrder()
                           ▼
                    ┌─────────────┐
         ┌──────────│   Placed    │──────────┐
         │          │   (State 1) │          │
         │          └──────┬──────┘          │
         │                 │                 │
    CancelOrder()     PriceBrokeOut()   MaxOrdersCanceled()
         │                 │                 │
         ▼                 ▼                 ▼
┌─────────────┐     ┌─────────────┐   ┌─────────────┐
│EntryOrder   │     │PriceBrokeOut│   │ Deactivated │
│Canceled     │     │   (State 5) │   │   (State 6) │
│  (State 2)  │     └──────┬──────┘   └─────────────┘
└──────┬──────┘            │
       │                   │ OrderFilled()
       │ ReplaceOrder()    │
       │                   ▼
       │            ┌─────────────┐
       └───────────▶│   Filled    │
                    │   (State 3) │
                    └──────┬──────┘
                           │ ClosePosition()
                           ▼
                    ┌─────────────┐
                    │   Closed    │
                    │   (State 4) │
                    └─────────────┘

Strategy Lifecycle (Full FSM from BOBDBOStrategiesFsm.cs)

┌──────────────┐
│ Instanciated │
│    (0)       │
└──────┬───────┘
       │ init
       ▼
┌──────────────┐
│    Idle      │
│    (1)       │
└──────┬───────┘
       │ StrategyCreationInitialized
       ▼
┌──────────────────────────────────────────────────────────┐
│                    ACTIVE (2)                            │
│                                                          │
│  ┌─────────────────┐   BreakoutPriceReached             │
│  │ Active_Created  │──────────────────┐                 │
│  │      (3)        │                  │                 │
│  └─────────────────┘                  ▼                 │
│                              ┌─────────────────┐        │
│                              │Active_Waiting   │        │
│                 ┌────────────│  Breakout (4)   │        │
│                 │            └────────┬────────┘        │
│                 │                     │                  │
│                 │  EntryOrder         │ ValidSignal     │
│                 │  Invalidated        │ Found           │
│                 │                     ▼                  │
│                 │            ┌─────────────────┐        │
│                 └────────────│Active_Waiting   │        │
│                              │  Signal (5)    │        │
│                              └────────┬────────┘        │
│                                       │                  │
│                                       │ ValidSignal     │
│                                       │ Found           │
│                                       ▼                  │
│                              ┌─────────────────┐        │
│                              │Active_Waiting   │        │
│                              │  Entering (6)  │ ←──┐   │
│                              └────────┬────────┘    │   │
│                                       │         Retry   │
│                                       │             │   │
└───────────────────────────────────────┼─────────────┘   │
        │  PUIReached / Failed / MaxReached                │
        ▼                                                  │
┌──────────────────────────────────────────────────────────┐
│                  INNACTIVE (7)                            │
│                                                          │
│  ┌────────────────┐  ┌──────────────────────┐            │
│  │  Completed (8) │  │ MaxTradeCreated (9)  │            │
│  └────────────────┘  └──────────────────────┘            │
│  ┌────────────────────────┐  ┌──────────────────────┐    │
│  │ MaxEntryCreated (10)   │  │ MaxPUIReached (11)   │    │
│  └────────────────────────┘  └──────────────────────┘    │
│  ┌────────────────────────┐                              │
│  │ StrategyFaulted (12)   │                              │
│  └────────────────────────┘                              │
└──────────────────────────────────────────────────────────┘
        │ cleanup
        ▼
┌──────────────┐
│    End (13)  │
└──────────────┘

State Transitions

From State Event To State Condition
Created PlaceOrder Placed Valid breakout price
Placed OrderCanceled EntryOrderCanceled CEOC < MaxEOC
Placed PriceBrokeOut PriceBrokeOut Price crossed breakout level
Placed MaxCancels Deactivated CEOC >= MaxEOC
EntryOrderCanceled ReplaceOrder Placed New breakout price set
PriceBrokeOut OrderFilled Filled Broker confirms fill
Filled ClosePosition Closed Exit condition met

Price Breakout Detection

Method IsPriceBrokeOut(lastBarCompleted: BarChaosItem):
  If BuySell == "S":
    If lastBarCompleted.Low < BreakoutPrice:
      PriceBrokeOut()
  
  If BuySell == "B":
    If lastBarCompleted.High > BreakoutPrice:
      PriceBrokeOut()

Creative Advancement Scenarios

Scenario 1: Create Fractal Breakout Strategy

Creative Advancement Scenario: Create New BDBO Strategy

Desired Outcome: Active strategy monitoring for EUR/USD H4 sell at 1.0850

Current Reality: User identified fractal sell opportunity on chart

Natural Progression Steps:
  1. User sets breakout price to fractal high (1.0850)
  2. User selects direction "Sell"
  3. CreateBdboStrategy called with parameters
  4. Strategy created with state "Created"
  5. THS snapshot saved for historical review
  6. Strategy appears in active list

Achieved Outcome: Strategy monitors EUR/USD H4 for price to break 1.0850

Supporting Features: NewBDBBOEntryStrategyUI, SDSService

Scenario 2: Strategy State Advancement

Creative Advancement Scenario: Price Breaks Out

Desired Outcome: Strategy advances to order placement

Current Reality: Price approaching breakout level

Natural Progression Steps:
  1. PDS updates price data
  2. CDB recalculated with new bar
  3. IsPriceBrokeOut() detects break
  4. State advances from Placed to PriceBrokeOut
  5. Order submission triggered
  6. State advances to Filled on confirmation

Achieved Outcome: Entry order executed at breakout level

Supporting Features: BDBOStrategySMEngine, price monitoring loop

Scenario 3: Review Order History

Creative Advancement Scenario: Analyze Trading History

Desired Outcome: Complete order history for strategy review

Current Reality: Strategy has completed lifecycle

Natural Progression Steps:
  1. User selects completed strategy
  2. GetBdboStrategyOrderHistory called
  3. All order events retrieved
  4. Timeline displayed with prices and times
  5. User analyzes execution quality

Achieved Outcome: Full audit trail for learning

Supporting Features: vBDBOStrategyOrderingHistory view

THS Integration

THS (Trading History Snapshots) captures market state when strategy events occur:

On CreateBdboStrategy:
  - Save CDB snapshot at creation time
  - Record strategy parameters
  - Tag with "BDBBO.Created"

On UpdateBdboStrategy:
  - Save CDB snapshot at update time
  - Record state change
  - Tag with "BDBBO.Updated"

This enables historical replay of trading decisions.


Implementation Notes for Python/TypeScript

Python Implementation

from enum import IntEnum
from dataclasses import dataclass
from datetime import datetime
from uuid import UUID, uuid4

class BDBOStrategyState(IntEnum):
    CREATED = 0
    PLACED = 1
    ENTRY_ORDER_CANCELED = 2
    FILLED = 3
    CLOSED = 4
    PRICE_BROKE_OUT = 5
    DEACTIVATED = 6

@dataclass
class BDBOStrategy:
    idug: UUID = field(default_factory=uuid4)
    instrument: str = ""
    timeframe: str = ""
    breakout_price: float = 0.0
    buy_sell: str = "B"  # "B" or "S"
    active: bool = True
    state: BDBOStrategyState = BDBOStrategyState.CREATED
    dt: datetime = field(default_factory=datetime.now)
    max_pip_risk: int = 120
    max_pui: int = 1000
    ceoc: int = 0
    max_eoc: int = 5
    
    def is_price_broke_out(self, bar: BarChaosItem) -> bool:
        if self.buy_sell == "S":
            return bar.low < self.breakout_price
        if self.buy_sell == "B":
            return bar.high > self.breakout_price
        return False

class SDSService:
    async def create_bdbo_strategy(
        self, 
        strategy: BDBOStrategy
    ) -> BDBOStrategy:
        """Create new BDBO strategy"""
        pass
    
    async def get_active_strategies(
        self,
        instrument: str = None,
        timeframe: str = None
    ) -> list[BDBOStrategy]:
        """Get filtered list of active strategies"""
        pass

TypeScript Implementation

enum BDBOStrategyState {
  Created = 0,
  Placed = 1,
  EntryOrderCanceled = 2,
  Filled = 3,
  Closed = 4,
  PriceBrokeOut = 5,
  Deactivated = 6
}

interface BDBOStrategy {
  idug: string;
  instrument: string;
  timeframe: string;
  breakoutPrice: number;
  buySell: 'B' | 'S';
  active: boolean;
  state: BDBOStrategyState;
  dt: Date;
  maxPipRisk: number;
  maxPui: number;
  ceoc: number;
  maxEoc: number;
}

interface ISDSService {
  createBdboStrategy(strategy: BDBOStrategy): Promise<BDBOStrategy>;
  getActiveStrategies(filter?: StrategyFilter): Promise<BDBOStrategy[]>;
  updateBdboStrategy(strategy: BDBOStrategy): Promise<void>;
  deleteStrategy(idug: string): Promise<void>;
}