-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathtelegram_sync_engine.py
More file actions
787 lines (655 loc) ยท 51.2 KB
/
telegram_sync_engine.py
File metadata and controls
787 lines (655 loc) ยท 51.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
787
# ==========================================================
# FILE: telegram_sync_engine.py
# ==========================================================
# ๐จ [AI ์์ด์ ํธ(Copilot/Claude) ์ ๋ ์ฃผ์ - ํ๊ฐ(Hallucination) ๋ฐฉ์ด๋ง]
# ์ 1ํ๋ฒ: queue_ledger.get_queue ๋ฑ ๋ชจ๋ ํ์ผ I/O ๋ฐ ๋ฝ ์ ์ ๋ฉ์๋๋ ๋ฌด์กฐ๊ฑด asyncio.to_thread๋ก ๋ํํ์ฌ ์ด๋ฒคํธ ๋ฃจํ ๊ต์ฐฉ(Deadlock)์ ์์ฒ ์ฐจ๋จํจ.
# MODIFIED: [V44.47 ์ด๋ฒคํธ ๋ฃจํ ๋ฐ๋๋ฝ ์๊ตฌ ์๊ฐ] ๋๊ธฐ์ ๋ธ๋กํน ํธ์ถ(์ฅ๋ถ I/O, JSON ํ์ฑ) ์ ๋ฉด ๋น๋๊ธฐ ๋ํ ๋ฐ Atomic Write ์ ์ฉ ์๋ฃ.
# MODIFIED: [V44.48 ๋ฐ๋์ฝ๋ ์๊ฐ] ํด๋์ค ๋ด๋ถ์ ์์กดํ๋ _verify_and_update_queue ๋ฉ์๋ ์ ์ฒด 100% ์๊ตฌ ์๊ฐ.
# ==========================================================
import logging
import datetime
from zoneinfo import ZoneInfo
import time
import os
import asyncio
import json
import tempfile
import traceback
import yfinance as yf
import pandas_market_calendars as mcal
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
class TelegramSyncEngine:
def __init__(self, config, broker, strategy, queue_ledger, view, tx_lock, sync_locks):
self.cfg = config
self.broker = broker
self.strategy = strategy
self.queue_ledger = queue_ledger
self.view = view
self.tx_lock = tx_lock
self.sync_locks = sync_locks
# ๐จ [๋น๋๊ธฐ ๋ํ] ํ์ผ I/O ๋ฐ๋๋ฝ ๋ฐฉ์ด๋ฅผ ์ํ async ์ ํ
async def _sync_escrow_cash(self, ticker):
rev_state = await asyncio.to_thread(self.cfg.get_reverse_state, ticker)
is_rev = rev_state.get("is_active", False)
if not is_rev:
await asyncio.to_thread(self.cfg.clear_escrow_cash, ticker)
return
ledger = await asyncio.to_thread(self.cfg.get_ledger)
target_recs = []
for r in reversed(ledger):
if r.get('ticker') == ticker:
if r.get('is_reverse', False):
target_recs.append(r)
else:
break
escrow = 0.0
for r in target_recs:
amt = r['qty'] * r['price']
if r['side'] == 'SELL':
escrow += amt
elif r['side'] == 'BUY':
escrow -= amt
await asyncio.to_thread(self.cfg.set_escrow_cash, ticker, max(0.0, escrow))
async def process_auto_sync(self, ticker, chat_id, context, silent_ledger=False):
if ticker not in self.sync_locks:
self.sync_locks[ticker] = asyncio.Lock()
if self.sync_locks[ticker].locked():
return "LOCKED"
async with self.sync_locks[ticker]:
async with self.tx_lock:
last_split_date = await asyncio.to_thread(self.cfg.get_last_split_date, ticker)
try:
split_ratio, split_date = await asyncio.wait_for(
asyncio.to_thread(self.broker.get_recent_stock_split, ticker, last_split_date),
timeout=10.0
)
except asyncio.TimeoutError:
split_ratio, split_date = 0.0, ""
logging.warning(f"โ ๏ธ [{ticker}] ์ผํ ํ์ด๋ธ์ค ์ก๋ฉด๋ถํ ์กฐํ ํ์์์ (10์ด ์ด๊ณผ), ์ด๋ฒ ์ฑํฌ์์ ์คํต")
if split_ratio > 0.0 and split_date != "":
await asyncio.to_thread(self.cfg.apply_stock_split, ticker, split_ratio)
await asyncio.to_thread(self.cfg.set_last_split_date, ticker, split_date)
split_type = "์ก๋ฉด๋ถํ " if split_ratio > 1.0 else "์ก๋ฉด๋ณํฉ(์ญ๋ถํ )"
await context.bot.send_message(chat_id, f"โ๏ธ <b>[{ticker}] ์ผํ ํ์ด๋ธ์ค {split_type} ์๋ ๊ฐ์ง!</b>\nโซ๏ธ ๊ฐ์ง๋ ๋น์จ: <b>{split_ratio}๋ฐฐ</b> (๋ฐ์์ผ: {split_date})\nโซ๏ธ ๋ด์ด ๊ธฐ์กด ์ฅ๋ถ์ ์๋๊ณผ ํ๋จ๊ฐ๋ฅผ 100% ๋ฌด์ธ ์๋ ์๊ธ ์กฐ์ ์๋ฃํ์ต๋๋ค.", parse_mode='HTML')
kst = ZoneInfo('Asia/Seoul')
now_kst = datetime.datetime.now(kst)
est = ZoneInfo('America/New_York')
now_est = datetime.datetime.now(est)
def _get_last_trade_date():
nyse = mcal.get_calendar('NYSE')
schedule = nyse.schedule(start_date=(now_est - datetime.timedelta(days=10)).date(), end_date=now_est.date())
return schedule
try:
schedule = await asyncio.wait_for(asyncio.to_thread(_get_last_trade_date), timeout=10.0)
if not schedule.empty:
last_trade_date = schedule.index[-1]
target_ledger_str = last_trade_date.strftime('%Y-%m-%d')
else:
target_ledger_str = now_est.strftime('%Y-%m-%d')
except Exception as e:
logging.error(f"โ ๏ธ [{ticker}] ๋ฌ๋ ฅ API ์๋ฌ/ํ์์์. Fallback์ผ๋ก ํ์ฌ ๋ ์ง ์ธํ
: {e}")
target_ledger_str = now_est.strftime('%Y-%m-%d')
_, holdings = await asyncio.to_thread(self.broker.get_account_balance)
if holdings is None:
await context.bot.send_message(chat_id, f"โ <b>[{ticker}] API ์ค๋ฅ</b>\n์๊ณ ๋ฅผ ๋ถ๋ฌ์ค์ง ๋ชปํ์ต๋๋ค.", parse_mode='HTML')
return "ERROR"
actual_qty = int(float(holdings.get(ticker, {'qty': 0}).get('qty') or 0))
actual_avg = float(holdings.get(ticker, {'avg': 0}).get('avg') or 0.0)
# ๐จ [๋น๋๊ธฐ ๋ํ] ์ฅ๋ถ ํ์ผ I/O ๋ฐ๋๋ฝ ๋ฐฉ์ด
full_ledger = await asyncio.to_thread(self.cfg.get_ledger)
recs_for_check = [r for r in full_ledger if r['ticker'] == ticker]
ledger_qty_for_check, _, _, _ = await asyncio.to_thread(self.cfg.calculate_holdings, ticker, recs_for_check)
vrev_ledger_qty_for_check = 0
is_rev = (await asyncio.to_thread(self.cfg.get_version, ticker) == "V_REV")
if is_rev:
if not getattr(self, 'queue_ledger', None):
from queue_ledger import QueueLedger
self.queue_ledger = QueueLedger()
q_data_check = await asyncio.to_thread(self.queue_ledger.get_queue, ticker)
vrev_ledger_qty_for_check = sum(int(float(item.get("qty") or 0)) for item in q_data_check)
max_check_qty = max(ledger_qty_for_check, vrev_ledger_qty_for_check)
kis_search_start = (now_kst - datetime.timedelta(days=4)).strftime('%Y%m%d')
query_end_dt = now_kst.strftime('%Y%m%d')
def filter_to_est(execs_raw):
filtered = []
if not execs_raw: return filtered
for ex in execs_raw:
ord_dt = ex.get('ord_dt') or ex.get('ord_strt_dt')
if not ord_dt: continue
ord_tmd = ex.get('ord_tmd')
if not ord_tmd or len(str(ord_tmd)) != 6:
ord_tmd = '000000'
try:
k_dt = datetime.datetime.strptime(f"{ord_dt}{ord_tmd}", "%Y%m%d%H%M%S").replace(tzinfo=kst)
e_dt = k_dt.astimezone(est)
if e_dt.strftime('%Y-%m-%d') == target_ledger_str:
filtered.append(ex)
except Exception as e:
logging.error(f"๐จ ํ์์กด ํ์ฑ ์๋ฌ: {e}")
return filtered
raw_execs = []
target_execs = []
if actual_qty == 0 and max_check_qty > 0:
max_retries = 6
prev_sold_today = -1
stable_cnt = 0
for attempt in range(max_retries):
raw_execs = await asyncio.to_thread(self.broker.get_execution_history, ticker, kis_search_start, query_end_dt)
target_execs = filter_to_est(raw_execs)
sold_today = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in target_execs if ex.get('sll_buy_dvsn_cd') == "01")
if sold_today >= max_check_qty:
if sold_today == prev_sold_today:
stable_cnt += 1
if stable_cnt >= 1:
break
else:
stable_cnt = 0
prev_sold_today = sold_today
if attempt < max_retries - 1:
logging.info(f"โณ [{ticker}] ์ฒด๊ฒฐ ์์ฅ ์ง์ฐ(Lag) ๊ฐ์ง. ๋ฐ์ดํฐ ์์ ํ ๋ฐ EST ๋งคํ ๊ฒ์ฆ ์ค... ({attempt+1}/{max_retries})")
await asyncio.sleep(2.0)
else:
raw_execs = await asyncio.to_thread(self.broker.get_execution_history, ticker, kis_search_start, query_end_dt)
target_execs = filter_to_est(raw_execs)
if target_execs:
calibrated_count = await asyncio.to_thread(self.cfg.calibrate_ledger_prices, ticker, target_ledger_str, target_execs)
if calibrated_count > 0:
logging.info(f"๐ง [{ticker}] LOC/MOC ์ฃผ๋ฌธ {calibrated_count}๊ฑด์ ๋ํด ์ค์ ์ฒด๊ฒฐ ๋จ๊ฐ ์๊ธ ์
๋ฐ์ดํธ๋ฅผ ์๋ฃํ์ต๋๋ค.")
full_ledger = await asyncio.to_thread(self.cfg.get_ledger)
recs = [r for r in full_ledger if r['ticker'] == ticker]
ledger_qty, avg_price, _, _ = await asyncio.to_thread(self.cfg.calculate_holdings, ticker, recs)
diff = actual_qty - ledger_qty
price_diff = abs(actual_avg - avg_price)
today_recs = [r for r in recs if r['date'] == target_ledger_str and 'INIT' not in str(r.get('exec_id', '')) and 'CALIB' not in str(r.get('exec_id', ''))]
ledger_today_buy = sum(r['qty'] for r in today_recs if r['side'] == 'BUY')
ledger_today_sell = sum(r['qty'] for r in today_recs if r['side'] == 'SELL')
exec_today_buy = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in target_execs if ex.get('sll_buy_dvsn_cd') == "02")
exec_today_sell = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in target_execs if ex.get('sll_buy_dvsn_cd') == "01")
needs_reconstruction = (diff != 0) or (ledger_today_buy != exec_today_buy) or (ledger_today_sell != exec_today_sell)
if not needs_reconstruction and price_diff < 0.01:
pass
elif not needs_reconstruction and price_diff >= 0.01:
await asyncio.to_thread(self.cfg.calibrate_avg_price, ticker, actual_avg)
await context.bot.send_message(chat_id, f"๐ง <b>[{ticker}] ์ฅ๋ถ ํ๋จ๊ฐ ๋ฏธ์ธ ์ค์ฐจ({price_diff:.4f}) ๊ต์ ์๋ฃ!</b>", parse_mode='HTML')
elif needs_reconstruction:
temp_recs = [r for r in recs if r['date'] != target_ledger_str or 'INIT' in str(r.get('exec_id', ''))]
temp_qty, temp_avg, _, _ = await asyncio.to_thread(self.cfg.calculate_holdings, ticker, temp_recs)
temp_sim_qty = temp_qty
temp_sim_avg = temp_avg
new_target_records = []
if target_execs:
target_execs.sort(key=lambda x: str(x.get('ord_dt', '00000000')) + str(x.get('ord_tmd', '000000')))
for ex in target_execs:
side_cd = ex.get('sll_buy_dvsn_cd')
exec_qty = int(float(ex.get('ft_ccld_qty') or '0'))
exec_price = float(ex.get('ft_ccld_unpr3') or '0')
if side_cd == "02":
new_avg = ((temp_sim_qty * temp_sim_avg) + (exec_qty * exec_price)) / (temp_sim_qty + exec_qty) if (temp_sim_qty + exec_qty) > 0 else exec_price
temp_sim_qty += exec_qty
temp_sim_avg = new_avg
else:
temp_sim_qty -= exec_qty
rec_item = {
'date': target_ledger_str, 'side': "BUY" if side_cd == "02" else "SELL",
'qty': exec_qty, 'price': exec_price, 'avg_price': temp_sim_avg
}
if is_rev:
rec_item['is_reverse'] = True
new_target_records.append(rec_item)
gap_qty = actual_qty - temp_sim_qty
if gap_qty != 0:
calib_side = "BUY" if gap_qty > 0 else "SELL"
calib_price = actual_avg
if calib_side == "SELL" and actual_avg <= 0.0:
actual_clear_price_calib = 0.0
if target_execs:
sell_execs_calib = [ex for ex in target_execs if ex.get('sll_buy_dvsn_cd') == "01"]
if sell_execs_calib:
tot_amt_calib = sum(int(float(ex.get('ft_ccld_qty') or '0')) * float(ex.get('ft_ccld_unpr3') or '0') for ex in sell_execs_calib)
tot_q_calib = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in sell_execs_calib)
if tot_q_calib > 0:
actual_clear_price_calib = round(tot_amt_calib / tot_q_calib, 4)
if actual_clear_price_calib == 0.0 and raw_execs:
recent_sells = [ex for ex in raw_execs if ex.get('sll_buy_dvsn_cd') == "01"]
if recent_sells:
recent_sells.sort(key=lambda x: f"{x.get('ord_dt', '')}{x.get('ord_tmd', '')}", reverse=True)
last_sell_dt = recent_sells[0].get('ord_dt')
same_day_sells = [ex for ex in recent_sells if ex.get('ord_dt') == last_sell_dt]
tot_amt = sum(int(float(ex.get('ft_ccld_qty') or '0')) * float(ex.get('ft_ccld_unpr3') or '0') for ex in same_day_sells)
tot_q = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in same_day_sells)
if tot_q > 0:
actual_clear_price_calib = round(tot_amt / tot_q, 4)
if actual_clear_price_calib > 0.0:
calib_price = actual_clear_price_calib
logging.info(f"๐ก๏ธ [{ticker}] CALIB_SELL 0๋ฌ๋ฌ ์ญ์ฐ ๋ฐฉ์ด: ๋น์ผ/์ต๊ทผ ์ฒด๊ฒฐ ์์ฅ์ ์ค์ ๋งค๋ ํ๊ท ๊ฐ(${calib_price:.4f})๋ฅผ ํฉํธ ์ฃผ์
ํ์ต๋๋ค.")
else:
calib_price = temp_sim_avg if temp_sim_avg > 0 else (temp_avg if temp_avg > 0 else 0.01)
logging.info(f"๐ก๏ธ [{ticker}] CALIB_SELL 0๋ฌ๋ฌ ํด๋ฐฑ ๋ฐฉ์ด: ์์ฅ ๊ฒฐ์ธก์ผ๋ก ๊ธฐ์กด ์ฅ๋ถ ํ๋จ๊ฐ(${calib_price:.4f})๋ฅผ ๊ฐ์ ์ฃผ์
ํ์ต๋๋ค.")
calib_avg = temp_sim_avg
elif calib_side == "BUY" and actual_avg <= 0.0:
calib_price = temp_sim_avg if temp_sim_avg > 0 else (temp_avg if temp_avg > 0 else 0.01)
calib_avg = temp_sim_avg
logging.info(f"๐ก๏ธ [{ticker}] CALIB_BUY 0๋ฌ๋ฌ ํด๋ฐฑ ๋ฐฉ์ด: ๊ธฐ์กด ์ฅ๋ถ ํ๋จ๊ฐ(${calib_price:.4f})๋ฅผ ๊ฐ์ ์ฃผ์
ํ์ต๋๋ค.")
else:
calib_price = actual_avg if actual_avg > 0 else temp_sim_avg
calib_avg = actual_avg if actual_avg > 0 else temp_sim_avg
calib_item = {
'date': target_ledger_str,
'side': calib_side,
'qty': abs(gap_qty),
'price': calib_price,
'avg_price': calib_avg,
'exec_id': f"CALIB_{int(time.time())}",
'desc': "๋นํ๊ดด ๋ณด์ "
}
if is_rev:
calib_item['is_reverse'] = True
new_target_records.append(calib_item)
if new_target_records:
if actual_qty > 0:
for r in new_target_records:
r['avg_price'] = actual_avg
elif temp_recs:
if actual_qty > 0:
temp_recs[-1]['avg_price'] = actual_avg
await asyncio.to_thread(self.cfg.overwrite_incremental_ledger, ticker, temp_recs, new_target_records)
if gap_qty != 0:
await context.bot.send_message(chat_id, f"๐ง <b>[{ticker}] ํตํฉ ๋ฉ์ธ ์ฅ๋ถ(MAIN LEDGER) ๋นํ๊ดด ๋ณด์ ์๋ฃ!</b>\nโซ๏ธ KIS ์ค์๊ณ ์ค์ฐจ ์๋({gap_qty}์ฃผ)์ ์ญ์ฌ ๋ณด์กด ์ํ๋ก ์์ ํ๊ฒ ๊ต์ ํ์ต๋๋ค.", parse_mode='HTML')
elif exec_today_buy > 0 or exec_today_sell > 0:
logging.info(f"๐ [{ticker}] ๋น์ผ ๋ฐ์ดํธ๋ ์ด๋ฉ ์ฒด๊ฒฐ ์์ฅ(์ ๋ก์ฌ ํ๊ท)์ด ๋ฉ์ธ ์ฅ๋ถ์ ์๋ฒฝํ ๋ณต์ ๊ธฐ์
๋์์ต๋๋ค.")
# ==========================================================
# V-REV ํ ๊ด๋ฆฌ ๋ฐ 0์ฃผ ์กธ์
ํ๋ณ ๋ก์ง ์์
# ==========================================================
if is_rev:
q_data_before = await asyncio.to_thread(self.queue_ledger.get_queue, ticker)
vrev_ledger_qty = sum(int(float(item.get("qty") or 0)) for item in q_data_before)
sold_today_vrev = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in target_execs if ex.get('sll_buy_dvsn_cd') == "01") if target_execs else 0
avwap_qty_global = 0
tracking_cache_global = None
try:
jobs = context.job_queue.jobs() if context.job_queue else []
job_data = jobs[0].data if jobs and len(jobs) > 0 and jobs[0].data is not None else {}
tracking_cache_global = job_data.get('sniper_tracking', {})
avwap_qty_global = tracking_cache_global.get(f"AVWAP_QTY_{ticker}", 0)
if avwap_qty_global == 0:
strategy = job_data.get('strategy')
if strategy and hasattr(strategy, 'v_avwap_plugin'):
avwap_state = await asyncio.to_thread(strategy.v_avwap_plugin.load_state, ticker, now_est)
avwap_qty_global = int(avwap_state.get('qty', 0))
except Exception:
pass
adjusted_actual_qty = max(0, actual_qty - avwap_qty_global)
if adjusted_actual_qty == 0 and (vrev_ledger_qty > 0 or sold_today_vrev > 0):
if actual_qty == 0 and avwap_qty_global > 0:
logging.warning(f"๐จ [{ticker}] V-REV 0์ฃผ ์กธ์
ํ๋ณ ํ์ ! ๊ทธ๋ฌ๋ AVWAP ์ ๋ น ๋ฌผ๋({avwap_qty_global}์ฃผ) ๊ฐ์ง. ์ฆ๊ฐ 100% ์๊ตฌ ์๊ฐ(Format)ํฉ๋๋ค.")
try:
if tracking_cache_global is not None:
tracking_cache_global[f"AVWAP_QTY_{ticker}"] = 0
tracking_cache_global[f"AVWAP_AVG_{ticker}"] = 0.0
tracking_cache_global[f"AVWAP_BOUGHT_{ticker}"] = False
tracking_cache_global[f"AVWAP_SHUTDOWN_{ticker}"] = True
strategy = job_data.get('strategy')
if strategy and hasattr(strategy, 'v_avwap_plugin'):
state_data = {
'bought': False,
'shutdown': True,
'qty': 0,
'avg_price': 0.0,
'strikes': tracking_cache_global.get(f"AVWAP_STRIKES_{ticker}", 0) if tracking_cache_global is not None else 0
}
await asyncio.to_thread(strategy.v_avwap_plugin.save_state, ticker, now_est, state_data)
except Exception as e:
logging.error(f"๐จ [{ticker}] AVWAP ํ๊ฐ ์๊ฐ ์ค ์์ธ ๋ฐ์: {e}")
if now_kst.hour < 10:
await context.bot.send_message(chat_id, "โณ <b>์ฆ๊ถ์ฌ ํ์ ์ ์ฐ(10:00 KST) ๋๊ธฐ ์ค์
๋๋ค.</b> ๊ฐ๊ฒฐ์ ์ค์ฐจ ๋ฐฉ์ง๋ฅผ ์ํด ์กธ์
์นด๋ ๋ฐ๊ธ ๋ฐ ์ฅ๋ถ ์ด๊ธฐํ๊ฐ ๋ณด๋ฅ๋ฉ๋๋ค.", parse_mode='HTML')
await self._sync_escrow_cash(ticker)
return "SUCCESS"
added_seed = 0.0
_vrev_snap_ok = False
snapshot = None
try:
actual_clear_price = 0.0
tot_q = 0
if target_execs:
sell_execs = [ex for ex in target_execs if ex.get('sll_buy_dvsn_cd') == "01"]
if sell_execs:
tot_amt = sum(int(float(ex.get('ft_ccld_qty') or '0')) * float(ex.get('ft_ccld_unpr3') or '0') for ex in sell_execs)
tot_q = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in sell_execs)
if tot_q > 0:
actual_clear_price = round(tot_amt / tot_q, 4)
if actual_clear_price == 0.0:
if raw_execs:
recent_sells = [ex for ex in raw_execs if ex.get('sll_buy_dvsn_cd') == "01"]
if recent_sells:
recent_sells.sort(key=lambda x: f"{x.get('ord_dt', '')}{x.get('ord_tmd', '')}", reverse=True)
last_sell_dt = recent_sells[0].get('ord_dt')
same_day_sells = [ex for ex in recent_sells if ex.get('ord_dt') == last_sell_dt]
tot_amt = sum(int(float(ex.get('ft_ccld_qty') or '0')) * float(ex.get('ft_ccld_unpr3') or '0') for ex in same_day_sells)
tot_q = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in same_day_sells)
if tot_q > 0:
actual_clear_price = round(tot_amt / tot_q, 4)
logging.info(f"๐ [{ticker}] ๊ณผ๊ฑฐ 4์ผ์น ๊ด์ญ ์ค์บ ๋ฐ ์ต๊ทผ์ผ({last_sell_dt}) ์ถ์ถ ํด๋ฐฑ์ผ๋ก ๋งค๋ ๋จ๊ฐ(${actual_clear_price})๋ฅผ ๋ณต์ํ์ต๋๋ค.")
if tot_q > vrev_ledger_qty:
missing_qty = tot_q - vrev_ledger_qty
buy_execs = [ex for ex in (target_execs or []) if ex.get('sll_buy_dvsn_cd') == "02"]
temp_invested = sum(float(item.get("qty", 0)) * float(item.get("price", 0)) for item in q_data_before)
temp_avg = temp_invested / vrev_ledger_qty if vrev_ledger_qty > 0 else 0.0
missing_price = temp_avg
if buy_execs:
b_tot_amt = sum(int(float(ex.get('ft_ccld_qty') or '0')) * float(ex.get('ft_ccld_unpr3') or '0') for ex in buy_execs)
b_tot_q = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in buy_execs)
if b_tot_q > 0:
q_today_amt = 0.0
q_today_qty = 0
for item in q_data_before:
if str(item.get("date", "")).startswith(target_ledger_str):
iq = int(float(item.get("qty", 0)))
q_today_qty += iq
q_today_amt += iq * float(item.get("price", 0))
pure_manual_q = b_tot_q - q_today_qty
pure_manual_amt = b_tot_amt - q_today_amt
if pure_manual_q >= missing_qty and pure_manual_q > 0 and pure_manual_amt > 0:
derived_price = pure_manual_amt / pure_manual_q
missing_price = round(derived_price, 4)
else:
missing_price = round(b_tot_amt / b_tot_q, 4)
q_data_before.append({
"date": now_est.strftime('%Y-%m-%d %H:%M:%S'),
"qty": missing_qty,
"price": missing_price,
"exec_id": "MANUAL_SYNC"
})
vrev_ledger_qty = tot_q
q_file = "data/queue_ledger.json"
try:
def _read_all_q(f_path):
if os.path.exists(f_path):
with open(f_path, 'r', encoding='utf-8') as f:
return json.load(f)
return {}
all_q = await asyncio.to_thread(_read_all_q, q_file)
all_q[ticker] = q_data_before
def _write_q_file(q_data_dict, file_path):
os.makedirs(os.path.dirname(file_path) if os.path.dirname(file_path) else '.', exist_ok=True)
fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(file_path) if os.path.dirname(file_path) else '.')
with os.fdopen(fd, 'w', encoding='utf-8') as f_out:
json.dump(q_data_dict, f_out, indent=4, ensure_ascii=False)
f_out.flush()
os.fsync(f_out.fileno())
os.replace(tmp_path, file_path)
await asyncio.to_thread(_write_q_file, all_q, q_file)
if hasattr(self.queue_ledger, 'data'):
self.queue_ledger.data = all_q
if hasattr(self.queue_ledger, 'queues'):
self.queue_ledger.queues = all_q
if hasattr(self.queue_ledger, 'load'):
await asyncio.to_thread(self.queue_ledger.load)
logging.info(f"๐ง [{ticker}] ๋ฏธ๋๊ธฐํ ์๋ ๋งค์ ๋ฌผ๋({missing_qty}์ฃผ, ์ง์ฑ๋จ๊ฐ ${missing_price})์ ์กธ์
ํ์ ๋ค์ด๋ ํธ ์์ํํ์ฌ PnL ์ค์ฐจ ๊ต์ ๋ฐ ์ค๋
์ท ์ถฉ๋ ๋ฐฉ์ด ์๋ฃ.")
except Exception as e:
logging.error(f"๐จ MANUAL_SYNC LIFO ํ ํ์ผ I/O ์์ํ ์คํจ: {e}")
total_invested = sum(float(item.get("qty", 0)) * float(item.get("price", 0)) for item in q_data_before)
q_avg_price = total_invested / vrev_ledger_qty if vrev_ledger_qty > 0 else 0.0
try:
curr_p = await asyncio.wait_for(asyncio.to_thread(self.broker.get_current_price, ticker), timeout=10.0)
except asyncio.TimeoutError:
curr_p = 0.0
logging.warning(f"โ ๏ธ [{ticker}] ํ์ฌ๊ฐ ์กฐํ ํ์์์ (10์ด), ์ค๋
์ท ๋ณด์ ์ฉ ๊ฐ๊ฒฉ์์ ์ ์ธ")
clear_price = actual_clear_price if actual_clear_price > 0.0 else (curr_p if curr_p and curr_p > 0 else q_avg_price * 1.006)
snapshot = await asyncio.to_thread(self.strategy.capture_vrev_snapshot, ticker, clear_price, q_avg_price, vrev_ledger_qty)
if snapshot:
realized_pnl = snapshot['realized_pnl']
yield_pct = snapshot['realized_pnl_pct']
compound_rate = float(await asyncio.to_thread(self.cfg.get_compound_rate, ticker)) / 100.0
if realized_pnl > 0 and compound_rate > 0:
added_seed = realized_pnl * compound_rate
current_seed = await asyncio.to_thread(self.cfg.get_seed, ticker)
await asyncio.to_thread(self.cfg.set_seed, ticker, current_seed + added_seed)
cap_dt = snapshot['captured_at']
cap_dt_str = cap_dt if isinstance(cap_dt, str) else cap_dt.strftime('%Y-%m-%d')
start_dt_str = q_data_before[0]['date'][:10] if q_data_before else cap_dt_str[:10]
hist_data = await asyncio.to_thread(self.cfg._load_json, self.cfg.FILES["HISTORY"], [])
new_hist = {
"id": int(time.time()),
"ticker": ticker,
"start_date": start_dt_str,
"end_date": cap_dt_str[:10],
"invested": total_invested,
"revenue": total_invested + realized_pnl,
"profit": realized_pnl,
"yield": yield_pct,
"trades": q_data_before
}
hist_data.append(new_hist)
await asyncio.to_thread(self.cfg._save_json, self.cfg.FILES["HISTORY"], hist_data)
_vrev_snap_ok = True
except Exception as e:
logging.error(f"๐จ ์ค๋
์ท ์บก์ฒ ๋ฐ ๋ณต๋ฆฌ ์ ์ฐ ์ค ์น๋ช
์ ์ค๋ฅ ๊ฐ์ง: {e}\n{traceback.format_exc()}")
snapshot = None
await asyncio.to_thread(self.queue_ledger.sync_with_broker, ticker, 0)
if _vrev_snap_ok:
msg = f"๐ <b>[{ticker} V-REV ์ญํ ์ค์(์ ๋ ์ต์ ) ๊ฐ์ง!]</b>\nโซ๏ธ ์๊ณ ๊ฐ 0์ฃผ๊ฐ ๋์ด LIFO ํ ์ง์ธต์ 100% ์๊ฐ(์ด๊ธฐํ)ํ์ต๋๋ค."
if added_seed > 0:
msg += f"\n๐ธ <b>์๋ ๋ณต๋ฆฌ +${added_seed:,.0f}</b> ์ด ๋ค์ ์ด์ฉ ์๋์ ์๋ฒฝํ๊ฒ ์ถ๊ฐ๋์์ต๋๋ค!"
await context.bot.send_message(chat_id, msg, parse_mode='HTML')
if snapshot:
try:
img_path = await asyncio.to_thread(
self.view.create_profit_image,
ticker=ticker, profit=snapshot['realized_pnl'],
yield_pct=snapshot['realized_pnl_pct'],
invested=snapshot['avg_price'] * snapshot['cleared_qty'],
revenue=snapshot['clear_price'] * snapshot['cleared_qty'],
end_date=cap_dt_str[:10]
)
if img_path and os.path.exists(img_path):
with open(img_path, 'rb') as f_out:
if img_path.lower().endswith('.gif'):
await context.bot.send_animation(chat_id=chat_id, animation=f_out)
else:
await context.bot.send_photo(chat_id=chat_id, photo=f_out)
except Exception as e:
logging.error(f"๐ธ V-REV ์ค๋
์ท ์ด๋ฏธ์ง ๋ ๋๋ง/๋ฐ์ก ์คํจ: {e}")
else:
await context.bot.send_message(chat_id, f"โ ๏ธ <b>[{ticker} V-REV 0์ฃผ ๊ฐ์ ์ ์ฐ ์๋ฃ]</b>\nโซ๏ธ 0์ฃผ๋ฅผ ํ์ธํ์ฌ ํ๋ฅผ ์์ ํ๊ฒ ๋น์ ์ผ๋ ํต์ ์ง์ฐ์ผ๋ก ์กธ์
์นด๋๋ ์๋ต๋์์ต๋๋ค.", parse_mode='HTML')
await self._sync_escrow_cash(ticker)
return "SUCCESS"
if adjusted_actual_qty == vrev_ledger_qty:
pass
else:
if adjusted_actual_qty > 0 and adjusted_actual_qty < vrev_ledger_qty:
gap_qty = vrev_ledger_qty - adjusted_actual_qty
vwap_state_file = f"data/vwap_state_REV_{ticker}.json"
if os.path.exists(vwap_state_file):
try:
def _read_v_state(f_path):
with open(f_path, 'r', encoding='utf-8') as vf:
return json.load(vf)
v_state = await asyncio.to_thread(_read_v_state, vwap_state_file)
if "executed" in v_state and "SELL_QTY" in v_state["executed"]:
old_sell_qty = v_state["executed"]["SELL_QTY"]
v_state["executed"]["SELL_QTY"] = max(0, old_sell_qty - gap_qty)
def _write_v_state(state_dict, f_path):
fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(f_path) or '.')
with os.fdopen(fd, 'w', encoding='utf-8') as _vf_out:
json.dump(state_dict, _vf_out, ensure_ascii=False, indent=4)
_vf_out.flush()
os.fsync(_vf_out.fileno())
os.replace(tmp_path, f_path)
await asyncio.to_thread(_write_v_state, v_state, vwap_state_file)
logging.info(f"๐ง [{ticker}] VWAP ์์ฐจ ์ํ์ ๋ณด์ ์๋ฃ: {old_sell_qty} -> {v_state['executed']['SELL_QTY']}")
except Exception as e:
logging.error(f"๐จ VWAP ์ํ ๊ต์ ์๋ฌ: {e}")
calibrated = await asyncio.to_thread(self.queue_ledger.sync_with_broker, ticker, adjusted_actual_qty, actual_avg)
if calibrated:
await context.bot.send_message(chat_id, f"๐ง <b>[{ticker}] V-REV ํ(Queue) ๋นํ๊ดด ๋ณด์ ์๋ฃ!</b>\nโซ๏ธ ์๋ ๋งค๋ ๋ฌผ๋(<b>{gap_qty}์ฃผ</b>)์ LIFO ํ์์ ์์ ํ๊ฒ ์ฐจ๊ฐํ์ต๋๋ค.", parse_mode='HTML')
elif adjusted_actual_qty > 0 and adjusted_actual_qty > vrev_ledger_qty:
gap_qty = adjusted_actual_qty - vrev_ledger_qty
real_buy_price = actual_avg
try:
buy_execs = [ex for ex in (target_execs or []) if ex.get('sll_buy_dvsn_cd') == "02"]
if buy_execs:
b_tot_amt = sum(int(float(ex.get('ft_ccld_qty') or '0')) * float(ex.get('ft_ccld_unpr3') or '0') for ex in buy_execs)
b_tot_q = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in buy_execs)
if b_tot_q > 0:
real_buy_price = round(b_tot_amt / b_tot_q, 4)
if real_buy_price == actual_avg:
search_start_dt = (now_kst - datetime.timedelta(days=4)).strftime('%Y%m%d')
past_raw = await asyncio.to_thread(self.broker.get_execution_history, ticker, search_start_dt, query_end_dt)
past_execs = filter_to_est(past_raw)
if past_execs:
p_buy_execs = [ex for ex in past_execs if ex.get('sll_buy_dvsn_cd') == "02"]
if p_buy_execs:
b_tot_amt = sum(int(float(ex.get('ft_ccld_qty') or '0')) * float(ex.get('ft_ccld_unpr3') or '0') for ex in p_buy_execs)
b_tot_q = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in p_buy_execs)
if b_tot_q > 0:
real_buy_price = round(b_tot_amt / b_tot_q, 4)
except Exception as e:
logging.error(f"๐จ ์๋๋งค์ ์ค์ ์ฒด๊ฒฐ๋จ๊ฐ ์ญ์ฐ ์ค ์์ธ ๋ฐ์ (๊ธฐ์กด ํ๋จ๊ฐ fallback): {e}")
if real_buy_price == actual_avg:
old_invested = sum(float(item.get("qty", 0)) * float(item.get("price", 0)) for item in q_data_before)
new_invested = adjusted_actual_qty * actual_avg
if new_invested > old_invested:
derived_price = (new_invested - old_invested) / gap_qty
real_buy_price = round(derived_price, 4) if derived_price > 0 else actual_avg
q_data = await asyncio.to_thread(self.queue_ledger.get_queue, ticker)
q_data.append({
"date": now_est.strftime('%Y-%m-%d %H:%M:%S'),
"qty": gap_qty,
"price": real_buy_price,
"exec_id": f"MANUAL_BUY_{int(time.time())}"
})
q_file = "data/queue_ledger.json"
try:
def _read_all_q_manual(f_path):
if os.path.exists(f_path):
with open(f_path, 'r', encoding='utf-8') as f:
return json.load(f)
return {}
all_q = await asyncio.to_thread(_read_all_q_manual, q_file)
all_q[ticker] = q_data
def _write_q_manual(q_dict, file_path):
os.makedirs(os.path.dirname(file_path) if os.path.dirname(file_path) else '.', exist_ok=True)
fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(file_path) if os.path.dirname(file_path) else '.')
with os.fdopen(fd, 'w', encoding='utf-8') as f_out:
json.dump(q_dict, f_out, indent=4, ensure_ascii=False)
f_out.flush()
os.fsync(f_out.fileno())
os.replace(tmp_path, file_path)
await asyncio.to_thread(_write_q_manual, all_q, q_file)
if hasattr(self.queue_ledger, 'data'):
self.queue_ledger.data = all_q
logging.info(f"๐ง [{ticker}] ์๋ ๋งค์ ๊ฐ์ง! KIS ์ค์๊ณ ์ ๋ง์ถฐ LIFO ํ์ ์ ๊ท ์ง์ธต({gap_qty}์ฃผ, ์ง์ฑ๋จ๊ฐ ${real_buy_price}) ๋ค์ด๋ ํธ ํธ์
๋ฐ ํ์ผ ์์ํ ์๋ฃ.")
await context.bot.send_message(chat_id, f"๐ง <b>[{ticker}] V-REV ํ(Queue) ์๋ ๋งค์ ํธ์
์๋ฃ!</b>\nโซ๏ธ KIS ์ค์๊ณ ์ ๋ง์ถฐ ์ ๊ท ์ง์ธต(<b>{gap_qty}์ฃผ</b>, ์ถ์ ๋จ๊ฐ ${real_buy_price})์ ์ ๋ฐ ์ถ๊ฐํ์ต๋๋ค.", parse_mode='HTML')
except Exception as e:
logging.error(f"๐จ LIFO ํ ๋ค์ด๋ ํธ ํ์ผ I/O ์ฐ๊ธฐ ์๋ฌ: {e}")
await self._sync_escrow_cash(ticker)
return "SUCCESS"
# ==========================================================
# V14 0์ฃผ ์กธ์
ํ๋ณ ๋ก์ง
# ==========================================================
if not is_rev:
sold_today_v14 = sum(int(float(ex.get('ft_ccld_qty') or '0')) for ex in target_execs if ex.get('sll_buy_dvsn_cd') == "01") if target_execs else 0
if actual_qty == 0 and (ledger_qty > 0 or sold_today_v14 > 0):
if now_kst.hour < 10:
await context.bot.send_message(chat_id, "โณ <b>์ฆ๊ถ์ฌ ํ์ ์ ์ฐ(10:00 KST) ๋๊ธฐ ์ค์
๋๋ค.</b> ๊ฐ๊ฒฐ์ ์ค์ฐจ ๋ฐฉ์ง๋ฅผ ์ํด ์กธ์
์นด๋ ๋ฐ๊ธ ๋ฐ ์ฅ๋ถ ์ด๊ธฐํ๊ฐ ๋ณด๋ฅ๋ฉ๋๋ค.", parse_mode='HTML')
else:
today_est_str = now_est.strftime('%Y-%m-%d')
try:
prev_c = await asyncio.wait_for(
asyncio.to_thread(self.broker.get_previous_close, ticker),
timeout=10.0
)
except asyncio.TimeoutError:
prev_c = 0.0
logging.warning(f"โ ๏ธ [{ticker}] ์ผํ ํ์ด๋ธ์ค ์ ์ผ ์ข
๊ฐ ์กฐํ ํ์์์ (10์ด). 0.0์ผ๋ก ๋์ฒด")
try:
new_hist, added_seed = await asyncio.to_thread(self.cfg.archive_graduation, ticker, today_est_str, prev_c)
if new_hist:
msg = f"๐ <b>[{ticker} ์กธ์
ํ์ธ!]</b>\n์ฅ๋ถ๋ฅผ ๋ช
์์ ์ ๋น์ ์ ์ฅํ๊ณ ์ ์ฌ์ดํด์ ์ค๋นํฉ๋๋ค."
if added_seed > 0:
msg += f"\n๐ธ <b>์๋ ๋ณต๋ฆฌ +${added_seed:,.0f}</b> ์ด ๋ค์ ์ด์ฉ ์๋์ ์๋ฒฝํ๊ฒ ์ถ๊ฐ๋์์ต๋๋ค!"
await context.bot.send_message(chat_id, msg, parse_mode='HTML')
try:
img_path = await asyncio.to_thread(
self.view.create_profit_image,
ticker=ticker, profit=new_hist['profit'], yield_pct=new_hist['yield'],
invested=new_hist['invested'], revenue=new_hist['revenue'], end_date=new_hist['end_date']
)
if img_path and os.path.exists(img_path):
with open(img_path, 'rb') as f_out:
if img_path.lower().endswith('.gif'):
await context.bot.send_animation(chat_id=chat_id, animation=f_out)
else:
await context.bot.send_photo(chat_id=chat_id, photo=f_out)
except Exception as e:
logging.error(f"๐ธ ์กธ์
์ด๋ฏธ์ง ๋ฐ์ก ์คํจ: {e}")
else:
full_ledger2 = await asyncio.to_thread(self.cfg.get_ledger)
all_recs = [r for r in full_ledger2 if r['ticker'] != ticker]
await asyncio.to_thread(self.cfg._save_json, self.cfg.FILES["LEDGER"], all_recs)
await context.bot.send_message(chat_id, f"โ ๏ธ <b>[{ticker} ๊ฐ์ ์ ์ฐ ์๋ฃ]</b>\n์๊ณ ๊ฐ 0์ฃผ์ด๋ ๋ง์ด๋์ค ์์ต ์ํ์ด๋ฏ๋ก ๋ช
์์ ์ ๋น ๋ฐ์ ์์ด ์ฅ๋ถ๋ฅผ ๋น์ฐ๊ณ ์์ถ๋ฐ ํ์ ์ ์ฅ์ ํฉ๋๋ค.", parse_mode='HTML')
except Exception as e:
logging.error(f"๊ฐ์ ์กธ์
์ฒ๋ฆฌ ์ค ์๋ฌ: {e}")
await self._sync_escrow_cash(ticker)
return "SUCCESS"
await self._sync_escrow_cash(ticker)
return "SUCCESS"
async def _display_ledger(self, ticker, chat_id, context, query=None, message_obj=None, pre_fetched_holdings=None):
full_ledger = await asyncio.to_thread(self.cfg.get_ledger)
recs = [r for r in full_ledger if r['ticker'] == ticker]
if not recs:
msg = f"๐ญ <b>[{ticker}]</b> ํ์ฌ ์งํ ์ค์ธ ์ฌ์ดํด์ด ์์ต๋๋ค (๋ณด์ ๋ 0์ฃผ)."
else:
from collections import OrderedDict
agg_dict = OrderedDict()
total_buy = 0.0
total_sell = 0.0
for rec in recs:
parts = rec['date'].split('-')
if len(parts) == 3:
date_short = f"{parts[1]}.{parts[2]}"
else:
date_short = rec['date']
side_str = "๐ด๋งค์" if rec['side'] == 'BUY' else "๐ต๋งค๋"
key = (date_short, side_str)
if key not in agg_dict:
agg_dict[key] = {'qty': 0, 'amt': 0.0}
agg_dict[key]['qty'] += rec['qty']
agg_dict[key]['amt'] += (rec['qty'] * rec['price'])
if rec['side'] == 'BUY':
total_buy += (rec['qty'] * rec['price'])
elif rec['side'] == 'SELL':
total_sell += (rec['qty'] * rec['price'])
report = f"๐ <b>[ {ticker} ์ผ์๋ณ ๋งค๋งค (ํตํฉ ๋ณ๋๋ถ) (์ด {len(agg_dict)}์ผ) ]</b>\n\n<code>No. ์ผ์ ๊ตฌ๋ถ ํ๊ท ๋จ๊ฐ ์๋\n"
report += "-"*30 + "\n"
idx = 1
for (date, side), data in agg_dict.items():
tot_qty = data['qty']
avg_prc = data['amt'] / tot_qty if tot_qty > 0 else 0.0
report += f"{idx:<3} {date} {side} ${avg_prc:<6.2f} {tot_qty}์ฃผ\n"
idx += 1
report += "-"*30 + "</code>\n"
actual_qty = int(float(pre_fetched_holdings.get(ticker, {'qty': 0})['qty'] or 0)) if pre_fetched_holdings else 0
actual_avg = float(pre_fetched_holdings.get(ticker, {'avg': 0})['avg'] or 0.0) if pre_fetched_holdings else 0.0
split = await asyncio.to_thread(self.cfg.get_split_count, ticker)
t_val, _ = await asyncio.to_thread(self.cfg.get_absolute_t_val, ticker, actual_qty, actual_avg)
report += "๐ <b>[ ํ์ฌ ์งํ ์ํฉ ์์ฝ ]</b>\n"
report += f"โช๏ธ ํ์ฌ T๊ฐ : {t_val:.4f} T ({int(split)}๋ถํ )\n"
report += f"โช๏ธ ๋ณด์ ์๋ : {actual_qty} ์ฃผ (ํ๋จ ${actual_avg:,.2f})\n"
report += f"โช๏ธ ์ด ๋งค์์ก : ${total_buy:,.2f}\n"
report += f"โช๏ธ ์ด ๋งค๋์ก : ${total_sell:,.2f}"
msg = report
active_tickers = await asyncio.to_thread(self.cfg.get_active_tickers)
keyboard = []
v_mode = await asyncio.to_thread(self.cfg.get_version, ticker)
if v_mode == "V_REV":
keyboard.append([InlineKeyboardButton(f"๐๏ธ {ticker} V-REV ํ(Queue) ์ ๋ฐ ๊ด๋ฆฌ", callback_data=f"QUEUE:VIEW:{ticker}")])
row = [InlineKeyboardButton(f"๐ {t} ์ฅ๋ถ ์
๋ฐ์ดํธ", callback_data=f"REC:SYNC:{t}") for t in active_tickers]
keyboard.append(row)
markup = InlineKeyboardMarkup(keyboard)
if query:
await query.edit_message_text(msg, reply_markup=markup, parse_mode='HTML')
elif message_obj:
await message_obj.edit_text(msg, reply_markup=markup, parse_mode='HTML')
else:
await context.bot.send_message(chat_id, msg, reply_markup=markup, parse_mode='HTML')