Files
foxhunt/final_trading_engine_fix.py
jgrusewski c0be3ca530 🔧 Major compilation fixes across entire workspace - Significant progress achieved
## Summary of Compilation Fixes

### Core Infrastructure Improvements
- **Fixed import system**: Established canonical type imports from common::types
- **Resolved syntax errors**: Fixed malformed use statements with embedded comments
- **Import consolidation**: Eliminated duplicate and conflicting type imports
- **Type visibility**: Improved public/private type access patterns

### Major Areas Fixed

#### Trading Engine (trading_engine/)
-  Fixed syntax errors in types/basic.rs with clean re-exports
-  Resolved OrderSide/Side naming conflicts
-  Fixed type_registry.rs malformed imports
-  Consolidated canonical type imports from common::types
-  Fixed broker_client.rs duplicate OrderStatus imports
- 🔄 Remaining: 41 type visibility errors (down from 286+ errors)

#### Common Types (common/)
-  Established as single source of truth for all types
-  Clean type definitions with proper visibility
-  Consistent error handling patterns

#### Data Pipeline (data/)
-  Updated imports to use canonical common::types
-  Fixed provider trait implementations
-  Resolved database integration issues

#### ML Components (ml/)
-  Fixed model interface imports
-  Updated feature extraction systems
-  Resolved training pipeline dependencies

#### Risk Management (risk/)
-  Fixed safety module imports
-  Updated VaR calculator dependencies
-  Consolidated compliance types

#### Services
-  Trading Service: Fixed repository implementations
-  Backtesting Service: Updated strategy engines
-  TLI: Fixed dashboard and UI components

#### Test Infrastructure
-  Updated integration test imports
-  Fixed performance benchmark dependencies
-  Resolved mock implementations

### Technical Achievements

#### Import System Overhaul
- Established common::types as canonical source
- Eliminated circular dependencies
- Fixed visibility modifiers (pub use vs use)
- Resolved naming conflicts (Side → OrderSide)

#### Type System Cleanup
- Consolidated duplicate type definitions
- Fixed malformed syntax (comments in use statements)
- Standardized error handling patterns
- Improved module structure

#### Configuration Management
- Enhanced config crate integration
- Fixed database configuration patterns
- Improved hot-reload mechanisms

### Error Reduction Progress
- **Before**: 371+ compilation errors across workspace
- **After**: ~202 errors remaining (46% reduction achieved)
- **Major**: Fixed critical syntax errors preventing any compilation
- **Infrastructure**: Resolved fundamental import and type system issues

### Files Modified: 347
- Core types and infrastructure
- Service implementations
- Test suites and benchmarks
- Configuration systems
- Database integrations

### Next Steps
- Complete remaining type visibility fixes in trading_engine
- Finalize import resolution in remaining modules
- Validate cross-crate dependencies
- Run comprehensive test suite

This represents a major milestone in achieving zero compilation errors across
the entire Foxhunt HFT trading system workspace. The foundational type system
and import structure has been successfully established and standardized.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-27 20:56:22 +02:00

214 lines
6.8 KiB
Python

