caishen

SE - SEngine (Charting Engine)

RISE Framework Specification

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

Creative Intent

What SE Enables Users to Create:

Desired Outcomes:

  1. Users see intuitive visual representation of market data
  2. Chart interactions feel natural and responsive
  3. Analysis annotations can be added and saved
  4. Charts can be exported for documentation

Core Components

SEngine (SE)

Central charting engine coordinating data and rendering.

Behavior:

Layout: Contains ChartArea, IndicatorPanels, ToolPalette

Chart Areas

ChartAreaMain

Primary price chart area.

Behavior:

Styling:

ChartAreaAO

Awesome Oscillator histogram panel.

Behavior:

Styling:

ChartAreaAC

Accelerator Oscillator histogram panel.

Behavior:


Chart Components

CChart

Main chart control for WinForms.

Behavior:

Layout:

┌─────────────────────────────────────┐
│           ChartAreaMain             │
│  ┌─────────────────────────────┐   │
│  │  Candlesticks + Alligator   │   │
│  │  + Fractals                 │   │
│  └─────────────────────────────┘   │
├─────────────────────────────────────┤
│           ChartAreaAO               │
│  ┌─────────────────────────────┐   │
│  │  Awesome Oscillator         │   │
│  └─────────────────────────────┘   │
├─────────────────────────────────────┤
│           ChartAreaAC               │
│  ┌─────────────────────────────┐   │
│  │  Accelerator                │   │
│  └─────────────────────────────┘   │
└─────────────────────────────────────┘

ChartDataElements

Data binding between CDB and chart series.

Behavior:

ChartingTools

Interactive tools for chart analysis.

Behavior:


Chart Series

Price Series

PriceSeries:
  Type: Candlestick or OHLC
  Data: List<(Date, Open, High, Low, Close)>
  Colors:
    - BullishFill: Green
    - BearishFill: Red
    - BullishBorder: DarkGreen
    - BearishBorder: DarkRed

Alligator Series

AlligatorSeries:
  LipsSeries:
    Type: Line
    Data: List<(Date, Value)>
    Color: Green
    LineWidth: 2
  
  TeethSeries:
    Type: Line
    Data: List<(Date, Value)>
    Color: Red
    LineWidth: 2
  
  JawSeries:
    Type: Line
    Data: List<(Date, Value)>
    Color: Blue
    LineWidth: 2

Fractal Series

FractalSeries:
  BuyFractals:
    Type: Marker
    Symbol: UpArrow
    Color: Green
    Data: List<(Date, Price)>
  
  SellFractals:
    Type: Marker
    Symbol: DownArrow
    Color: Red
    Data: List<(Date, Price)>

AO/AC Series

OscillatorSeries:
  Type: Histogram
  Data: List<(Date, Value)>
  ColorPositiveRising: Green
  ColorPositiveFalling: LightGreen
  ColorNegativeRising: Pink
  ColorNegativeFalling: Red
  ZeroLine: Gray

Creative Advancement Scenarios

Scenario 1: Render Chaos Chart

Creative Advancement Scenario: Display Complete Chaos Chart

Desired Outcome: Visual chart with all indicators

Current Reality: CDB data available from ADS

Natural Progression Steps:
  1. CChart receives ChaosDataBuilder
  2. ChartDataElements maps CDB to series
  3. Price series rendered as candlesticks
  4. Alligator overlay added
  5. Fractals marked on price chart
  6. AO and AC panels rendered below
  7. Chart ready for interaction

Achieved Outcome: Complete chaos chart displayed

Supporting Features: CChart, ChartDataElements

Scenario 2: Identify Entry Point

Creative Advancement Scenario: Visual Entry Identification

Desired Outcome: User identifies fractal breakout visually

Current Reality: Chart displays recent price action

Natural Progression Steps:
  1. User observes fractal pattern on chart
  2. Fractal arrow markers indicate levels
  3. User clicks near fractal to select
  4. Chart highlights breakout level
  5. Right-click opens strategy creation dialog

Achieved Outcome: Entry point identified and actionable

Supporting Features: Fractal markers, context menu

Chart Configuration

ChartingServiceParams

ChartingServiceParams:
  - ShowAlligator: bool = true
  - ShowFractals: bool = true
  - ShowAO: bool = true
  - ShowAC: bool = true
  - ShowGator: bool = false
  - ShowZones: bool = true
  - CandleWidth: int = 5
  - AOPanelHeight: int = 80
  - ACPanelHeight: int = 60

