271 lines
8.9 KiB
Python
Executable File
271 lines
8.9 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""
|
||
Auto-Trading Example Usage
|
||
Demonstrates how to use the auto-trading system
|
||
"""
|
||
|
||
import asyncio
|
||
import aiohttp
|
||
from datetime import datetime
|
||
|
||
|
||
BASE_URL = "http://localhost:8003"
|
||
|
||
|
||
async def configure_auto_trading():
|
||
"""Step 1: Configure auto-trading for a user"""
|
||
print("\n" + "="*60)
|
||
print("STEP 1: Configuring Auto-Trading")
|
||
print("="*60)
|
||
|
||
config = {
|
||
"config": {
|
||
"user_id": "demo_user",
|
||
"enabled": False, # Start disabled for safety
|
||
"symbols": ["BTC/USD", "ETH/USD"],
|
||
"max_risk_percent": 1.0,
|
||
"min_confidence": 0.75,
|
||
"paper_trading": True,
|
||
"require_confirmation": True,
|
||
"max_open_positions": 3,
|
||
"check_interval_minutes": 5
|
||
}
|
||
}
|
||
|
||
async with aiohttp.ClientSession() as session:
|
||
async with session.post(
|
||
f"{BASE_URL}/api/v1/auto-trade/config",
|
||
json=config
|
||
) as response:
|
||
if response.status == 200:
|
||
data = await response.json()
|
||
print("\n Configuration saved successfully!")
|
||
print(f"User ID: {data['user_id']}")
|
||
print(f"Enabled: {data['enabled']}")
|
||
print(f"Monitored Symbols: {', '.join(data['monitored_symbols'])}")
|
||
return data
|
||
else:
|
||
error = await response.text()
|
||
print(f"\nL Error: {error}")
|
||
return None
|
||
|
||
|
||
async def enable_auto_trading(user_id: str):
|
||
"""Step 2: Enable auto-trading"""
|
||
print("\n" + "="*60)
|
||
print("STEP 2: Enabling Auto-Trading")
|
||
print("="*60)
|
||
|
||
async with aiohttp.ClientSession() as session:
|
||
async with session.post(
|
||
f"{BASE_URL}/api/v1/auto-trade/enable/{user_id}"
|
||
) as response:
|
||
if response.status == 200:
|
||
data = await response.json()
|
||
print("\n Auto-trading enabled!")
|
||
print(f"Message: {data['message']}")
|
||
print(f"Active Since: {data['status']['active_since']}")
|
||
return True
|
||
else:
|
||
error = await response.text()
|
||
print(f"\nL Error: {error}")
|
||
return False
|
||
|
||
|
||
async def check_status(user_id: str):
|
||
"""Step 3: Check auto-trading status"""
|
||
print("\n" + "="*60)
|
||
print("STEP 3: Checking Status")
|
||
print("="*60)
|
||
|
||
async with aiohttp.ClientSession() as session:
|
||
async with session.get(
|
||
f"{BASE_URL}/api/v1/auto-trade/status/{user_id}"
|
||
) as response:
|
||
if response.status == 200:
|
||
data = await response.json()
|
||
print("\n=<3D> Current Status:")
|
||
print(f" Enabled: {data['enabled']}")
|
||
print(f" Total Decisions: {data['total_decisions']}")
|
||
print(f" Successful Trades: {data['successful_trades']}")
|
||
print(f" Pending Confirmations: {data['pending_confirmations']}")
|
||
print(f" Last Check: {data['last_check']}")
|
||
print(f" Monitored Symbols: {', '.join(data['monitored_symbols'])}")
|
||
return data
|
||
else:
|
||
error = await response.text()
|
||
print(f"\nL Error: {error}")
|
||
return None
|
||
|
||
|
||
async def wait_for_decisions(user_id: str, wait_time: int = 10):
|
||
"""Step 4: Wait and check for decisions"""
|
||
print("\n" + "="*60)
|
||
print(f"STEP 4: Waiting {wait_time}s for Auto-Trading Decisions")
|
||
print("="*60)
|
||
print("\n<EFBFBD> Monitoring system is analyzing markets...")
|
||
print(" (In production, this would check every 5 minutes)")
|
||
|
||
await asyncio.sleep(wait_time)
|
||
|
||
async with aiohttp.ClientSession() as session:
|
||
async with session.get(
|
||
f"{BASE_URL}/api/v1/auto-trade/pending/{user_id}"
|
||
) as response:
|
||
if response.status == 200:
|
||
decisions = await response.json()
|
||
print(f"\n=<3D> Found {len(decisions)} pending decision(s)")
|
||
|
||
for i, decision in enumerate(decisions, 1):
|
||
d = decision['decision']
|
||
print(f"\n Decision #{i}:")
|
||
print(f" Symbol: {d['symbol']}")
|
||
print(f" Action: {d['action']}")
|
||
print(f" Confidence: {d['confidence']:.2%}")
|
||
print(f" Reasoning: {d['reasoning']}")
|
||
print(f" Entry: ${d['entry_price']:.2f}")
|
||
print(f" Take Profit: ${d['take_profit']:.2f}")
|
||
print(f" Stop Loss: ${d['stop_loss']:.2f}")
|
||
print(f" Position Size: {d['position_size']}")
|
||
print(f" AMD Phase: {d['amd_phase']}")
|
||
|
||
return decisions
|
||
else:
|
||
error = await response.text()
|
||
print(f"\nL Error: {error}")
|
||
return []
|
||
|
||
|
||
async def view_all_decisions(user_id: str):
|
||
"""Step 5: View all decision history"""
|
||
print("\n" + "="*60)
|
||
print("STEP 5: Viewing Decision History")
|
||
print("="*60)
|
||
|
||
async with aiohttp.ClientSession() as session:
|
||
async with session.get(
|
||
f"{BASE_URL}/api/v1/auto-trade/decisions/{user_id}?limit=10"
|
||
) as response:
|
||
if response.status == 200:
|
||
logs = await response.json()
|
||
print(f"\n=<3D> Decision History ({len(logs)} total):")
|
||
|
||
for i, log in enumerate(logs, 1):
|
||
d = log['decision']
|
||
status = " Executed" if log['executed'] else "<EFBFBD> Pending"
|
||
print(f"\n {status} - {log['created_at']}")
|
||
print(f" {d['action']} {d['symbol']} @ ${d['entry_price']:.2f}")
|
||
print(f" Confidence: {d['confidence']:.2%}")
|
||
|
||
return logs
|
||
else:
|
||
error = await response.text()
|
||
print(f"\nL Error: {error}")
|
||
return []
|
||
|
||
|
||
async def confirm_decision(user_id: str, log_id: str):
|
||
"""Step 6: Confirm and execute a decision"""
|
||
print("\n" + "="*60)
|
||
print("STEP 6: Confirming Decision")
|
||
print("="*60)
|
||
|
||
payload = {"log_id": log_id}
|
||
|
||
async with aiohttp.ClientSession() as session:
|
||
async with session.post(
|
||
f"{BASE_URL}/api/v1/auto-trade/decisions/{user_id}/confirm",
|
||
json=payload
|
||
) as response:
|
||
if response.status == 200:
|
||
data = await response.json()
|
||
print(f"\n {data['message']}")
|
||
print(f" Log ID: {data['log_id']}")
|
||
return True
|
||
else:
|
||
error = await response.text()
|
||
print(f"\nL Error: {error}")
|
||
return False
|
||
|
||
|
||
async def disable_auto_trading(user_id: str):
|
||
"""Step 7: Disable auto-trading"""
|
||
print("\n" + "="*60)
|
||
print("STEP 7: Disabling Auto-Trading")
|
||
print("="*60)
|
||
|
||
async with aiohttp.ClientSession() as session:
|
||
async with session.post(
|
||
f"{BASE_URL}/api/v1/auto-trade/disable/{user_id}"
|
||
) as response:
|
||
if response.status == 200:
|
||
data = await response.json()
|
||
print(f"\n {data['message']}")
|
||
return True
|
||
else:
|
||
error = await response.text()
|
||
print(f"\nL Error: {error}")
|
||
return False
|
||
|
||
|
||
async def main():
|
||
"""Main example flow"""
|
||
print("\n" + "="*60)
|
||
print("AUTO-TRADING SYSTEM DEMO")
|
||
print("OrbiQuant IA Trading Platform")
|
||
print("="*60)
|
||
|
||
user_id = "demo_user"
|
||
|
||
try:
|
||
# Step 1: Configure
|
||
status = await configure_auto_trading()
|
||
if not status:
|
||
return
|
||
|
||
# Step 2: Enable
|
||
enabled = await enable_auto_trading(user_id)
|
||
if not enabled:
|
||
return
|
||
|
||
# Step 3: Check initial status
|
||
await check_status(user_id)
|
||
|
||
# Step 4: Wait for decisions (simulated)
|
||
# In production, the monitoring loop would run continuously
|
||
pending = await wait_for_decisions(user_id, wait_time=5)
|
||
|
||
# Step 5: View decision history
|
||
await view_all_decisions(user_id)
|
||
|
||
# Step 6: Confirm a decision (if any pending)
|
||
if pending and len(pending) > 0:
|
||
first_decision = pending[0]
|
||
await confirm_decision(user_id, first_decision['id'])
|
||
|
||
# Check status after execution
|
||
await check_status(user_id)
|
||
|
||
# Step 7: Disable
|
||
await disable_auto_trading(user_id)
|
||
|
||
# Final status check
|
||
await check_status(user_id)
|
||
|
||
print("\n" + "="*60)
|
||
print("DEMO COMPLETED")
|
||
print("="*60)
|
||
|
||
except Exception as e:
|
||
print(f"\nL Error during demo: {e}")
|
||
import traceback
|
||
traceback.print_exc()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
print("\n=<3D> Starting Auto-Trading Demo...")
|
||
print(" Make sure the LLM Agent service is running on port 8003")
|
||
print(" Start with: python -m src.main\n")
|
||
|
||
asyncio.run(main())
|