#!/usr/bin/env python3
"""
Final comprehensive fix for all trading_engine compilation issues
"""
import os
import re
def fix_all_trading_engine_issues():
"""Fix all remaining compilation issues in trading_engine"""
# 1. Fix the basic.rs file with all needed imports
basic_rs_path = "/home/jgrusewski/Work/foxhunt/trading_engine/src/types/basic.rs"
basic_content = """//! Basic types - Clean imports from canonical common::types
//!
//! This module provides clean re-exports of types from the canonical common::types module.
//! All type definitions have been moved to common::types to establish a single source of truth.
#![deny(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::unimplemented,
clippy::unreachable
)]
#![warn(clippy::pedantic, clippy::nursery, clippy::perf)]
// ============================================================================
// CANONICAL TYPE IMPORTS - Single Source of Truth from common::types
// ============================================================================
// Re-export all canonical types from common crate
// Core Trading Types
pub use common::types::{
Order, OrderId, OrderSide, OrderStatus, OrderType, OrderRef,
Price, Quantity, Volume, Symbol, Currency, TimeInForce, BrokerType,
Decimal, // Add Decimal
};
// Market Data Types
pub use common::types::{
MarketTick, TradingSignal, QuoteEvent, TradeEvent, BarEvent, Level2Update,
PriceLevel, MarketStatus, ConnectionEvent, ConnectionStatus, ErrorEvent,
OrderBookEvent, DataType, Subscription, MarketDataEvent,
};
pub use common::trading::{TickType, MarketRegime};
// Identifiers
pub use common::types::{
TradeId, EventId, FillId, AggregateId, AssetId, ClientId, AccountId,
};
// Infrastructure Types
pub use common::types::{
ServiceId, ServiceStatus, ConfigVersion, RequestId, Timestamp,
ConnectionInfo, ResourceLimits,
};
// Time Types
pub use common::types::{HftTimestamp, GenericTimestamp};
// Financial Types
pub use common::types::{Position, Execution, Money};
// Aggregate Types
pub use common::types::Aggregate;
// Import error type from crate for backward compatibility
use crate::types::errors::FoxhuntError;
// ============================================================================
// COMPATIBILITY BRIDGE FUNCTIONS
// ============================================================================
/// Bridge functions for existing code that expects TradingError static methods
/// These maintain backward compatibility while using the unified error system
#[derive(Debug)]
pub struct TradingError;
impl TradingError {
/// Create an invalid price error
#[must_use]
pub fn invalid_price(value: f64, message: &str) -> FoxhuntError {
FoxhuntError::InvalidPrice {
value: value.to_string(),
reason: message.to_owned(),
symbol: None,
}
}
/// Create an invalid quantity error
#[must_use]
pub fn invalid_quantity(value: f64, message: &str) -> FoxhuntError {
FoxhuntError::InvalidQuantity {
value: value.to_string(),
reason: message.to_owned(),
symbol: None,
}
}
/// Create a division by zero error
#[must_use]
pub fn division_by_zero(message: &str) -> FoxhuntError {
FoxhuntError::DivisionByZero {
operation: message.to_owned(),
context: None,
}
}
}
// ============================================================================
// TYPE ALIASES FOR BACKWARD COMPATIBILITY
// ============================================================================
// IMPORTANT: These are clean re-exports, not deprecated aliases
// They provide stable API for existing code while using canonical types
/// DateTime alias for convenience
pub use chrono::{DateTime, Utc};
/// UUID for unique identifiers
pub use uuid::Uuid;
// ============================================================================
// PRELUDE FOR COMMON IMPORTS
// ============================================================================
/// Common types and traits that are frequently used together
pub mod prelude {
pub use super::{
Order, OrderId, OrderSide, OrderStatus, OrderType,
Price, Quantity, Volume, Symbol, Currency, TimeInForce,
MarketTick, TickType, MarketRegime, TradingSignal,
TradeId, EventId, AccountId, HftTimestamp, Decimal,
};
pub use chrono::{DateTime, Utc};
pub use rust_decimal::Decimal as RustDecimal;
pub use uuid::Uuid;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_canonical_imports() {
// Test that canonical types are properly imported
let price = Price::from_f64(100.0).expect("Valid price");
assert!((price.to_f64() - 100.0).abs() < f64::EPSILON);
let qty = Quantity::from_f64(50.0).expect("Valid quantity");
assert!((qty.to_f64() - 50.0).abs() < f64::EPSILON);
let symbol = Symbol::from("AAPL");
assert_eq!(symbol.as_str(), "AAPL");
let order_id = OrderId::new();
assert!(order_id.value() > 0);
}
#[test]
fn test_compatibility_bridges() {
// Test that compatibility bridges work
let error = TradingError::invalid_price(0.0, "Price cannot be zero");
match error {
FoxhuntError::InvalidPrice { value, reason, .. } => {
assert_eq!(value, "0");
assert_eq!(reason, "Price cannot be zero");
}
_ => panic!("Wrong error type"),
}
}
}
"""
with open(basic_rs_path, 'w') as f:
f.write(basic_content)
print(f"Updated {basic_rs_path}")
# 2. Fix any remaining import issues in the trading_operations files
# Look for files that need import fixes
trading_ops_files = [
"/home/jgrusewski/Work/foxhunt/trading_engine/src/trading_operations.rs",
"/home/jgrusewski/Work/foxhunt/trading_engine/src/trading/account_manager.rs",
]
for file_path in trading_ops_files:
if os.path.exists(file_path):
with open(file_path, 'r') as f:
content = f.read()
# Fix common import issues
replacements = [
(r'use crate::trading_operations::\{([^}]*?)OrderSide([^}]*?)\}',
lambda m: f'use crate::trading_operations::{{{m.group(1)}{m.group(2)}}}'),
(r'use common::types::OrderSide;', ''), # Remove duplicate imports
]
for pattern, replacement in replacements:
if callable(replacement):
content = re.sub(pattern, replacement, content)
else:
content = re.sub(pattern, replacement, content)
with open(file_path, 'w') as f:
f.write(content)
print(f"Updated {file_path}")
if __name__ == "__main__":
fix_all_trading_engine_issues()