Files
foxhunt/data/examples/order_submission.rs
jgrusewski d7697823cb Wave 139: Regime detection fixes - 13/19 tests passing (68.4%)
**Agent Execution Summary (10+ parallel agents):**
- Agent 180: Fixed trend detection feature indexing for 6-feature simplified mode
- Agent 182: Fixed volume test to read correct feature index (5 instead of 0)
- Agent 183: Fixed crisis confidence calculation (added to agreement check, increased bonus 0.25→0.30)
- Agent 187: Eliminated all 55 compilation warnings → 0 warnings
- Agent 188: Implemented mode-aware feature extraction (simplified vs full)
- Agent 190: Fixed 4 blocking compilation errors (Cargo.toml + type errors in examples)

**Key Production Fixes:**
1. Crisis detection confidence boost (lines 4541, 4573 in mod.rs)
2. Mode-aware feature extraction (lines 776-857 in mod.rs)
3. Trend detection indexing for 6-feature mode (lines 4476-4501 in mod.rs)
4. Volume test index correction (line 566 in regime_transition_tests.rs)

**Test Results:**
- Workspace: 198/206 tests (96.1%)
- Regime tests: 13/19 tests (68.4%)
- Compilation: Clean (0 errors, 0 warnings)

**Files Modified:**
- adaptive-strategy/src/regime/mod.rs (crisis confidence, mode-aware extraction, trend indexing)
- adaptive-strategy/tests/regime_transition_tests.rs (volume test fix, warning suppressions)
- adaptive-strategy/Cargo.toml (lint configuration fix)
- data/examples/*.rs (type error fixes)

**Remaining Work:**
6 test failures to fix for 100% target:
- test_regime_detection_volatile_to_stable
- test_regime_detection_trending_to_ranging
- test_volume_regime_thin_to_thick_liquidity
- test_volatility_regime_low_to_high_to_low
- test_extreme_market_conditions
- test_feature_extraction_with_regime_change
2025-10-11 22:11:21 +02:00

244 lines
7.6 KiB
Rust

//! Order Submission Example
//!
//! This example demonstrates how to submit different types of orders
//! to Interactive Brokers TWS.
//!
//! Usage:
//! cargo run --example order_submission
//!
//! Prerequisites:
//! - TWS or IB Gateway running with API enabled
//! - Paper trading account recommended for testing
#![allow(unused_crate_dependencies)]
use common::{Order, OrderId, OrderSide, OrderStatus, OrderType, Price, Quantity, Symbol, TimeInForce};
use data::brokers::interactive_brokers::{IBConfig, InteractiveBrokersAdapter};
use data::brokers::{BrokerClient, common::TradingOrder};
use std::time::Duration;
use tokio::time::sleep;
use tracing::{error, info, warn};
// use trading_engine::prelude::*; // REMOVED - prelude does not exist
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Initialize logging
tracing_subscriber::fmt::init();
info!("=== Interactive Brokers Order Submission Example ===");
// Create adapter and connect
let config = IBConfig {
host: "127.0.0.1".to_string(),
port: 7497, // Paper trading TWS port
client_id: 1001,
account_id: "DU123456".to_string(),
connection_timeout: 30,
max_reconnect_attempts: 3,
heartbeat_interval: 60,
request_timeout: 10,
};
let mut adapter = InteractiveBrokersAdapter::new(config);
info!("Connecting to TWS...");
adapter.connect().await?;
if !adapter.is_connected() {
error!("Failed to establish connection");
return Err("Connection failed".into());
}
info!("✅ Connected to TWS");
// Start message processing to handle order responses
let adapter_arc = std::sync::Arc::new(adapter);
let process_handle = {
let adapter = adapter_arc.clone();
tokio::spawn(async move {
if let Err(e) = adapter.process_messages().await {
error!("Message processing error: {}", e);
}
})
};
// Wait for connection to stabilize
sleep(Duration::from_secs(2)).await;
// Example 1: Market Order
info!("\n--- Example 1: Market Order ---");
let mut market_order = Order::new(
Symbol::from("AAPL"),
OrderSide::Buy,
Quantity::new(10.0)?,
None, // price
OrderType::Market,
);
market_order.time_in_force = TimeInForce::Day;
info!("Submitting market order: Buy 10 AAPL at market");
let trading_order = TradingOrder::from_common_order(&market_order)?;
match adapter_arc.submit_order(&trading_order).await {
Ok(tws_order_id) => {
info!("✅ Market order submitted, TWS ID: {}", tws_order_id);
// Wait for order processing
sleep(Duration::from_secs(3)).await;
// Cancel the order (for demo purposes)
info!("Cancelling market order");
adapter_arc.cancel_order(&tws_order_id).await?;
info!("✅ Market order cancelled");
},
Err(e) => {
error!("❌ Failed to submit market order: {}", e);
},
}
sleep(Duration::from_secs(2)).await;
// Example 2: Limit Order
info!("\n--- Example 2: Limit Order ---");
let mut limit_order = Order::new(
Symbol::from("GOOGL"),
OrderSide::Sell,
Quantity::new(5.0)?,
Some(Price::new(2500.00)?), // Limit price
OrderType::Limit,
);
limit_order.time_in_force = TimeInForce::GoodTillCancel;
info!("Submitting limit order: Sell 5 GOOGL at $2500.00");
let trading_order = TradingOrder::from_common_order(&limit_order)?;
match adapter_arc.submit_order(&trading_order).await {
Ok(tws_order_id) => {
info!("✅ Limit order submitted, TWS ID: {}", tws_order_id);
// Wait for order processing
sleep(Duration::from_secs(3)).await;
// Cancel the order
info!("Cancelling limit order");
adapter_arc.cancel_order(&tws_order_id).await?;
info!("✅ Limit order cancelled");
},
Err(e) => {
error!("❌ Failed to submit limit order: {}", e);
},
}
sleep(Duration::from_secs(2)).await;
// Example 3: Stop Order
info!("\n--- Example 3: Stop Order ---");
let mut stop_order = Order::new(
Symbol::from("MSFT"),
OrderSide::Buy,
Quantity::new(20.0)?,
Some(Price::new(350.00)?), // price
OrderType::Stop,
);
stop_order.stop_price = Some(Price::new(350.00)?);
stop_order.time_in_force = TimeInForce::Day;
info!("Submitting stop order: Buy 20 MSFT stop at $350.00");
let trading_order = TradingOrder::from_common_order(&stop_order)?;
match adapter_arc.submit_order(&trading_order).await {
Ok(tws_order_id) => {
info!("✅ Stop order submitted, TWS ID: {}", tws_order_id);
// Wait for order processing
sleep(Duration::from_secs(3)).await;
// Cancel the order
info!("Cancelling stop order");
adapter_arc.cancel_order(&tws_order_id).await?;
info!("✅ Stop order cancelled");
},
Err(e) => {
error!("❌ Failed to submit stop order: {}", e);
},
}
sleep(Duration::from_secs(2)).await;
// Example 4: Multiple Orders
info!("\n--- Example 4: Multiple Orders ---");
let mut order1 = Order::new(
Symbol::from("TSLA"),
OrderSide::Buy,
Quantity::new(1.0)?,
Some(Price::new(200.00)?),
OrderType::Limit,
);
order1.time_in_force = TimeInForce::Day;
let mut order2 = Order::new(
Symbol::from("NVDA"),
OrderSide::Sell,
Quantity::new(2.0)?,
Some(Price::new(800.00)?),
OrderType::Limit,
);
order2.time_in_force = TimeInForce::Day;
let orders = vec![order1, order2];
let mut submitted_orders = Vec::new();
for (i, order) in orders.into_iter().enumerate() {
info!(
"Submitting order {}: {} {} {} @ ${:.2}",
i + 1,
match order.side {
OrderSide::Buy => "Buy",
OrderSide::Sell => "Sell",
},
order.quantity.to_f64(),
order.symbol.to_string(),
order.price.as_ref().unwrap().to_f64()
);
let trading_order = TradingOrder::from_common_order(&order)?;
match adapter_arc.submit_order(&trading_order).await {
Ok(tws_order_id) => {
info!("✅ Order {} submitted, TWS ID: {}", i + 1, tws_order_id);
submitted_orders.push(tws_order_id);
},
Err(e) => {
error!("❌ Failed to submit order {}: {}", i + 1, e);
},
}
// Small delay between orders
sleep(Duration::from_millis(500)).await;
}
// Wait for order processing
info!("Waiting for order processing...");
sleep(Duration::from_secs(5)).await;
// Cancel all submitted orders
info!("Cancelling all submitted orders...");
for (i, tws_order_id) in submitted_orders.into_iter().enumerate() {
match adapter_arc.cancel_order(&tws_order_id).await {
Ok(()) => {
info!("✅ Cancelled order {}", i + 1);
},
Err(e) => {
warn!("⚠️ Failed to cancel order {}: {}", i + 1, e);
},
}
}
// Stop message processing
info!("Stopping message processing...");
process_handle.abort();
// Disconnect
let mut adapter_mut =
std::sync::Arc::try_unwrap(adapter_arc).map_err(|_| "Failed to unwrap adapter")?;
adapter_mut.disconnect().await?;
info!("=== Order submission example completed ===");
Ok(())
}