forked from magnaopus1/Synthron-Crypto-Trader
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsupertradex.py
More file actions
executable file
·340 lines (287 loc) · 11.8 KB
/
supertradex.py
File metadata and controls
executable file
·340 lines (287 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#!/usr/bin/env python3
"""
SupertradeX Comprehensive Launcher
Provides multiple ways to start and manage SupertradeX services
"""
import argparse
import asyncio
import os
import subprocess
import sys
import time
import signal
from pathlib import Path
from typing import Optional
def check_dependencies():
"""Check if required dependencies are available"""
project_root = Path(__file__).parent
venv_python = project_root / '.venv' / 'bin' / 'python'
if not venv_python.exists():
print("❌ Virtual environment not found!")
print("💡 Please run: python -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt")
return False, sys.executable
print("✅ Virtual environment found")
return True, str(venv_python)
def check_processes():
"""Check what SupertradeX processes are currently running"""
try:
import psutil
processes = {
'manager': [],
'main': [],
'web': []
}
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
cmdline = ' '.join(proc.info['cmdline'] or [])
if 'supertradex_manager.py' in cmdline:
processes['manager'].append(proc.info['pid'])
elif 'main.py' in cmdline and 'supertradex' in cmdline.lower():
processes['main'].append(proc.info['pid'])
elif 'run_web.py' in cmdline:
processes['web'].append(proc.info['pid'])
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
return processes
except ImportError:
print("⚠️ psutil not available, cannot check running processes")
return None
def kill_existing_processes():
"""Kill any existing SupertradeX processes"""
processes = check_processes()
if not processes:
return
total_killed = 0
for proc_type, pids in processes.items():
for pid in pids:
try:
import psutil
proc = psutil.Process(pid)
proc.terminate()
total_killed += 1
print(f"🔪 Killed {proc_type} process (PID: {pid})")
except Exception as e:
print(f"⚠️ Could not kill {proc_type} process {pid}: {e}")
if total_killed > 0:
print(f"⏳ Waiting 3 seconds for processes to shut down...")
time.sleep(3)
def show_status():
"""Show current status of SupertradeX services"""
print("📊 SupertradeX Status:")
print("=" * 50)
processes = check_processes()
if not processes:
print("❓ Cannot determine process status")
return
# Check manager
if processes['manager']:
print(f"🔧 Service Manager: ✅ Running (PIDs: {', '.join(map(str, processes['manager']))})")
else:
print("🔧 Service Manager: ❌ Not running")
# Check main trading system
if processes['main']:
print(f"💰 Trading System: ✅ Running (PIDs: {', '.join(map(str, processes['main']))})")
else:
print("💰 Trading System: ❌ Not running")
# Check web dashboard
if processes['web']:
print(f"🌐 Web Dashboard: ✅ Running (PIDs: {', '.join(map(str, processes['web']))})")
else:
print("🌐 Web Dashboard: ❌ Not running")
# Check port 8000
try:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
result = s.connect_ex(('localhost', 8000))
if result == 0:
print("🌐 Dashboard Port 8000: ✅ Open")
print("📊 Dashboard URL: http://127.0.0.1:8000")
else:
print("🌐 Dashboard Port 8000: ❌ Closed")
except Exception:
print("🌐 Dashboard Port 8000: ❓ Cannot check")
print("=" * 50)
def run_service_manager(python_exec: str):
"""Run the service manager directly"""
project_root = Path(__file__).parent
manager_script = project_root / 'supertradex_manager.py'
if not manager_script.exists():
print(f"❌ Service manager not found: {manager_script}")
return False
try:
print("🚀 Starting SupertradeX Service Manager...")
subprocess.run([python_exec, str(manager_script)], cwd=project_root, check=True)
return True
except KeyboardInterrupt:
print("\n👋 SupertradeX stopped by user")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Service manager failed: {e}")
return False
def run_main_only(python_exec: str):
"""Run only the main trading system"""
project_root = Path(__file__).parent
main_script = project_root / 'main.py'
if not main_script.exists():
print(f"❌ Main script not found: {main_script}")
return False
try:
print("💰 Starting Main Trading System only...")
subprocess.run([python_exec, str(main_script)], cwd=project_root, check=True)
return True
except KeyboardInterrupt:
print("\n👋 Main trading system stopped by user")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Main trading system failed: {e}")
return False
def run_web_only(python_exec: str):
"""Run only the web dashboard"""
project_root = Path(__file__).parent
web_script = project_root / 'run_web.py'
if not web_script.exists():
print(f"❌ Web script not found: {web_script}")
return False
try:
print("🌐 Starting Web Dashboard only...")
print("📊 Dashboard URL: http://127.0.0.1:8000")
subprocess.run([python_exec, str(web_script)], cwd=project_root, check=True)
return True
except KeyboardInterrupt:
print("\n👋 Web dashboard stopped by user")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Web dashboard failed: {e}")
return False
def run_background():
"""Run SupertradeX in background using nohup"""
project_root = Path(__file__).parent
bash_script = project_root / 'run_supertradex.sh'
if not bash_script.exists():
print(f"❌ Bash launcher not found: {bash_script}")
return False
try:
print("🚀 Starting SupertradeX in background...")
subprocess.Popen(
['nohup', 'bash', str(bash_script)],
cwd=project_root,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
preexec_fn=os.setsid
)
print("✅ SupertradeX started in background")
print("📊 Dashboard URL: http://127.0.0.1:8000")
print("📋 Check status with: python start_supertradex.py --status")
return True
except Exception as e:
print(f"❌ Failed to start in background: {e}")
return False
def install_system_service():
"""Install SupertradeX as a system service"""
print("🔧 Installing SupertradeX as system service...")
project_root = Path(__file__).parent
if sys.platform.startswith('darwin'): # macOS
plist_file = project_root / 'launchd-service' / 'com.supertradex.plist'
target_dir = Path.home() / 'Library' / 'LaunchAgents'
target_file = target_dir / 'com.supertradex.plist'
if not plist_file.exists():
print(f"❌ LaunchD plist not found: {plist_file}")
return False
try:
target_dir.mkdir(parents=True, exist_ok=True)
subprocess.run(['cp', str(plist_file), str(target_file)], check=True)
subprocess.run(['launchctl', 'load', str(target_file)], check=True)
print("✅ SupertradeX installed as macOS LaunchAgent")
print("🚀 Service will start automatically on login")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Failed to install service: {e}")
return False
elif sys.platform.startswith('linux'): # Linux
service_file = project_root / 'systemd-service' / 'supertradex.service'
if not service_file.exists():
print(f"❌ Systemd service file not found: {service_file}")
return False
try:
# Copy service file
subprocess.run([
'sudo', 'cp', str(service_file), '/etc/systemd/system/'
], check=True)
# Reload systemd and enable service
subprocess.run(['sudo', 'systemctl', 'daemon-reload'], check=True)
subprocess.run(['sudo', 'systemctl', 'enable', 'supertradex.service'], check=True)
subprocess.run(['sudo', 'systemctl', 'start', 'supertradex.service'], check=True)
print("✅ SupertradeX installed as systemd service")
print("🚀 Service will start automatically on boot")
print("📋 Check status with: sudo systemctl status supertradex")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Failed to install service: {e}")
return False
else:
print(f"❌ System service installation not supported on {sys.platform}")
return False
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description="SupertradeX Comprehensive Launcher",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python start_supertradex.py # Start with service manager (recommended)
python start_supertradex.py --main-only # Start only trading system
python start_supertradex.py --web-only # Start only web dashboard
python start_supertradex.py --background # Start in background
python start_supertradex.py --status # Show current status
python start_supertradex.py --kill # Kill all processes
python start_supertradex.py --install # Install as system service
"""
)
parser.add_argument('--main-only', action='store_true', help='Run only the main trading system')
parser.add_argument('--web-only', action='store_true', help='Run only the web dashboard')
parser.add_argument('--background', action='store_true', help='Run in background')
parser.add_argument('--status', action='store_true', help='Show current status')
parser.add_argument('--kill', action='store_true', help='Kill all SupertradeX processes')
parser.add_argument('--install', action='store_true', help='Install as system service')
parser.add_argument('--force-kill', action='store_true', help='Force kill all processes before starting')
args = parser.parse_args()
# Handle status check
if args.status:
show_status()
return
# Handle kill command
if args.kill:
kill_existing_processes()
print("✅ All SupertradeX processes killed")
return
# Handle system service installation
if args.install:
install_system_service()
return
# Check dependencies
venv_ok, python_exec = check_dependencies()
if not venv_ok:
sys.exit(1)
# Force kill if requested
if args.force_kill:
kill_existing_processes()
# Choose run mode
if args.main_only:
success = run_main_only(python_exec)
elif args.web_only:
success = run_web_only(python_exec)
elif args.background:
success = run_background()
else:
# Default: run with service manager
success = run_service_manager(python_exec)
if not success:
sys.exit(1)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n👋 Goodbye!")
except Exception as e:
print(f"❌ Unexpected error: {e}")
sys.exit(1)