-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
399 lines (349 loc) · 14.1 KB
/
main.py
File metadata and controls
399 lines (349 loc) · 14.1 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#!/usr/bin/env python3
"""
Main CLI script for Jesse optimization tool.
This script provides a command-line interface for creating and monitoring
optimization sessions with configurable parameters.
"""
import argparse
import sys
import time
from typing import List
from optimization_lib import OptimizationAPI, OptimizationClient, OptimizationConfig
from optimization_lib.config import (
create_default_config_files,
load_exchanges_from_file,
load_symbols_from_file,
)
def create_optimization_batch(
client: OptimizationClient,
symbols: List[str],
exchanges: List[str],
config: OptimizationConfig,
monitor: bool = False,
) -> None:
"""Create optimizations for all symbol-exchange combinations"""
total_combinations = len(symbols) * len(exchanges)
print(f"Creating {total_combinations} optimization(s)...")
print(f"Symbols: {len(symbols)}")
print(f"Exchanges: {len(exchanges)}")
print("-" * 50)
created_sessions = []
for i, exchange in enumerate(exchanges, 1):
for j, symbol in enumerate(symbols, 1):
combination_num = (i - 1) * len(symbols) + j
print(
f"[{combination_num}/{total_combinations}] Creating optimization: {exchange}@{symbol}"
)
result = client.create_optimization(
exchange=exchange,
symbol=symbol,
strategy=config.strategy,
timeframe=config.timeframe,
data_timeframes=config.data_timeframes,
training_start_date=config.training_start_date,
training_finish_date=config.training_finish_date,
testing_start_date=config.testing_start_date,
testing_finish_date=config.testing_finish_date,
warm_up_candles=config.warm_up_candles,
trials=config.trials,
objective_function=config.objective_function,
ratio=config.ratio,
balance=config.balance,
fee=config.fee,
exchange_type=config.exchange_type,
futures_leverage_mode=config.futures_leverage_mode,
futures_leverage=config.futures_leverage,
optimal_total=config.optimal_total,
fast_mode=config.fast_mode,
debug_mode=config.debug_mode,
cpu_cores=config.cpu_cores,
)
if result["success"]:
print(f"✅ Optimization created successfully!")
print(f" ID: {result['optimization_id']}")
print(f" Status: {result['status_code']}")
created_sessions.append(
{
"id": result["optimization_id"],
"exchange": exchange,
"symbol": symbol,
"result": result,
}
)
# If monitoring is enabled, monitor this session immediately
if monitor:
print(f"\nStarting monitoring for {exchange}@{symbol}...")
api = OptimizationAPI(base_url=config.base_url, auth_token=config.auth_token)
try:
api.monitor_session(
session_id=result["optimization_id"],
interval=config.monitor_interval,
max_attempts=config.max_monitor_attempts,
)
except KeyboardInterrupt:
print(f"\nMonitoring stopped by user for {exchange}@{symbol}")
break
except Exception as e:
print(f"Error monitoring {exchange}@{symbol}: {e}")
else:
print(
f"❌ Failed to create optimization: {result.get('error', 'Unknown error')}"
)
print("-" * 30)
# Add delay between requests to avoid overwhelming the server
if combination_num < total_combinations:
time.sleep(1)
print(
f"\nSummary: {len(created_sessions)}/{total_combinations} optimizations created successfully"
)
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description="Jesse Optimization CLI Tool",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Create default config files
python main.py --init
# Run optimization with default config
python main.py
# Run with custom symbols and exchanges
python main.py --symbols BTC-USDT ETH-USDT --exchanges "Bybit Spot" "Binance Spot"
# Run with symbols from file
python main.py --symbols-file symbols.txt --exchanges-file exchanges.txt
# Run with custom config file
python main.py --config custom_config.json
# Run with monitoring
python main.py --monitor
# Run single optimization
python main.py --single --symbol BTC-USDT --exchange "Bybit Spot"
# Run single optimization with lists from files
python main.py --single --symbols-file symbols.txt --exchanges-file exchanges.txt
""",
)
# Configuration options
parser.add_argument(
"--config",
"-c",
type=str,
default="config.json",
help="Path to configuration file (default: config.json)",
)
parser.add_argument(
"--init",
action="store_true",
help="Create default configuration files and exit",
)
# Symbol and exchange options
parser.add_argument(
"--symbols",
nargs="+",
type=str,
help="List of trading symbols (e.g., BTC-USDT ETH-USDT)",
)
parser.add_argument(
"--symbols-file", type=str, help="File containing symbols (one per line)"
)
parser.add_argument(
"--exchanges",
nargs="+",
type=str,
help='List of exchanges (e.g., "Bybit Spot" "Binance Spot")',
)
parser.add_argument(
"--exchanges-file", type=str, help="File containing exchanges (one per line)"
)
# Single optimization options
parser.add_argument(
"--single", action="store_true", help="Run single optimization mode (supports both single values and lists)"
)
parser.add_argument(
"--symbol", type=str, help="Single symbol for optimization (use with --single, overrides symbols from files)"
)
parser.add_argument(
"--exchange",
type=str,
help="Single exchange for optimization (use with --single, overrides exchanges from files)",
)
# Monitoring options
parser.add_argument(
"--monitor",
"-m",
action="store_true",
help="Monitor optimization sessions after creation",
)
parser.add_argument(
"--monitor-interval",
type=int,
default=60,
help="Monitoring interval in seconds (default: 60)",
)
parser.add_argument(
"--max-attempts",
type=int,
default=100,
help="Maximum monitoring attempts (default: 100)",
)
# Override options
parser.add_argument("--strategy", type=str, help="Override strategy name")
parser.add_argument("--timeframe", type=str, help="Override timeframe")
parser.add_argument("--trials", type=str, help="Override number of trials")
parser.add_argument("--cpu-cores", type=int, help="Override number of CPU cores")
args = parser.parse_args()
# Initialize default config files if requested
if args.init:
create_default_config_files()
print("\nDefault configuration files created successfully!")
print("Edit config.json, symbols.txt, and exchanges.txt as needed.")
return 0
# Load configuration
config = OptimizationConfig.from_file(args.config)
# Override with command line arguments
if args.monitor_interval:
config.monitor_interval = args.monitor_interval
if args.max_attempts:
config.max_monitor_attempts = args.max_attempts
if args.strategy:
config.strategy = args.strategy
if args.timeframe:
config.timeframe = args.timeframe
if args.trials:
config.trials = args.trials
if args.cpu_cores:
config.cpu_cores = args.cpu_cores
# Load symbols
symbols = []
if args.symbols:
symbols = args.symbols
elif args.symbols_file:
symbols = load_symbols_from_file(args.symbols_file)
else:
# Try to load from default file
symbols = load_symbols_from_file("symbols.txt")
if not symbols:
print(
"Error: No symbols specified. Use --symbols, --symbols-file, or create symbols.txt"
)
return 1
# Load exchanges
exchanges = []
if args.exchanges:
exchanges = args.exchanges
elif args.exchanges_file:
exchanges = load_exchanges_from_file(args.exchanges_file)
else:
# Try to load from default file
exchanges = load_exchanges_from_file("exchanges.txt")
if not exchanges:
print(
"Error: No exchanges specified. Use --exchanges, --exchanges-file, or create exchanges.txt"
)
return 1
# Create client
client = OptimizationClient(base_url=config.base_url, auth_token=config.auth_token)
print("=== Jesse Optimization CLI ===")
print(f"Server: {config.base_url}")
print(f"Token: {config.auth_token[:8]}...")
print(f"Strategy: {config.strategy}")
print(f"Timeframe: {config.timeframe}")
print(f"Trials: {config.trials}")
print()
try:
if args.single:
# Single optimization mode - support both single values and lists
single_symbols = []
single_exchanges = []
# Check for single symbol/exchange parameters
if args.symbol:
single_symbols = [args.symbol]
if args.exchange:
single_exchanges = [args.exchange]
# If no single parameters, use the loaded lists
if not single_symbols:
single_symbols = symbols
if not single_exchanges:
single_exchanges = exchanges
# Validate that we have both symbols and exchanges
if not single_symbols or not single_exchanges:
print("Error: --single mode requires either --symbol/--exchange or symbols/exchanges from files")
return 1
# If we have only one symbol and one exchange, use the original single optimization logic
if len(single_symbols) == 1 and len(single_exchanges) == 1:
print(f"Creating single optimization: {single_exchanges[0]}@{single_symbols[0]}")
result = client.create_optimization(
exchange=single_exchanges[0],
symbol=single_symbols[0],
strategy=config.strategy,
timeframe=config.timeframe,
data_timeframes=config.data_timeframes,
training_start_date=config.training_start_date,
training_finish_date=config.training_finish_date,
testing_start_date=config.testing_start_date,
testing_finish_date=config.testing_finish_date,
warm_up_candles=config.warm_up_candles,
trials=config.trials,
objective_function=config.objective_function,
ratio=config.ratio,
balance=config.balance,
fee=config.fee,
exchange_type=config.exchange_type,
futures_leverage_mode=config.futures_leverage_mode,
futures_leverage=config.futures_leverage,
optimal_total=config.optimal_total,
fast_mode=config.fast_mode,
debug_mode=config.debug_mode,
cpu_cores=config.cpu_cores,
)
if result["success"]:
print("✅ Optimization created successfully!")
print(f"ID: {result['optimization_id']}")
print(f"Status: {result['status_code']}")
if args.monitor:
print("\nStarting monitoring...")
api = OptimizationAPI(
base_url=config.base_url, auth_token=config.auth_token
)
try:
api.monitor_session(
session_id=result["optimization_id"],
interval=config.monitor_interval,
max_attempts=config.max_monitor_attempts,
)
except KeyboardInterrupt:
print("\nMonitoring stopped by user")
else:
print(
f"❌ Failed to create optimization: {result.get('error', 'Unknown error')}"
)
return 1
else:
# Multiple symbols/exchanges in single mode - use batch logic but with single mode messaging
print(f"Creating {len(single_symbols) * len(single_exchanges)} optimization(s) in single mode...")
print(f"Symbols: {len(single_symbols)}")
print(f"Exchanges: {len(single_exchanges)}")
print("-" * 50)
create_optimization_batch(
client=client,
symbols=single_symbols,
exchanges=single_exchanges,
config=config,
monitor=args.monitor,
)
else:
# Batch optimization mode
create_optimization_batch(
client=client,
symbols=symbols,
exchanges=exchanges,
config=config,
monitor=args.monitor,
)
except KeyboardInterrupt:
print("\nOperation cancelled by user")
return 1
except Exception as e:
print(f"Error: {e}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())