Skip to content

Commit e7ded77

Browse files
TexasCodingclaude
andcommitted
feat(examples): replace old examples with comprehensive working SDK demos
Replace outdated and broken example files with 7 comprehensive, fully working examples that demonstrate all major ProjectX Python SDK features using MNQ micro contracts for safe testing. ## New Examples Added: - 01_basic_client_connection.py: Authentication and account verification - 02_order_management.py: Comprehensive order placement and management - 03_position_management.py: Position tracking and risk management - 04_realtime_data.py: Multi-timeframe real-time data streaming - 05_orderbook_analysis.py: Level 2 orderbook and market depth analysis - 06_multi_timeframe_strategy.py: Complete algorithmic trading strategy - 07_technical_indicators.py: Technical analysis with all indicators - README.md: Comprehensive documentation and usage guide ## Key Features: ✅ All examples use MNQ micro contracts for minimal risk ✅ Robust market data fallback systems for closed markets ✅ Proper EOF handling for piped input scenarios ✅ Real order placement with safety confirmations ✅ Multi-timeframe analysis and real-time capabilities ✅ Professional error handling and logging ✅ Comprehensive technical indicator demonstrations ✅ Risk management and position sizing examples ## Removed Files: - Cleaned up 14 old/broken example files - Removed outdated demo scripts with issues - Consolidated into professional, working examples ## Technical Improvements: - Fixed import statements (create_data_manager vs create_realtime_data_manager) - Added proper realtime client initialization patterns - Fixed method signatures for P&L calculations - Implemented market data fallback for closed markets - Added safety checks for order placement - Enhanced error handling throughout 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 8170bee commit e7ded77

22 files changed

