Files
nt8-sdk/implementation_attention_points.md
Billy Valentine 92f3732b3d
Some checks failed
Build and Test / build (push) Has been cancelled
Phase 0 completion: NT8 SDK core framework with risk management and position sizing
2025-09-09 17:06:37 -04:00

9.1 KiB

NT8 Institutional SDK - Implementation Attention Points

Overview

This document highlights specific areas of the implementation that require special attention during development to ensure correctness, performance, and maintainability.

1. Risk Management Implementation

Thread Safety

  • File: src/NT8.Core/Risk/BasicRiskManager.cs
  • Attention Points:
    • All public methods must be thread-safe using the existing lock mechanism
    • Ensure no race conditions in state updates (daily P&L, exposure tracking)
    • Verify that emergency halt functionality is atomic
  • Implementation Details:
    • The _lock object is already defined and should be used for all state modifications
    • All state variables (_dailyPnL, _maxDrawdown, _tradingHalted, _symbolExposure) must be accessed within lock blocks

Risk Calculations

  • File: src/NT8.Core/Risk/BasicRiskManager.cs
  • Attention Points:
    • Tick values must match exactly as specified in the package documentation
    • Risk escalation thresholds (50%, 80% of daily limit) must be precise
    • Trade risk calculation: stopTicks * tickValue per contract
  • Implementation Details:
    • ES = $12.50, MES = $1.25, NQ = $5.00, MNQ = $0.50, CL = $10.00, GC = $10.00
    • Daily loss limit breach check: _dailyPnL <= -config.DailyLossLimit
    • Emergency halt at 90%: dayPnL <= -(_dailyPnL * 0.9)

Emergency Handling

  • File: src/NT8.Core/Risk/BasicRiskManager.cs
  • Attention Points:
    • Emergency flatten must be truly atomic (no partial state changes)
    • ResetDaily method must clear ALL state variables
    • Exception handling in async EmergencyFlatten method
  • Implementation Details:
    • _tradingHalted flag controls all order validation
    • ResetDaily clears exposure dictionary and resets all counters

2. Position Sizing Implementation

Calculation Accuracy

  • File: src/NT8.Core/Sizing/BasicPositionSizer.cs
  • Attention Points:
    • Fixed dollar risk uses Math.Floor for conservative contract calculation
    • Tick values must match exactly as specified
    • Clamping must be applied after calculation, not before
  • Implementation Details:
    • Optimal contracts: targetRisk / (stopTicks * tickValue)
    • Final contracts: Math.Floor(optimalContracts)
    • Clamping: Math.Max(min, Math.Min(max, contracts))

Parameter Validation

  • File: src/NT8.Core/Sizing/BasicPositionSizer.cs
  • Attention Points:
    • ValidateConfig method must check all edge cases
    • Method-specific parameter requirements (FixedContracts needs "contracts" parameter)
    • Type conversion in GetParameterValue method
  • Implementation Details:
    • MinContracts >= 0, MaxContracts > 0, Min <= Max
    • RiskPerTrade > 0
    • FixedContracts method requires "contracts" parameter > 0

3. Interface Contracts

IStrategy Interface

  • File: src/NT8.Core/Common/Interfaces/IStrategy.cs
  • Attention Points:
    • OnTick method has default implementation that returns null
    • Metadata property is read-only
    • Initialize method parameters are well-defined
  • Implementation Details:
    • Strategies should not modify context or intent objects
    • Strategy implementations will be created in Phase 1

IRiskManager Interface

  • File: src/NT8.Core/Risk/IRiskManager.cs
  • Attention Points:
    • ValidateOrder method must never return null
    • RiskDecision object must always be fully populated
    • EmergencyFlatten method is async and returns Task
  • Implementation Details:
    • RiskLevel enum values have specific meanings (Low/Medium/High/Critical)
    • RiskMetrics dictionary should contain relevant calculation details

IPositionSizer Interface

  • File: src/NT8.Core/Sizing/IPositionSizer.cs
  • Attention Points:
    • CalculateSize method must handle invalid intents gracefully
    • SizingResult should always contain calculation details
  • GetMetadata method provides component information
  • Implementation Details:
    • SizingMethod enum defines supported algorithms
    • SizingConfig contains all necessary parameters

4. Model Validation