ConstantsCharting

ConstantsCharting:
  - COLOR_ALLIGATOR_LIPS: "#00FF00"
  - COLOR_ALLIGATOR_TEETH: "#FF0000"
  - COLOR_ALLIGATOR_JAW: "#0000FF"
  - COLOR_FRACTAL_BUY: "#00AA00"
  - COLOR_FRACTAL_SELL: "#AA0000"
  - COLOR_AO_UP: "#00FF00"
  - COLOR_AO_DOWN: "#FF0000"
  - COLOR_ZONE_GREEN: "#00FF00"
  - COLOR_ZONE_RED: "#FF0000"
  - COLOR_ZONE_GRAY: "#808080"

Chart Modes

ChartingModeEnum

ChartingModeEnum:
  - Normal = 0         # Standard viewing mode
  - FractalFocus = 1   # Highlights fractal patterns
  - Divergence = 2     # Shows divergence analysis
  - Strategy = 3       # Shows strategy overlay
  - Playback = 4       # Historical playback mode

Web Chart (CCWebChart)

Alternative chart implementation for web display.

Behavior:


Implementation Notes for Python/TypeScript

Python Implementation (using matplotlib or plotly)

import plotly.graph_objects as go
from plotly.subplots import make_subplots
from typing import List

class ChaosChart:
    def __init__(self, cdb: ChaosDataBuilder):
        self.cdb = cdb
        self.fig = None
    
    def create_chart(self) -> go.Figure:
        """Create complete chaos chart"""
        self.fig = make_subplots(
            rows=3, cols=1,
            shared_xaxes=True,
            vertical_spacing=0.02,
            row_heights=[0.6, 0.2, 0.2],
            subplot_titles=('Price', 'AO', 'AC')
        )
        
        self._add_candlesticks()
        self._add_alligator()
        self._add_fractals()
        self._add_ao()
        self._add_ac()
        
        return self.fig
    
    def _add_candlesticks(self):
        """Add OHLC candlestick series"""
        dates = [b.dt for b in self.cdb.chart_bars]
        opens = [float(b.open) for b in self.cdb.chart_bars]
        highs = [float(b.high) for b in self.cdb.chart_bars]
        lows = [float(b.low) for b in self.cdb.chart_bars]
        closes = [float(b.close) for b in self.cdb.chart_bars]
        
        self.fig.add_trace(
            go.Candlestick(
                x=dates,
                open=opens,
                high=highs,
                low=lows,
                close=closes,
                name='Price'
            ),
            row=1, col=1
        )
    
    def _add_alligator(self):
        """Add Alligator indicator lines"""
        dates = [b.dt for b in self.cdb.chart_bars]
        lips = [b.lips for b in self.cdb.chart_bars]
        teeth = [b.teeth for b in self.cdb.chart_bars]
        jaw = [b.jaw for b in self.cdb.chart_bars]
        
        self.fig.add_trace(
            go.Scatter(x=dates, y=lips, name='Lips',
                      line=dict(color='green', width=2)),
            row=1, col=1
        )
        self.fig.add_trace(
            go.Scatter(x=dates, y=teeth, name='Teeth',
                      line=dict(color='red', width=2)),
            row=1, col=1
        )
        self.fig.add_trace(
            go.Scatter(x=dates, y=jaw, name='Jaw',
                      line=dict(color='blue', width=2)),
            row=1, col=1
        )
    
    def _add_fractals(self):
        """Add fractal markers"""
        for bar in self.cdb.chart_bars:
            if bar.fractal_buy:
                self.fig.add_trace(
                    go.Scatter(
                        x=[bar.dt],
                        y=[bar.fractal_buy],
                        mode='markers',
                        marker=dict(symbol='triangle-up', size=10, color='green'),
                        name='Fractal Buy'
                    ),
                    row=1, col=1
                )
            if bar.fractal_sell:
                self.fig.add_trace(
                    go.Scatter(
                        x=[bar.dt],
                        y=[bar.fractal_sell],
                        mode='markers',
                        marker=dict(symbol='triangle-down', size=10, color='red'),
                        name='Fractal Sell'
                    ),
                    row=1, col=1
                )
    
    def _add_ao(self):
        """Add Awesome Oscillator histogram"""
        dates = [b.dt for b in self.cdb.chart_bars]
        ao = [b.ao for b in self.cdb.chart_bars]
        # Color logic: green (rising positive), lightgreen (falling positive), 
        # pink (rising negative), red (falling negative)
        colors = []
        for i in range(len(ao)):
            if i == 0:
                colors.append('green' if ao[i] >= 0 else 'red')
            elif ao[i] >= 0:
                colors.append('green' if ao[i] > ao[i-1] else 'lightgreen')
            else:
                colors.append('pink' if ao[i] > ao[i-1] else 'red')
        
        self.fig.add_trace(
            go.Bar(x=dates, y=ao, marker_color=colors, name='AO'),
            row=2, col=1
        )
    
    def _add_ac(self):
        """Add Accelerator Oscillator histogram"""
        dates = [b.dt for b in self.cdb.chart_bars]
        ac = [b.ac for b in self.cdb.chart_bars]
        
        self.fig.add_trace(
            go.Bar(x=dates, y=ac, name='AC'),
            row=3, col=1
        )