+3601
-4621
lines changed
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Basic Client Connection and Authentication Example
4+
5+
Shows how to connect to ProjectX, authenticate, and verify account access.
6+
This is the foundation for all other examples.
7+
8+
Usage:
9+
Run with: uv run examples/01_basic_client_connection.py
10+
Or use test.sh which sets environment variables: ./test.sh
11+
12+
Author: TexasCoding
13+
Date: July 2025
14+
"""
15+
16+
from project_x_py import ProjectX, setup_logging
17+
18+
19+
def main():
20+
"""Demonstrate basic client connection and account verification."""
21+
logger = setup_logging(level="INFO")
22+
logger.info("🚀 Starting Basic Client Connection Example")
23+
24+
try:
25+
# Create client using environment variables
26+
# This uses PROJECT_X_API_KEY, PROJECT_X_USERNAME, PROJECT_X_ACCOUNT_NAME
27+
print("🔑 Creating ProjectX client from environment...")
28+
client = ProjectX.from_env()
29+
print("✅ Client created successfully!")
30+
31+
# Get account information
32+
print("\n📊 Getting account information...")
33+
account = client.get_account_info()
34+
35+
if not account:
36+
print("❌ No account information available")
37+
return False
38+
39+
print("✅ Account Information:")
40+
print(f" Account ID: {account.id}")
41+
print(f" Account Name: {account.name}")
42+
print(f" Balance: ${account.balance:,.2f}")
43+
print(f" Trading Enabled: {account.canTrade}")
44+
print(f" Simulated Account: {account.simulated}")
45+
46+
# Verify trading capability
47+
if not account.canTrade:
48+
print("⚠️ Warning: Trading is not enabled on this account")
49+
50+
if account.simulated:
51+
print("✅ This is a simulated account - safe for testing")
52+
else:
53+
print("⚠️ This is a LIVE account - be careful with real money!")
54+
55+
# Test JWT token generation (needed for real-time features)
56+
print("\n🔐 Testing JWT token generation...")
57+
try:
58+
jwt_token = client.get_session_token()
59+
if jwt_token:
60+
print("✅ JWT token generated successfully")
61+
print(f" Token length: {len(jwt_token)} characters")
62+
else:
63+
print("❌ Failed to generate JWT token")
64+
except Exception as e:
65+
print(f"❌ JWT token error: {e}")
66+
67+
# Search for MNQ instrument (our testing instrument)
68+
print("\n🔍 Searching for MNQ (Micro E-mini NASDAQ) instrument...")
69+
instruments = client.search_instruments("MNQ")
70+
71+
if instruments:
72+
print(f"✅ Found {len(instruments)} MNQ instruments:")
73+
for i, inst in enumerate(instruments[:3]): # Show first 3
74+
print(f" {i + 1}. {inst.name}")
75+
print(f" ID: {inst.id}")
76+
print(f" Description: {inst.description}")
77+
print(f" Tick Size: ${inst.tickSize}")
78+
print(f" Tick Value: ${inst.tickValue}")
79+
else:
80+
print("❌ No MNQ instruments found")
81+
82+
# Get specific MNQ instrument for trading
83+
print("\n📈 Getting current MNQ contract...")
84+
mnq_instrument = client.get_instrument("MNQ")
85+
86+
if mnq_instrument:
87+
print("✅ Current MNQ Contract:")
88+
print(f" Contract ID: {mnq_instrument.id}")
89+
print(f" Name: {mnq_instrument.name}")
90+
print(f" Description: {mnq_instrument.description}")
91+
print(f" Minimum Tick: ${mnq_instrument.tickSize}")
92+
print(f" Tick Value: ${mnq_instrument.tickValue}")
93+
else:
94+
print("❌ Could not get MNQ instrument")
95+
96+
# Test basic market data access
97+
print("\n📊 Testing market data access...")
98+
try:
99+
# Get recent data with different intervals to find what works
100+
for interval in [15, 5, 1]: # Try 15-min, 5-min, 1-min
101+
data = client.get_data("MNQ", days=1, interval=interval)
102+
103+
if data is not None and not data.is_empty():
104+
print(
105+
f"✅ Retrieved {len(data)} bars of {interval}-minute MNQ data"
106+
)
107+
108+
# Show the most recent bar
109+
latest_bar = data.tail(1)
110+
for row in latest_bar.iter_rows(named=True):
111+
print(f" Latest {interval}-min Bar:")
112+
print(f" Time: {row['timestamp']}")
113+
print(f" Open: ${row['open']:.2f}")
114+
print(f" High: ${row['high']:.2f}")
115+
print(f" Low: ${row['low']:.2f}")
116+
print(f" Close: ${row['close']:.2f}")
117+
print(f" Volume: {row['volume']:,}")
118+
break # Stop after first successful data retrieval
119+
else:
120+
# If no interval worked, try with different days
121+
for days in [2, 5, 7]:
122+
data = client.get_data("MNQ", days=days, interval=15)
123+
if data is not None and not data.is_empty():
124+
print(
125+
f"✅ Retrieved {len(data)} bars of 15-minute MNQ data ({days} days)"
126+
)
127+
latest_bar = data.tail(1)
128+
for row in latest_bar.iter_rows(named=True):
129+
print(
130+
f" Latest Bar: ${row['close']:.2f} @ {row['timestamp']}"
131+
)
132+
break
133+
else:
134+
print("❌ No market data available (may be outside market hours)")
135+
print(
136+
" Note: Historical data availability depends on market hours and trading sessions"
137+
)
138+
139+
except Exception as e:
140+
print(f"❌ Market data error: {e}")
141+
142+
# Check current positions and orders
143+
print("\n💼 Checking current positions...")
144+
try:
145+
positions = client.search_open_positions()
146+
if positions:
147+
print(f"✅ Found {len(positions)} open positions:")
148+
for pos in positions:
149+
direction = "LONG" if pos.type == 1 else "SHORT"
150+
print(
151+
f" {direction} {pos.size} {pos.contractId} @ ${pos.averagePrice:.2f}"
152+
)
153+
else:
154+
print("📝 No open positions")
155+
except Exception as e:
156+
print(f"❌ Position check error: {e}")
157+
158+
print("\n📋 Order Management Information:")
159+
print(" i Order management requires the OrderManager component")
160+
print(
161+
" Example: order_manager = create_order_manager(client, realtime_client)"
162+
)
163+
print(" See examples/02_order_management.py for complete order functionality")
164+
165+
print("\n✅ Basic client connection example completed successfully!")
166+
print("\n📝 Next Steps:")
167+
print(" - Try examples/02_order_management.py for order placement")
168+
print(" - Try examples/03_position_management.py for position tracking")
169+
print(" - Try examples/04_realtime_data.py for real-time data feeds")
170+
171+
return True
172+
173+
except Exception as e:
174+
logger.error(f"❌ Example failed: {e}")
175+
print(f"❌ Error: {e}")
176+
return False
177+
178+
179+
if __name__ == "__main__":
180+
success = main()
181+
exit(0 if success else 1)

0 commit comments

Comments
 (0)