Trading_server / deploy.py
DakshGoyal1506's picture
Upload 20 files
f1331a5 verified
Raw History Blame Contribute Delete
8.34 kB
#!/usr/bin/env python3
"""
Deployment helper script for AI Trading Simulation
Helps test and deploy the application locally and to Hugging Face Spaces
"""
import os
import sys
import subprocess
import time
import signal
from pathlib import Path
def check_requirements():
"""Check if all required files exist"""
required_files = [
"app_simple.py",
"requirements.txt",
"README.md",
"util.py",
"accounts.py",
"database.py",
"trading_floor.py"
]
missing = []
for file in required_files:
if not Path(file).exists():
missing.append(file)
if missing:
print(f"❌ Missing required files: {missing}")
return False
print("βœ… All required files present")
return True
def install_dependencies():
"""Install Python dependencies"""
print("πŸ“¦ Installing dependencies...")
try:
subprocess.run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"],
check=True, capture_output=True, text=True)
print("βœ… Dependencies installed successfully")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Failed to install dependencies: {e.stderr}")
return False
def check_env_vars():
"""Check environment variables setup"""
print("πŸ”§ Checking environment variables...")
# Load .env if it exists
env_file = Path(".env")
if env_file.exists():
from dotenv import load_dotenv
load_dotenv()
print("βœ… .env file loaded")
else:
print("⚠️ No .env file found - using system environment variables")
# Check for at least one AI API key
ai_keys = ["OPENAI_API_KEY", "DEEPSEEK_API_KEY", "GOOGLE_API_KEY", "GROK_API_KEY", "OPENROUTER_API_KEY"]
has_ai_key = any(os.getenv(key) for key in ai_keys)
if has_ai_key:
print("βœ… At least one AI API key configured")
else:
print("⚠️ No AI API keys found - will run in demo mode")
polygon_key = os.getenv("POLYGON_API_KEY")
if polygon_key:
print("βœ… Polygon API key configured")
else:
print("⚠️ No Polygon API key - will use mock market data")
return True
def test_simple_app():
"""Test the simple app version"""
print("πŸ§ͺ Testing simple app...")
try:
# Import test
import app_simple
print("βœ… Simple app imports successfully")
return True
except ImportError as e:
print(f"❌ Simple app import failed: {e}")
return False
def run_simple_app():
"""Run the simple demo app"""
print("πŸš€ Starting simple demo app...")
print("πŸ’‘ This will start a Gradio interface on http://localhost:7860")
print("πŸ’‘ Press Ctrl+C to stop")
try:
subprocess.run([sys.executable, "app_simple.py"])
except KeyboardInterrupt:
print("\nπŸ›‘ App stopped")
def test_mcp_servers():
"""Test MCP servers individually"""
print("πŸ§ͺ Testing MCP servers...")
servers = ["accounts_server.py", "market_server.py", "push_server.py"]
working_servers = []
for server in servers:
if Path(server).exists():
try:
# Test import
module_name = server.replace(".py", "")
__import__(module_name)
working_servers.append(server)
print(f"βœ… {server} - OK")
except Exception as e:
print(f"⚠️ {server} - {e}")
else:
print(f"❌ {server} - Not found")
return working_servers
def run_full_app():
"""Run the full app with MCP servers"""
print("πŸš€ Starting full app with MCP servers...")
print("πŸ’‘ This will start MCP servers and the main application")
print("πŸ’‘ Press Ctrl+C to stop all processes")
processes = []
try:
# Start MCP servers
servers = ["accounts_server.py", "market_server.py", "push_server.py"]
for server in servers:
if Path(server).exists():
print(f"πŸ”§ Starting {server}...")
proc = subprocess.Popen([sys.executable, server])
processes.append(proc)
time.sleep(1)
# Wait a bit for servers to start
time.sleep(3)
# Start main app
print("πŸ”§ Starting main application...")
main_proc = subprocess.Popen([sys.executable, "app.py"])
processes.append(main_proc)
# Wait for interrupt
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\nπŸ›‘ Stopping all processes...")
finally:
# Clean up processes
for proc in processes:
try:
proc.terminate()
proc.wait(timeout=5)
except:
try:
proc.kill()
except:
pass
def create_hf_space_files():
"""Create files needed for Hugging Face Spaces deployment"""
print("πŸ“„ Creating Hugging Face Spaces files...")
# Update README.md for HF Spaces
readme_content = """---
title: AI Trading Simulation
emoji: πŸ“ˆ
colorFrom: blue
colorTo: green
sdk: gradio
sdk_version: "4.44.0"
app_file: app_simple.py
pinned: false
license: mit
short_description: Real-time AI trading agents with different strategies
---
# πŸ€– AI Trading Simulation
A real-time simulation of AI trading agents with different personalities and strategies.
## Features
- 4 AI Trading Agents with unique personalities
- Real-time portfolio tracking
- Interactive dashboard with live updates
- Multiple AI models (GPT-4, DeepSeek, Gemini, Grok)
## How to Use
1. Click "Start Demo Simulation" to begin
2. Watch the AI agents make trading decisions
3. Monitor portfolio values and trading logs
4. Explore different agent strategies
*Note: This is a demo version with simulated data for Hugging Face Spaces.*
"""
with open("README.md", "w") as f:
f.write(readme_content)
print("βœ… README.md updated for Hugging Face Spaces")
print("βœ… Ready for deployment!")
def main():
"""Main deployment helper"""
print("πŸ€– AI Trading Simulation - Deployment Helper")
print("=" * 50)
if len(sys.argv) < 2:
print("""
Usage: python deploy.py <command>
Commands:
check - Check requirements and setup
install - Install dependencies
test - Test the application
simple - Run simple demo app
full - Run full app with MCP servers
hf - Prepare for Hugging Face Spaces deployment
all - Run complete setup and test
""")
return
command = sys.argv[1].lower()
if command == "check":
check_requirements()
check_env_vars()
elif command == "install":
install_dependencies()
elif command == "test":
check_requirements()
test_simple_app()
test_mcp_servers()
elif command == "simple":
if check_requirements():
run_simple_app()
elif command == "full":
if check_requirements():
run_full_app()
elif command == "hf":
create_hf_space_files()
elif command == "all":
print("πŸ”„ Running complete setup...")
if (check_requirements() and
install_dependencies() and
check_env_vars() and
test_simple_app()):
print("\nβœ… All checks passed!")
print("πŸ’‘ You can now run:")
print(" python deploy.py simple - For demo mode")
print(" python deploy.py full - For full MCP mode")
print(" python deploy.py hf - To prepare for HF Spaces")
else:
print("\n❌ Setup incomplete - please fix issues above")
else:
print(f"❌ Unknown command: {command}")
if __name__ == "__main__":
main()