TypeScript Implementation (using lightweight-charts)

import { createChart, IChartApi, ISeriesApi } from 'lightweight-charts';

interface ChartConfig {
  showAlligator: boolean;
  showFractals: boolean;
  showAO: boolean;
  showAC: boolean;
}

class ChaosChart {
  private chart: IChartApi;
  private candlestickSeries: ISeriesApi<'Candlestick'>;
  private lipsSeries: ISeriesApi<'Line'>;
  private teethSeries: ISeriesApi<'Line'>;
  private jawSeries: ISeriesApi<'Line'>;
  
  constructor(
    container: HTMLElement,
    private config: ChartConfig = {
      showAlligator: true,
      showFractals: true,
      showAO: true,
      showAC: true
    }
  ) {
    this.chart = createChart(container, {
      width: container.clientWidth,
      height: 600,
      layout: {
        background: { color: '#1e1e1e' },
        textColor: '#d1d4dc'
      }
    });
    
    this.initializeSeries();
  }
  
  private initializeSeries() {
    // Candlestick series for price
    this.candlestickSeries = this.chart.addCandlestickSeries({
      upColor: '#26a69a',
      downColor: '#ef5350',
      borderVisible: false,
      wickUpColor: '#26a69a',
      wickDownColor: '#ef5350'
    });
    
    if (this.config.showAlligator) {
      // Alligator lines
      this.lipsSeries = this.chart.addLineSeries({
        color: '#00ff00',
        lineWidth: 2
      });
      
      this.teethSeries = this.chart.addLineSeries({
        color: '#ff0000',
        lineWidth: 2
      });
      
      this.jawSeries = this.chart.addLineSeries({
        color: '#0000ff',
        lineWidth: 2
      });
    }
  }
  
  setChaosData(cdb: ChaosDataBuilder) {
    // Set candlestick data
    const candleData = cdb.chartBars.map(bar => ({
      time: bar.dt.getTime() / 1000,
      open: bar.open,
      high: bar.high,
      low: bar.low,
      close: bar.close
    }));
    this.candlestickSeries.setData(candleData);
    
    if (this.config.showAlligator) {
      // Set Alligator data
      this.lipsSeries.setData(
        cdb.chartBars.map(b => ({ time: b.dt.getTime() / 1000, value: b.lips }))
      );
      this.teethSeries.setData(
        cdb.chartBars.map(b => ({ time: b.dt.getTime() / 1000, value: b.teeth }))
      );
      this.jawSeries.setData(
        cdb.chartBars.map(b => ({ time: b.dt.getTime() / 1000, value: b.jaw }))
      );
    }
    
    if (this.config.showFractals) {
      // Add fractal markers
      const markers = [];
      for (const bar of cdb.chartBars) {
        if (bar.fractalBuy) {
          markers.push({
            time: bar.dt.getTime() / 1000,
            position: 'belowBar',
            color: '#00ff00',
            shape: 'arrowUp',
            text: 'Buy'
          });
        }
        if (bar.fractalSell) {
          markers.push({
            time: bar.dt.getTime() / 1000,
            position: 'aboveBar',
            color: '#ff0000',
            shape: 'arrowDown',
            text: 'Sell'
          });
        }
      }
      this.candlestickSeries.setMarkers(markers);
    }
  }
}