-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram_bot.py
More file actions
786 lines (635 loc) Β· 39.2 KB
/
Copy pathtelegram_bot.py
File metadata and controls
786 lines (635 loc) Β· 39.2 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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
# ==========================================================
# [telegram_bot.py] - π 100% ν΅ν© 무결μ μμ±λ³Έ (Full Version) π
# MODIFIED: [V28.16 μ§μμ(UI) μ€λ
μ· λ컀νλ§ κ·Έλλ μμ ]
# 1) V-REV μ§μμ λ λλ§ μ μ€μκ° ν(Queue) μ₯λΆ μ‘°νλ₯Ό μ λ©΄ μκ°νκ³ ,
# 17:05 μ€λ
μ·(cached_snap)μ λ°μ λ λ§€λ μ£Όλ¬Έ(SELL)μ μ§μ νμ±νμ¬
# μΆλ ₯νλλ‘ μλ²½ν λ컀νλ§(Decoupling) μ μ©. (μ₯μ€ νμ λ³λ μμ² μ°¨λ¨)
# 2) V14 (μ€λ¦¬μ§λ LOC) λͺ¨λ μ€λ
μ· λ‘λ λΆκΈ° μ μ€.
# 3) V14-VWAP λͺ¨λ μ€λ
μ· μλ Key('initial_qty') λΆμΌμΉ ν©νΈ κ΅μ .
# 4) [2μ°¨ 보μ] νλμ½λ©λ '[1μΈ΅ λ¨λ
]' λ¬Έμμ΄ μμ‘΄μ± 100% μκ° λ°
# μ μ°ν λμ λ²νΈ λΆμ¬(Pop1, Pop2...) νμ± μν€ν
μ² μ΄μ.
# 5) [3μ°¨ 보μ] V-REV μν νμ μ€μκ° λ³μ΄ λ°©μ΄λ₯Ό μν΄ actual_avg λμ
# μ€λ
μ·μ λ°μ λ avg_price μ΅μ»€ μ΅μ°μ μ μ©.
# MODIFIED: [V28.22 μ€λ
μ· λ λλ§ λ컀νλ§ μμ ] μ‘Έμ
μΉ΄λ λͺ©λ‘μμ
# κ³Όκ±° λ΄μμ μ‘°νν λ, ν΄λΉ λ΄μμ κ³ μ μλ³μ(ID)λ₯Ό λ·° μμ§μΌλ‘
# 100% μ λ¬νλλ‘ λΌμ°ν
λ°°μ (history_id=hid) κ΅μ μλ£.
# MODIFIED: [V28.28 μ΄λ²€νΈ 루ν μ§μ μ°¨λ¨(Blocking) μμ² λ°©μ΄]
# /sync νΈλ€λ¬ λ΄λΆμμ get_account_balance() λκΈ° ν¨μκ° μ΄λ²€νΈ 루νλ₯Ό
# μꡬ μ μ νλ μΉλͺ
μ λ²κ·Έλ₯Ό asyncio.to_thread() λνμΌλ‘ μλ²½ κ΅μ .
# NEW: [V28.31] νλ¨ κ³ μ ν€λ³΄λ νκΈ μ νΈ λ¬΄μλ΅ λ§Ήμ μλ²½ μμ (λΌμ°ν
볡ꡬ)
# π¨ [V28.50 NEW] AVWAP μμ΄μ μ μ© 'μ‘°κΈ°ν΄κ·Ό/νκ²μ€μ ' λ
립 UI λΌμ°ν° κ°ν΅
# π¨ [V29.04 MODIFIED] UI λ λλ§ ννΈν μμ : /history λͺ
λ Ήμ΄(cmd_history)μ ꡬν μΆλ ₯μ μ΅μ ν μ½λ°± UI(HIST:LIST)μ 100% λμΌνκ² ν΅μΌν μλ£.
# π¨ [V29.05 ν΅μ¬ μμ ] νλ¨κ° νλ°© μ€μΌ λ컀νλ§: V-REV μ§μμ(κ°μ΄λμ€) μ°μ° μ νν¬ νλ¨κ°(actual_avg) κ°μ
μ μꡬ μ°¨λ¨νκ³ , ν(Queue) μ§μΈ΅ κΈ°λ° μμ μμ° λ‘μ§ 100% μ΄μ μλ£.
# π¨ [V29.08 ν©νΈ κ΅μ ] μ₯λ§κ°(CLOSE) νμ¬κ° μΆλ ₯ μμ : μ νν°λ§μΌ μ’
λ£ νμλ μ€μκ° κ°κ²©($100.25) λμ 'μ κ·μ₯ μ’
κ°($98.09)'λ₯Ό νμ¬κ°(curr)λ‘ κ°μ κ³ μ νμ¬ HTSμ 100% λκΈ°ν μλ£.
# ==========================================================
import logging
import datetime
import pytz
import time
import os
import math
import asyncio
import html
import yfinance as yf
import pandas_market_calendars as mcal
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes, CommandHandler, CallbackQueryHandler, MessageHandler, filters
from telegram_view import TelegramView
from telegram_sync_engine import TelegramSyncEngine
from telegram_states import TelegramStates
from telegram_callbacks import TelegramCallbacks
class TelegramController:
def __init__(self, config, broker, strategy, tx_lock=None, queue_ledger=None, strategy_rev=None):
self.cfg = config
self.broker = broker
self.strategy = strategy
self.view = TelegramView()
self.user_states = {}
self.admin_id = self.cfg.get_chat_id()
self.sync_locks = {}
self.tx_lock = tx_lock or asyncio.Lock()
self.queue_ledger = queue_ledger
self.strategy_rev = strategy_rev
self.sync_engine = TelegramSyncEngine(self.cfg, self.broker, self.strategy, self.queue_ledger, self.view, self.tx_lock, self.sync_locks)
self.states_handler = TelegramStates(self.cfg, self.broker, self.queue_ledger, self.sync_engine)
self.callbacks_handler = TelegramCallbacks(self.cfg, self.broker, self.strategy, self.queue_ledger, self.sync_engine, self.view, self.tx_lock)
def _is_admin(self, update: Update):
if self.admin_id is None:
self.admin_id = self.cfg.get_chat_id()
if self.admin_id is None:
print("β οΈ λ³΄μ κ²½κ³ : ADMIN_CHAT_IDκ° μ€μ λμ§ μμ μ μ μλ μ¬μ©μμ μ κ·Όμ μ°¨λ¨νμ΅λλ€.")
return False
return update.effective_chat.id == int(self.admin_id)
def _get_dst_info(self):
est = pytz.timezone('US/Eastern')
now_est = datetime.datetime.now(est)
is_dst = now_est.dst() != datetime.timedelta(0)
if is_dst:
return (17, "π <b>μλ¨Ένμ μ μ© (Summer)</b>")
else:
return (18, "βοΈ <b>μλ¨Ένμ ν΄μ (Winter)</b>")
def _get_market_status(self):
est = pytz.timezone('US/Eastern')
now = datetime.datetime.now(est)
nyse = mcal.get_calendar('NYSE')
schedule = nyse.schedule(start_date=now.date(), end_date=now.date())
if schedule.empty:
return "CLOSE", "β μ₯ν΄μΌ"
market_open = schedule.iloc[0]['market_open'].astimezone(est)
market_close = schedule.iloc[0]['market_close'].astimezone(est)
pre_start = market_open.replace(hour=4, minute=0)
after_end = market_close.replace(hour=20, minute=0)
if pre_start <= now < market_open:
return "PRE", "π
ν리λ§μΌ"
elif market_open <= now < market_close:
return "REG", "π₯ μ κ·μ₯"
elif market_close <= now < after_end:
return "AFTER", "π μ νν°λ§μΌ"
else:
return "CLOSE", "β μ₯λ§κ°"
def _calculate_budget_allocation(self, cash, tickers):
sorted_tickers = sorted(tickers, key=lambda x: 0 if x == "SOXL" else (1 if x == "TQQQ" else 2))
allocated = {}
rem_cash = cash
for tx in sorted_tickers:
rev_state = self.cfg.get_reverse_state(tx)
is_rev = rev_state.get("is_active", False)
if is_rev:
allocated[tx] = 0.0
else:
split = self.cfg.get_split_count(tx)
portion = self.cfg.get_seed(tx) / split if split > 0 else 0
if rem_cash >= portion:
allocated[tx] = portion
rem_cash -= portion
else:
allocated[tx] = 0
return sorted_tickers, allocated
def setup_handlers(self, application):
application.add_handler(CommandHandler("start", self.cmd_start))
application.add_handler(CommandHandler("sync", self.cmd_sync))
application.add_handler(CommandHandler("record", self.cmd_record))
application.add_handler(CommandHandler("history", self.cmd_history))
application.add_handler(CommandHandler("settlement", self.cmd_settlement))
application.add_handler(CommandHandler("seed", self.cmd_seed))
application.add_handler(CommandHandler("ticker", self.cmd_ticker))
application.add_handler(CommandHandler("mode", self.cmd_mode))
application.add_handler(CommandHandler("version", self.cmd_version))
application.add_handler(CommandHandler("queue", self.cmd_queue))
application.add_handler(CommandHandler("add_q", self.cmd_add_q))
application.add_handler(CommandHandler("clear_q", self.cmd_clear_q))
application.add_handler(CommandHandler("reset", self.cmd_reset))
application.add_handler(CommandHandler("update", self.cmd_update))
# π¨ [V28.50 NEW] μμ΄μ μ μ© λͺ
λ Ήμ΄ μ μ€
application.add_handler(CommandHandler("avwap", self.cmd_avwap))
application.add_handler(CallbackQueryHandler(self.handle_callback))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_message))
async def handle_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
await self.callbacks_handler.handle_callback(update, context, self)
async def handle_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
if not self._is_admin(update):
return
text = update.message.text
if "μ₯λΆ μ‘°ν" in text:
return await self.cmd_record(update, context)
elif "μλ λ³κ²½" in text:
return await self.cmd_seed(update, context)
elif "λͺ¨λ μ ν" in text:
return await self.cmd_ticker(update, context)
elif "λΆν λ³κ²½" in text or "νκ²½ μ€μ " in text or "μΈν
" in text:
return await self.cmd_settlement(update, context)
elif "μ€λμ΄νΌ" in text:
return await self.cmd_mode(update, context)
elif "λͺ
μμ μ λΉ" in text or "μ‘Έμ
" in text:
return await self.cmd_history(update, context)
# π¨ [V28.50 NEW] λ€μ΄λ νΈ ν¨μ€μ μμ΄μ ν€μλ μ΄μ
elif "μμ΄μ" in text or "μ‘°κΈ°" in text:
return await self.cmd_avwap(update, context)
await self.states_handler.handle_message(update, context, self)
# π¨ [V28.50 NEW] μμ΄μ μ μ© μ‘°κΈ°ν΄κ·Ό UI λΌμ°ν°
async def cmd_avwap(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
if not self._is_admin(update):
return
t = "SOXL"
is_hybrid_on = self.cfg.get_avwap_hybrid_mode(t)
if not is_hybrid_on:
msg = f"β οΈ <b>[AVWAP μμ΄μ μ€νλΌμΈ]</b>\n"
msg += f"β«οΈ νμ¬ {t}μ AVWAP νμ΄λΈλ¦¬λ λͺ¨λκ° κΊΌμ Έμμ΅λλ€.\n"
msg += f"β«οΈ <code>/settlement</code> λ©λ΄μμ λ¨Όμ νμ±νν΄μ£ΌμΈμ."
return await update.message.reply_text(msg, parse_mode='HTML')
early_mode = self.cfg.get_avwap_early_exit_mode(t)
early_target = self.cfg.get_avwap_early_target(t)
msg = f"π« <b>[ {t} AVWAP μμ΄μ μ μ΄ μ½μ ]</b>\n\n"
if early_mode:
msg += "πββοΈ <b>νμ¬ λͺ¨λ: [μ‘°κΈ° ν΄κ·Ό (μ¬μ©μ λ§μΆ€ν)]</b>\n"
msg += f"β«οΈ μ₯μ€ μκ°μ ꡬμ λ°μ§ μκ³ <b>+{early_target}%</b> μμ΅ λλ¬ μ μ¦κ° μ λ μ΅μ νκ³ ν΄κ·Όν©λλ€.\n"
msg += "β«οΈ μ₯λ§ν λ³λμ± λ¦¬μ€ν¬λ₯Ό ννΌνκ³ μΌμΌ μμ΅μ νμ μ§λ λ° μ 리ν©λλ€.\n"
else:
msg += "π¦
<b>νμ¬ λͺ¨λ: [μ€λ¦¬μ§λ μ€ν΄μ¦ νκ²ν
]</b>\n"
msg += "β«οΈ μμ΅μ΄ λλ κΈ°λ€λ Έλ€κ° <b>μ€ν 2μ 30λΆ(EST)</b> μ΄ν λ°μνλ κΈ°κ΄ μ컀λ²λ§ μ€ν΄μ¦(+3% μ΄μ)λ₯Ό λ
Έλ¦½λλ€.\n"
msg += "β«οΈ ν©μ μ₯μΈμμλ μ’
κ°μ μμ΅μ λ°λ©ν 리μ€ν¬κ° μμ΅λλ€.\n"
keyboard = [
[
InlineKeyboardButton(f"βͺ μ€λ¦¬μ§λ λͺ¨λλ‘ μ ν" if early_mode else "π― μ€λ¦¬μ§λ λͺ¨λ (νμ¬ μ μ©)", callback_data=f"AVWAP:EARLY:OFF:{t}"),
InlineKeyboardButton(f"π― μ‘°κΈ° ν΄κ·Ό λͺ¨λ (νμ¬ μ μ©)" if early_mode else "πββοΈ μ‘°κΈ° ν΄κ·Ό λͺ¨λλ‘ μ ν", callback_data=f"AVWAP:EARLY:ON:{t}")
],
[
InlineKeyboardButton(f"βοΈ λͺ©ν μμ΅λ₯ μ€μ (νμ¬: {early_target}%)", callback_data=f"AVWAP:TARGET_SET:{t}")
]
]
await update.message.reply_text(msg, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode='HTML')
async def cmd_update(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
if not self._is_admin(update):
return
status_msg = await update.message.reply_text("β³ <b>[μμ€ν
μ
λ°μ΄νΈ]</b> κΉνλΈ μ격 μλ²μ ν΅μ μ μμν©λλ€...", parse_mode='HTML')
try:
from plugin_updater import SystemUpdater
updater = SystemUpdater()
success, msg = await updater.pull_latest_code()
safe_msg = html.escape(msg)
if success:
await status_msg.edit_text(f"β
<b>[λκΈ°ν μλ£]</b> {safe_msg}\n\nπ μμ€ν
λ°λͺ¬(pipiosbot)μ OS λ¨μμ μ¬κ°λν©λλ€. λ€μ΄νμ ν λ΄μ΄ λ€μ κΉ¨μ΄λ©λλ€.", parse_mode='HTML')
updater.restart_daemon()
else:
await status_msg.edit_text(f"β <b>[λκΈ°ν μ€ν¨]</b>\nβ«οΈ μ¬μ : {safe_msg}", parse_mode='HTML')
except Exception as e:
safe_err = html.escape(str(e))
await status_msg.edit_text(f"π¨ <b>[μΉλͺ
μ μ€λ₯]</b> νλ¬κ·ΈμΈ νΈμΆ λ° νλ‘μΈμ€ μμΈ λ°μ: {safe_err}", parse_mode='HTML')
async def cmd_queue(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
if not self._is_admin(update):
return
args = context.args
if not args:
return await update.message.reply_text("β μ’
λͺ©λͺ
μ μ
λ ₯νμΈμ. μ: /queue SOXL")
ticker = args[0].upper()
if not getattr(self, 'queue_ledger', None):
from queue_ledger import QueueLedger
self.queue_ledger = QueueLedger()
q_data = self.queue_ledger.get_queue(ticker)
msg, reply_markup = self.view.get_queue_management_menu(ticker, q_data)
await update.message.reply_text(text=msg, reply_markup=reply_markup, parse_mode='HTML')
async def cmd_add_q(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
if not self._is_admin(update):
return
try:
args = context.args
if len(args) < 4:
return await update.message.reply_text("β μ νν μμ: <code>/add_q SOXL 2026-04-06 20 52.16</code>", parse_mode='HTML')
ticker = args[0].upper()
date_str = args[1]
try:
qty = int(args[2])
price = float(args[3])
except ValueError:
return await update.message.reply_text("β μλμ μ μ, νλ¨κ°λ μ«μλ‘ μ
λ ₯νμΈμ.")
try:
curr_p = await asyncio.wait_for(
asyncio.to_thread(self.broker.get_current_price, ticker),
timeout=3.0
)
if curr_p and curr_p > 0:
if price < curr_p * 0.7 or price > curr_p * 1.3:
return await update.message.reply_text(f"π¨ <b>μ€μ
λ ₯ μ°¨λ¨:</b> μ
λ ₯νμ νλ¨κ°(<b>${price:.2f}</b>)κ° νμ¬κ° λλΉ Β±30%λ₯Ό λ²μ΄λ©λλ€. μ€νλ₯Ό νμΈνμΈμ!", parse_mode='HTML')
except asyncio.TimeoutError:
pass
except Exception:
pass
q_file = "data/queue_ledger.json"
all_q = {}
if os.path.exists(q_file):
try:
import json
with open(q_file, 'r', encoding='utf-8') as f:
all_q = json.load(f)
except Exception:
pass
ticker_q = all_q.get(ticker, [])
ticker_q.append({
"qty": qty,
"price": price,
"date": f"{date_str} 23:59:59",
"type": "MANUAL_OVERRIDE"
})
ticker_q.sort(key=lambda x: x.get('date', ''), reverse=True)
chat_id = update.effective_chat.id
await self.sync_engine._verify_and_update_queue(ticker, ticker_q, context, chat_id)
await update.message.reply_text(f"β
<b>[{ticker}] μλ μ§μΈ΅ μ½μ
μλ£!</b>\nβ«οΈ {date_str} | {qty}μ£Ό | ${price:.2f}", parse_mode='HTML')
except Exception as e:
await update.message.reply_text(f"β μ μ μλ μλ¬ λ°μ: {e}")
async def cmd_clear_q(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
if not self._is_admin(update):
return
args = context.args
if not args:
return await update.message.reply_text("β μ’
λͺ©λͺ
μ μ
λ ₯νμΈμ. μ: /clear_q SOXL")
ticker = args[0].upper()
try:
chat_id = update.effective_chat.id
await self.sync_engine._verify_and_update_queue(ticker, [], context, chat_id)
await update.message.reply_text(f"ποΈ <b>[{ticker}] μ₯λΆκ° μμ ν μκ°λμμ΅λλ€.</b>\nμλ‘μ΄ μ§μΈ΅μ ꡬμΆν μ€λΉκ° μλ£λμμ΅λλ€.", parse_mode='HTML')
except Exception as e:
await update.message.reply_text(f"β μκ° μ€ μλ¬ λ°μ: {e}")
async def cmd_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
if not self._is_admin(update):
return
target_hour, season_icon = self._get_dst_info()
latest_version = self.cfg.get_latest_version()
msg = self.view.get_start_message(target_hour, season_icon, latest_version)
await update.message.reply_text(msg, parse_mode='HTML')
async def cmd_sync(self, update, context):
if not self._is_admin(update):
return
await update.message.reply_text("π μμ₯ λΆμ λ° μ§μμ μμ± μ€...")
async with self.tx_lock:
cash, holdings = await asyncio.to_thread(self.broker.get_account_balance)
if holdings is None:
await update.message.reply_text("β KIS API ν΅μ μ€λ₯λ‘ κ³μ’ μ 보λ₯Ό λΆλ¬μ¬ μ μμ΅λλ€. μ μ ν λ€μ μλν΄μ£ΌμΈμ.")
return
target_hour, _ = self._get_dst_info()
dst_txt = "π μλ¨Ένμ (17:30)" if target_hour == 17 else "βοΈ κ²¨μΈ (18:30)"
status_code, status_text = self._get_market_status()
tickers = self.cfg.get_active_tickers()
sorted_tickers, allocated_cash = self._calculate_budget_allocation(cash, tickers)
ticker_data_list = []
total_buy_needed = 0.0
tracking_cache = {}
try:
jobs = context.job_queue.jobs() if context.job_queue else []
job_data = jobs[0].data if jobs and jobs[0].data is not None else {}
tracking_cache = job_data.get('sniper_tracking', {})
except (IndexError, AttributeError):
tracking_cache = {}
est = pytz.timezone('US/Eastern')
now_est = datetime.datetime.now(est)
is_sniper_active_time = False
try:
nyse = mcal.get_calendar('NYSE')
schedule = nyse.schedule(start_date=now_est.date(), end_date=now_est.date())
if not schedule.empty:
market_open = schedule.iloc[0]['market_open'].astimezone(est)
switch_time = market_open + datetime.timedelta(minutes=50)
if now_est >= switch_time:
is_sniper_active_time = True
except Exception:
if now_est.weekday() < 5 and now_est.time() >= datetime.time(10, 20):
is_sniper_active_time = True
for t in sorted_tickers:
h = holdings.get(t, {'qty':0, 'avg':0})
curr = await asyncio.to_thread(self.broker.get_current_price, t, is_market_closed=(status_code == "CLOSE"))
prev_close = await asyncio.to_thread(self.broker.get_previous_close, t)
ma_5day = await asyncio.to_thread(self.broker.get_5day_ma, t)
day_high, day_low = await asyncio.to_thread(self.broker.get_day_high_low, t)
actual_avg = float(h['avg']) if h['avg'] else 0.0
actual_qty = int(h['qty'])
safe_prev_close = prev_close if prev_close else 0.0
# μΌν νμ΄λΈμ€ μ κ·μ₯ μ’
κ° μ€μΊ
if status_code in ["AFTER", "CLOSE", "PRE"]:
try:
def get_yf_close():
df = yf.Ticker(t).history(period="5d", interval="1d")
return float(df['Close'].iloc[-1]) if not df.empty else None
yf_close = await asyncio.wait_for(asyncio.to_thread(get_yf_close), timeout=3.0)
if yf_close and yf_close > 0:
safe_prev_close = yf_close
except Exception as e:
logging.debug(f"YF μ κ·μ₯ μ’
κ° λ‘€μ€λ² μ€μΊ μ€ν¨ ({t}): {e}")
# π’ [V29.08 ν©νΈ κ΅μ ] μ₯λ§κ°(CLOSE) μνμΌ κ²½μ°,
# μ νν°λ§μΌ λ³λ κ°κ²©μ 무μνκ³ μ κ·μ₯ μ’
κ°λ₯Ό νμ¬κ°λ‘ κ°μ μΉν
if status_code == "CLOSE":
curr = safe_prev_close
idx_ticker = "SOXX" if t == "SOXL" else "QQQ"
dynamic_pct_obj = await asyncio.to_thread(self.broker.get_dynamic_sniper_target, idx_ticker)
dynamic_pct = float(dynamic_pct_obj) if dynamic_pct_obj is not None else (8.79 if t == "SOXL" else 4.95)
tracking_status = tracking_cache.get(t, {})
current_day_high = tracking_status.get('day_high', day_high)
hybrid_target_price = current_day_high * (1 - (abs(dynamic_pct) / 100.0))
trigger_reason = f"-{abs(dynamic_pct)}%"
is_already_ordered = self.cfg.check_lock(t, "REG") or self.cfg.check_lock(t, "SNIPER")
ver = self.cfg.get_version(t)
is_manual_vwap = getattr(self.cfg, 'get_manual_vwap_mode', lambda x: False)(t)
cached_snap = None
if ver == "V_REV":
cached_snap = self.strategy.v_rev_plugin.load_daily_snapshot(t)
elif ver == "V14":
if is_manual_vwap:
cached_snap = self.strategy.v14_vwap_plugin.load_daily_snapshot(t)
else:
if hasattr(self.strategy, 'v14_plugin') and hasattr(self.strategy.v14_plugin, 'load_daily_snapshot'):
cached_snap = self.strategy.v14_plugin.load_daily_snapshot(t)
logic_qty = actual_qty
if cached_snap:
if "total_q" in cached_snap:
logic_qty = cached_snap["total_q"]
elif "initial_qty" in cached_snap:
logic_qty = cached_snap["initial_qty"]
plan = self.strategy.get_plan(
t, curr, actual_avg, logic_qty, safe_prev_close, ma_5day=ma_5day,
market_type="REG", available_cash=allocated_cash[t],
is_simulation=True
)
split = self.cfg.get_split_count(t)
seed = self.cfg.get_seed(t)
t_val = plan.get('t_val', 0.0)
is_rev = plan.get('is_reverse', False)
if dynamic_pct_obj and hasattr(dynamic_pct_obj, 'metric_val'):
real_val = float(dynamic_pct_obj.metric_val)
else:
real_val = 0.0
vol_status = "ON" if real_val >= 20.0 else "OFF"
v_rev_q_qty = 0
v_rev_q_lots = 0
v_rev_guidance = ""
is_avwap_active = False
avwap_budget = 0.0
avwap_qty = 0
avwap_avg = 0.0
avwap_status_txt = ""
if ver == "V_REV":
if not getattr(self, 'queue_ledger', None):
from queue_ledger import QueueLedger
self.queue_ledger = QueueLedger()
q_list = self.queue_ledger.get_queue(t)
v_rev_q_lots = len(q_list)
v_rev_q_qty = sum(item.get('qty', 0) for item in q_list)
one_portion_cash = seed * 0.15
plan['one_portion'] = one_portion_cash
half_portion_cash = one_portion_cash * 0.5
tag = "VWAP" if is_manual_vwap else "LOC"
# ==========================================================
# π¨ [V29.05 ν΅μ¬ μμ ] V-REV λ§€λκ° κ°μ΄λμ€(μ§μμ) 100% λ컀νλ§ μ΄μ
# ==========================================================
if cached_snap and "orders" in cached_snap and v_rev_q_qty > 0:
sell_idx = 1
for o in cached_snap["orders"]:
if o.get('side') == 'SELL':
v_rev_guidance += f"βπ΅ λ§€λ{sell_idx}(Pop{sell_idx}) ${o['price']:.2f} <b>{o['qty']}μ£Ό</b> ({tag})\n"
sell_idx += 1
if not is_manual_vwap:
if 'avg_price' in cached_snap:
snap_avg = cached_snap['avg_price']
else:
total_q = sum(item.get('qty', 0) for item in q_list)
total_inv = sum(item.get('qty', 0) * item.get('price', 0.0) for item in q_list)
snap_avg = total_inv / total_q if total_q > 0 else 0.0
target_jackpot = round(snap_avg * 1.01, 2) if snap_avg > 0 else 0.0
v_rev_guidance += f"βπ― [μ 체 μν] ${target_jackpot:.2f} <b>{logic_qty}μ£Ό</b> (μ΅μ
)\n"
elif q_list and logic_qty > 0:
l1_qty = q_list[-1].get('qty', 0)
l1_price = q_list[-1].get('price', safe_prev_close)
target_l1 = round(l1_price * 1.006, 2)
v_rev_guidance += f"βπ΅ λ§€λ1(Pop1) ${target_l1:.2f} <b>{l1_qty}μ£Ό</b> ({tag})\n"
upper_qty = sum(item.get('qty', 0) for item in q_list[:-1])
if upper_qty > 0:
upper_invested = sum(item.get('qty', 0) * item.get('price', 0.0) for item in q_list[:-1])
upper_avg = upper_invested / upper_qty
target_upper = round(upper_avg * 1.005, 2)
v_rev_guidance += f"βπ΅ λ§€λ2(Pop2) ${target_upper:.2f} <b>{upper_qty}μ£Ό</b> ({tag})\n"
if not is_manual_vwap:
total_q = sum(item.get('qty', 0) for item in q_list)
total_inv = sum(item.get('qty', 0) * item.get('price', 0.0) for item in q_list)
pure_queue_avg = total_inv / total_q if total_q > 0 else 0.0
target_jackpot = round(pure_queue_avg * 1.01, 2) if pure_queue_avg > 0 else 0.0
v_rev_guidance += f"βπ― [μ 체 μν] ${target_jackpot:.2f} <b>{logic_qty}μ£Ό</b> (μ΅μ
)\n"
else:
v_rev_guidance += "βπ΅ λ§€λ: λκΈ° λ¬Όλ μμ (κ΄λ§)\n"
if safe_prev_close > 0:
b1_price = round(safe_prev_close / 0.935 if logic_qty == 0 else safe_prev_close * 0.995, 2)
b2_price = round(safe_prev_close * 0.999 if logic_qty == 0 else safe_prev_close * 0.9725, 2)
b1_qty = math.floor(half_portion_cash / b1_price) if b1_price > 0 else 0
b2_qty = math.floor(half_portion_cash / b2_price) if b2_price > 0 else 0
if b1_qty > 0:
v_rev_guidance += f"βπ΄ λ§€μ1(Buy1) ${b1_price:.2f} <b>{b1_qty}μ£Ό</b> ({tag})\n"
if b2_qty > 0:
v_rev_guidance += f"βπ΄ λ§€μ2(Buy2) ${b2_price:.2f} <b>{b2_qty}μ£Ό</b> ({tag})\n"
if logic_qty == 0:
v_rev_guidance += "βπ« <code>[0μ£Ό μμΆλ°] κΈ°μ€ νλ¨κ° λΆμ¬λ‘ μ€μ€ μλ΅ (1μΈ΅ ν보μ μμ° 100% μ§μ€)</code>"
elif b2_qty > 0 and b2_price > 0:
if not is_manual_vwap:
grid_start = round(half_portion_cash / (b2_qty + 1), 2)
grid_end = round(half_portion_cash / (b2_qty + 5), 2)
if grid_start >= 0.01 and grid_start < b2_price:
grid_end = max(grid_end, 0.01)
v_rev_guidance += f"βπ§Ή μ€μ€(5κ°): ${grid_start:.2f} ~ ${grid_end:.2f} ({tag})"
else:
v_rev_guidance += "βπ΄ λ§€μ λκΈ°: νμ μ°μ° λκΈ° μ€"
if is_manual_vwap:
v_rev_guidance += "\n\nπ¨ <b>[ β μΉλͺ
μ κ²½κ³ : μλ VWAP μ€μ ]</b> π¨\n"
v_rev_guidance += "νν¬ μ±(Vμ±)μμ μλ μ£Όλ¬Έμ κ±°μ€ λ, <b>μ λλ‘ 'ν루 μ’
μΌ'λ‘ μ€μ νμ§ λ§μμμ€!</b>\n"
v_rev_guidance += "μλ μκ°μ λ°λμ \n<b>[μ₯ λ§κ° 30λΆ μ ~ μ₯ λ§κ°]</b>\nμΌλ‘λ§ μΈν
νμ
μΌ ν©λλ€.\n"
v_rev_guidance += "μ₯μ€ λ΄λ΄ μλνκ² λ κ²½μ° V-REV μ½μ΄ μ λ΅μ μμ΅λ₯ μ΄ μ¬κ°νκ² νκ΄΄λ©λλ€."
if hasattr(self.cfg, 'get_avwap_hybrid_mode') and self.cfg.get_avwap_hybrid_mode(t):
is_avwap_active = True
avwap_qty = tracking_cache.get(f"AVWAP_QTY_{t}", 0)
avwap_avg = tracking_cache.get(f"AVWAP_AVG_{t}", 0.0)
avwap_budget = cash
if tracking_cache.get(f"AVWAP_SHUTDOWN_{t}"):
avwap_status_txt = "π μꡬλκ²° (SHUTDOWN)"
elif tracking_cache.get(f"AVWAP_BOUGHT_{t}"):
avwap_status_txt = "π― λ₯λ§€μ μλ£ (μ΅μ /μμ κ°μμ€)"
else:
avwap_status_txt = "π μ₯μ΄λ° νν° μ€μΊ λ° νμ λκΈ°"
ticker_data_list.append({
'ticker': t, 'version': ver, 't_val': t_val, 'split': split, 'curr': curr, 'avg': actual_avg, 'qty': actual_qty,
'profit_amt': (curr - actual_avg) * actual_qty if actual_qty > 0 else 0,
'profit_pct': (curr - actual_avg) / actual_avg * 100 if actual_avg > 0 else 0,
'upward_sniper': "ON" if self.cfg.get_upward_sniper_mode(t) else "OFF",
'target': self.cfg.get_target_profit(t), 'star_pct': round(plan.get('star_ratio', 0) * 100, 2) if 'star_ratio' in plan else 0.0,
'seed': seed, 'one_portion': plan.get('one_portion', 0.0), 'plan': plan,
'is_locked': is_already_ordered, 'mode': "REG",
'is_reverse': is_rev, 'star_price': plan.get('star_price', 0.0),
'escrow': self.cfg.get_escrow_cash(t),
'hybrid_target': hybrid_target_price,
'trigger_reason': trigger_reason,
'sniper_trigger': abs(float(dynamic_pct)),
'day_high': day_high,
'day_low': day_low,
'prev_close': safe_prev_close,
'tracking_info': tracking_status,
'dynamic_obj': dynamic_pct_obj,
'is_sniper_active_time': is_sniper_active_time,
'vol_weight': round(real_val, 2),
'vol_status': vol_status,
'v_rev_q_lots': v_rev_q_lots,
'v_rev_q_qty': v_rev_q_qty,
'v_rev_guidance': v_rev_guidance,
'avwap_active': is_avwap_active,
'avwap_budget': avwap_budget,
'avwap_qty': avwap_qty,
'avwap_avg': avwap_avg,
'avwap_status': avwap_status_txt,
'is_manual_vwap': is_manual_vwap
})
total_buy_needed += sum(o['price']*o['qty'] for o in plan.get('orders', []) if o.get('side')=='BUY')
surplus = cash - total_buy_needed
rp_amount = surplus * 0.95 if surplus > 0 else 0
final_msg, markup = self.view.create_sync_report(status_text, dst_txt, cash, rp_amount, ticker_data_list, status_code in ["PRE", "REG"], p_trade_data={})
await update.message.reply_text(final_msg, reply_markup=markup, parse_mode='HTML')
async def cmd_record(self, update, context):
if not self._is_admin(update):
return
chat_id = update.message.chat_id
status_msg = await context.bot.send_message(chat_id, "π‘οΈ <b>μ₯λΆ λ¬΄κ²°μ± κ²μ¦ λ° λκΈ°ν μ€...</b>", parse_mode='HTML')
success_tickers = []
for t in self.cfg.get_active_tickers():
res = await self.sync_engine.process_auto_sync(t, chat_id, context, silent_ledger=True)
if res == "SUCCESS":
success_tickers.append(t)
if success_tickers:
async with self.tx_lock:
_, holdings = self.broker.get_account_balance()
await self.sync_engine._display_ledger(success_tickers[0], chat_id, context, message_obj=status_msg, pre_fetched_holdings=holdings)
else:
await status_msg.edit_text("β
<b>λκΈ°ν μλ£</b> (νμν μ§ν μ€μΈ μ₯λΆκ° μκ±°λ μλ¬ λκΈ° μ€μ
λλ€)", parse_mode='HTML')
async def cmd_history(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
if not self._is_admin(update):
return
try:
history_data = self.cfg.get_history()
except Exception:
history_data = []
if not history_data:
await update.message.reply_text("π <b>λͺ
μμ μ λΉ (μ‘Έμ
κΈ°λ‘)μ΄ λΉμ΄μμ΅λλ€.</b>", parse_mode='HTML')
return
sorted_hist = sorted(history_data, key=lambda x: x.get('end_date', ''), reverse=True)
msg = "π <b>[ λͺ
μμ μ λΉ (κ³Όκ±° μ‘Έμ
κΈ°λ‘) ]</b>\n\n"
msg += "μμΈ λ΄μμ μ‘°νν κΈ°λ‘μ μ ννμΈμ.\n"
keyboard = []
for h in sorted_hist[:15]:
t = h.get('ticker', 'UNK')
p = h.get('profit', 0.0)
date_str = h.get('end_date', '')[:10].replace("-", ".")
sign = "+" if p >= 0 else "-"
btn_text = f"π
{date_str} [{t}] {sign}${abs(p):.2f}"
keyboard.append([InlineKeyboardButton(btn_text, callback_data=f"HIST:VIEW:{h['id']}")])
keyboard.append([InlineKeyboardButton("β λ«κΈ°", callback_data="RESET:CANCEL")])
await update.message.reply_text(msg, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode='HTML')
async def cmd_mode(self, update, context):
if not self._is_admin(update):
return
active_tickers = self.cfg.get_active_tickers()
report = "π <b>[ μμ¨μ£Όν λ³λμ± λ§μ€ν° μ§ν μμΈ λΆμ ]</b>\n\n"
report += "<b>[ π§ μ§μ λ²μ λ²λ‘ (ON/OFF κΆμ₯) ]</b>\n"
report += "π§ <code>~ 15.00</code> : κ·Ήμ λ³λμ± (OFF)\n"
report += "π© <code>15.00 ~ 20.00</code> : μ μ κΆ€λ (OFF)\n"
report += "π¨ <code>20.00 ~ 25.00</code> : λ³λμ± νλ (ON)\n"
report += "π₯ <code>25.00 μ΄μ </code> : ν¨λ μ
λ§ (ON)\n\n"
for t in active_tickers:
idx_ticker = "SOXX" if t == "SOXL" else "QQQ"
dynamic_pct_obj = await asyncio.to_thread(self.broker.get_dynamic_sniper_target, idx_ticker)
if dynamic_pct_obj and hasattr(dynamic_pct_obj, 'metric_val'):
real_val = float(dynamic_pct_obj.metric_val)
real_name = dynamic_pct_obj.metric_name
else:
real_val = 0.0
real_name = "μ§ν"
if real_val <= 15.0:
diag_text = "κ·Ήμ λ³λμ± (μ°μΈ‘ 꼬리 μ λ¨ λ°©μ§λ₯Ό μν΄ μ€λμ΄νΌ OFF)"
status_icon = "π§"
elif real_val <= 20.0:
diag_text = "μ μ κΆ€λ μμ°© (μ€λμ΄νΌ OFF)"
status_icon = "π©"
elif real_val <= 25.0:
diag_text = "λ³λμ± νλ μ₯μΈ (κ³μ’ λ°©μ΄λ₯Ό μν΄ μ€λμ΄νΌ ON)"
status_icon = "π¨"
else:
diag_text = "ν¨λ μ
λ§ λ° μμ€ν
좩격 (μ€λμ΄νΌ νμ κ°λ)"
status_icon = "π₯"
report += f"π <b>[ {t} κ΅λ©΄ λΆμ ]</b>\n"
report += f"β«οΈ λΉμΌ μ λ μ§μ({real_name}): {real_val:.2f}\n"
report += f"β«οΈ μ§λ¨ : {status_icon} {diag_text}\n\n"
report += "π― <b>[ μλ μλ°© μ€λμ΄νΌ λ
립 μ μ΄ ]</b>\n"
keyboard = []
for t in active_tickers:
is_sniper = self.cfg.get_upward_sniper_mode(t)
status_txt = 'ON (κ°λμ€)' if is_sniper else 'OFF (λκΈ°μ€)'
report += f"β«οΈ {t} νμ¬ μν : {status_txt}\n"
keyboard.append([
InlineKeyboardButton(f"{t} βͺ OFF", callback_data=f"MODE:OFF:{t}"),
InlineKeyboardButton(f"{t} π― ON", callback_data=f"MODE:ON:{t}")
])
await update.message.reply_text(report, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode='HTML')
async def cmd_reset(self, update, context):
if not self._is_admin(update):
return
active_tickers = self.cfg.get_active_tickers()
msg, markup = self.view.get_reset_menu(active_tickers)
await update.message.reply_text(msg, reply_markup=markup, parse_mode='HTML')
async def cmd_seed(self, update, context):
if not self._is_admin(update):
return
msg = "π΅ <b>[ μ’
λͺ©λ³ μλλ¨Έλ κ΄λ¦¬ ]</b>\n\n"
keyboard = []
for t in self.cfg.get_active_tickers():
current_seed = self.cfg.get_seed(t)
msg += f"π <b>{t}</b>: ${current_seed:,.0f}\n"
keyboard.append([
InlineKeyboardButton(f"β {t} μΆκ°", callback_data=f"SEED:ADD:{t}"),
InlineKeyboardButton(f"β {t} κ°μ", callback_data=f"SEED:SUB:{t}"),
InlineKeyboardButton(f"π’ {t} κ³ μ ", callback_data=f"SEED:SET:{t}")
])
await update.message.reply_text(msg, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode='HTML')
async def cmd_ticker(self, update, context):
if not self._is_admin(update):
return
msg, markup = self.view.get_ticker_menu(self.cfg.get_active_tickers())
await update.message.reply_text(msg, reply_markup=markup, parse_mode='HTML')
async def cmd_settlement(self, update, context):
if not self._is_admin(update):
return
active_tickers = self.cfg.get_active_tickers()
atr_data = {}
dynamic_target_data = {}
status_msg = await update.message.reply_text("β³ <b>μ€μκ° μμ₯ μ§ν(HV/VXN) μ°μ° μ€...</b>", parse_mode='HTML')
est = pytz.timezone('US/Eastern')
now_est = datetime.datetime.now(est)
for t in active_tickers:
atr_data[t] = (0.0, 0.0)
dynamic_target_data[t] = None
msg, markup = self.view.get_settlement_message(active_tickers, self.cfg, atr_data, dynamic_target_data)
await status_msg.edit_text(msg, reply_markup=markup, parse_mode='HTML')
async def cmd_version(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
if not self._is_admin(update):
return
history_data = self.cfg.get_full_version_history()
msg, markup = self.view.get_version_message(history_data, page_index=None)
await update.message.reply_text(msg, reply_markup=markup, parse_mode='HTML')