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

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

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

                    ┌─────────────┐
                    │   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) │
                    └─────────────┘

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>;
}