StrategyIntent Validation

  • Files: src/NT8.Core/Common/Models/StrategyIntent.cs
  • Attention Points:
    • IsValid method checks all required fields
    • Confidence must be between 0.0 and 1.0
    • Symbol cannot be null or empty
    • StopTicks must be positive
    • Reason cannot be null or empty
    • Side cannot be Flat for valid intents
  • Implementation Details:
    • IntentId is automatically generated
    • Timestamp is set to UTC now

Configuration Models

  • Files: Various model files in src/NT8.Core/Common/Models/
  • Attention Points:
    • Record types are immutable by design
    • Constructor parameters define required fields
    • Default values should be sensible
  • Implementation Details:
    • StrategyConfig contains risk and sizing settings
    • RiskConfig defines daily limits and position constraints
    • SizingConfig contains method-specific parameters

5. Test Suite Implementation

Risk Management Tests

  • Files: tests/NT8.Core.Tests/Risk/BasicRiskManagerTests.cs
  • Attention Points:
    • Test all Tier 1 risk controls (daily limit, trade risk, position limits)
    • Verify thread safety with concurrent access tests
    • Test edge cases (zero values, boundary conditions)
    • Validate logging calls where appropriate
  • Implementation Details:
    • Use TestDataBuilder for consistent test data
    • Test both valid and invalid scenarios
    • Verify exception handling for null parameters

Position Sizing Tests

  • Files: tests/NT8.Core.Tests/Sizing/BasicPositionSizerTests.cs
  • Attention Points:
    • Test both sizing methods with various parameters
    • Verify clamping behavior at boundaries
    • Test calculation accuracy for all supported symbols
  • Validate configuration error handling
  • Implementation Details:
    • Use theory tests for multiple symbol/value combinations
    • Test deterministic behavior (same inputs = same outputs)
    • Verify error cases return appropriate SizingResult

Scenario Tests

  • Files: tests/NT8.Core.Tests/Risk/RiskScenarioTests.cs
  • Attention Points:
    • Test realistic trading scenarios
    • Verify risk level escalation patterns
    • Test recovery after reset
    • Validate multi-symbol handling
  • Implementation Details:
    • Simulate complete trading days with various conditions
    • Test emergency halt and recovery workflows
    • Verify system behavior under stress

6. Error Handling and Logging

Exception Handling

  • Attention Points:
    • All public methods must validate null parameters
    • Use specific exception types (ArgumentNullException, NotSupportedException)
  • Provide meaningful error messages
  • Do not catch and ignore exceptions silently
  • Implementation Details:
    • Parameter validation at method entry
    • Specific exception messages for debugging
    • Preserve stack traces where appropriate

Logging

  • Attention Points:
    • Use appropriate log levels (Debug, Information, Warning, Critical)
    • Include relevant context in log messages
    • Log important state changes
    • Do not log sensitive information
  • Implementation Details:
    • Use structured logging with placeholders
    • Log validation failures and rejections
    • Log significant events in risk management
    • Include calculation details in debug logs

7. Performance Considerations

Memory Management

  • Attention Points:
    • Minimize object allocations in hot paths
    • Use efficient data structures
    • Avoid unnecessary string concatenation
    • Consider pooling for frequently created objects
  • Implementation Details:
    • Use StringBuilder for dynamic strings
    • Prefer Dictionary over List for lookups
    • Reuse objects where safe to do so

Thread Safety

  • Attention Points:
    • All shared state must be properly synchronized
    • Avoid deadlocks in lock ordering
    • Minimize lock contention
    • Consider read-write locks for read-heavy scenarios
  • Implementation Details:
    • Use consistent lock ordering
    • Keep lock blocks small and focused
    • Consider concurrent collections where appropriate

8. Configuration and Extensibility

Configuration Validation

  • Attention Points:
    • Validate all configuration at startup
    • Provide clear error messages for invalid configurations
    • Document all configuration options
    • Handle missing optional configuration gracefully
  • Implementation Details:
    • Static validation methods in configuration classes
    • Early failure on invalid configuration
    • Sensible defaults for optional settings

Extension Points

  • Attention Points:
    • Design interfaces for future extension
    • Provide abstract base classes where appropriate
    • Document extension mechanisms
    • Maintain backward compatibility
  • Implementation Details:
    • Strategy interface allows for custom algorithms
    • Risk manager can be replaced with custom implementations
    • Position sizer supports multiple algorithms

Conclusion

This document highlights the critical areas that require careful attention during implementation. By focusing on these points, we can ensure a robust, maintainable, and high-quality SDK implementation that meets all specified requirements.