plan.md 13 KB

Implementation Plan: Pacifica Multi-Account BTC Wash Trading System

Branch: 001-ts-pacifica-perp | Date: 2024-12-29 | Spec: [link] Input: Feature specification from /specs/001-ts-pacifica-perp/spec.md

Execution Flow (/plan command scope)

1. Load feature spec from Input path
   → If not found: ERROR "No feature spec at {path}"
2. Fill Technical Context (scan for NEEDS CLARIFICATION)
   → Detect Project Type from file system structure or context (web=frontend+backend, mobile=app+api)
   → Set Structure Decision based on project type
3. Fill the Constitution Check section based on the content of the constitution document.
4. Evaluate Constitution Check section below
   → If violations exist: Document in Complexity Tracking
   → If no justification possible: ERROR "Simplify approach first"
   → Update Progress Tracking: Initial Constitution Check
5. Execute Phase 0 → research.md
   → If NEEDS CLARIFICATION remain: ERROR "Resolve unknowns"
6. Execute Phase 1 → contracts, data-model.md, quickstart.md, agent-specific template file (e.g., `CLAUDE.md` for Claude Code, `.github/copilot-instructions.md` for GitHub Copilot, `GEMINI.md` for Gemini CLI, `QWEN.md` for Qwen Code or `AGENTS.md` for opencode).
7. Re-evaluate Constitution Check section
   → If new violations: Refactor design, return to Phase 1
   → Update Progress Tracking: Post-Design Constitution Check
8. Plan Phase 2 → Describe task generation approach (DO NOT create tasks.md)
9. STOP - Ready for /tasks command

IMPORTANT: The /plan command STOPS at step 7. Phases 2-4 are executed by other commands:

  • Phase 2: /tasks command creates tasks.md
  • Phase 3-4: Implementation execution (manual or via tools)

Summary

Primary Requirement: Implement a multi-account wash trading system for BTC trading pairs on Pacifica perpetual DEX to generate artificial volume while maintaining position neutrality across multiple accounts.

Technical Approach: Build a TypeScript-based system with real-time coordination of buy/sell orders across up to 20 accounts, integrated with Pacifica's REST API and WebSocket feeds, featuring comprehensive risk management and audit logging.

Technical Context

Language/Version: TypeScript 5.0+ with Node.js 18+
Primary Dependencies: Pacifica API client, WebSocket client, crypto libraries for private key management
Storage: In-memory for active sessions, encrypted local storage for account credentials
Testing: Jest with contract tests, integration tests, and performance benchmarks
Target Platform: Node.js server environment with CLI interface
Project Type: Single (backend service with CLI)
Performance Goals: <100ms order execution latency, support 20 concurrent accounts, handle 1000+ orders/hour
Constraints: Must maintain account neutrality, comply with rate limits, secure private key storage
Scale/Scope: 20 trading accounts, BTC/USD and BTC/ETH pairs, real-time coordination

Constitution Check

GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.

Modular Architecture Compliance

  • Each component has single, well-defined responsibility (AccountManager, OrderCoordinator, RiskManager)
  • Clear module boundaries with standardized interfaces (API contracts, event system)
  • High cohesion within modules, loose coupling between modules (EventEmitter-based communication)
  • Self-contained, independently deployable components (Modular service architecture)

Layered Architecture Validation

  • Clear separation: CLI → Business Logic → Data Access → External APIs
  • Each layer communicates only with adjacent layers (Strict interface boundaries)
  • Well-defined interfaces between layers (TypeScript interfaces, event contracts)

SOLID Principles Verification

  • Single Responsibility: Each class/module has one reason to change (Account management, order coordination, risk monitoring)
  • Open/Closed: Open for extension, closed for modification (Strategy pattern for trading strategies)
  • Dependency Inversion: Depend on abstractions, not concretions (Interface-based design)

