Skip to content

Commit a31f67f

Browse files
committed
example cleanup
1 parent 0c1f7a5 commit a31f67f

13 files changed

+218
-120
lines changed

examples/01_basic_client_connection_v3.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ async def main() -> bool:
6969
stats = suite.get_stats()
7070
print(f" Connected: {stats['connected']}")
7171
print(f" Instrument: {stats['instrument']}")
72-
print(f" Features: {stats['features']}")
72+
print(f" Features: {stats['components']}")
7373

7474
# Clean disconnect
7575
await suite.disconnect()

examples/02_order_management.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ async def main() -> bool:
245245
print(" (Will trigger if price reaches this level)")
246246

247247
if await wait_for_user_confirmation("Place stop order?"):
248-
stop_response = await order_manager.place_stop_order( # type: ignore[misc]
248+
stop_response = await order_manager.place_stop_order(
249249
contract_id=contract_id,
250250
side=0, # Buy
251251
size=1,
@@ -286,7 +286,7 @@ async def main() -> bool:
286286
print(" Risk/Reward: 1:2 ratio")
287287

288288
if await wait_for_user_confirmation("Place bracket order?"):
289-
bracket_response = await order_manager.place_bracket_order( # type: ignore[misc]
289+
bracket_response = await order_manager.place_bracket_order(
290290
contract_id=contract_id,
291291
side=0, # Buy
292292
size=1,
@@ -504,7 +504,7 @@ async def main() -> bool:
504504
f"Closing {side_text} position: {position.contractId} ({position.size} contracts)"
505505
)
506506

507-
response = await order_manager.close_position( # type: ignore[misc]
507+
response = await order_manager.close_position(
508508
position.contractId, method="market"
509509
)
510510

examples/03_position_management.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -137,17 +137,17 @@ async def display_risk_metrics(position_manager: "PositionManager") -> None:
137137
try:
138138
# Get risk metrics if available
139139
try:
140-
if hasattr(position_manager, "check_risk_limits"):
141-
risk_check = await position_manager.check_risk_limits()
140+
if hasattr(position_manager, "get_risk_metrics"):
141+
risk_check = await position_manager.get_risk_metrics()
142142
if risk_check and risk_check.get("within_limits"):
143143
print("✅ All positions within risk limits")
144144
else:
145145
print("❌ Risk limit violations detected")
146146
else:
147147
print("Risk limits check not available")
148148

149-
if hasattr(position_manager, "get_risk_summary"):
150-
risk_summary = await position_manager.get_risk_summary()
149+
if hasattr(position_manager, "get_risk_metrics"):
150+
risk_summary = await position_manager.get_risk_metrics()
151151
print("\nRisk Summary:")
152152
print(
153153
f" Total Exposure: ${risk_summary.get('total_exposure', 0):,.2f}"
@@ -218,9 +218,9 @@ async def monitor_positions(
218218
print(f" Total P&L: ${total_pnl:,.2f}")
219219

220220
# Get summary if available
221-
if hasattr(position_manager, "get_portfolio_summary"):
221+
if hasattr(position_manager, "get_portfolio_pnl"):
222222
try:
223-
summary = await position_manager.get_portfolio_summary()
223+
summary = await position_manager.get_portfolio_pnl()
224224
print(
225225
f" Win rate: {summary.get('win_rate', 0):.1%} ({summary.get('winning_trades', 0)}/{summary.get('total_trades', 0)})"
226226
)
@@ -330,8 +330,8 @@ async def main() -> bool:
330330
print("\n📊 Portfolio Statistics:")
331331
print("-" * 80)
332332
try:
333-
if hasattr(suite.positions, "get_portfolio_statistics"):
334-
stats = await suite.positions.get_portfolio_statistics()
333+
if hasattr(suite.positions, "get_portfolio_pnl"):
334+
stats = await suite.positions.get_portfolio_pnl()
335335
print(f" Total Trades: {stats.get('total_trades', 0)}")
336336
print(f" Winning Trades: {stats.get('winning_trades', 0)}")
337337
print(f" Average Win: ${stats.get('average_win', 0):,.2f}")
@@ -347,8 +347,8 @@ async def main() -> bool:
347347
print("\n📈 Performance Analytics:")
348348
print("-" * 80)
349349
try:
350-
if hasattr(suite.positions, "get_performance_analytics"):
351-
analytics = await suite.positions.get_performance_analytics()
350+
if hasattr(suite.positions, "get_portfolio_pnl"):
351+
analytics = await suite.positions.get_portfolio_pnl()
352352
print(f" Total P&L: ${analytics.get('total_pnl', 0):,.2f}")
353353
print(f" Max Drawdown: ${analytics.get('max_drawdown', 0):,.2f}")
354354
print(
@@ -419,8 +419,8 @@ async def main() -> bool:
419419
print("=" * 80)
420420

421421
try:
422-
if hasattr(suite.positions, "get_session_summary"):
423-
session_summary = await suite.positions.get_session_summary()
422+
if hasattr(suite.positions, "get_portfolio_pnl"):
423+
session_summary = await suite.positions.get_portfolio_pnl()
424424
print(f" Session Duration: {session_summary.get('duration', 'N/A')}")
425425
print(
426426
f" Positions Opened: {session_summary.get('positions_opened', 0)}"

examples/04_realtime_data.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,13 @@
3434
TradingSuite,
3535
setup_logging,
3636
)
37+
from project_x_py.types.protocols import RealtimeDataManagerProtocol
3738

3839
if TYPE_CHECKING:
3940
from project_x_py.realtime_data_manager import RealtimeDataManager
4041

4142

42-
async def display_current_prices(data_manager: "RealtimeDataManager"):
43+
async def display_current_prices(data_manager: "RealtimeDataManager") -> None:
4344
"""Display current prices across all timeframes asynchronously."""
4445
print("\n📊 Current Prices:")
4546

@@ -84,7 +85,7 @@ async def display_current_prices(data_manager: "RealtimeDataManager"):
8485
print(f" {timeframe:>6}: No data")
8586

8687

87-
async def display_memory_stats(data_manager):
88+
async def display_memory_stats(data_manager: "RealtimeDataManager") -> None:
8889
"""Display memory usage statistics asynchronously."""
8990
try:
9091
# get_memory_stats is synchronous in async data manager
@@ -106,7 +107,7 @@ async def display_memory_stats(data_manager):
106107
print(f" ❌ Memory stats error: {e}")
107108

108109

109-
async def display_system_statistics(data_manager):
110+
async def display_system_statistics(data_manager: "RealtimeDataManager") -> None:
110111
"""Display comprehensive system and validation statistics asynchronously."""
111112
try:
112113
# Use validation status instead of get_statistics (which doesn't exist)
@@ -138,7 +139,7 @@ async def display_system_statistics(data_manager):
138139
print(f" ❌ System stats error: {e}")
139140

140141

141-
async def demonstrate_historical_analysis(data_manager):
142+
async def demonstrate_historical_analysis(data_manager: "RealtimeDataManager") -> None:
142143
"""Demonstrate historical data analysis asynchronously."""
143144
print("\n📈 Historical Data Analysis:")
144145

@@ -158,7 +159,7 @@ async def demonstrate_historical_analysis(data_manager):
158159
if data is not None and not data.is_empty():
159160
# Calculate basic statistics
160161
avg_price = data["close"].mean()
161-
price_range = data["close"].max() - data["close"].min()
162+
price_range = float(data["close"].max()) - float(data["close"].min())
162163
total_volume = data["volume"].sum()
163164

164165
print(f" {tf} Analysis (last 100 bars):")
@@ -172,7 +173,7 @@ async def demonstrate_historical_analysis(data_manager):
172173
print(f" ❌ Analysis error: {e}")
173174

174175

175-
async def new_bar_callback(data):
176+
async def new_bar_callback(data: dict[str, Any]) -> None:
176177
"""Handle new bar creation asynchronously."""
177178
timestamp = datetime.now().strftime("%H:%M:%S")
178179
timeframe = data["timeframe"]
@@ -182,7 +183,7 @@ async def new_bar_callback(data):
182183
)
183184

184185

185-
async def main():
186+
async def main() -> bool:
186187
"""Main async real-time data streaming demonstration."""
187188

188189
# Setup logging
@@ -248,7 +249,7 @@ async def main():
248249
print("\n🔔 Registering optional event handlers for demonstration...")
249250
try:
250251
# Use the EventBus through TradingSuite
251-
suite.on(EventType.NEW_BAR, new_bar_callback)
252+
await suite.on(EventType.NEW_BAR, new_bar_callback)
252253
print("✅ Optional event handlers registered!")
253254
except Exception as e:
254255
print(f"⚠️ Event handler registration error: {e}")
@@ -266,19 +267,19 @@ async def main():
266267
print("=" * 60)
267268

268269
# Create concurrent monitoring tasks
269-
async def monitor_prices():
270+
async def monitor_prices() -> None:
270271
"""Monitor and display prices periodically."""
271272
while True:
272273
await asyncio.sleep(10) # Update every 10 seconds
273274
await display_current_prices(data_manager)
274275

275-
async def monitor_statistics():
276+
async def monitor_statistics() -> None:
276277
"""Monitor and display statistics periodically."""
277278
while True:
278279
await asyncio.sleep(30) # Update every 30 seconds
279280
await display_system_statistics(data_manager)
280281

281-
async def monitor_memory():
282+
async def monitor_memory() -> None:
282283
"""Monitor and display memory usage periodically."""
283284
while True:
284285
await asyncio.sleep(60) # Update every minute

examples/05_orderbook_analysis.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
from project_x_py.orderbook import OrderBook
4242

4343

44-
async def display_best_prices(orderbook):
44+
async def display_best_prices(orderbook: OrderBook) -> None:
4545
"""Display current best bid/ask prices."""
4646
best_prices = await orderbook.get_best_bid_ask()
4747
best_bid = best_prices.get("bid")
@@ -67,7 +67,7 @@ async def display_best_prices(orderbook):
6767
print(" No bid/ask available", flush=True)
6868

6969

70-
async def display_market_depth(orderbook):
70+
async def display_market_depth(orderbook: OrderBook) -> None:
7171
"""Display market depth on both sides."""
7272
# Get bid and ask levels separately
7373
bids_df = await orderbook.get_orderbook_bids(levels=5)
@@ -116,7 +116,7 @@ async def display_market_depth(orderbook):
116116
print("(Balanced ⚖️)", flush=True)
117117

118118

119-
async def display_trade_flow(orderbook):
119+
async def display_trade_flow(orderbook: OrderBook) -> None:
120120
"""Display recent trade flow analysis."""
121121
trades = await orderbook.get_recent_trades(count=10)
122122

@@ -153,7 +153,7 @@ async def display_trade_flow(orderbook):
153153
)
154154

155155

156-
async def display_market_microstructure(orderbook):
156+
async def display_market_microstructure(orderbook: OrderBook) -> None:
157157
"""Display market microstructure analysis."""
158158
# Use get_advanced_market_metrics instead
159159
try:
@@ -189,7 +189,7 @@ async def display_market_microstructure(orderbook):
189189
)
190190

191191

192-
async def display_iceberg_detection(orderbook):
192+
async def display_iceberg_detection(orderbook: OrderBook) -> None:
193193
"""Display potential iceberg orders."""
194194
# Use detect_iceberg_orders instead of detect_icebergs
195195
icebergs = await orderbook.detect_iceberg_orders()
@@ -215,7 +215,7 @@ async def display_iceberg_detection(orderbook):
215215
print(" No iceberg orders detected", flush=True)
216216

217217

218-
async def monitor_orderbook_realtime(orderbook: OrderBook, duration: int = 45):
218+
async def monitor_orderbook_realtime(orderbook: OrderBook, duration: int = 45) -> None:
219219
"""Monitor orderbook in real-time for specified duration."""
220220
print(f"\n🔄 Real-time Monitoring ({duration} seconds)...", flush=True)
221221
print("=" * 60, flush=True)
@@ -253,7 +253,7 @@ async def monitor_orderbook_realtime(orderbook: OrderBook, duration: int = 45):
253253
print("\n✅ Real-time monitoring completed", flush=True)
254254

255255

256-
async def demonstrate_comprehensive_methods(orderbook: OrderBook):
256+
async def demonstrate_comprehensive_methods(orderbook: OrderBook) -> None:
257257
"""Demonstrate all comprehensive orderbook methods after 2 minutes."""
258258
print("\n⏰ Waiting 2 minutes for data accumulation...", flush=True)
259259
print(
@@ -398,7 +398,7 @@ async def demonstrate_comprehensive_methods(orderbook: OrderBook):
398398
print(f" Error: {e}", flush=True)
399399

400400

401-
async def main():
401+
async def main() -> bool:
402402
"""Main async orderbook analysis demonstration."""
403403
logger = setup_logging(level="INFO")
404404
print("🚀 Async Level 2 Orderbook Analysis Example (v3.0.0)", flush=True)

0 commit comments

Comments
 (0)