File size: 7,698 Bytes
9f44dc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
UI Launcher for Algorithmic Trading System

Provides multiple UI options:
- Streamlit: Quick prototyping and data science workflows
- Dash: Enterprise-grade interactive dashboards
- Jupyter: Notebook-based interfaces
- WebSocket: Real-time trading interfaces
"""

import argparse
import sys
import os
import subprocess
import webbrowser
import time
import threading
from typing import Optional

def check_dependencies():
    """Check if required UI dependencies are installed"""
    required_packages = [
        'streamlit',
        'dash',
        'plotly',
        'ipywidgets'
    ]
    
    missing_packages = []
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print(f"❌ Missing required packages: {', '.join(missing_packages)}")
        print("Please install them using: pip install -r requirements.txt")
        return False
    
    return True

def launch_streamlit():
    """Launch Streamlit application"""
    print("πŸš€ Launching Streamlit UI...")
    
    # Create streamlit app file if it doesn't exist
    streamlit_app_path = "ui/streamlit_app.py"
    if not os.path.exists(streamlit_app_path):
        print(f"❌ Streamlit app not found at {streamlit_app_path}")
        return False
    
    try:
        # Launch Streamlit
        cmd = [
            sys.executable, "-m", "streamlit", "run", 
            streamlit_app_path,
            "--server.port", "8501",
            "--server.address", "0.0.0.0",
            "--browser.gatherUsageStats", "false"
        ]
        
        print(f"Running: {' '.join(cmd)}")
        subprocess.run(cmd)
        return True
        
    except Exception as e:
        print(f"❌ Error launching Streamlit: {e}")
        return False

def launch_dash():
    """Launch Dash application"""
    print("πŸš€ Launching Dash UI...")
    
    # Create dash app file if it doesn't exist
    dash_app_path = "ui/dash_app.py"
    if not os.path.exists(dash_app_path):
        print(f"❌ Dash app not found at {dash_app_path}")
        return False
    
    try:
        # Launch Dash
        cmd = [
            sys.executable, dash_app_path
        ]
        
        print(f"Running: {' '.join(cmd)}")
        subprocess.run(cmd)
        return True
        
    except Exception as e:
        print(f"❌ Error launching Dash: {e}")
        return False

def launch_jupyter():
    """Launch Jupyter interface"""
    print("πŸš€ Launching Jupyter UI...")
    
    try:
        # Launch Jupyter Lab
        cmd = [
            sys.executable, "-m", "jupyter", "lab",
            "--port", "8888",
            "--ip", "0.0.0.0",
            "--no-browser"
        ]
        
        print(f"Running: {' '.join(cmd)}")
        subprocess.run(cmd)
        return True
        
    except Exception as e:
        print(f"❌ Error launching Jupyter: {e}")
        return False

def launch_websocket_server():
    """Launch WebSocket server"""
    print("πŸš€ Launching WebSocket Server...")
    
    try:
        from ui.websocket_server import create_websocket_server
        
        server = create_websocket_server(host="0.0.0.0", port=8765)
        server_thread = server.run_server()
        
        print("βœ… WebSocket server started on ws://0.0.0.0:8765")
        print("Press Ctrl+C to stop the server")
        
        # Keep the main thread alive
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\nπŸ›‘ Stopping WebSocket server...")
        
        return True
        
    except Exception as e:
        print(f"❌ Error launching WebSocket server: {e}")
        return False

def open_browser(url: str, delay: int = 2):
    """Open browser after delay"""
    def open_url():
        time.sleep(delay)
        try:
            webbrowser.open(url)
            print(f"🌐 Opened browser to: {url}")
        except Exception as e:
            print(f"⚠️ Could not open browser: {e}")
    
    browser_thread = threading.Thread(target=open_url)
    browser_thread.daemon = True
    browser_thread.start()

def main():
    """Main launcher function"""
    parser = argparse.ArgumentParser(
        description="UI Launcher for Algorithmic Trading System",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python ui_launcher.py streamlit    # Launch Streamlit UI
  python ui_launcher.py dash         # Launch Dash UI
  python ui_launcher.py jupyter      # Launch Jupyter Lab
  python ui_launcher.py websocket    # Launch WebSocket server
  python ui_launcher.py all          # Launch all UIs
        """
    )
    
    parser.add_argument(
        "ui_type",
        choices=["streamlit", "dash", "jupyter", "websocket", "all"],
        help="Type of UI to launch"
    )
    
    parser.add_argument(
        "--no-browser",
        action="store_true",
        help="Don't automatically open browser"
    )
    
    parser.add_argument(
        "--port",
        type=int,
        help="Custom port number (overrides default)"
    )
    
    args = parser.parse_args()
    
    # Check dependencies
    if not check_dependencies():
        sys.exit(1)
    
    print("πŸ€– Algorithmic Trading System - UI Launcher")
    print("=" * 50)
    
    success = False
    
    if args.ui_type == "streamlit":
        success = launch_streamlit()
        if success and not args.no_browser:
            open_browser("http://localhost:8501")
    
    elif args.ui_type == "dash":
        success = launch_dash()
        if success and not args.no_browser:
            open_browser("http://localhost:8050")
    
    elif args.ui_type == "jupyter":
        success = launch_jupyter()
        if success and not args.no_browser:
            open_browser("http://localhost:8888")
    
    elif args.ui_type == "websocket":
        success = launch_websocket_server()
    
    elif args.ui_type == "all":
        print("πŸš€ Launching all UI interfaces...")
        
        # Launch WebSocket server in background
        websocket_thread = threading.Thread(target=launch_websocket_server)
        websocket_thread.daemon = True
        websocket_thread.start()
        
        # Launch Streamlit
        streamlit_thread = threading.Thread(target=launch_streamlit)
        streamlit_thread.daemon = True
        streamlit_thread.start()
        
        # Launch Dash
        dash_thread = threading.Thread(target=launch_dash)
        dash_thread.daemon = True
        dash_thread.start()
        
        # Launch Jupyter
        jupyter_thread = threading.Thread(target=launch_jupyter)
        jupyter_thread.daemon = True
        jupyter_thread.start()
        
        if not args.no_browser:
            open_browser("http://localhost:8501", 3)  # Streamlit
            open_browser("http://localhost:8050", 5)  # Dash
            open_browser("http://localhost:8888", 7)  # Jupyter
        
        print("βœ… All UIs launched!")
        print("πŸ“Š Streamlit: http://localhost:8501")
        print("πŸ“ˆ Dash: http://localhost:8050")
        print("πŸ““ Jupyter: http://localhost:8888")
        print("πŸ”Œ WebSocket: ws://localhost:8765")
        
        # Keep main thread alive
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\nπŸ›‘ Stopping all UIs...")
        
        success = True
    
    if success:
        print("βœ… UI launched successfully!")
    else:
        print("❌ Failed to launch UI")
        sys.exit(1)

if __name__ == "__main__":
    main()