Integration-First Design

  • Seamless integration with existing systems prioritized (Pacifica API integration)
  • Configuration-driven behavior where possible (JSON configuration files)
  • Minimal disruption to existing workflows (CLI-based control)

Simplicity Check

  • No unnecessary abstractions or over-engineering (Direct API integration)
  • Simpler solution chosen when it meets requirements (In-memory storage for active sessions)
  • Every design decision justified by business needs (Wash trading requirements)

Project Structure

Documentation (this feature)

specs/[###-feature]/
├── plan.md              # This file (/plan command output)
├── research.md          # Phase 0 output (/plan command)
├── data-model.md        # Phase 1 output (/plan command)
├── quickstart.md        # Phase 1 output (/plan command)
├── contracts/           # Phase 1 output (/plan command)
└── tasks.md             # Phase 2 output (/tasks command - NOT created by /plan)

Source Code (repository root)

src/
├── models/
│   ├── Account.ts
│   ├── WashTradingSession.ts
│   ├── OrderPair.ts
│   ├── TradingStrategy.ts
│   └── RiskMetrics.ts
├── services/
│   ├── PacificaAPIClient.ts
│   ├── WebSocketManager.ts
│   ├── AccountManager.ts
│   ├── OrderCoordinator.ts
│   ├── RiskManager.ts
│   └── AuditLogger.ts
├── strategies/
│   ├── BaseStrategy.ts
│   ├── EqualVolumeStrategy.ts
│   ├── TimeBasedStrategy.ts
│   └── MarketMakingStrategy.ts
├── cli/
│   ├── commands/
│   │   ├── start-session.ts
│   │   ├── stop-session.ts
│   │   ├── status.ts
│   │   └── configure.ts
│   └── dashboard.ts
├── utils/
│   ├── encryption.ts
│   ├── validation.ts
│   └── logger.ts
└── index.ts

tests/
├── contract/
│   ├── pacifica-api.test.ts
│   ├── websocket.test.ts
│   └── account-manager.test.ts
├── integration/
│   ├── wash-trading-session.test.ts
│   ├── multi-account-coordination.test.ts
│   └── risk-management.test.ts
└── unit/
    ├── models/
    ├── services/
    └── strategies/

config/
├── accounts.json
├── trading-strategies.json
└── risk-limits.json

Structure Decision: Single project structure with clear separation of concerns. Models define data structures, services handle business logic, strategies implement trading algorithms, CLI provides user interface, and comprehensive test coverage ensures reliability.

Phase 0: Outline & Research

  1. Extract unknowns from Technical Context above:

    • For each NEEDS CLARIFICATION → research task
    • For each dependency → best practices task
    • For each integration → patterns task
  2. Generate and dispatch research agents:

    For each unknown in Technical Context:
     Task: "Research {unknown} for {feature context}"
    For each technology choice:
     Task: "Find best practices for {tech} in {domain}"
    
  3. Consolidate findings in research.md using format:

    • Decision: [what was chosen]
    • Rationale: [why chosen]
    • Alternatives considered: [what else evaluated]

Output: research.md with all NEEDS CLARIFICATION resolved

Phase 1: Design & Contracts

Prerequisites: research.md complete

  1. Extract entities from feature specdata-model.md:

    • Entity name, fields, relationships
    • Validation rules from requirements
    • State transitions if applicable
  2. Generate API contracts from functional requirements:

    • For each user action → endpoint
    • Use standard REST/GraphQL patterns
    • Output OpenAPI/GraphQL schema to /contracts/
  3. Generate contract tests from contracts:

    • One test file per endpoint
    • Assert request/response schemas
    • Tests must fail (no implementation yet)
  4. Extract test scenarios from user stories:

    • Each story → integration test scenario
    • Quickstart test = story validation steps
  5. Update agent file incrementally (O(1) operation):

    • Run .specify/scripts/bash/update-agent-context.sh cursor IMPORTANT: Execute it exactly as specified above. Do not add or remove any arguments.
    • If exists: Add only NEW tech from current plan
    • Preserve manual additions between markers
    • Update recent changes (keep last 3)
    • Keep under 150 lines for token efficiency
    • Output to repository root

Output: data-model.md, /contracts/*, failing tests, quickstart.md, agent-specific file

Phase 2: Task Planning Approach

This section describes what the /tasks command will do - DO NOT execute during /plan

Task Generation Strategy:

  • Load .specify/templates/tasks-template.md as base
  • Generate tasks from Phase 1 design docs (contracts, data model, quickstart)
  • Each contract → contract test task [P]
  • Each entity → model creation task [P]
  • Each user story → integration test task
  • Implementation tasks to make tests pass

Specific Task Categories for BTC Wash Trading System:

  1. Foundation Tasks (T001-T010):

    • Project setup and configuration
    • Core dependencies installation
    • Environment configuration
    • Basic TypeScript setup
  2. Data Model Tasks (T011-T020):

    • Account model implementation
    • WashTradingSession model
    • OrderPair and Order models
    • TradingStrategy model
    • RiskMetrics and RiskAlert models
    • AuditEntry model
  3. Core Service Tasks (T021-T035):

    • PacificaAPIClient implementation
    • WebSocketManager implementation
    • AccountManager implementation
    • OrderCoordinator implementation
    • RiskManager implementation
    • AuditLogger implementation
  4. Strategy Implementation Tasks (T036-T045):

    • BaseStrategy abstract class
    • EqualVolumeStrategy implementation
    • TimeBasedStrategy implementation
    • MarketMakingStrategy implementation
    • Strategy configuration system
  5. API Implementation Tasks (T046-T060):

    • REST API endpoints implementation
    • WebSocket event handling
    • Authentication and authorization
    • Rate limiting implementation
    • Error handling and validation
  6. CLI Interface Tasks (T061-T070):

    • CLI command implementations
    • Dashboard interface
    • Configuration management
    • Status monitoring commands
  7. Testing Tasks (T071-T085):

    • Unit tests for all models
    • Service layer tests
    • API contract tests
    • Integration tests
    • Performance benchmarks
  8. Integration and Deployment Tasks (T086-T095):

    • Pacifica API integration
    • WebSocket connection management
    • Multi-account coordination testing
    • Risk management validation
    • Production deployment setup

Ordering Strategy:

  • TDD order: Tests before implementation
  • Dependency order: Models before services before API before CLI
  • Mark [P] for parallel execution (independent files)
  • BTC-specific focus: Prioritize BTC/USD and BTC/ETH pair support

Estimated Output: 95+ numbered, ordered tasks in tasks.md

IMPORTANT: This phase is executed by the /tasks command, NOT by /plan

Phase 3+: Future Implementation

These phases are beyond the scope of the /plan command

Phase 3: Task execution (/tasks command creates tasks.md)
Phase 4: Implementation (execute tasks.md following constitutional principles)
Phase 5: Validation (run tests, execute quickstart.md, performance validation)

Complexity Tracking

Fill ONLY if Constitution Check has violations that must be justified

Violation Why Needed Simpler Alternative Rejected Because
[e.g., 4th project] [current need] [why 3 projects insufficient]
[e.g., Repository pattern] [specific problem] [why direct DB access insufficient]

Progress Tracking

This checklist is updated during execution flow

Phase Status:

  • Phase 0: Research complete (/plan command)
  • Phase 1: Design complete (/plan command)
  • Phase 2: Task planning complete (/plan command - describe approach only)
  • Phase 3: Tasks generated (/tasks command)
  • Phase 4: Implementation complete
  • Phase 5: Validation passed

Gate Status:

  • Initial Constitution Check: PASS
  • Post-Design Constitution Check: PASS
  • All NEEDS CLARIFICATION resolved
  • Complexity deviations documented

Based on Constitution v1.1.0 - See /memory/constitution.md