-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathvwap_core_engine.py
More file actions
612 lines (496 loc) ยท 44.6 KB
/
Copy pathvwap_core_engine.py
File metadata and controls
612 lines (496 loc) ยท 44.6 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
# ==========================================================
# FILE: vwap_core_engine.py
# ==========================================================
# ๐จ VERIFIED: [๋๋ฉ์ธ ์ฃผ๋ ์ค๊ณ (DDD) ์ ๊ท ํ์ผ] ์ ๊ท์ฅ V-REV ๋งค๋งค๋ง ์ ๋ด ์์ง
# ๐จ NEW: [์๋ฐฉํฅ Gap Hijack ํฉํธ ๊ฒฐ์] ๊ธฐ์กด ํ๋ฐฉ(-2%) ์ ์ฉ์ด๋ ์๋์ฐ ์์ง์ ์๋ฐฉ(+2.0% ํ๋์ฝ๋ฉ) ๋งค๋ ํ์ด์ฌํน(Upward Sell Hijack) ์์ง 100% ํฉํธ ์ด์ ์๋ฃ.
# ๐จ MODIFIED: [์์ ๊ฑฐ๋ ๊ฐ์ญ ๋ฐฉ์ด] ์๋ฐฉ ๋งค๋ ํ์ด์ฌํน ์ฑ๊ณต ์ upward_hijacked ํ๋๊ทธ๋ฅผ ์์์ ์ผ๋ก ๋ฝ์จํ์ฌ ์์ฌ 1๋ถ ์ฌ๋ผ์ด์ฑ ๋งค์/๋งค๋ ํ์๋ฅผ ์๋ฒฝํ ๋ง๋น.
# ๐จ MODIFIED: [์ 2ํ๋ฒ ์ค์] ์ค์ผ์ค๋ฌ์์ ๋ถ๋ฆฌ๋์ด ๋จ์ผ ์ฑ
์ ์์น(SRP)์ 100% ์ค์ํ๋ ์์ ๋งค๋งค ์งํ ์ฝ์ด ๋ชจ๋.
# ๐จ MODIFIED: [์ 1ํ๋ฒ ์ ๋ ์ค์] ๋ก์ปฌ ์ํ ํ์ผ I/O, Config ์กฐํ, ํ ์ฅ๋ถ ์ฐ์ฐ ์ ์ญ์ `asyncio.wait_for` ํ์์์ ์กฑ์ ๊ฐ์ .
# ๐จ MODIFIED: [Case 32 & 33 ์ ๋ ๊ท์น] Gap Hijack ๋ฐ 1๋ถ ์ฌ๋ผ์ด์ฑ ์ ์ญ์ 3๋จ ์ง์ ๋ฐฑ์คํ์ TPS ์บกํ(0.06s) ์๋์์น ๋ฝ์จ.
# ๐จ MODIFIED: [Case 39 & 40 ํ์๋ผ์ธ ์ญ์ ๋ฐฉ์ด] 16:01 ์ ํํฐ์ฅ์ผ๋ก ์ง์ฐ ์ด๊ด์ด ํ์ ๋ ๋ณธ์ง ํ๋์ด ์กด์ฌํ๋ค๋ฉด ์ ๊ท์ฅ ๋ง๊ฐ ์ง์ ์ Gap Hijack ๋ฐ ์ฌ๋ผ์ด์ฑ ๋ฃจํ๋ฅผ ์ ๋ฉด ๋ฐ์ดํจ์ค(Bypass)ํ์ฌ Double Spending ์์ฒ ์ฐจ๋จ.
# ๐จ MODIFIED: [Case 35 ๊ฒฐ์ธก์น ๋งน๋
์ฑ ๋ฐฉ์ด] ๊ฐญ ํ์ด์ฌํน ํ๋ณ์ ์ํ ๊ธฐ์ด์ง์ VWAP ์ฐ์ฐ ์, `ffill().bfill()` ๋ํ์ ๊ฐ์ ํ์ฌ NaN ์ ์ด(Math Collapse) ์์ฒ ์ฐจ๋จ.
# ๐จ MODIFIED: [๋ฌด๋คํ ์ ๋ฐ ์๊ฒฉ ์ฌ์] ๋ชฉํ๊ฐ ๋ฏธ์ถฉ์กฑ ์ 1์ฃผ๋ ์ฌ์ง ์๋ ๊ด๋ง์ธ ์ ์ง ๋ฐ 15:57 ํด๋ฆฐ์
ํ์ด์ฆ ์ ๊ฐ์ ๋คํ(Dumping) ๋ก์ง ์ ๋ฉด ์๊ฐ ์ ์ง.
# ๐จ MODIFIED: [V-REV ์ผ์๋ถ ์๊ฒฉ ํจ๋ฌ๋
์ค ๋ฐฉ์ด] 0์ฃผ ์์ถ๋ฐ ๋งค์์ฒ๋ผ ๋ชฉํ๊ฐ๊ฐ ํ์ฌ๊ฐ ๋๋น +2%๋ฅผ ์ด๊ณผํ์ฌ ํฐ๋ฌด๋์์ด ๋์ ๊ฒฝ์ฐ, ์ ๋ ์ค์(Sweep)์ ๊ฐ์ ํด์ ํ๊ณ ์ ์์ ์ธ 1๋ถ ์ฌ๋ผ์ด์ฑ ๊ถค๋๋ก ๋ณต๊ตฌ ๋ฝ์จ.
# ๐จ MODIFIED: [Ghost-Dumping ๋ถ๊ดด ๋ฐฉ์ด] 1๋ถ ์ฌ๋ผ์ด์ฑ ๋งค๋ ํ๊ฒฉ ์ง์ ์ KIS ์ค์๊ณ ๋ฅผ ์ค์บํ์ฌ ์๋์ ์ ๋ฐ ์บกํ(`min(qty, rt_qty)`).
# ๐จ MODIFIED: [Event Loop Deadlock ๋ฐฉ์ด] ํ
๋ ๊ทธ๋จ ํต์ (send_message)์ `asyncio.wait_for(timeout=15.0)` ์กฑ์ 100% ๋ํ.
# ๐จ MODIFIED: [Time Paradox ํฉํธ ๊ต์ ] ์์ฒด ์ฌ๋ผ์ด์ฑ ์ฒด๊ฒฐ ๊ฒ์ฆ์ ์ํ KIS ์์ฅ ์กฐํ ์ KST ํฉํธ ์ฃผ์
์๋ฃ.
# ๐จ NEW: [Scope Mismatch ๊ถ๊ทน ๋ฐฉ์ด] ํ์ผ I/O ์ค๋ ๋๋ก ์์๋๋ `_sync_ledger_atomic` ํจ์์ ๋ช
์์ ํ๋ผ๋ฏธํฐ๋ฅผ ์ฃผ์
ํ์ฌ ํด๋ก์ ์ค์ผ์ผ๋ก ์ธํ `UnboundLocalError` ์์ฒ ๋ด์.
# ๐จ MODIFIED: [ํ ์ฅ๋ถ ์ ๋์ฃผ์ ํ๋ฒ ์๋ณต] ์์จ์ฃผํ ํ์ด์ฌํน ์์ง์ด KIS ์ค์๊ณ ๋ฅผ ์ค์ธํ์ฌ 0์ฃผ ์ํ์์ V14 ๋ฌผ๋์ ์ ๋ น ๋งค๋(Ghost Selling)ํ๋ ์๊ถํ์๋ฅผ ํ ์ฅ๋ถ ํ๋ ์บกํ(vrev_q_qty)์ผ๋ก ์์ฒ ์ฐจ๋จ.
# ==========================================================
import logging
import asyncio
import math
import time
import datetime
from zoneinfo import ZoneInfo
import html
import functools
from scheduler_core import get_budget_allocation
from state_io_manager import _read_json_safe_sync, _atomic_write_json_sync
def _safe_float(val):
""" ๐จ [์ํ ์ฐ์ฐ ๋ถ๊ดด ๋ฐฉ์ด] NaN, Infinity ๋ฐ String-Comma ๋งน๋
์ฑ ๋ฐ์ดํฐ ์ ๋ฐ ํํฐ๋ง """
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):
""" ๐จ [Case 32, 33] ์ค์ ์ง์คํ TPS ์บกํ ๋ฐ ์ง์ ๋ฐฑ์คํ ๋น๋๊ธฐ ๋ํผ """
for attempt in range(3):
try:
await asyncio.sleep(0.06)
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):
""" ๐จ [Event Loop Deadlock ๋ฐฉ์ด] ํ
๋ ๊ทธ๋จ ํต์ ์๋๋ฐ์ค ๋ํ """
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
async def execute_vwap_init(tx_lock, cfg, broker, chat_id, context, vwap_cache):
""" ๐จ [๊ด์ธก๋ง ๊ธฐ์] V-REV ์ฌ๋ผ์ด์ฑ ๋ฐ ๊ฐญ ํ์ด์ฌํน ๋ชจ๋ํฐ๋ง ์์ ๋ธ๋ฆฌํ """
async with tx_lock:
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 ์์ง / Gap Hijack ์๋์ฐ ๊ด์ธก๋ง ๊ธฐ์</b>\n"
msg += f"โซ๏ธ KIS ์์ฝ ๋ซ ๊ด๋ง ๋ฐ ์ฅ ๋ง๊ฐ 34๋ถ ์ ๋ก์ปฌ ํ์ค ํ๊ฒฉ ์์ง์ ๊ฐ๋ ๋๊ธฐ๋ฅผ ํ์ธํ์ต๋๋ค.\n"
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):
""" ๐จ [์ฝ์ด ์์ง] ์๋ฐฉํฅ Gap Hijack ํ์ง, ์์ฒด 1๋ถ Slicing, ๋ฌด๋คํ ์ ๋ฐ ์๊ฒฉ ํ๊ฒฉ๋ง ๋ฉ์ธ ๋ฃจํ """
est = ZoneInfo('America/New_York')
now_est = datetime.datetime.now(est)
today_hyphen = now_est.strftime('%Y-%m-%d')
# ๐จ NEW: [Time Paradox ํฉํธ ๊ต์ ] ์์ฒด ์ฌ๋ผ์ด์ฑ KIS ์์ฅ ์กฐํ๋ฅผ ์ํ KST ํฉํธ ์ฃผ์
kst_zone = ZoneInfo('Asia/Seoul')
now_kst = datetime.datetime.now(kst_zone)
today_kst_str = now_kst.strftime('%Y%m%d')
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
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)))
# ๐จ NEW: [ํ ์ฅ๋ถ ์ ๋์ฃผ์ ์๋ณต] KIS ์๊ณ ์ค์ธ ๋คํ ๋ฐฉ์ด๋ฅผ ์ํ ํ ์ฅ๋ถ ์๋ ํฉํธ ์ถ์ถ
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"
# ๐จ NEW: [Case 39 & 40 ํ์๋ผ์ธ ์ญ์ ํจ๋ฌ๋
์ค ์ฐจ๋จ] ์ ํํฐ์ฅ ์ง์ฐ ์ด๊ด ์ํ ๊ต์ฐจ ๊ฒ์ฆ (Timeline Inversion ๋ฐฉ์ด)
try:
after_state_file = f"data/vrev_aftermarket_state_{t}.json"
after_state = await _retry_api(_read_json_safe_sync, after_state_file, today_hyphen, default={})
if after_state.get('date') == today_hyphen:
pending_aftermarket = any(isinstance(o, dict) and str(o.get('status')) == 'PENDING' for o in after_state.get('orders', []))
if pending_aftermarket:
logging.info(f"โณ [{t}] ์ ํํฐ์ฅ(16:01) ์ด๊ด ๋๊ธฐ ์ค. ์ ๊ท์ฅ ๋ง๊ฐ ์ง์ (16:00)์ Gap Hijack ๋ฐ ์ฌ๋ผ์ด์ฑ ์์ง์ ์ ๋ฉด ๋ฐ์ดํจ์คํฉ๋๋ค.")
continue
except Exception as e:
logging.error(f"๐จ [{t}] ์ ํํฐ์ฅ ์ด๊ด ์ํ ๊ต์ฐจ ๊ฒ์ฆ ์๋ฌ: {e}")
# ======================================================
# [ 1. Gap Hijack (์๋ฐฉํฅ ๊ฐญ ํ์ด์ฌํน) ๋ชจ๋ํฐ๋ง ]
# ======================================================
is_downward_hijacked_now = vwap_cache.get(f"REV_{t}_gap_hijack_fired", False)
is_upward_hijacked_now = vwap_cache.get(f"REV_{t}_upward_hijack_fired", False)
if version == "V_REV" and not (is_downward_hijacked_now or is_upward_hijacked_now):
# ๐จ MODIFIED: ๊ธฐ์ด์์ฐ(base_tkr) ๋์ ๋ณธ์ข
๋ชฉ(t) 100% ํฉํธ ํ๊ฒฉ ๋กค์ค๋ฒ
t_curr_p = _safe_float(await _retry_api(broker.get_current_price, t))
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()
# ๐จ [Time Paradox ๋ถ๊ดด ๊ถ๊ทน ์์ ] 5์ผ์น(5d) ์บ๋ค ํฉ์ฐ์ผ๋ก ์ธํ VWAP ์ค์ผ ํจ๋ฌ๋
์ค ์์ฒ ์ฐจ๋จ
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:
# ๐จ MODIFIED: [Case 35 ๊ฒฐ์ธก์น ๋งน๋
์ฑ ๋ฐฉ์ด] ffill ๊ฐ์ ๋ฝ์จ
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
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
# ----------------------------------------------------
# ๐จ [A. ํ๋ฐฉ ๋งค์ ํ์ด์ฌํน ๊ฒฉ๋ฐ๋ง]
# ----------------------------------------------------
if gap_pct <= gap_thresh:
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
# ๐จ SELL ๊ตฌ์ถ๋ง ์์กด ๋ฝ์จ (์์ฝ ์ฃผ๋ฌธ)
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:
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
# ๐จ SELL ๊ตฌ์ถ๋ง ์์กด ๋ฝ์จ (์ผ๋ฐ ๋ฏธ์ฒด๊ฒฐ ์ฃผ๋ฌธ)
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:
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 _retry_api(_read_json_safe_sync, slice_file, today_hyphen, default={})
s_state['hijacked'] = True
s_state['date'] = today_hyphen
await _retry_api(_atomic_write_json_sync, slice_file, s_state)
logging.info(f"โก [{t}] ๋ก์ปฌ 1๋ถ ์ฌ๋ผ์ด์ฑ ์์ง ๋ฌดํจํ (hijacked) ๋งํน ์๋ฃ.")
except Exception as e:
logging.error(f"๐จ [{t}] ๋ก์ปฌ ์ฌ๋ผ์ด์ค ๋ฌดํจํ ์ฒ๋ฆฌ ์๋ฌ: {e}")
await asyncio.sleep(2.0)
seed = await _retry_api(cfg.get_seed, t, default=0.0)
daily_limit = _safe_float(seed) * 0.15
alloc_cash = _safe_float(allocated_cash.get(t, 0.0))
safe_alloc_cash = min(alloc_cash, daily_limit) if daily_limit > 0 else alloc_cash
total_spent = 0.0
if hasattr(strategy, 'v_rev_plugin'):
spent_dict = strategy.v_rev_plugin.executed.get("BUY_BUDGET")
safe_spent_dict = spent_dict if isinstance(spent_dict, dict) else {}
total_spent = _safe_float(safe_spent_dict.get(t, 0.0))
rem_budget = max(0.0, safe_alloc_cash - total_spent)
ask_price = _safe_float(await _retry_api(broker.get_ask_price, t))
curr_p = _safe_float(await _retry_api(broker.get_current_price, t))
exec_price = ask_price if ask_price > 0 else curr_p
buy_qty = int(math.floor(rem_budget / exec_price)) if exec_price > 0 else 0
if buy_qty > 0:
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
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"โซ๏ธ KIS ์์ฝ/๋ฏธ์ฒด๊ฒฐ ๋งค์ ๋ซ({nuked_count}๊ฑด) ํ๊ธฐ ๋ฐ ๋ก์ปฌ ์์ง ์คํฑ ํ, ์์ฌ ์์ฐ 100%๋ฅผ ๋งค๋ 1ํธ๊ฐ๋ก ์ผ๊ด ์ค์(Sweep) ํ๊ฒฉํ์ต๋๋ค!\n"
msg += f"โซ๏ธ ์ค์ ์๋: <b>{buy_qty}์ฃผ</b> (๋จ๊ฐ: ${exec_price:.2f})"
await _safe_send(context, chat_id, msg, parse_mode='HTML')
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, "GAP_HIJACK_BUY")
else:
err_msg = html.escape(str(safe_res.get('msg1') or '์๋ต ์์/ํต์ ์ฅ์ '))
logging.error(f"๐จ [{t}] V-REV ํ๋ฐฉ ๊ฐญ ํ์ด์ฌํน KIS ์๋ฒ ๊ฑฐ์ : {err_msg}")
reject_msg = (
f"๐จ <b>[{html.escape(str(t))}] V-REV ํ๋ฐฉ ๊ฐญ ํ์ด์ฌํน ์ค์(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 ๊ฒฉ๋ฐ ์กฐ๊ฑด์ ๋ง์กฑํ์ผ๋ ์์ฌ ์์ฐ ์์ง์ผ๋ก ์ค์ ๋งค์ ์๋ต (ํ๋๊ทธ ๋ฝ์จ ์๋ฃ).")
# ----------------------------------------------------
# ๐จ [B. ์๋ฐฉ ๋งค๋ ํ์ด์ฌํน (Upward Sell Hijack) ๊ฒฉ๋ฐ๋ง]
# ----------------------------------------------------
# ๐จ MODIFIED: [ํ ์ฅ๋ถ ์ ๋์ฃผ์ ์๋ณต] KIS ์ค์๊ณ (actual_qty) ์ค์ธ ๋ฐฉ์ด๋ฅผ ์ํด ํ ์ฅ๋ถ ์๋(vrev_q_qty) ํฉํธ ๊ต์ฐจ ๊ฒ์ฆ ๋ฝ์จ
elif gap_pct >= 2.0 and vrev_q_qty > 0 and actual_qty > 0:
logging.info(f"โก [{t}] Upward Sell Hijack Triggered! gap: {gap_pct:.2f}% >= +2.0%")
nuked_count = 0
# ๐จ [๊ฒฉ๋ฆฌ ํ๊ฒฉ ๋ฝ์จ] ์ค์ง ํ ์ฅ๋ถ ํ๋๊น์ง๋ง ํ๊ฒฉํ์ฌ KIS ์๊ณ ์ ์์ธ ํ ์ ๋ต ๋ฌผ๋์ ์ ๋ ๋ฐฉ์ด
target_sell_qty = min(actual_qty, vrev_q_qty)
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
# ๐จ BUY๋ ๋ณด์กดํ๊ณ SELL๋ง ํ์
์๊ฐ (ํ๋ฐฉ๊ณผ ์ ๋ฐ๋)
side_cd = str(req.get('sll_buy_dvsn_cd') or req.get('sll_buy_dvsn') or '')
if side_cd == '02': 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:
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 == '02': 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:
c_res = await _retry_api(broker.cancel_order, t, u_odno)
if c_res: nuked_count += 1
logging.info(f"โก [{t}] KIS ์ค์์ฅ ์ค์บ: ์์ฝ ๋ฐ ์ผ๋ฐ ๋งค๋(SELL) ๋ซ {nuked_count}๊ฑด ํฉํธ ํ๊ธฐ ์๋ฃ (BUY ๋ซ ๋ณด์กด).")
except Exception as e:
logging.error(f"๐จ [{t}] ์๋ฐฉ ๋งค๋ ํ์ด์ฌํน KIS ์ค์์ฅ ๋ซ ์ค์บ ์๋ฌ: {e}")
try:
s_state = await _retry_api(_read_json_safe_sync, slice_file, today_hyphen, default={})
s_state['hijacked'] = True
s_state['upward_hijacked'] = True
s_state['date'] = today_hyphen
await _retry_api(_atomic_write_json_sync, slice_file, s_state)
logging.info(f"โก [{t}] ์๋ฐฉ ํ์ด์ฌํน: ๋ก์ปฌ 1๋ถ ์ฌ๋ผ์ด์ฑ ์์ง ๋ฌดํจํ (upward_hijacked) ๋งํน ์๋ฃ.")
except Exception as e:
logging.error(f"๐จ [{t}] ์๋ฐฉ ํ์ด์ฌํน ๋ก์ปฌ ์ฌ๋ผ์ด์ค ๋ฌดํจํ ์ฒ๋ฆฌ ์๋ฌ: {e}")
await asyncio.sleep(2.0)
bid_price = _safe_float(await _retry_api(broker.get_bid_price, t))
curr_p = _safe_float(await _retry_api(broker.get_current_price, t))
exec_price = bid_price if bid_price > 0 else curr_p
if exec_price > 0:
res = await _retry_api(broker.send_order, t, "SELL", target_sell_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}_upward_hijack_fired"] = True
is_upward_hijacked_now = True
# ํ ์ฅ๋ถ ์๊ฐ (์์ต ํ์ )
if queue_ledger:
await _retry_api(queue_ledger.clear_queue, t)
msg = f"๐ <b>[{html.escape(str(t))}] ๐ค ์๋ฐฉ ๋ชจ๋ฉํ
์์จ์ฃผํ (Sell Hijack) ๊ฒฉ๋ฐ!</b>\n"
msg += f"โซ๏ธ ๋น์ผ ๋์ VWAP ๋๋น ํ์ฌ๊ฐ ์ํ
(<b>+{gap_pct:.2f}%</b>)์ด ์ต์ ์๊ณ์น(<b>+2.0%</b>)๋ฅผ ๊ดํตํ์ต๋๋ค.\n"
msg += f"โซ๏ธ KIS ์์ฝ/๋ฏธ์ฒด๊ฒฐ ๋งค๋ ๋ซ({nuked_count}๊ฑด) ํ๊ธฐ ํ, ํ ์ฅ๋ถ ๋ณด์ ๋ฌผ๋์ ๋งค์ 1ํธ๊ฐ๋ก ์ผ๊ด ์ค์(Sweep) ๋คํํ์ฌ ์ข
๊ฐ ๊ฑฐํ ๋ถ๊ดด๋ฅผ ํํผํฉ๋๋ค!\n"
msg += f"โซ๏ธ ์ ๋ ์ต์ ์๋: <b>{target_sell_qty}์ฃผ</b> (๋จ๊ฐ: ${exec_price:.2f})\n"
msg += f"โซ๏ธ <b>๋น์ผ ์ฌ๋ผ์ด์ฑ ์์ง ๊ฐ๋์ ์ ๋ฉด ๋ง๋น์ํต๋๋ค (์กฐ๊ธฐ ํด๊ทผ ๋ฝ์จ).</b>"
await _safe_send(context, chat_id, msg, parse_mode='HTML')
else:
err_msg = html.escape(str(safe_res.get('msg1') or '์๋ต ์์/ํต์ ์ฅ์ '))
logging.error(f"๐จ [{t}] V-REV ์๋ฐฉ ๊ฐญ ํ์ด์ฌํน KIS ์๋ฒ ๊ฑฐ์ : {err_msg}")
reject_msg = (
f"๐จ <b>[{html.escape(str(t))}] V-REV ์๋ฐฉ ํ์ด์ฌํน ์ค์(Sweep) ์๋ฒ ๊ฑฐ์ !</b>\n"
f"โซ๏ธ ์ฌ์ : <code>{err_msg}</code>\n"
f"โซ๏ธ ์กฐ์น: ๋ค์ ์ค์บ ์ ์ฌ์๋ํฉ๋๋ค."
)
await _safe_send(context, chat_id, reject_msg, parse_mode='HTML')
# ======================================================
# [ 2. ์์ฒด VWAP 1๋ถ ์ฌ๋ผ์ด์ฑ ๋ก์ปฌ ์์ง ๊ฐ๋ ]
# ======================================================
curr_time_obj = now_est.time()
time_start = datetime.time(15, 27)
time_end = datetime.time(15, 57, 59)
if time_start <= curr_time_obj <= time_end:
slice_state = await _retry_api(_read_json_safe_sync, slice_file, today_hyphen, default={})
# ๐จ MODIFIED: [Date Schema Mismatch ์์ฒ ์ฐจ๋จ] today_hyphen ๊ฐ์ ๊ฒฐ์
if slice_state.get('date') != today_hyphen:
continue
is_state_hijacked = slice_state.get('hijacked', False) or is_downward_hijacked_now
is_state_upward_hijacked = slice_state.get('upward_hijacked', False) or is_upward_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 = {}
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
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'))
side = str(o.get('side', 'BUY'))
last_odno = str(o.get('last_odno', ''))
# ๐จ [์์ ๊ฑฐ๋ ๊ฐ์ญ ์ฐจ๋จ] ์/ํ๋ฐฉ ํ์ด์ฌํน ์ ์ฌ๋ผ์ด์ฑ ๋ง๋น ๋ฝ์จ
if (is_state_hijacked or is_state_upward_hijacked) and side == 'BUY':
continue
if is_state_upward_hijacked and side == 'SELL':
continue # ์๋ฐฉ ํ์ด์ฌํน์ผ๋ก ์ด๋ฏธ ์ ๋ ๋์ก์ผ๋ฏ๋ก SELL ์ฌ๋ผ์ด์ฑ ์ ๋ฉด ๋ง๋น
if filled_qty >= total_qty and not last_odno:
continue
ccld_qty_this_tick = 0
if last_odno:
cancel_successful = False
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
await asyncio.sleep(0.5)
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:
# ๐จ NEW: [Time Paradox ํฉํธ ๊ต์ ] KIS ์์ฅ 100% ๋๊ธฐํ๋ฅผ ์ํด today_kst_str ์ฃผ์
_execs = await _retry_api(broker.get_execution_history, t, today_kst_str, today_kst_str, default=[])
_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:
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:
ccld_qty_this_tick = 0
real_exec_price = 0.0
except Exception as e:
logging.error(f"๐จ [{t}] ์์ฒด ์ฌ๋ผ์ด์ฑ ์ฒด๊ฒฐ ์์ฅ ๊ต์ฐจ ๊ฒ์ฆ ์๋ฌ: {e}")
ccld_qty_this_tick = 0
real_exec_price = 0.0
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)
# ๐จ NEW: [Scope Mismatch ๊ถ๊ทน ๋ฐฉ์ด] ํด๋ก์ (Closure) ์ค์ผ์ ๋ฐฉ์งํ๊ธฐ ์ํ ๋ช
์์ ํ๋ผ๋ฏธํฐ ํจ์ฑ ๋ฝ์จ
def _sync_ledger_atomic(tkr, sde, c_qty, r_price, q_ledger, strat):
if q_ledger:
if sde == "BUY":
q_ledger.add_lot(tkr, c_qty, r_price, "VREV_VWAP_BUY")
else:
q_ledger.pop_lots(tkr, c_qty, r_price)
if hasattr(strat, 'v_rev_plugin'):
strat.v_rev_plugin.record_execution(tkr, sde, c_qty, r_price)
try:
# ๐จ MODIFIED: [์ 1ํ๋ฒ] ํ๋ผ๋ฏธํฐ ๋ช
์์ ์ ๋ฌ ๋ฐ wait_for ํ์์์ ๋ํ
p_sync = functools.partial(_sync_ledger_atomic, t, side, ccld_qty_this_tick, real_exec_price, queue_ledger, strategy)
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 "๋งค๋"
await _safe_send(context, chat_id, f"โก <b>[{html.escape(str(t))}] V-REV ์๋ ์์ง ์ฒด๊ฒฐ ํฉํธ ์ฅ๋ถ ๋๊ธฐํ!</b>\nโซ๏ธ {msg_side}: {ccld_qty_this_tick}์ฃผ @ ${real_exec_price:.2f}", parse_mode='HTML')
filled_qty += ccld_qty_this_tick
o['filled_qty'] = filled_qty
o['last_odno'] = ""
o['last_sent_qty'] = 0
state_changed = True
# ๐จ NEW: [๋ฌด๋คํ ์ ๋ ํ๋ฒ ํฉํธ ๊ฒฐ์]
if is_cleanup_phase:
continue # 15:57 ์ดํ๋ก๋ ๋ฏธ์ฒด๊ฒฐ ์ทจ์๋ง ์งํํ๊ณ ์ ๊ท ํ๊ฒฉ์ ์ ๋ฉด ๋ฐ์ดํจ์ค(Bypass)
if filled_qty >= total_qty: continue
target_cum_qty = round(total_qty * cum_weight)
qty_to_send = target_cum_qty - filled_qty
exec_price = 0.0
if side == "BUY":
exec_price = _safe_float(await _retry_api(broker.get_ask_price, t))
else:
exec_price = _safe_float(await _retry_api(broker.get_bid_price, t))
if exec_price <= 0.0:
exec_price = _safe_float(await _retry_api(broker.get_current_price, t))
# ๐จ NEW: [๋ฌด๋คํ ์ ๋ฐ ์๊ฒฉ ์ฌ์] ๋ชฉํ ํ์ ์ถฉ์กฑ ์์๋ง 100% ์ฆ์ ํ๊ฒฉ (๋ฏธ์ถฉ์กฑ ์ ์ฒ ์ ํ ๊ด๋ง์ธ)
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 is_target_hit:
# ๐จ NEW: [V-REV ์ผ์๋ถ ์๊ฒฉ ํจ๋ฌ๋
์ค ๋ฐฉ์ด] ๋ชฉํ๊ฐ๊ฐ ํฐ๋ฌด๋์์ด ๋ฉ๋ฆฌ ์๋ ๊ฒฝ์ฐ ์ค์(Sweep)์ ๊ฐ์ ํด์ ํ๊ณ 1๋ถ ์ฌ๋ผ์ด์ฑ ๊ถค๋ ๋ฝ์จ
if side == "BUY" and target_price > exec_price * 1.02:
qty_to_send = target_cum_qty - filled_qty
elif side == "SELL" and target_price < exec_price * 0.98:
qty_to_send = target_cum_qty - filled_qty
else:
qty_to_send = total_qty - filled_qty # ์ ์ ์๊ฒฉ ํฉํธ ์ค์
else:
continue # ๋ชฉํ๊ฐ ๋ฏธ์ถฉ์กฑ ์ 1์ฃผ๋ ์ฌ์ง ์๊ณ ์ฒ ์ ํ ๊ด๋ง์ธ (Bypass)
if qty_to_send <= 0: continue
if exec_price > 0:
# ๐จ NEW: [Ghost-Dumping ๋ถ๊ดด ๋ฐฉ์ด] 1๋ถ ์ฌ๋ผ์ด์ฑ ๋งค๋ ํ๊ฒฉ ์ง์ ์ KIS ์ค์๊ณ ๋ฅผ ์ค์บํ์ฌ ๋งค๋ ์๋์ ์บกํ.
if side == "SELL" and qty_to_send > 0:
rt_qty = qty_to_send
bal_tuple = await _retry_api(broker.get_account_balance)
if isinstance(bal_tuple, (list, tuple)) and len(bal_tuple) > 1:
rt_qty = int(_safe_float(bal_tuple[1].get(t, {}).get('qty', 0)))
qty_to_send = min(qty_to_send, rt_qty)
res = None
if qty_to_send > 0:
res = await _retry_api(broker.send_order, t, side, qty_to_send, exec_price, "LIMIT")
else:
logging.warning(f"๐จ [{t}] VWAP ์ฌ๋ผ์ด์ฑ ๋งค๋ ์คํต: KIS ์ค์๊ณ 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 asyncio.wait_for(asyncio.to_thread(_atomic_write_json_sync, slice_file, slice_state), timeout=10.0)
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