-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbroker.py
More file actions
1077 lines (793 loc) · 45.8 KB
/
Copy pathbroker.py
File metadata and controls
1077 lines (793 loc) · 45.8 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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ==========================================================
# FILE: broker.py
# ==========================================================
# MODIFIED: [V28.15 장부 2배 뻥튀기(Double Counting) 원천 차단]
# KIS API(TTTS3012R)가 동일 종목을 다중 거래소(NASD, AMEX 등) 응답으로
# 중복 반환할 때 발생하던 누적 합산(21+21=42) 맹점 전면 수술.
# 이종 거래소 분할 결제를 대비한 합산 로직은 유지하되, 동일한 수량과
# 평단가로 들어오는 '유령 중복 응답'은 무시하도록 멱등성 가드 이식.
# MODIFIED: [V28.27 GCP 무한 대기 교착(Deadlock) 및 액면분할 에러 전면 수술]
# 타임아웃(Timeout) 족쇄가 없어 GCP 환경에서 봇을 영원히 기절시키던
# yfinance의 fast_info 모듈을 전면 소각하고, 지연 발생 시 즉각 KIS API로
# 우회(Fallback)하도록 Safe-Casting 방어막 이식. 액면분할 파싱 에러(str) 완벽 픽스.
# MODIFIED: [V28.28 yfinance 버전 호환 및 타임아웃 방어]
# 최신 yfinance 라이브러리가 액면분할 날짜 키를 문자열(str)로 반환 시
# 발생하는 strftime 에러를 Timestamp 강제 변환 및 슬라이싱으로 완벽히 교정.
# MODIFIED: [V28.34 17시 잔고 스캔 API 크래시 완벽 방어 및 타입 세이프 쉴드 이식]
# KIS API가 0주 상태이거나 서버 응답 변동 시 output2를 빈 리스트([])로 반환하여
# AttributeError 런타임 붕괴를 유발하던 치명적 맹점을 isinstance 기반의
# 타입 락온(Lock-on) 방어막으로 원천 차단 완료.
# MODIFIED: [V29.18 런타임 붕괴 방어 및 페이징 결함 수술]
# 1) get_unfilled_orders_detail 및 get_execution_history에서 ctx_area_fk200 파싱 시
# 결측치(None) 유입으로 인한 AttributeError 런타임 붕괴를 Safe Casting으로 원천 차단.
# 2) get_account_balance 함수에 tr_cont 헤더 기반의 페이징(Pagination) 로직을 이식하여
# 20종목 초과 시 발생하는 잔고 스캔 데이터 기아(Data Starvation) 맹점 완벽 교정.
# 3) 논리적 앵커 통일을 위해 America/New_York을 US/Eastern으로 100% 락온(Lock-on) 형변환.
# MODIFIED: [V30.09 핫픽스] pytz 영구 적출 및 ZoneInfo 도입으로 LMT 버그 차단 및 타임존 무결성 100% 확보
# MODIFIED: [V40.XX 옴니 매트릭스] 거래소 동적 탐색 실패 시 SOXS 티커 AMEX Fallback 이식 및 타겟 인덱스 방어막 락온
# NEW: [V40.XX 옴니 매트릭스] 전일 팩트 VWAP 및 당일 실시간 VWAP 듀얼 파싱 엔진(get_daily_vwap_info) 탑재
# 🚨 MODIFIED: [V44.76 팩트 교정] 당일 고가/저가 스캔 시 프리마켓 진폭 100% 합산 롤백 (보수적 체력 방어막 복원)
# 🚨 MODIFIED: [V47.00 하이킨아시 파서 open 컬럼 강제 수혈 락온]
# 🚨 MODIFIED: [V49.11 체력 스캔 프리/애프터장 팩트 수혈] ATR5/ATR14 연산 시 prepost=True 속성을 강제 주입하여 장외 진폭까지 100% 반영
# ==========================================================
import requests
import json
import time
import datetime
import os
import math
import yfinance as yf
from zoneinfo import ZoneInfo
import tempfile
import shutil
import pandas as pd
import numpy as np
import volatility_engine as ve
import logging
# MODIFIED: [제6계명 야후 파이낸스 MultiIndex 변이 방어] 런타임 붕괴(KeyError) 영구 소각
def _flatten_columns(df: pd.DataFrame) -> pd.DataFrame:
""" 🚨 [수술 완료] 야후 파이낸스 API 업데이트로 인한 MultiIndex 순서 붕괴 방어 """
if isinstance(df.columns, pd.MultiIndex):
if 'Ticker' in df.columns.names:
df.columns = df.columns.droplevel('Ticker')
elif df.columns.nlevels == 2:
price_fields = {'Close', 'High', 'Low', 'Open', 'Volume', 'Adj Close'}
level0_vals = set(df.columns.get_level_values(0))
drop_level = 0 if not level0_vals.intersection(price_fields) else 1
df.columns = df.columns.droplevel(drop_level)
return df
class KoreaInvestmentBroker:
def __init__(self, app_key, app_secret, cano, acnt_prdt_cd="01"):
self.app_key = app_key
self.app_secret = app_secret
self.cano = cano
self.acnt_prdt_cd = acnt_prdt_cd
self.base_url = "https://openapi.koreainvestment.com:9443"
self.token_file = f"data/token_{cano}.dat"
self.token = None
self._excg_cd_cache = {}
self._get_access_token()
def _get_access_token(self, force=False):
kst = ZoneInfo('Asia/Seoul')
if not force and os.path.exists(self.token_file):
try:
with open(self.token_file, 'r') as f:
saved = json.load(f)
expire_time = datetime.datetime.strptime(saved['expire'], '%Y-%m-%d %H:%M:%S')
now_kst_naive = datetime.datetime.now(kst).replace(tzinfo=None)
if expire_time > now_kst_naive + datetime.timedelta(hours=1):
self.token = saved['token']
return
except Exception: pass
if force and os.path.exists(self.token_file):
try: os.remove(self.token_file)
except Exception: pass
url = f"{self.base_url}/oauth2/tokenP"
body = {"grant_type": "client_credentials", "appkey": self.app_key, "appsecret": self.app_secret}
try:
res = requests.post(url, headers={"content-type": "application/json"}, data=json.dumps(body), timeout=10)
data = res.json()
if 'access_token' in data:
self.token = data['access_token']
expire_str = (datetime.datetime.now(kst).replace(tzinfo=None) + datetime.timedelta(seconds=int(data['expires_in']))).strftime('%Y-%m-%d %H:%M:%S')
dir_name = os.path.dirname(self.token_file)
if dir_name and not os.path.exists(dir_name):
os.makedirs(dir_name, exist_ok=True)
fd, temp_path = tempfile.mkstemp(dir=dir_name, text=True)
try:
# MODIFIED: [V49.10 런타임 붕괴 방어] 들여쓰기 오염 교정 (21 -> 20칸)
with os.fdopen(fd, 'w', encoding='utf-8') as f:
json.dump({'token': self.token, 'expire': expire_str}, f)
f.flush()
os.fsync(f.fileno())
shutil.move(temp_path, self.token_file)
finally:
if os.path.exists(temp_path):
try: os.remove(temp_path)
except Exception: pass
else:
print(f"❌ [Broker] 토큰 발급 실패: {data.get('error_description', '알 수 정 없는 오류')}")
except Exception as e:
print(f"❌ [Broker] 토큰 통신 에러: {e}")
def _get_header(self, tr_id):
return {
"content-type": "application/json; charset=utf-8",
"authorization": f"Bearer {self.token}",
"appkey": self.app_key,
"appsecret": self.app_secret,
"tr_id": tr_id,
"custtype": "P"
}
def _api_request(self, method, url, headers, params=None, data=None):
TOKEN_EXPIRY_KEYWORDS = frozenset([
'expired', '인증', 'authorization', 'egt0001', 'egt0002', 'oauth',
'접근토큰이 만료', '토큰이 유효하지'
])
for attempt in range(2):
try:
if method.upper() == "GET":
res = requests.get(url, headers=headers, params=params, timeout=10)
else:
res = requests.post(url, headers=headers, data=json.dumps(data) if data else None, timeout=10)
resp_json = res.json()
if resp_json.get('rt_cd') != '0':
msg1_lower = resp_json.get('msg1', '').lower()
msg_cd = resp_json.get('msg_cd', '').lower()
if any(x in msg1_lower or x in msg_cd for x in TOKEN_EXPIRY_KEYWORDS):
if attempt == 0:
old_token = self.token
print(f"\n🚨 [안전장치 가동] API 토큰 만료 감지! : {msg1_lower}")
self._get_access_token(force=True)
if self.token == old_token or self.token is None:
print("🚨 [Broker] 토큰 갱신 실패. 재시도 중단.")
return res, resp_json
headers["authorization"] = f"Bearer {self.token}"
time.sleep(1.0)
continue
return res, resp_json
except Exception as e:
print(f"⚠️ API 통신 중 예외 발생: {e}")
if attempt == 1: return None, {}
time.sleep(1.0)
return None, {}
def _call_api(self, tr_id, url_path, method="GET", params=None, body=None):
headers = self._get_header(tr_id)
url = f"{self.base_url}{url_path}"
res, resp_json = self._api_request(method, url, headers, params=params, data=body)
if not resp_json: return {'rt_cd': '999', 'msg1': '통신 오류 또는 최대 재시도 횟수 초과'}
return resp_json
def _ceil_2(self, value):
if value is None: return 0.0
return max(0.01, math.ceil(value * 100) / 100.0)
def _safe_float(self, value):
try: return float(str(value).replace(',', ''))
except Exception: return 0.0
def _get_exchange_code(self, ticker, target_api="PRICE"):
if ticker in self._excg_cd_cache:
codes = self._excg_cd_cache[ticker]
return codes['PRICE'] if target_api == "PRICE" else codes['ORDER']
price_cd = "NAS"
order_cd = "NASD"
dynamic_success = False
try:
for prdt_type in ["512", "513", "529"]:
params = {
"PRDT_TYPE_CD": prdt_type,
"PDNO": ticker
}
res = self._call_api("CTPF1702R", "/uapi/overseas-price/v1/quotations/search-info", "GET", params=params)
if res.get('rt_cd') == '0' and res.get('output'):
excg_name = str(res['output'].get('ovrs_excg_cd', '')).upper()
if "NASD" in excg_name or "NASDAQ" in excg_name:
price_cd, order_cd = "NAS", "NASD"
dynamic_success = True
break
elif "NYSE" in excg_name or "NEW YORK" in excg_name:
price_cd, order_cd = "NYS", "NYSE"
dynamic_success = True
break
elif "AMEX" in excg_name:
price_cd, order_cd = "AMS", "AMEX"
dynamic_success = True
break
except Exception as e:
print(f"⚠️ [Broker] 거래소 동적 획득 실패: {ticker} - {e}")
if not dynamic_success:
if ticker in ["SOXL", "SOXS"]: price_cd, order_cd = "AMS", "AMEX"
elif ticker == "TQQQ": price_cd, order_cd = "NAS", "NASD"
self._excg_cd_cache[ticker] = {'PRICE': price_cd, 'ORDER': order_cd}
return price_cd if target_api == "PRICE" else order_cd
def get_account_balance(self):
cash = 0.0
holdings = {}
api_success = False
params = {"CANO": self.cano, "ACNT_PRDT_CD": self.acnt_prdt_cd, "WCRC_FRCR_DVSN_CD": "02", "NATN_CD": "840", "TR_MKET_CD": "00", "INQR_DVSN_CD": "00"}
res = self._call_api("CTRP6504R", "/uapi/overseas-stock/v1/trading/inquire-present-balance", "GET", params=params)
if res.get('rt_cd') == '0':
api_success = True
o2 = res.get('output2', {})
if isinstance(o2, list):
o2 = o2[0] if len(o2) > 0 else {}
dncl_amt = self._safe_float(o2.get('frcr_dncl_amt_2', 0))
sll_amt = self._safe_float(o2.get('frcr_sll_amt_smtl', 0))
buy_amt = self._safe_float(o2.get('frcr_buy_amt_smtl', 0))
raw_bp = dncl_amt + sll_amt - buy_amt
cash = max(0.0, math.floor((raw_bp * 0.9945) * 100) / 100.0)
target_excgs = ["NASD", "AMEX", "NYSE"]
for excg in target_excgs:
fk200, nk200 = "", ""
for attempt in range(20):
params_hold = {"CANO": self.cano, "ACNT_PRDT_CD": self.acnt_prdt_cd, "OVRS_EXCG_CD": excg, "TR_CRCY_CD": "USD", "CTX_AREA_FK200": fk200, "CTX_AREA_NK200": nk200}
headers = self._get_header("TTTS3012R")
url = f"{self.base_url}/uapi/overseas-stock/v1/trading/inquire-balance"
res_hold, resp_json = self._api_request("GET", url, headers, params=params_hold)
if res_hold and resp_json.get('rt_cd') == '0':
api_success = True
if cash <= 0:
o2 = resp_json.get('output2', {})
if isinstance(o2, list):
# MODIFIED: [V49.10 런타임 붕괴 방어] 들여쓰기 오염 교정 (29 -> 28칸)
o2 = o2[0] if len(o2) > 0 else {}
new_cash = self._safe_float(o2.get('ovrs_ord_psbl_amt', 0))
if new_cash > cash: cash = new_cash
for item in (resp_json.get('output1') or []):
ticker = item.get('ovrs_pdno')
if not ticker:
continue
qty = int(self._safe_float(item.get('ovrs_cblc_qty', 0)))
ord_psbl_qty = int(self._safe_float(item.get('ord_psbl_qty', 0)))
avg = self._safe_float(item.get('pchs_avg_pric', 0))
if qty > 0 and ord_psbl_qty == 0:
ord_psbl_qty = qty
if qty > 0:
if ticker not in holdings:
holdings[ticker] = {'qty': qty, 'ord_psbl_qty': ord_psbl_qty, 'avg': avg}
else:
prev = holdings[ticker]
if prev['qty'] == qty and abs(prev['avg'] - avg) < 0.001:
continue
total_qty = prev['qty'] + qty
new_avg = ((prev['avg'] * prev['qty']) + (avg * qty)) / total_qty if total_qty > 0 else avg
holdings[ticker]['qty'] = total_qty
holdings[ticker]['ord_psbl_qty'] += ord_psbl_qty
holdings[ticker]['avg'] = new_avg
tr_cont = res_hold.headers.get('tr_cont', '') if hasattr(res_hold, 'headers') else ''
fk200 = (resp_json.get('ctx_area_fk200', '') or '').strip()
nk200 = (resp_json.get('ctx_area_nk200', '') or '').strip()
if tr_cont in ['M', 'F'] and nk200:
time.sleep(0.2)
continue
else:
break
else:
break
if api_success: return cash, holdings
else: return cash, None
def get_daily_vwap_info(self, ticker):
"""
최근 5일간의 1분봉 데이터를 로드하여 정규장(09:30~15:59) 거래 내역만 추출,
일자별 순수 VWAP을 계산하여 반환합니다.
"""
try:
stock = yf.Ticker(ticker)
df = stock.history(period="5d", interval="1m", prepost=False, timeout=10)
if df.empty: return 0.0, 0.0
df = _flatten_columns(df)
est = ZoneInfo('America/New_York')
if df.index.tz is None:
df.index = df.index.tz_localize('UTC').tz_convert(est)
else:
df.index = df.index.tz_convert(est)
regular_market = df.between_time('09:30', '15:59').copy()
if regular_market.empty: return 0.0, 0.0
regular_market['Typical_Price'] = (regular_market['High'] + regular_market['Low'] + regular_market['Close']) / 3.0
regular_market['Vol_x_Price'] = regular_market['Typical_Price'] * regular_market['Volume']
regular_market['Date'] = regular_market.index.date
daily_stats = regular_market.groupby('Date').agg(
Total_Vol_Price=('Vol_x_Price', 'sum'),
Total_Vol=('Volume', 'sum')
)
daily_stats['VWAP'] = np.where(daily_stats['Total_Vol'] > 0,
daily_stats['Total_Vol_Price'] / daily_stats['Total_Vol'],
np.nan)
daily_stats = daily_stats.dropna(subset=['VWAP'])
if len(daily_stats) >= 2:
prev_vwap = float(daily_stats['VWAP'].iloc[-2])
curr_vwap = float(daily_stats['VWAP'].iloc[-1])
elif len(daily_stats) == 1:
prev_vwap = 0.0
curr_vwap = float(daily_stats['VWAP'].iloc[-1])
else:
prev_vwap = 0.0
curr_vwap = 0.0
return round(prev_vwap, 4), round(curr_vwap, 4)
except Exception as e:
logging.error(f"⚠️ [Broker] 일별 VWAP 파싱 실패 ({ticker}): {e}")
return 0.0, 0.0
def get_current_5min_candle(self, ticker):
try:
stock = yf.Ticker(ticker)
df = stock.history(period="5d", interval="1m", prepost=True, timeout=5)
if df.empty: return None
df = _flatten_columns(df)
est = ZoneInfo('America/New_York')
if df.index.tz is None:
df.index = df.index.tz_localize('UTC').tz_convert(est)
else:
df.index = df.index.tz_convert(est)
regular_market = df.between_time('09:30', '15:59')
if regular_market.empty: return None
today_date = pd.Timestamp.now(tz=est).normalize()
regular_market = regular_market[regular_market.index >= today_date]
if regular_market.empty: return None
regular_market = regular_market.dropna(subset=['Volume', 'High', 'Low', 'Close'])
typical_price = (regular_market['High'] + regular_market['Low'] + regular_market['Close']) / 3.0
vol_price = typical_price * regular_market['Volume']
cum_vol_price = vol_price.cumsum()
cum_vol = regular_market['Volume'].cumsum()
vwap_series = pd.Series(np.where(cum_vol > 0, cum_vol_price / cum_vol, np.nan), index=cum_vol.index).ffill()
current_vwap = float(vwap_series.iloc[-1]) if not vwap_series.empty else 0.0
if pd.isna(current_vwap):
current_vwap = 0.0
resampled = regular_market.resample('5min', label='left', closed='left').agg({
'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last', 'Volume': 'sum'
}).dropna()
if resampled.empty: return None
resampled['Vol_MA10'] = resampled['Volume'].rolling(10, min_periods=1).mean()
resampled['Vol_MA20'] = resampled['Volume'].rolling(20, min_periods=1).mean()
last_candle = resampled.iloc[-1]
vol_ma10 = float(last_candle['Vol_MA10']) if not pd.isna(last_candle['Vol_MA10']) else float(last_candle['Volume'])
vol_ma20 = float(last_candle['Vol_MA20']) if not pd.isna(last_candle['Vol_MA20']) else float(last_candle['Volume'])
latest_1m = regular_market.iloc[-1]
return {
'open': float(last_candle['Open']),
'high': float(last_candle['High']),
'low': float(last_candle['Low']),
'close': float(latest_1m['Close']),
'volume': float(last_candle['Volume']),
'vol_ma10': vol_ma10,
'vol_ma20': vol_ma20,
'vwap': current_vwap
}
except Exception as e:
print(f"⚠️ [Broker] 실시간 5분봉 조회 실패 ({ticker}): {e}")
return None
def get_current_price(self, ticker, is_market_closed=False):
try:
stock = yf.Ticker(ticker)
hist = stock.history(period="1d", interval="1m", prepost=True, timeout=5)
if not hist.empty: return float(hist['Close'].iloc[-1])
else: raise ValueError("YF 실시간 데이터 응답 지연 (timeout)")
except Exception as e:
print(f"⚠️ [야후] 현재가 에러, 한투 API 우회 가동: {e}")
try:
excg_cd = self._get_exchange_code(ticker, target_api="PRICE")
params = {"AUTH": "", "EXCD": excg_cd, "SYMB": ticker}
res = self._call_api("HHDFS76200200", "/uapi/overseas-price/v1/quotations/price", "GET", params=params)
if res.get('rt_cd') == '0':
return float(res.get('output', {}).get('last', 0.0))
except Exception as e:
pass
return 0.0
def get_ask_price(self, ticker):
try:
excg_cd = self._get_exchange_code(ticker, target_api="PRICE")
params = {"AUTH": "", "EXCD": excg_cd, "SYMB": ticker}
res = self._call_api("HHDFS76200100", "/uapi/overseas-price/v1/quotations/inquire-asking-price", "GET", params=params)
if res.get('rt_cd') == '0':
output2 = res.get('output2', [])
if isinstance(output2, list) and len(output2) > 0: return float(output2[0].get('pask1', 0.0))
elif isinstance(output2, dict): return float(output2.get('pask1', 0.0))
except Exception as e:
pass
return 0.0
def get_bid_price(self, ticker):
try:
excg_cd = self._get_exchange_code(ticker, target_api="PRICE")
params = {"AUTH": "", "EXCD": excg_cd, "SYMB": ticker}
res = self._call_api("HHDFS76200100", "/uapi/overseas-price/v1/quotations/inquire-asking-price", "GET", params=params)
if res.get('rt_cd') == '0':
output2 = res.get('output2', [])
if isinstance(output2, list) and len(output2) > 0: return float(output2[0].get('pbid1', 0.0))
elif isinstance(output2, dict): return float(output2.get('pbid1', 0.0))
except Exception as e:
pass
return 0.0
def get_previous_close(self, ticker):
try:
stock = yf.Ticker(ticker)
hist = stock.history(period="5d", timeout=5)
if not hist.empty:
est = ZoneInfo('America/New_York')
now_est = datetime.datetime.now(est)
cutoff_date = now_est.date()
if now_est.time() <= datetime.time(16, 0, 30): cutoff_date -= datetime.timedelta(days=1)
if hist.index.tzinfo is None: hist.index = hist.index.tz_localize('UTC').tz_convert(est)
else: hist.index = hist.index.tz_convert(est)
past_hist = hist[hist.index.date <= cutoff_date]
if not past_hist.empty: return float(past_hist['Close'].dropna().iloc[-1])
except Exception as e:
print(f"⚠️ [야후] 전일 종가 파싱 에러, 한투 API 우회 가동: {e}")
try:
excg_cd = self._get_exchange_code(ticker, target_api="PRICE")
params = {"AUTH": "", "EXCD": excg_cd, "SYMB": ticker}
res = self._call_api("HHDFS76200200", "/uapi/overseas-price/v1/quotations/price", "GET", params=params)
if res.get('rt_cd') == '0': return float(res.get('output', {}).get('base', 0.0))
except Exception as e:
pass
return 0.0
def get_5day_ma(self, ticker):
try:
stock = yf.Ticker(ticker)
hist = stock.history(period="10d", timeout=5)
if len(hist) >= 5: return float(hist['Close'][-5:].mean())
except Exception as e:
pass
try:
excg_cd = self._get_exchange_code(ticker, target_api="PRICE")
params = {"AUTH": "", "EXCD": excg_cd, "SYMB": ticker, "GUBN": "0", "BYMD": "", "MODP": "1"}
res = self._call_api("HHDFS76240000", "/uapi/overseas-price/v1/quotations/dailyprice", "GET", params=params)
if res.get('rt_cd') == '0':
output2 = res.get('output2', [])
if isinstance(output2, list) and len(output2) >= 5:
closes = [float(x['clos']) for x in output2[:5]]
return sum(closes) / len(closes)
except Exception as e:
pass
return 0.0
def get_1min_candles_df(self, ticker):
try:
stock = yf.Ticker(ticker)
df = stock.history(period="1d", interval="1m", prepost=True, timeout=5)
if df.empty: return None
df = _flatten_columns(df)
est = ZoneInfo('America/New_York')
if df.index.tz is None: df.index = df.index.tz_localize('UTC').tz_convert(est)
else: df.index = df.index.tz_convert(est)
# MODIFIED: [V47.00 하이킨아시 파서 open 컬럼 강제 수혈 락온]
df = df.rename(columns={'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Volume': 'volume'})
df['time_est'] = df.index.strftime('%H%M00')
return df[['open', 'high', 'low', 'close', 'volume', 'time_est']]
except Exception as e:
return None
def get_unfilled_orders_detail(self, ticker):
excg_cd = self._get_exchange_code(ticker, target_api="ORDER")
valid_orders = []
fk200, nk200 = "", ""
for attempt in range(10):
params = {
"CANO": self.cano, "ACNT_PRDT_CD": self.acnt_prdt_cd, "OVRS_EXCG_CD": excg_cd,
"SORT_SQN": "DS", "CTX_AREA_FK200": fk200, "CTX_AREA_NK200": nk200
}
headers = self._get_header("TTTS3018R")
url = f"{self.base_url}/uapi/overseas-stock/v1/trading/inquire-nccs"
res, resp_json = self._api_request("GET", url, headers, params=params)
if res and resp_json.get('rt_cd') == '0':
output = resp_json.get('output', [])
if isinstance(output, dict): output = [output]
valid_orders.extend([item for item in output if item.get('pdno') == ticker])
tr_cont = res.headers.get('tr_cont', '') if hasattr(res, 'headers') else ''
fk200 = (resp_json.get('ctx_area_fk200', '') or '').strip()
nk200 = (resp_json.get('ctx_area_nk200', '') or '').strip()
if tr_cont in ['M', 'F'] and nk200:
time.sleep(0.3)
continue
else: break
else:
return False
return valid_orders
def get_unfilled_orders(self, ticker):
details = self.get_unfilled_orders_detail(ticker)
if details is False:
return []
return [item.get('odno') for item in details]
def cancel_all_orders_safe(self, ticker, side=None):
for i in range(3):
orders = self.get_unfilled_orders_detail(ticker)
if orders is False:
return False
if not orders: return True
target_orders = orders
if side == "BUY": target_orders = [o for o in orders if o.get('sll_buy_dvsn_cd') == '02']
elif side == "SELL": target_orders = [o for o in orders if o.get('sll_buy_dvsn_cd') == '01']
if not target_orders: return True
for o in target_orders: self.cancel_order(ticker, o.get('odno'))
time.sleep(5)
final_orders = self.get_unfilled_orders_detail(ticker)
if final_orders is False:
return False
failed_orders = []
if side == "BUY": failed_orders = [o for o in final_orders if o.get('sll_buy_dvsn_cd') == '02']
elif side == "SELL": failed_orders = [o for o in final_orders if o.get('sll_buy_dvsn_cd') == '01']
else: failed_orders = final_orders
if failed_orders:
return False
return True
def cancel_targeted_orders(self, ticker, side, target_ord_dvsn):
sll_buy_cd = '02' if side == "BUY" else '01'
orders = self.get_unfilled_orders_detail(ticker)
if orders is False or not orders: return 0
target_orders = []
for o in orders:
dvsn = o.get('ord_dvsn_cd') or o.get('ord_dvsn') or ''
if o.get('sll_buy_dvsn_cd') == sll_buy_cd and dvsn == target_ord_dvsn:
target_orders.append(o)
for o in target_orders:
self.cancel_order(ticker, o.get('odno'))
time.sleep(0.3)
return len(target_orders)
def cancel_orders_by_price(self, ticker, side, target_prices):
sll_buy_cd = '02' if side == "BUY" else '01'
orders = self.get_unfilled_orders_detail(ticker)
if orders is False or not orders: return 0
target_orders = []
for o in orders:
if o.get('sll_buy_dvsn_cd') == sll_buy_cd:
raw_p1, raw_p2, raw_p3 = o.get('ft_ord_unpr3', 0), o.get('ord_unpr', 0), o.get('ovrs_ord_unpr', 0)
o_price = 0.0
for rp in [raw_p1, raw_p2, raw_p3]:
try:
val = float(rp)
if val > 0:
o_price = val
break
except (TypeError, ValueError):
pass
for tp in target_prices:
if o_price > 0 and abs(o_price - tp) < 0.005:
target_orders.append(o)
break
for o in target_orders:
self.cancel_order(ticker, o.get('odno'))
time.sleep(0.3)
return len(target_orders)
def send_order(self, ticker, side, qty, price, order_type="LIMIT"):
try:
order_qty = int(float(qty))
except (TypeError, ValueError):
return {'rt_cd': '999', 'msg1': f'유효하지 않은 주문 수량 타입: {qty!r}'}
if order_qty <= 0:
return {'rt_cd': '999', 'msg1': f'유효하지 않은 주문 수량: {qty}'}
for attempt in range(2):
tr_id = "TTTT1002U" if side == "BUY" else "TTTT1006U"
excg_cd = self._get_exchange_code(ticker, target_api="ORDER")
if order_type == "LOC": ord_dvsn = "34"
elif order_type == "MOC": ord_dvsn = "33"
elif order_type == "LOO": ord_dvsn = "02"
elif order_type == "MOO": ord_dvsn = "31"
elif order_type == "AFTER_LIMIT":
ord_dvsn = "00"
else: ord_dvsn = "00"
final_price = self._ceil_2(price)
if order_type in ["MOC", "MOO"]: final_price = 0
elif order_type not in ["MOC", "MOO"] and final_price <= 0.0:
return {'rt_cd': '999', 'msg1': f'유효하지 않은 주문 가격: {price}'}
body = {
"CANO": self.cano, "ACNT_PRDT_CD": self.acnt_prdt_cd, "OVRS_EXCG_CD": excg_cd,
"PDNO": ticker, "ORD_QTY": str(order_qty), "OVRS_ORD_UNPR": str(final_price),
"ORD_SVR_DVSN_CD": "0", "ORD_DVSN": ord_dvsn
}
res = self._call_api(tr_id, "/uapi/overseas-stock/v1/trading/order", "POST", body=body)
rt_cd = res.get('rt_cd', '999')
msg1 = res.get('msg1', '오류')
output = res.get('output', {})
odno = output.get('ODNO', '') if isinstance(output, dict) else ''
if rt_cd != '0' and attempt == 0 and ("거래소" in msg1 or "시장" in msg1 or "exchange" in msg1.lower() or "코드" in msg1):
if ticker in self._excg_cd_cache:
del self._excg_cd_cache[ticker]
time.sleep(0.5)
continue
return {'rt_cd': rt_cd, 'msg1': msg1, 'odno': odno}
return {'rt_cd': '999', 'msg1': '거래소 캐시 재시도 최대 횟수 초과'}
def cancel_order(self, ticker, order_id):
excg_cd = self._get_exchange_code(ticker, target_api="ORDER")
body = {
"CANO": self.cano, "ACNT_PRDT_CD": self.acnt_prdt_cd, "OVRS_EXCG_CD": excg_cd,
"PDNO": ticker, "ORGN_ODNO": order_id, "RVSE_CNCL_DVSN_CD": "02",
"ORD_QTY": "0", "OVRS_ORD_UNPR": "0", "ORD_SVR_DVSN_CD": "0"
}
self._call_api("TTTT1004U", "/uapi/overseas-stock/v1/trading/order-rvsecncl", "POST", body=body)
def get_execution_history(self, ticker, start_date, end_date):
excg_cd = self._get_exchange_code(ticker, target_api="ORDER")
valid_execs = []
odno_map = {}
fk200, nk200 = "", ""
for attempt in range(10):
params = {
"CANO": self.cano, "ACNT_PRDT_CD": self.acnt_prdt_cd, "PDNO": ticker,
"ORD_STRT_DT": start_date, "ORD_END_DT": end_date, "SLL_BUY_DVSN": "00",
"CCLD_NCCS_DVSN": "00", "OVRS_EXCG_CD": excg_cd, "SORT_SQN": "DS",
"ORD_DT": "", "ORD_GNO_BRNO": "", "ODNO": "", "CTX_AREA_FK200": fk200,
"CTX_AREA_NK200": nk200
}
headers = self._get_header("TTTS3035R")
url = f"{self.base_url}/uapi/overseas-stock/v1/trading/inquire-ccnl"
res, resp_json = self._api_request("GET", url, headers, params=params)
if res and resp_json.get('rt_cd') == '0':
output = resp_json.get('output', [])
if isinstance(output, dict): output = [output]
for item in output:
try:
raw_qty = item.get('ft_ccld_qty') or '0'
raw_unpr = item.get('ft_ccld_unpr3') or '0'
item_qty = float(raw_qty)
item_price = float(raw_unpr)
if item_qty > 0:
odno = item.get('odno') or ''
if not odno:
odno_map[f"__nk_{id(item)}"] = {
"item": dict(item),
"total_qty": item_qty,
"total_amt": item_qty * item_price
}
elif odno not in odno_map:
odno_map[odno] = {
# MODIFIED: [V49.10 런타임 붕괴 방어] 딕셔너리 내부 및 else 블록 들여쓰기 단차 교정
"item": dict(item),
"total_qty": item_qty,
"total_amt": item_qty * item_price
}
else:
odno_map[odno]["total_qty"] += item_qty
odno_map[odno]["total_amt"] += (item_qty * item_price)
except (TypeError, ValueError) as e:
continue
tr_cont = res.headers.get('tr_cont', '') if hasattr(res, 'headers') else ''
fk200 = (resp_json.get('ctx_area_fk200', '') or '').strip()
nk200 = (resp_json.get('ctx_area_nk200', '') or '').strip()
if tr_cont in ['M', 'F'] and nk200:
time.sleep(0.3)
continue
else: break
else:
break
for key, data in odno_map.items():
merged_item = data["item"]
merged_item["ft_ccld_qty"] = str(data["total_qty"])
avg_price = data["total_amt"] / data["total_qty"] if data["total_qty"] > 0 else 0.0
merged_item["ft_ccld_unpr3"] = str(avg_price)
valid_execs.append(merged_item)
return valid_execs
def get_genesis_ledger(self, ticker, limit_date_str=None):
_, holdings = self.get_account_balance()
if holdings is None: return None, 0, 0.0
ticker_info = holdings.get(ticker, {'qty': 0, 'avg': 0.0})
curr_qty = int(ticker_info.get('qty', 0))
final_qty = curr_qty
final_avg = float(ticker_info.get('avg', 0.0))
if curr_qty == 0: return [], 0, 0.0
ledger_records = []
est = ZoneInfo('America/New_York')
target_date = datetime.datetime.now(est)
genesis_reached = False
loop_counter = 0
while curr_qty > 0 and not genesis_reached and loop_counter < 365:
if target_date.weekday() < 5:
loop_counter += 1
date_str = target_date.strftime('%Y%m%d')
if limit_date_str and date_str < limit_date_str: break
execs = self.get_execution_history(ticker, date_str, date_str)
if execs:
execs.sort(key=lambda x: x.get('ord_tmd', '000000'), reverse=True)
for ex in execs:
try:
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')
except (TypeError, ValueError) as e:
# MODIFIED: [V49.10 런타임 붕괴 방어] 들여쓰기 오염 교정
continue
record_qty = exec_qty
if side_cd == "02":
if curr_qty <= exec_qty:
record_qty = curr_qty
curr_qty = 0
genesis_reached = True
else: curr_qty -= exec_qty
else: curr_qty += exec_qty
ledger_records.append({
'date': f"{date_str[:4]}-{date_str[4:6]}-{date_str[6:]}",
'side': "BUY" if side_cd == "02" else "SELL",
'qty': record_qty, 'price': exec_price
})
if genesis_reached: break
target_date -= datetime.timedelta(days=1)
time.sleep(0.1)
if curr_qty > 0 and loop_counter >= 365:
ledger_records.append({
'date': 'INCOMPLETE', 'side': 'UNKNOWN', 'qty': curr_qty, 'price': final_avg, 'is_incomplete': True
})
ledger_records.reverse()
return ledger_records, final_qty, final_avg
def get_recent_stock_split(self, ticker, last_date_str):
try:
stock = yf.Ticker(ticker)
splits = stock.splits
if splits is not None and not splits.empty:
if last_date_str == "":
est = ZoneInfo('America/New_York')
seven_days_ago = datetime.datetime.now(est) - datetime.timedelta(days=7)
safe_last_date = seven_days_ago.strftime('%Y-%m-%d')
else: safe_last_date = last_date_str
for split_date_dt, ratio in splits.items():
if isinstance(split_date_dt, str):
split_date = split_date_dt[:10]
else:
split_date = pd.Timestamp(split_date_dt).strftime('%Y-%m-%d')
if split_date > safe_last_date: return float(ratio), split_date
except Exception as e:
logging.warning(f"⚠️ [야후 파이낸스] 액면분할 조회 에러: {e}")
return 0.0, ""
def get_dynamic_sniper_target(self, index_ticker):
if index_ticker in ["SOXX", "SOXL", "SOXS"]:
target_index = "SOXX"
else:
target_index = index_ticker
try:
# MODIFIED: [V49.10 런타임 붕괴 방어] 들여쓰기 오염 교정 (13 -> 12칸)
class TargetFloat(float): pass
if target_index == "SOXX":
hv_val, weight, target_drop, base_amp = ve.get_soxl_target_drop_full()
ret = TargetFloat(target_drop)
ret.metric_val, ret.weight, ret.base_amp, ret.metric_name = hv_val, weight, base_amp, "SOXX HV"
ret.metric_base = round(hv_val / weight, 2) if weight > 0 else 25.0