Repository navigation
Expand file tree
/
Copy pathvwap_core_engine.py
More file actions
642 lines (520 loc) ยท 41 KB
/
Copy pathvwap_core_engine.py
File metadata and controls
642 lines (520 loc) ยท 41 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
# ==========================================================
# FILE: vwap_core_engine.py
# ==========================================================
# ๐จ MODIFIED: [๋จ์ผ ์ง์ธต ํฝ์ฐฝ ํจ๋ฌ๋
์ค ๊ถ๊ทน ์์ (Parameter Amnesia)] ์ค์๊ฐ ๋งค์/๋งค๋ ์ฒด๊ฒฐ ํ ํ ์ฅ๋ถ์ ํฉํธ๋ฅผ ์ฃผ์
ํ ๋, ๋ถํ ์ฐ์ฐ์ ํ์์ ์ธ `prev_close`์ `portion_budget` ํ๋ผ๋ฏธํฐ๊ฐ ์ ์ค๋์ง ์๋๋ก ํ๊ฒฉ ๋ฃจํ ์ ๋จ์์ ์ค์๊ฐ์ผ๋ก 100% ๋ฌด๊ฒฐ์ฑ ์ฃผ์
์ ๊ฒฐ์.
# ๐จ MODIFIED: [NameError ์ฆ์ฌ ๋ฒ๊ทธ ์๊ตฌ ์๊ฐ (V96.80)] ์ ์ญ ํจ์ ์ค์ฝํ ๋ด๋ถ์ ๋งน๋
์ฑ์ผ๋ก ์์กดํ๋ `self._safe_float` ์ฐ๊บผ๊ธฐ๋ฅผ ์ ๋ฉด ํ๊ธฐํ๊ณ , ์ ์ญ ํฌํผ `_safe_float` ๋ค์ด๋ ํธ ํธ์ถ๋ก 100% ํฉํธ ๊ต์ ์๋ฃ.
# ==========================================================
import logging
import asyncio
import math
import time
import datetime
import json
from zoneinfo import ZoneInfo
import html
import functools
import pandas as pd
from scheduler_core import get_budget_allocation
from state_io_manager import _read_json_safe_sync, _atomic_write_json_sync
from global_throttle import GlobalThrottle # ๐จ ์ ์ญ ํต์ ์ ๊ฒฐ์
_MCAL_SCHEDULE_CACHE = {}
def _safe_float(val):
try:
f_val = float(str(val or 0.0).replace(',', ''))
if math.isnan(f_val) or math.isinf(f_val):
return 0.0
return f_val
except Exception:
return 0.0
async def _retry_api(func, *args, timeout=15.0, default=None, **kwargs):
for attempt in range(3):
try:
await asyncio.to_thread(GlobalThrottle.wait_api_sync)
if asyncio.iscoroutinefunction(func):
return await asyncio.wait_for(func(*args, **kwargs), timeout=timeout)
else:
p_func = functools.partial(func, *args, **kwargs)
return await asyncio.wait_for(asyncio.to_thread(p_func), timeout=timeout)
except Exception as e:
if attempt == 2:
func_name = getattr(func, '__name__', 'unknown_func')
logging.debug(f"๐จ API ๋ํผ ์ต์ข
์คํจ ({func_name}): {e}")
return default
await asyncio.sleep(1.0 * (2 ** attempt))
return default
async def _safe_send(context, chat_id, text, timeout=15.0, **kwargs):
if not chat_id: return None
try:
return await asyncio.wait_for(context.bot.send_message(chat_id=chat_id, text=text, **kwargs), timeout=timeout)
except Exception as e:
logging.error(f"๐จ ํ
๋ ๊ทธ๋จ ์ ์ก ์คํจ: {e}")
return None
def _fetch_market_schedule_sync(now_est):
date_str = now_est.strftime('%Y-%m-%d')
if date_str in _MCAL_SCHEDULE_CACHE:
return _MCAL_SCHEDULE_CACHE[date_str]
GlobalThrottle.wait_api_sync()
import pandas_market_calendars as mcal
nyse = mcal.get_calendar('NYSE')
sched = nyse.schedule(start_date=now_est.date(), end_date=now_est.date())
_MCAL_SCHEDULE_CACHE[date_str] = sched
return sched
async def _get_market_close_time(now_est):
schedule = None
for attempt in range(3):
try:
schedule = await asyncio.wait_for(asyncio.to_thread(_fetch_market_schedule_sync, now_est), timeout=10.0)
break
except asyncio.TimeoutError:
if attempt == 2: logging.error("โ ๏ธ ์ฅ๋ง๊ฐ์๊ฐ ๋ฌ๋ ฅ API ํ์์์. ํ์ผ ๊ฐ์ ๋ง๊ฐ์๊ฐ(16:00 EST) ์ธํ
.")
else: await asyncio.sleep(1.0 * (2 ** attempt))
except Exception as e:
if attempt == 2: logging.error(f"โ ๏ธ ์ฅ๋ง๊ฐ์๊ฐ ๋ฌ๋ ฅ API ์๋ฌ({e}). ํ์ผ ๊ฐ์ ๋ง๊ฐ์๊ฐ(16:00 EST) ์ธํ
.")
else: await asyncio.sleep(1.0 * (2 ** attempt))
if schedule is not None and not schedule.empty:
return schedule.iloc[0]['market_close'].astimezone(now_est.tzinfo)
elif schedule is not None and schedule.empty:
return None
else:
if now_est.weekday() < 5:
return now_est.replace(hour=16, minute=0, second=0, microsecond=0)
else:
return None
def _read_json_ignore_date_sync(filepath):
with GlobalThrottle.get_file_lock(filepath):
try:
with open(filepath, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception:
return {}
async def _read_state_safe(filepath, date_str, default_val):
return await _retry_api(_read_json_safe_sync, filepath, date_str, default=default_val)
async def _write_state_safe(filepath, state_dict):
return await _retry_api(_atomic_write_json_sync, filepath, state_dict)
async def execute_vwap_init(tx_lock, cfg, broker, chat_id, context, vwap_cache):
active_tickers = await _retry_api(cfg.get_active_tickers, default=[])
if isinstance(active_tickers, str): active_tickers = [active_tickers]
elif not isinstance(active_tickers, list): active_tickers = []
for raw_t in active_tickers:
t = str(raw_t).strip().upper()
if not t: continue
try:
version = await _retry_api(cfg.get_version, t, default="V14")
is_manual_vwap = await _retry_api(getattr(cfg, 'get_manual_vwap_mode', lambda x: False), t, default=False)
if version == "V_REV" or (version == "V14" and is_manual_vwap):
if not vwap_cache.get(f"REV_{t}_nuked"):
msg = f"๐
<b>[{html.escape(str(t))}] ์์ฒด 1๋ถ ์ฌ๋ผ์ด์ฑ VWAP ์์ง ๊ธฐ์</b>\n"
msg += f"โซ๏ธ KIS ์์ฝ ๋ซ ๊ด๋ง ๋ฐ ์ฅ ๋ง๊ฐ 34๋ถ ์ ๋ก์ปฌ ํ์ค ํ๊ฒฉ ์์ง์ ๊ฐ๋ ๋๊ธฐ๋ฅผ ํ์ธํ์ต๋๋ค.\n"
if version == "V_REV":
msg += f"โซ๏ธ ์ด์ฉ์ข
๋ชฉ ๊ฐญ ์ดํ ๊ฐ์ง ์ ์ฆ๊ฐ ๊ฐ์
(Gap Hijack)ํ๋ ํญ๋ฝ์ฅ ์ค์ ๋ชจ๋๊ฐ ํจ๊ป ๊ฐ๋๋ฉ๋๋ค. โ๏ธ"
vwap_cache[f"REV_{t}_nuked"] = True
await _safe_send(context, chat_id, msg, parse_mode='HTML', disable_notification=True)
except Exception as e:
logging.error(f"๐จ [{t}] ๊ด์ธก ๋ชจ๋ ์๋๋ฐ์ค ์๋ฌ (๊ฒฉ๋ฆฌ ์๋ฃ): {e}")
vwap_cache[f"REV_{t}_nuked"] = False
async def execute_vwap_trade(tx_lock, cfg, broker, strategy, queue_ledger, chat_id, context, base_map, vwap_cache):
est = ZoneInfo('America/New_York')
now_est = datetime.datetime.now(est)
today_hyphen = now_est.strftime('%Y-%m-%d')
kst_zone = ZoneInfo('Asia/Seoul')
now_kst = datetime.datetime.now(kst_zone)
async with tx_lock:
res = await _retry_api(broker.get_account_balance, timeout=15.0)
cash = _safe_float(res[0]) if isinstance(res, (list, tuple)) and len(res) > 0 else 0.0
holdings = res[1] if isinstance(res, (list, tuple)) and len(res) > 1 else {}
if not isinstance(holdings, dict): holdings = {}
if res is None: return
active_tickers = await _retry_api(cfg.get_active_tickers, default=[])
if isinstance(active_tickers, str): active_tickers = [active_tickers]
elif not isinstance(active_tickers, list): active_tickers = []
alloc_res = await _retry_api(get_budget_allocation, cash, active_tickers, cfg, default=({}, {}))
allocated_cash = alloc_res[1] if isinstance(alloc_res, (list, tuple)) and len(alloc_res) > 1 else {}
if not isinstance(allocated_cash, dict): allocated_cash = {}
t_curr_p = 0.0
t_ask_p = 0.0
t_bid_p = 0.0
nuked_count = 0
for raw_t in active_tickers:
t = str(raw_t).strip().upper()
if not t: continue
actual_qty = int(_safe_float(holdings.get(t, {}).get('qty', 0)))
vrev_q_qty = 0
if queue_ledger:
q_data = await _retry_api(queue_ledger.get_queue, t, default=[])
vrev_q_qty = sum(int(_safe_float(item.get("qty"))) for item in (q_data or []) if isinstance(item, dict))
try:
version = await _retry_api(cfg.get_version, t, default="V14")
is_manual_vwap = await _retry_api(getattr(cfg, 'get_manual_vwap_mode', lambda x: False), t, default=False)
if version == "V_REV" or (version == "V14" and is_manual_vwap):
slice_file = f"data/vrev_slice_state_{t}.json"
safe_prev_c = 0.0
for attempt in range(3):
try:
await asyncio.to_thread(GlobalThrottle.wait_api_sync)
p_val = await asyncio.wait_for(asyncio.to_thread(broker.get_previous_close, t), timeout=45.0)
# MODIFIED: [NameError ์ฆ์ฌ ๋ฒ๊ทธ ์๊ฐ] self._safe_float โ _safe_float
safe_prev_c = _safe_float(p_val)
if safe_prev_c > 0: break
except Exception:
if attempt == 2: pass
else: await asyncio.sleep(1.0 * (2 ** attempt))
safe_seed = await _retry_api(cfg.get_seed, t, default=0.0)
portion_budget = safe_seed * 0.15
t_curr_p = _safe_float(await _retry_api(broker.get_current_price, t))
t_ask_p = _safe_float(await _retry_api(broker.get_ask_price, t))
t_bid_p = _safe_float(await _retry_api(broker.get_bid_price, t))
is_capital_locked_now = False
try:
after_state_file = f"data/vrev_aftermarket_state_{t}.json"
after_state = await _read_state_safe(after_state_file, today_hyphen, {})
if after_state.get('date') == today_hyphen:
if any(isinstance(o, dict) and str(o.get('status')) == 'PENDING' for o in after_state.get('orders', [])):
is_capital_locked_now = True
logging.info(f"โณ [{t}] ์๋ณธ ์ ๊น ๊ฐ์ง: ์ ํํฐ์ฅ(16:01) ์ด๊ด ๋๊ธฐ ์ค. ํ๋ฐฉ Gap Hijack์ ์ฐจ๋จํ๊ณ ๋งค๋ ์ฌ๋ผ์ด์ฑ๋ง ์ ์ ์งํํฉ๋๋ค.")
except Exception as e:
logging.error(f"๐จ [{t}] ์ ํํฐ์ฅ ์ด๊ด ์ํ ๊ต์ฐจ ๊ฒ์ฆ ์๋ฌ: {e}")
slice_state_disk = await _read_state_safe(slice_file, today_hyphen, {})
if slice_state_disk.get('date') != today_hyphen:
if not vwap_cache.get(f"REV_{t}_bypass_warned"):
msg = f"๐จ <b>[{html.escape(str(t))}] VWAP ์ฌ๋ผ์ด์ฑ ์ฝ์ด ๋ฐ์ดํจ์ค(Bypass) ๊ฐ์ง!</b>\nโซ๏ธ ๋น์ผ({today_hyphen}) ์์ฑ๋ ์ง์์(slice_state)๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค.\nโซ๏ธ 15:26 ์ค์ผ์ค๋ฌ ๋ณ๋ชฉ์ผ๋ก ๋ณธ์ง ํ๋ ์ฐ์ฐ์ด ๋๋ฝ๋ ๊ฒ์ผ๋ก ์ถ์ ๋ฉ๋๋ค.\nโซ๏ธ <b>์๋ ํ๊ฒฉ ๊ถ๊ณ :</b> ๊ด์ ํ( /avwap )์์ <b>[1ํ๋ถ ์๋๋งค์/๋งค๋]</b> ์ธ๋ผ์ธ ๋ฒํผ์ ํตํด ์ง์ฐ๋ ํ๊ฒฉ์ ์ง์ ์งํํ์ญ์์ค."
await _safe_send(context, chat_id, msg, parse_mode='HTML')
vwap_cache[f"REV_{t}_bypass_warned"] = True
continue
disk_hijacked = slice_state_disk.get('hijacked', False)
is_downward_hijacked_now = vwap_cache.get(f"REV_{t}_gap_hijack_fired", False) or disk_hijacked
# ======================================================
# [ 1. Gap Hijack (์ค์ง ํ๋ฐฉ ํญ๋ฝ์ฅ ์ ๋์ ์ค์ ๊ฐ์) ]
# ======================================================
if version == "V_REV" and not is_downward_hijacked_now and not is_capital_locked_now:
df_1min_t = await _retry_api(broker.get_1min_candles_df, t)
if df_1min_t is not None and not df_1min_t.empty:
df_t = df_1min_t.copy()
df_t = df_t[df_t.index.date == now_est.date()]
if 'time_est' in df_t.columns:
df_t = df_t[(df_t['time_est'] >= '093000') & (df_t['time_est'] <= '155900')]
if not df_t.empty:
df_t['high'] = df_t['high'].ffill().bfill()
df_t['low'] = df_t['low'].ffill().bfill()
df_t['close'] = df_t['close'].ffill().bfill()
df_t['volume'] = df_t['volume'].ffill().bfill().fillna(0)
df_t['tp'] = (df_t['high'].astype(float) + df_t['low'].astype(float) + df_t['close'].astype(float)) / 3.0
df_t['vol'] = df_t['volume'].astype(float)
df_t['vol_tp'] = df_t['tp'] * df_t['vol']
c_vol = df_t['vol'].sum()
t_vwap = df_t['vol_tp'].sum() / c_vol if c_vol > 0 else t_curr_p
gap_pct = ((t_curr_p - t_vwap) / t_vwap * 100.0) if t_vwap > 0 else 0.0
# MODIFIED: [NameError ์ฆ์ฌ ๋ฒ๊ทธ ์๊ฐ] self._safe_float โ _safe_float
gap_thresh = _safe_float(await _retry_api(getattr(cfg, 'get_vrev_gap_threshold', lambda x: -2.0), t, default=-2.0))
if gap_thresh == -0.67: gap_thresh = -2.0
if gap_pct <= gap_thresh:
slice_state_check = slice_state_disk
has_buy_plan = any(isinstance(o, dict) and str(o.get('side')) == 'BUY' for o in slice_state_check.get('orders', []))
sell_orders = [o for o in slice_state_check.get('orders', []) if str(o.get('side')) == 'SELL']
is_sell_condition = False
for o in sell_orders:
# MODIFIED: [NameError ์ฆ์ฌ ๋ฒ๊ทธ ์๊ฐ] self._safe_float โ _safe_float
tp_val = _safe_float(o.get('target_price', o.get('price', 0.0)))
if tp_val > 0.0 and t_curr_p >= tp_val:
is_sell_condition = True
break
buy_orders = [o for o in slice_state_check.get('orders', []) if str(o.get('side')) == 'BUY']
max_buy_target = 0.0
if buy_orders:
# MODIFIED: [NameError ์ฆ์ฌ ๋ฒ๊ทธ ์๊ฐ] self._safe_float โ _safe_float
max_buy_target = max(_safe_float(o.get('target_price', o.get('price', 0.0))) for o in buy_orders)
if not has_buy_plan:
if not vwap_cache.get(f"REV_{t}_gap_hijack_blocked_log", False):
logging.info(f"โก [{t}] ํ๋ฐฉ Gap Hijack ์กฐ๊ฑด ๋๋ฌ({gap_pct:.2f}%) โ ๐ ๊ธ์ผ ํตํฉ์ง์์์ ๋งค์(BUY) ํ๋์ด ์์ด ์ค์ ๋งค์๋ฅผ ์ ๋ฉด ์ฐจ๋จ(Bypass)ํฉ๋๋ค.")
vwap_cache[f"REV_{t}_gap_hijack_blocked_log"] = True
vwap_cache[f"REV_{t}_gap_hijack_fired"] = True
is_downward_hijacked_now = True
elif is_sell_condition:
if not vwap_cache.get(f"REV_{t}_gap_hijack_sell_blocked_log", False):
logging.info(f"โก [{t}] ํ๋ฐฉ Gap Hijack ์กฐ๊ฑด ๋๋ฌ({gap_pct:.2f}%) โ ๐ ํ์ฌ๊ฐ(${t_curr_p:.2f})๊ฐ ๋งค๋(SELL) ํ์ ์ด์์ด๋ฏ๋ก ์ค์ ๋งค์๋ฅผ ์ฐจ๋จํ๊ณ ๊ด๋งํฉ๋๋ค (Buy Low ์์น ์ฌ์).")
vwap_cache[f"REV_{t}_gap_hijack_sell_blocked_log"] = True
elif max_buy_target > 0.0 and t_curr_p > max_buy_target:
if not vwap_cache.get(f"REV_{t}_gap_hijack_price_blocked_log", False):
logging.info(f"โก [{t}] ํ๋ฐฉ Gap Hijack ์กฐ๊ฑด ๋๋ฌ({gap_pct:.2f}%) โ ๐ ํ์ฌ๊ฐ(${t_curr_p:.2f})๊ฐ ์ง์์ ๋งค์ ๋ชฉํ๊ฐ(${max_buy_target:.2f})๋ณด๋ค ๋น์๋๋ค. ๋น์ผ ๊ฐ๊ฒฉ์ ํ์ด์ฌํน๋๋ ๊ฒ์ ์ฐจ๋จํ๊ณ ๋งค์ ๋จ๊ฐ๋ฅผ ๊ธฐ๋ค๋ฆฝ๋๋ค (Buy Low).")
vwap_cache[f"REV_{t}_gap_hijack_price_blocked_log"] = True
else:
vwap_cache.pop(f"REV_{t}_gap_hijack_sell_blocked_log", None)
vwap_cache.pop(f"REV_{t}_gap_hijack_price_blocked_log", None)
logging.info(f"โก [{t}] Downward Gap Hijack Triggered! gap: {gap_pct:.2f}%, thresh: {gap_thresh}%")
nuked_count = 0
try:
est_now = datetime.datetime.now(ZoneInfo('America/New_York'))
d_str = est_now.strftime('%Y%m%d')
resv_orders = await _retry_api(broker.get_reservation_orders, t, d_str, d_str, default=[])
safe_resv_orders = resv_orders if isinstance(resv_orders, list) else []
for req in safe_resv_orders:
if not isinstance(req, dict): continue
side_cd = str(req.get('sll_buy_dvsn_cd') or req.get('sll_buy_dvsn') or '')
if side_cd == '01': continue
odno = str(req.get('ovrs_rsvn_odno') or req.get('odno') or '')
ord_dt = str(req.get('rsvn_ord_rcit_dt') or req.get('ord_dt') or d_str)
if odno:
async with tx_lock:
c_res = await _retry_api(broker.cancel_reservation_order, ord_dt, odno)
if c_res: nuked_count += 1
unfilled = await _retry_api(broker.get_unfilled_orders_detail, t, default=[])
safe_unfilled = unfilled if isinstance(unfilled, list) else []
for uo in safe_unfilled:
if not isinstance(uo, dict): continue
side_cd = str(uo.get('sll_buy_dvsn_cd') or uo.get('sll_buy_dvsn') or '')
if side_cd == '01': continue
dvsn = str(uo.get('ord_dvsn_cd') or uo.get('ord_dvsn') or '').strip().zfill(2)
if dvsn in ['36', '00']:
u_odno = str(uo.get('odno') or '')
if u_odno:
async with tx_lock:
c_res = await _retry_api(broker.cancel_order, t, u_odno)
if c_res: nuked_count += 1
logging.info(f"โก [{t}] KIS ์ค์์ฅ ์ค์บ: ์์ฝ ๋ฐ ์ผ๋ฐ ๋งค์(BUY) ๋ซ {nuked_count}๊ฑด ํฉํธ ํ๊ธฐ ์๋ฃ (SELL ๊ตฌ์ถ๋ง ๋ณด์กด).")
except Exception as e:
logging.error(f"๐จ [{t}] KIS ์ค์์ฅ ๋ซ ์ค์บ ์๋ฌ: {e}")
try:
s_state = await _read_state_safe(slice_file, today_hyphen, {})
s_state['hijacked'] = True
s_state['date'] = today_hyphen
await _write_state_safe(slice_file, s_state)
logging.info(f"โก [{t}] ๋ก์ปฌ 1๋ถ ์ฌ๋ผ์ด์ฑ ์์ง ๋ฌดํจํ (hijacked) ์ ์ ๋งํน ์๋ฃ.")
except Exception as e:
logging.error(f"๐จ [{t}] ๋ก์ปฌ ์ฌ๋ผ์ด์ค ๋ฌดํจํ ์ฒ๋ฆฌ ์๋ฌ: {e}")
buy_qty = 0
for ox in slice_state_disk.get('orders', []):
if str(ox.get('side')) == 'BUY':
# MODIFIED: [NameError ์ฆ์ฌ ๋ฒ๊ทธ ์๊ฐ] self._safe_float โ _safe_float
_tot = int(_safe_float(ox.get('total_qty', 0)))
_fil = int(_safe_float(ox.get('filled_qty', 0)))
if _tot - _fil > 0:
buy_qty += (_tot - _fil)
exec_price = t_ask_p if t_ask_p > 0 else t_curr_p
if buy_qty > 0:
async with tx_lock:
res = await _retry_api(broker.send_order, t, "BUY", buy_qty, exec_price, "LIMIT")
safe_res = res if isinstance(res, dict) else {}
odno = str(safe_res.get('odno') or '')
if safe_res.get('rt_cd') == '0' and odno:
vwap_cache[f"REV_{t}_gap_hijack_fired"] = True
is_downward_hijacked_now = True
try:
final_slice_state = await _read_state_safe(slice_file, today_hyphen, {})
for o in final_slice_state.get('orders', []):
if str(o.get('side')) == 'BUY':
o['filled_qty'] = o.get('total_qty', 0)
final_slice_state['hijacked'] = True
final_slice_state['date'] = today_hyphen
await _write_state_safe(slice_file, final_slice_state)
except Exception as e:
logging.error(f"๐จ [{t}] ํ์ด์ฌํน ์ฒด๊ฒฐ ํ ๋ก์ปฌ ์ง์์ ์๋ ๋ง๊ธฐ ์ฒ๋ฆฌ ์๋ฌ: {e}")
msg = f"โก <b>[{html.escape(str(t))}] ๐ค ํ๋ฐฉ ๋ชจ๋ฉํ
์์จ์ฃผํ (Gap Hijack) ์ค์ ์ค๋ฒ๋ผ์ด๋ ๊ฒฉ๋ฐ!</b>\n"
msg += f"โซ๏ธ ๋น์ผ ๋์ VWAP ์ดํ๋ฅ (<b>{gap_pct:+.2f}%</b>)์ด ์๊ณ์น(<b>{gap_thresh}%</b>)๋ฅผ ํํฅ ๋ํํ์ต๋๋ค.\n"
msg += f"โซ๏ธ ์์ฝ/๋ฏธ์ฒด๊ฒฐ ๋ซ({nuked_count}๊ฑด) ํ๊ธฐ ํ, ์ค๋
์ท <b>์์ฌ ๋ชฉํ ์๋ ์ ๋</b>์ ๋งค๋ 1ํธ๊ฐ๋ก ์ผ๊ด ํ๊ฒฉ(Sweep)ํ์ต๋๋ค!\n"
msg += f"โซ๏ธ ์ ๋์ ์ค์ ์๋: <b>{buy_qty}์ฃผ</b> (๋จ๊ฐ: ${exec_price:.2f})\n"
msg += f"โซ๏ธ ์ ์ฝ๋ ๋ง๋ํ ์์๊ธ์ 100% ์จ์ ํ ๋ณด์กด๋์ด ์ด์(Runway)๋ก ๋ฐํ๋ฉ๋๋ค."
await _safe_send(context, chat_id, msg, parse_mode='HTML')
if version == "V_REV":
if hasattr(strategy, 'v_rev_plugin'):
await _retry_api(strategy.v_rev_plugin.record_execution, t, "BUY", buy_qty, exec_price)
if queue_ledger:
await _retry_api(queue_ledger.add_lot, t, buy_qty, exec_price, "VREV_VWAP_BUY", prev_close=safe_prev_c, portion_budget=portion_budget)
else:
if hasattr(strategy, 'v14_vwap_plugin'):
await _retry_api(strategy.v14_vwap_plugin.record_execution, t, "BUY", buy_qty, exec_price)
else:
err_msg = html.escape(str(safe_res.get('msg1') or '์๋ต ์์/ํต์ ์ฅ์ '))
logging.error(f"๐จ [{t}] ํ๋ฐฉ ๊ฐญ ํ์ด์ฌํน KIS ์๋ฒ ๊ฑฐ์ : {err_msg}")
reject_msg = (
f"๐จ <b>[{html.escape(str(t))}] ํ๋ฐฉ ๊ฐญ ํ์ด์ฌํน ์ค์(Sweep) ์๋ฒ ๊ฑฐ์ (Reject)!</b>\n"
f"โซ๏ธ ์ฌ์ : <code>{err_msg}</code>\n"
f"โซ๏ธ ์กฐ์น: ๋ค์ ์ค์บ ์ ์ฌ์๋ํฉ๋๋ค."
)
await _safe_send(context, chat_id, reject_msg, parse_mode='HTML')
else:
vwap_cache[f"REV_{t}_gap_hijack_fired"] = True
is_downward_hijacked_now = True
logging.info(f"โก [{t}] ํ๋ฐฉ Gap Hijack ๊ฒฉ๋ฐ ์กฐ๊ฑด์ ๋ง์กฑํ์ผ๋ ๋น์ผ ์ ๋ ์๋ ์ถฉ์กฑ์ผ๋ก ๋งค์ ์๋ต (ํ๋๊ทธ ๋ฝ์จ ์๋ฃ).")
# ======================================================
# [ 2. ์์ฒด VWAP 1๋ถ ์ฌ๋ผ์ด์ฑ ๋ก์ปฌ ์์ง ๊ฐ๋ ]
# ======================================================
curr_time_obj = now_est.time()
time_start = datetime.time(15, 27)
time_end = datetime.time(15, 59, 59)
if time_start <= curr_time_obj <= time_end:
slice_state = await _read_state_safe(slice_file, today_hyphen, {})
if slice_state.get('date') != today_hyphen:
continue
is_state_hijacked = slice_state.get('hijacked', False) or is_downward_hijacked_now
orders = slice_state.get('orders', [])
if not isinstance(orders, list): orders = []
if not orders: continue
is_cleanup_phase = (curr_time_obj >= datetime.time(15, 57))
curr_hm = now_est.strftime("%H:%M")
try:
vwap_profile = await _retry_api(cfg.get_vwap_profile, t, default={})
if not isinstance(vwap_profile, dict): vwap_profile = {}
except Exception: vwap_profile = {}
# MODIFIED: [NameError ์ฆ์ฌ ๋ฒ๊ทธ ์๊ฐ] self._safe_float โ _safe_float
cum_weight = _safe_float(vwap_profile.get(curr_hm, 0.0))
if is_cleanup_phase:
cum_weight = 1.0
elif cum_weight == 0.0:
start_mins = 15 * 60 + 27
curr_mins = now_est.hour * 60 + now_est.minute
elapsed = max(0, curr_mins - start_mins + 1)
cum_weight = min(1.0, max(0.0, elapsed / 29.0))
state_changed = False
for o in orders:
if not isinstance(o, dict): continue
# MODIFIED: [NameError ์ฆ์ฌ ๋ฒ๊ทธ ์๊ฐ] self._safe_float โ _safe_float
total_qty = int(_safe_float(o.get('total_qty')))
filled_qty = int(_safe_float(o.get('filled_qty')))
target_price = _safe_float(o.get('target_price', o.get('price', 0.0)))
side = str(o.get('side', 'BUY'))
last_odno = str(o.get('last_odno', ''))
if is_state_hijacked and side == 'BUY':
continue
if filled_qty >= total_qty and not last_odno:
continue
ccld_qty_this_tick = 0
if last_odno:
cancel_successful = False
async with tx_lock:
c_res = await _retry_api(broker.cancel_order, t, last_odno, timeout=10.0)
if isinstance(c_res, dict) and str(c_res.get('rt_cd', '')) == '0':
cancel_successful = True
is_still_open = False
if not cancel_successful:
unf = await _retry_api(broker.get_unfilled_orders_detail, t, default=[])
safe_unf = unf if isinstance(unf, list) else []
if any(isinstance(x, dict) and str(x.get('odno', '')) == last_odno for x in safe_unf):
is_still_open = True
if is_still_open:
logging.warning(f"๐จ [{t}] ์ทจ์ ์คํจ ๋ฐ ๋ฏธ์ฒด๊ฒฐ ์์กด ํ์ธ (Double Spending ๋ฐฉ์ด). ๋ค์ ๋ถ์ผ๋ก ์ด์ฐํฉ๋๋ค.")
continue
try:
now_kst_fresh = datetime.datetime.now(ZoneInfo('Asia/Seoul'))
kis_search_start_fresh = (now_kst_fresh - datetime.timedelta(days=2)).strftime('%Y%m%d')
query_end_dt_fresh = now_kst_fresh.strftime('%Y%m%d')
_execs = await _retry_api(broker.get_execution_history, t, kis_search_start_fresh, query_end_dt_fresh, default=None)
if _execs is None:
logging.warning(f"๐จ [{t}] ์ฒด๊ฒฐ ์์ฅ API ์กฐํ ์คํจ(Timeout). ๊ธฐ์ต ์์ค(Amnesia) ๋ฐฉ์ด๋ฅผ ์ํด ๋ค์ ๋ถ์ผ๋ก ์ด์ฐํฉ๋๋ค.")
continue
_safe_execs = _execs if isinstance(_execs, list) else []
_filled_rec = next((ex for ex in _safe_execs if isinstance(ex, dict) and str(ex.get('odno', '')) == last_odno), None)
if _filled_rec:
# MODIFIED: [NameError ์ฆ์ฌ ๋ฒ๊ทธ ์๊ฐ] self._safe_float โ _safe_float
ccld_qty_this_tick = int(_safe_float(_filled_rec.get('ft_ccld_qty')))
real_exec_price = _safe_float(_filled_rec.get('ft_ccld_unpr3'))
if real_exec_price == 0.0: real_exec_price = target_price
else:
if not cancel_successful:
logging.warning(f"๐จ [{t}] ๋ฏธ์ฒด๊ฒฐ์๋ ์๊ณ ์์ฅ์๋ ์์. KIS ๋(Lag) ๊ฐ์ง. ์ด์ค ํ๊ฒฉ ๋ฐฉ์ด๋ฅผ ์ํด ๋ค์ ๋ถ์ผ๋ก ์ด์ฐํฉ๋๋ค.")
continue
ccld_qty_this_tick = 0
real_exec_price = 0.0
except Exception as e:
logging.error(f"๐จ [{t}] ์์ฒด ์ฌ๋ผ์ด์ฑ ์ฒด๊ฒฐ ์์ฅ ๊ต์ฐจ ๊ฒ์ฆ ์๋ฌ: {e}")
continue
if ccld_qty_this_tick > 0:
processed_odnos = vwap_cache.setdefault(f"PROCESSED_ODNOS_{t}", set())
if last_odno not in processed_odnos:
processed_odnos.add(last_odno)
def _sync_ledger_atomic(tkr, sde, c_qty, r_price, q_ledger, strat, ver, prev_c=None, portion_b=None):
if ver == "V_REV":
if q_ledger:
if sde == "BUY":
q_ledger.add_lot(tkr, c_qty, r_price, "VREV_VWAP_BUY", prev_close=prev_c, portion_budget=portion_b)
else:
q_ledger.pop_lots(tkr, c_qty, r_price, prev_close=prev_c, portion_budget=portion_b)
if hasattr(strat, 'v_rev_plugin'):
strat.v_rev_plugin.record_execution(tkr, sde, c_qty, r_price)
else:
if hasattr(strat, 'v14_vwap_plugin'):
strat.v14_vwap_plugin.record_execution(tkr, sde, c_qty, r_price)
try:
p_sync = functools.partial(_sync_ledger_atomic, t, side, ccld_qty_this_tick, real_exec_price, queue_ledger, strategy, version, prev_c=safe_prev_c, portion_b=portion_budget)
await asyncio.wait_for(asyncio.to_thread(p_sync), timeout=10.0)
logging.info(f"๐พ [{t}] ์์ฒด ์ฌ๋ผ์ด์ฑ ์ฒด๊ฒฐ ์ฅ๋ถ ์์์ ๋๊ธฐํ ์๋ฃ: {side} {ccld_qty_this_tick}์ฃผ @ ${real_exec_price:.2f}")
except Exception as e:
processed_odnos.remove(last_odno)
logging.error(f"๐จ [{t}] ์์ฒด ์ฌ๋ผ์ด์ฑ ์ฒด๊ฒฐ ์ฅ๋ถ ๋๊ธฐํ ์คํจ (์บ์ ๋กค๋ฐฑ): {e}")
msg_side = "๋งค์" if side == "BUY" else "๋งค๋"
logging.info(f"โก [{t}] ์๋ ์์ง ์ฒด๊ฒฐ ํฉํธ ์ฅ๋ถ ๋๊ธฐํ ์๋ฃ: {msg_side} {ccld_qty_this_tick}์ฃผ @ ${real_exec_price:.2f} (ํ
๋ ๊ทธ๋จ ํ์ ๋ฐ์ดํจ์ค)")
filled_qty += ccld_qty_this_tick
o['filled_qty'] = filled_qty
o['last_odno'] = ""
o['last_sent_qty'] = 0
state_changed = True
if is_cleanup_phase:
continue
target_cum_qty = round(total_qty * cum_weight)
exec_price = 0.0
if side == "BUY":
exec_price = t_ask_p
else:
exec_price = t_bid_p
if exec_price <= 0.0:
exec_price = t_curr_p
if target_price > 0.0:
is_target_hit = False
if side == "BUY" and exec_price <= target_price:
is_target_hit = True
elif side == "SELL" and exec_price >= target_price:
is_target_hit = True
if not is_target_hit:
continue
qty_to_send = target_cum_qty - filled_qty
if qty_to_send <= 0: continue
if exec_price > 0:
if side == "SELL" and qty_to_send > 0:
if version == "V_REV":
if vrev_q_qty <= 0:
qty_to_send = 0
else:
qty_to_send = min(qty_to_send, vrev_q_qty)
else:
if actual_qty <= 0:
qty_to_send = 0
else:
qty_to_send = min(qty_to_send, actual_qty)
res = None
if qty_to_send > 0:
avwap_state_file = f"data/avwap_trade_state_{t}.json"
if side == "BUY":
avwap_state = await _retry_api(_read_json_ignore_date_sync, avwap_state_file)
if avwap_state and avwap_state.get('qty', 0) > 0 and avwap_state.get('sell_odno'):
avwap_sell_odno = avwap_state.get('sell_odno')
logging.info(f"๐ก๏ธ [{t}] ์์ ๊ฑฐ๋ ๋ฐฉ์ด: ์์ด์ ๋ซ({avwap_sell_odno}) ์์ ์ทจ์ ์งํ ๋ฐ ํํ ํจ๋ฌ๋
์ค ์ฐจ๋จ")
async with tx_lock:
c_res = await _retry_api(broker.cancel_order, t, avwap_sell_odno, timeout=10.0)
if isinstance(c_res, dict) and str(c_res.get('rt_cd', '')) == '0':
avwap_state['sell_odno'] = ""
avwap_state['suppress_sell'] = True
if chat_id and not vwap_cache.get(f"REV_{t}_wash_trade_msg"):
vwap_cache[f"REV_{t}_wash_trade_msg"] = True
await _safe_send(context, chat_id, f"๐ก๏ธ <b>[{html.escape(t)} ์์ ๊ฑฐ๋ ๋ฐฉ์ด ๋ฐ ํํ ํจ๋ฌ๋
์ค ์ฐจ๋จ ๊ฐ๋]</b>\nโซ๏ธ ๋ณธ์ง ์ฌ๋ผ์ด์ฑ ํ๊ฒฉ ์ค ์์ ๊ฑฐ๋ ๋ฐ ๋ฌดํ ์ฌ์ฅ์ ๋ณ๋ชฉ์ ๋ง๊ธฐ ์ํด ์์ด์ ๋งค๋ ๋ซ์ ์ผ๊ด ์๊ฑฐ(suppress_sell=True)ํฉ๋๋ค. (์ ํํฐ์ฅ ์ฌ์ฅ์ ์์ )", parse_mode='HTML')
await _write_state_safe(avwap_state_file, avwap_state)
await asyncio.sleep(1.0)
async with tx_lock:
res = await _retry_api(broker.send_order, t, side, qty_to_send, exec_price, "LIMIT")
else:
logging.warning(f"๐จ [{t}] VWAP ์ฌ๋ผ์ด์ฑ ๋งค๋ ์คํต: ํ/์๊ณ 0์ฃผ ์บกํ (Ghost-Dumping ๋ฐฉ์ด)")
res = {'rt_cd': '999', 'msg1': '๋ณด์ ์๋ 0์ฃผ ์บกํ์ผ๋ก ๋งค๋ ์คํต'}
safe_res = res if isinstance(res, dict) else {}
if safe_res.get('rt_cd') == '0' and safe_res.get('odno'):
o['last_odno'] = safe_res.get('odno')
o['last_sent_qty'] = qty_to_send
o['last_price'] = exec_price
state_changed = True
logging.info(f"๐ช [{t}] ์ ๋ฐ ์๊ฒฉ๋ง(Slicing): {side} {qty_to_send}์ฃผ @ ${exec_price:.2f} (๋์ {cum_weight*100:.1f}%)")
else:
logging.error(f"๐จ [{t}] VWAP ์ฌ๋ผ์ด์ฑ ๊ฑฐ์ : {safe_res.get('msg1')}")
if state_changed:
try:
await _write_state_safe(slice_file, slice_state)
except Exception as e:
logging.error(f"๐จ [{t}] ๋ก์ปฌ 1๋ถ ์ฌ๋ผ์ด์ฑ ์์ง ์ํ ๊ธฐ๋ก ์คํจ (Atomic Write): {e}")
except Exception as e:
logging.error(f"๐จ [{t}] ์๋์ฐ ์์ง ๋จ์ผ ์ข
๋ชฉ ์ฐ์ฐ ์ค ์น๋ช
์ ์ค๋ฅ (Cascade ๋ฐฉ์ด): {e}", exc_info=True)
continue