Repository navigation
Expand file tree
/
Copy pathgtt_tools.py
More file actions
597 lines (472 loc) · 19.5 KB
/
Copy pathgtt_tools.py
File metadata and controls
597 lines (472 loc) · 19.5 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
"""
GTT CLI Tools for GTT triggers.
Issue #340: CLI integration for Good-Till-Triggered persistent triggers.
This module wraps the GTT module functions for the CLI.
"""
import logging
from typing import Any, Dict, List, Literal, Optional, Tuple
logger = logging.getLogger(__name__)
# =============================================================================
# Helper Functions
# =============================================================================
def _get_gtt_manager():
"""Get GTTManager instance."""
try:
from src.trading.gtt.gtt_manager import get_gtt_manager
return get_gtt_manager()
except Exception as e:
logger.error(f"Failed to get GTT manager: {e}")
return None
def _get_condition_type(condition_str: str):
"""Convert condition string to ConditionType enum."""
from src.trading.gtt.gtt_manager import ConditionType
mapping = {
# Phase 1: Price-based
"above": ConditionType.PRICE_ABOVE,
"price_above": ConditionType.PRICE_ABOVE,
"below": ConditionType.PRICE_BELOW,
"price_below": ConditionType.PRICE_BELOW,
"gain": ConditionType.PCT_GAIN,
"pct_gain": ConditionType.PCT_GAIN,
"loss": ConditionType.PCT_LOSS,
"pct_loss": ConditionType.PCT_LOSS,
"trailing": ConditionType.TRAILING_STOP,
"trailing_stop": ConditionType.TRAILING_STOP,
# Phase 2: Time-based
"time": ConditionType.TIME_WINDOW,
"time_window": ConditionType.TIME_WINDOW,
# Phase 2: Volume-based
"volume": ConditionType.VOLUME_ABOVE,
"volume_above": ConditionType.VOLUME_ABOVE,
"spike": ConditionType.VOLUME_SPIKE,
"volume_spike": ConditionType.VOLUME_SPIKE,
}
return mapping.get(condition_str.lower())
def _checked_text(symbol: str, is_order: bool) -> str:
"""When the routines check a new trigger, for its confirmation message (#658)."""
if is_order:
return f"Checked at the routines while {symbol} is held."
return (
f"Checked at both routines while {symbol} is held, and at the evening routine "
"when it isn't (if a fresh price exists)."
)
def _get_action_type(action_str: str):
"""Convert action string to ActionType enum."""
from src.trading.gtt.gtt_manager import ActionType
mapping = {
"alert": ActionType.ALERT,
"order": ActionType.PLACE_ORDER,
"place_order": ActionType.PLACE_ORDER,
}
return mapping.get(action_str.lower())
def _value_text(condition_type: str, value: float) -> str:
"""A trigger's value as the user gave it: a percent for gain, loss and trailing."""
from src.trading.gtt.gtt_manager import ConditionType
if condition_type == ConditionType.TRAILING_STOP.value:
return f"{value * 100:g}%" # stored as a fraction
if condition_type in (ConditionType.PCT_GAIN.value, ConditionType.PCT_LOSS.value):
return f"{value:g}%"
return f"{value:g}"
def _trigger_details(
symbol: str, condition_type, action_type, value, side, quantity
) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
"""
The action_config a new trigger needs (#635).
An order trigger names its order, and a gain or loss trigger the price it's measured
from, without which it can never fire.
Returns:
(action_config, None), or (None, what's wrong)
"""
from src.trading.gtt.gtt_manager import ActionType, ConditionType
is_percent = condition_type in (
ConditionType.PCT_GAIN,
ConditionType.PCT_LOSS,
ConditionType.TRAILING_STOP,
)
if value <= 0 or (is_percent and value >= 100):
return None, f"Invalid value {value:g}: a percent from 0 to 100, or a price above 0"
config: Dict[str, Any] = {}
if action_type == ActionType.PLACE_ORDER:
if side not in ("buy", "sell") or not quantity or quantity <= 0:
return None, "An order trigger needs a side (buy or sell) and a positive quantity"
config.update(order_type="market", side=side, qty=quantity)
if condition_type in (ConditionType.PCT_GAIN, ConditionType.PCT_LOSS):
from src.trading.utils.unified_price_fetcher import get_current_price
reference_price = get_current_price(symbol)
if not reference_price:
return None, f"Could not get {symbol}'s price to measure the change from"
config["reference_price"] = reference_price
return config, None
def create_gtt_trigger(
symbol: str,
condition: str,
value: float,
action: str = "alert",
expiration_days: Optional[int] = None,
max_triggers: Optional[int] = None,
notes: Optional[str] = None,
side: Optional[Literal["buy", "sell"]] = None,
quantity: Optional[int] = None,
) -> Dict[str, Any]:
"""
Create a new GTT (Good-Till-Triggered) trigger.
GTT triggers persist across sessions and are checked twice daily (morning 9:20 AM and
evening 3:50 PM ET) for symbols held; symbols not held are
checked at the evening routine only, when a fresh price exists, and only alerts run there.
Args:
symbol: Stock ticker symbol (e.g., "SPY", "AAPL")
condition: Trigger condition - "above", "below", "gain", "loss", "trailing"
value: A price for above and below; a percent for gain, loss and trailing (5 = 5%).
Gain and loss are measured from the price when the trigger is created.
action: Action to take - "alert" (default), "order"
expiration_days: Days until trigger expires (None = no expiration)
max_triggers: Max times to fire (None = unlimited, 1 = one-time; an order trigger
defaults to 1)
notes: Optional notes for the trigger
side: "buy" or "sell", required for an order
quantity: Shares, required for an order
Returns:
Dict with status and trigger details
Examples:
- "Alert if SPY hits $620": condition="above", value=620
- "Alert if AAPL drops to $180": condition="below", value=180
- "Alert on a 10% gain in TSLA": condition="gain", value=10
- "Sell 5 SPY if it drops to $700": condition="below", value=700, action="order",
side="sell", quantity=5
"""
try:
from src.trading.gtt.gtt_manager import ActionType, ConditionType
mgr = _get_gtt_manager()
if not mgr:
return {"status": "error", "message": "GTT manager not available"}
condition_type = _get_condition_type(condition)
if not condition_type:
return {
"status": "error",
"message": f"Unknown condition: {condition}. Use: above, below, gain, loss, trailing",
}
action_type = _get_action_type(action)
if not action_type:
return {"status": "error", "message": f"Unknown action: {action}. Use: alert, order"}
action_config, problem = _trigger_details(
symbol.upper(), condition_type, action_type, value, side, quantity
)
if problem:
return {"status": "error", "message": problem}
is_order = action_type == ActionType.PLACE_ORDER
trigger = mgr.create_trigger(
symbol=symbol,
condition_type=condition_type,
trigger_value=value / 100 if condition_type == ConditionType.TRAILING_STOP else value,
action_type=action_type,
action_config=action_config,
expiration_days=expiration_days,
max_triggers=1 if is_order and max_triggers is None else max_triggers,
notes=notes,
)
if trigger:
return {
"status": "success",
"trigger_id": trigger.id,
"symbol": trigger.symbol,
"condition": trigger.condition_type,
"value": trigger.trigger_value,
"action": trigger.action_type,
"expiration": trigger.expiration_date,
"max_triggers": trigger.max_triggers or "unlimited",
"message": (
f"GTT trigger created: {trigger.symbol} {trigger.condition_type} "
f"{_value_text(trigger.condition_type, trigger.trigger_value)}"
+ (f", then {side} {quantity} at market" if is_order else "")
+ f". {_checked_text(trigger.symbol, is_order)}"
),
}
return {"status": "error", "message": "Failed to create trigger"}
except Exception as e:
logger.error(f"Error creating GTT trigger: {e}", exc_info=True)
return {"status": "error", "error": str(e)}
def create_gtt_oco_pair(
symbol: str,
condition_a: str,
value_a: float,
condition_b: str,
value_b: float,
expiration_days: Optional[int] = None,
) -> Dict[str, Any]:
"""
Create an OCO (One-Cancels-Other) trigger pair.
When one trigger fires, both are automatically disabled.
Useful for breakout/breakdown strategies.
Args:
symbol: Stock ticker symbol
condition_a: First trigger condition (e.g., "above")
value_a: First trigger value (e.g., 620 for $620)
condition_b: Second trigger condition (e.g., "below")
value_b: Second trigger value (e.g., 580 for $580)
expiration_days: Days until triggers expire
Returns:
Dict with status and both trigger details
Example:
"Alert if SPY breaks above $620 or below $580":
condition_a="above", value_a=620, condition_b="below", value_b=580
"""
try:
mgr = _get_gtt_manager()
if not mgr:
return {"status": "error", "message": "GTT manager not available"}
cond_type_a = _get_condition_type(condition_a)
cond_type_b = _get_condition_type(condition_b)
if not cond_type_a or not cond_type_b:
return {"status": "error", "message": "Invalid condition type"}
trigger_a, trigger_b = mgr.create_oco_pair(
symbol=symbol,
condition_a=cond_type_a,
value_a=value_a,
condition_b=cond_type_b,
value_b=value_b,
expiration_days=expiration_days,
notes_a=f"OCO: {condition_a} ${value_a}",
notes_b=f"OCO: {condition_b} ${value_b}",
)
if trigger_a and trigger_b:
return {
"status": "success",
"oco_group_id": trigger_a.oco_group_id,
"trigger_a": {
"id": trigger_a.id,
"condition": trigger_a.condition_type,
"value": trigger_a.trigger_value,
},
"trigger_b": {
"id": trigger_b.id,
"condition": trigger_b.condition_type,
"value": trigger_b.trigger_value,
},
"message": f"OCO pair created: {symbol} {condition_a} ${value_a} OR {condition_b} ${value_b}",
}
return {"status": "error", "message": "Failed to create OCO pair"}
except Exception as e:
logger.error(f"Error creating OCO pair: {e}", exc_info=True)
return {"status": "error", "error": str(e)}
def list_gtt_triggers(
symbol: Optional[str] = None,
include_disabled: bool = False,
) -> Dict[str, Any]:
"""
List GTT triggers.
Args:
symbol: Optional filter by symbol
include_disabled: Include disabled triggers (default: False)
Returns:
Dict with status and list of triggers
"""
try:
mgr = _get_gtt_manager()
if not mgr:
return {"status": "error", "message": "GTT manager not available"}
if symbol:
triggers = mgr.get_triggers(
symbol=symbol, enabled_only=not include_disabled, active_only=False
)
else:
triggers = mgr.get_all_triggers(include_disabled=include_disabled)
trigger_list = [t.to_dict() for t in triggers]
return {
"status": "success",
"count": len(trigger_list),
"triggers": trigger_list,
"filter_symbol": symbol,
}
except Exception as e:
logger.error(f"Error listing GTT triggers: {e}", exc_info=True)
return {"status": "error", "error": str(e)}
def delete_gtt_trigger(trigger_id: int) -> Dict[str, Any]:
"""
Delete a GTT trigger.
Args:
trigger_id: ID of trigger to delete
Returns:
Dict with status
"""
try:
mgr = _get_gtt_manager()
if not mgr:
return {"status": "error", "message": "GTT manager not available"}
# Get trigger info before deleting
trigger = mgr.get_trigger(trigger_id)
if not trigger:
return {"status": "error", "message": f"Trigger {trigger_id} not found"}
success = mgr.delete_trigger(trigger_id)
if success:
return {
"status": "success",
"message": f"Deleted GTT trigger {trigger_id} ({trigger.symbol} {trigger.condition_type})",
}
return {"status": "error", "message": f"Failed to delete trigger {trigger_id}"}
except Exception as e:
logger.error(f"Error deleting GTT trigger: {e}", exc_info=True)
return {"status": "error", "error": str(e)}
def disable_gtt_trigger(trigger_id: int) -> Dict[str, Any]:
"""
Disable a GTT trigger (can be re-enabled later).
Args:
trigger_id: ID of trigger to disable
Returns:
Dict with status
"""
try:
mgr = _get_gtt_manager()
if not mgr:
return {"status": "error", "message": "GTT manager not available"}
trigger = mgr.get_trigger(trigger_id)
if not trigger:
return {"status": "error", "message": f"Trigger {trigger_id} not found"}
success = mgr.disable_trigger(trigger_id)
if success:
return {
"status": "success",
"message": f"Disabled GTT trigger {trigger_id} ({trigger.symbol} {trigger.condition_type})",
}
return {"status": "error", "message": f"Failed to disable trigger {trigger_id}"}
except Exception as e:
logger.error(f"Error disabling GTT trigger: {e}", exc_info=True)
return {"status": "error", "error": str(e)}
def enable_gtt_trigger(trigger_id: int) -> Dict[str, Any]:
"""
Enable a previously disabled GTT trigger.
Args:
trigger_id: ID of trigger to enable
Returns:
Dict with status
"""
try:
mgr = _get_gtt_manager()
if not mgr:
return {"status": "error", "message": "GTT manager not available"}
trigger = mgr.get_trigger(trigger_id)
if not trigger:
return {"status": "error", "message": f"Trigger {trigger_id} not found"}
success = mgr.enable_trigger(trigger_id)
if success:
return {
"status": "success",
"message": f"Enabled GTT trigger {trigger_id} ({trigger.symbol} {trigger.condition_type})",
}
return {"status": "error", "message": f"Failed to enable trigger {trigger_id}"}
except Exception as e:
logger.error(f"Error enabling GTT trigger: {e}", exc_info=True)
return {"status": "error", "error": str(e)}
def get_gtt_summary() -> Dict[str, Any]:
"""
Get summary of GTT triggers.
Returns:
Dict with status and summary statistics
"""
try:
mgr = _get_gtt_manager()
if not mgr:
return {"status": "error", "message": "GTT manager not available"}
summary = mgr.get_summary()
summary["status"] = "success"
return summary
except Exception as e:
logger.error(f"Error getting GTT summary: {e}", exc_info=True)
return {"status": "error", "error": str(e)}
# =============================================================================
# Display Functions
# =============================================================================
def show_gtt_triggers(symbol: Optional[str] = None) -> str: # noqa: C901
"""Display GTT triggers with formatted output."""
result = list_gtt_triggers(symbol=symbol, include_disabled=True)
if result["status"] == "error":
return f"Error: {result.get('error', result.get('message', 'Unknown'))}"
triggers = result.get("triggers", [])
if not triggers:
if symbol:
return f"No GTT triggers for {symbol.upper()}"
return "No GTT triggers. Use 'alert if SYMBOL hits PRICE' to create one."
lines = [f"GTT Triggers ({len(triggers)})", "=" * 60]
for t in triggers:
lines.extend(_trigger_lines(t))
lines.append("")
return "\n".join(lines)
def _trigger_lines(t: Dict[str, Any]) -> List[str]:
"""Display lines for one trigger dict (from GTTTrigger.to_dict())."""
# Status indicator
if not t.get("enabled"):
status = "DISABLED"
elif t.get("is_expired"):
status = "EXPIRED"
elif not t.get("is_active"):
status = "INACTIVE"
else:
status = "ACTIVE"
# Build line
lines = [
f"[{t['id']}] {t['symbol']} {t['condition_type']} "
f"@ {_value_text(t['condition_type'], t['trigger_value'])}",
f" Action: {t['action_type']} | Status: {status}",
]
# Additional info
extras = []
if t.get("expiration_date"):
extras.append(f"Expires: {t['expiration_date'][:10]}")
if t.get("max_triggers"):
extras.append(f"Max: {t['max_triggers']} (fired: {t.get('trigger_count', 0)})")
if t.get("oco_group_id"):
extras.append(f"OCO Group: {t['oco_group_id']}")
if extras:
lines.append(f" {' | '.join(extras)}")
if t.get("notes"):
lines.append(f" Notes: {t['notes']}")
return lines
def show_gtt_trigger(trigger_id: int) -> str:
"""Display one GTT trigger's details."""
try:
mgr = _get_gtt_manager()
if not mgr:
return "Error: GTT manager not available"
trigger = mgr.get_trigger(trigger_id)
if not trigger:
return f"No GTT trigger with ID {trigger_id}"
t = trigger.to_dict()
lines = [f"GTT Trigger {trigger_id}", "=" * 60, *_trigger_lines(t)]
if t.get("action_config"):
lines.append(f" Action config: {t['action_config']}")
lines.append(f" Fired: {t.get('trigger_count', 0)} time(s)")
if t.get("last_triggered_at"):
lines.append(f" Last fired: {t['last_triggered_at']}")
if t.get("created_at"):
lines.append(f" Created: {t['created_at']}")
return "\n".join(lines)
except Exception as e:
logger.error(f"Error showing GTT trigger {trigger_id}: {e}", exc_info=True)
return f"Error: {e}"
def show_gtt_summary() -> str:
"""Display GTT summary with formatted output."""
result = get_gtt_summary()
if result["status"] == "error":
return f"Error: {result.get('error', result.get('message', 'Unknown'))}"
lines = [
"GTT Summary",
"=" * 40,
f" Total triggers: {result.get('total_triggers', 0)}",
f" Active triggers: {result.get('active_triggers', 0)}",
f" Expired triggers: {result.get('expired_triggers', 0)}",
f" Symbols monitored: {result.get('symbols_monitored', 0)}",
f" OCO groups: {result.get('oco_groups', 0)}",
]
return "\n".join(lines)
# =============================================================================
# Export
# =============================================================================
__all__ = [
"create_gtt_trigger",
"create_gtt_oco_pair",
"list_gtt_triggers",
"delete_gtt_trigger",
"disable_gtt_trigger",
"enable_gtt_trigger",
"show_gtt_triggers",
"show_gtt_summary",
]