## 1. Architecture design

```mermaid
graph TD
  A[User Browser] --> B[React Frontend Application]
  B --> C[Express.js Backend API]
  C --> D[SQLite Database]
  C --> E[start.bat Script]

  subgraph "Frontend Layer"
      B
  end

  subgraph "Backend Layer"
      C
  end

  subgraph "Data Layer"
      D
  end

  subgraph "Deployment Layer"
      E
  end
```

## 2. Technology Description
- Frontend: React@18 + tailwindcss@3 + vite
- Initialization Tool: vite-init
- Backend: Express@4 + Node.js
- Database: SQLite3
- Build Tool: Vite
- Styling: Tailwind CSS with custom dark theme

## 3. Route definitions
| Route | Purpose |
|-------|---------|
| / | Dashboard page, displays trading performance overview and analytics |
| /trade-entry | Trade entry page, allows users to add new trades with detailed information |
| /trade-history | Trade history page, provides searchable and filterable list of all trades |
| /api/trades | API endpoint for trade CRUD operations |
| /api/analytics | API endpoint for dashboard analytics and metrics |

## 4. API definitions

### 4.1 Trade Management API

**Get all trades with filtering**
```
GET /api/trades
```

Request Parameters:
| Param Name | Param Type | isRequired | Description |
|------------|------------|------------|-------------|
| start_date | string | false | Filter trades from this date (YYYY-MM-DD) |
| end_date | string | false | Filter trades until this date (YYYY-MM-DD) |
| direction | string | false | Filter by trade direction ('long' or 'short') |
| symbol | string | false | Filter by trading symbol |

Response:
| Param Name | Param Type | Description |
|------------|------------|-------------|
| trades | array | Array of trade objects |
| total_count | number | Total number of trades |

**Create new trade**
```
POST /api/trades
```

Request Body:
| Param Name | Param Type | isRequired | Description |
|------------|------------|------------|-------------|
| symbol | string | true | Trading symbol (e.g., 'AAPL', 'BTC') |
| direction | string | true | Trade direction ('long' or 'short') |
| entry_price | number | true | Entry price of the trade |
| exit_price | number | true | Exit price of the trade |
| position_size | number | true | Size of the position |
| entry_date | string | true | Entry date and time (ISO 8601) |
| exit_date | string | true | Exit date and time (ISO 8601) |
| notes | string | false | Additional notes about the trade |
| confluence | number | false | Confluence score (0-100) |

**Get dashboard analytics**
```
GET /api/analytics
```

Response:
| Param Name | Param Type | Description |
|------------|------------|-------------|
| net_pnl | number | Net profit and loss |
| total_profit | number | Total profit from winning trades |
| total_loss | number | Total loss from losing trades |
| win_rate | number | Win rate percentage |
| profit_factor | number | Profit factor ratio |
| avg_confluence | number | Average confluence score |
| largest_win | number | Largest winning trade |
| largest_loss | number | Largest losing trade |
| best_streak | number | Best consecutive win streak |
| total_trades | number | Total number of trades |
| long_trades_win_rate | number | Win rate for long trades |
| short_trades_win_rate | number | Win rate for short trades |
| recent_trades | array | 5 most recent trades |

## 5. Server architecture diagram

```mermaid
graph TD
  A[Client / Frontend] --> B[Express Routes Layer]
  B --> C[Controller Layer]
  C --> D[Service Layer]
  D --> E[Repository Layer]
  E --> F[(SQLite Database)]

  subgraph "Express Server"
      B
      C
      D
      E
  end
```

## 6. Data model

### 6.1 Data model definition

```mermaid
erDiagram
  TRADE {
    integer id PK
    string symbol
    string direction
    decimal entry_price
    decimal exit_price
    decimal position_size
    datetime entry_date
    datetime exit_date
    decimal pnl
    text notes
    integer confluence
    datetime created_at
    datetime updated_at
  }
```

### 6.2 Data Definition Language

**Trades Table**
```sql
-- Create trades table
CREATE TABLE trades (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    symbol VARCHAR(20) NOT NULL,
    direction VARCHAR(10) NOT NULL CHECK (direction IN ('long', 'short')),
    entry_price DECIMAL(10, 2) NOT NULL,
    exit_price DECIMAL(10, 2) NOT NULL,
    position_size DECIMAL(10, 4) NOT NULL,
    entry_date DATETIME NOT NULL,
    exit_date DATETIME NOT NULL,
    pnl DECIMAL(10, 2) GENERATED ALWAYS AS ((exit_price - entry_price) * position_size * CASE WHEN direction = 'long' THEN 1 ELSE -1 END) STORED,
    notes TEXT,
    confluence INTEGER CHECK (confluence >= 0 AND confluence <= 100),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes for performance
CREATE INDEX idx_trades_entry_date ON trades(entry_date);
CREATE INDEX idx_trades_symbol ON trades(symbol);
CREATE INDEX idx_trades_direction ON trades(direction);
CREATE INDEX idx_trades_pnl ON trades(pnl);

-- Create view for analytics
CREATE VIEW trade_analytics AS
SELECT 
    COUNT(*) as total_trades,
    COUNT(CASE WHEN pnl > 0 THEN 1 END) as winning_trades,
    COUNT(CASE WHEN pnl < 0 THEN 1 END) as losing_trades,
    ROUND(COUNT(CASE WHEN pnl > 0 THEN 1 END) * 100.0 / COUNT(*), 2) as win_rate,
    SUM(pnl) as net_pnl,
    SUM(CASE WHEN pnl > 0 THEN pnl ELSE 0 END) as total_profit,
    SUM(CASE WHEN pnl < 0 THEN pnl ELSE 0 END) as total_loss,
    ROUND(SUM(CASE WHEN pnl > 0 THEN pnl ELSE 0 END) / ABS(SUM(CASE WHEN pnl < 0 THEN pnl ELSE 0 END)), 2) as profit_factor,
    ROUND(AVG(confluence), 2) as avg_confluence,
    MAX(CASE WHEN pnl > 0 THEN pnl ELSE 0 END) as largest_win,
    MIN(pnl) as largest_loss
FROM trades;

-- Insert sample data for testing
INSERT INTO trades (symbol, direction, entry_price, exit_price, position_size, entry_date, exit_date, notes, confluence) VALUES
('AAPL', 'long', 150.00, 155.00, 100, '2026-01-15 09:30:00', '2026-01-15 15:30:00', 'Breakout trade', 85),
('TSLA', 'short', 200.00, 195.00, 50, '2026-01-16 10:00:00', '2026-01-16 14:00:00', 'Earnings play', 75),
('BTC', 'long', 45000, 46000, 0.5, '2026-01-17 08:00:00', '2026-01-17 20:00:00', 'Crypto momentum', 90);
```

**start.bat Script Content**
```batch
@echo off
echo Starting Trading Journal Application...
echo.

:: Check if Node.js is installed
node --version >nul 2>&1
if errorlevel 1 (
    echo Node.js is not installed. Please install Node.js first.
    pause
    exit /b 1
)

:: Install dependencies if node_modules doesn't exist
if not exist "node_modules" (
    echo Installing dependencies...
    npm install
    if errorlevel 1 (
        echo Failed to install dependencies.
        pause
        exit /b 1
    )
)

:: Start the backend server
echo Starting backend server...
start cmd /k "cd backend && npm run dev"

:: Wait a moment for backend to start
timeout /t 3 /nobreak > nul

:: Start the frontend development server
echo Starting frontend development server...
cd frontend && npm run dev

:: Keep the batch file window open