-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathkis_api_client.py
More file actions
249 lines (215 loc) Β· 12.5 KB
/
Copy pathkis_api_client.py
File metadata and controls
249 lines (215 loc) Β· 12.5 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
# ==========================================================
# FILE: kis_api_client.py
# ==========================================================
# π¨ MODIFIED: [νμ¬λ ν¨ν΄ 1λ¨κ³] KIS API μμ ν΅μ λ° ν ν° μ μ΄ λλ©μΈ λΆλ¦¬
# π¨ MODIFIED: [Case 08] TOCTOU λ μ΄μ€ 컨λμ
μ μ λ°νλ os.path.exists μꡬ μκ° λ° EAFP ν¨ν΄ λ½μ¨
# π¨ MODIFIED: [Case 16] μμμ μ°κΈ°(Atomic Write) κ°μ λ° tempfile μ€μ½ν μ μ§ λ°°μΉ
# π¨ MODIFIED: [Case 32 & 33] KIS API μ΄λΉ 20건 ν΅μ μ ν(TPS) λ°©μ΄μ© 0.06μ΄ μΊ‘ν λ° 3λ¨ μ§μ λ°±μ€ν λ½μ¨
# π¨ MODIFIED: [Insight 14 & 25] NaN, Infinity λ° String-Comma λ§Ήλ
μ± λ°μ΄ν° μ λ° νν°λ§ μ λ μ΄λ λ΄μ¬ν
# π¨ MODIFIED: [μ 3νλ² μ€μ] ν ν° λ§λ£ μ°μ° μ μμ‘΄νλ KST νΌμ© λκ΄ μ λ©΄ μκ° λ° EST νμλΌμΈ 100% ν΅ν©
# π¨ MODIFIED: [AttributeError κΆκ·Ή μμ ] μλ² μλ΅(msg1, msg_cd) NoneType μ μ
μ .lower() λΆκ΄΄ μμ² μ°¨λ¨
# π¨ MODIFIED: [λ‘κΉ
μ¦λ° λ°©μ΄] ν€λ리μ€(Headless) νκ²½μμ μ¦λ°νλ print() λ°λμ½λ μ λ©΄ μκ° λ° logging μ²΄κ³ 100% λ½μ¨
# ==========================================================
import requests
import json
import time
import datetime
import os
import math
import tempfile
import logging
from zoneinfo import ZoneInfo
class KisApiClient:
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):
# π¨ MODIFIED: [μ 3νλ² μ λ λ½μ¨] KST νΌμ© νμ΄νλΌμΈ μ λ©΄ μκ° λ° EST 100% λ§€ν
est = ZoneInfo('America/New_York')
# π¨ MODIFIED: [Case 08] os.path.exists μκ° λ° EAFP ν¨ν΄μΌλ‘ TOCTOU λ μ΄μ€ 컨λμ
μ°¨λ¨
if not force:
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_est_naive = datetime.datetime.now(est).replace(tzinfo=None)
if expire_time > now_est_naive + datetime.timedelta(hours=1):
self.token = saved['token']
return
except OSError: pass
except json.JSONDecodeError: pass
except Exception: pass
if force:
try: os.remove(self.token_file)
except OSError: pass
url = f"{self.base_url}/oauth2/tokenP"
body = {"grant_type": "client_credentials", "appkey": self.app_key, "appsecret": self.app_secret}
# π¨ MODIFIED: [Case 33] 3λ¨ μ§μ λ°±μ€ν ν ν° λ°κΈ μ΄μ
for attempt in range(3):
try:
# π¨ NEW: [Case 32] KIS TPS μΊ‘ν
time.sleep(0.06)
res = requests.post(url, headers={"content-type": "application/json"}, data=json.dumps(body), timeout=10)
data = res.json()
# π¨ MODIFIED: [AttributeError λΆκ΄΄ λ°©μ΄] JSON μλ΅μ΄ λμ
λλ¦¬κ° μλ κ²½μ° λΉ λμ
λλ¦¬λ‘ ν΄λ°±
if not isinstance(data, dict):
data = {}
if 'access_token' in data:
self.token = data['access_token']
# π¨ MODIFIED: [Float λΆκ΄΄ λ°©μ΄] expires_in λ°μ΄ν° μ€μΌ μ ValueError μ°¨λ¨μ μν _safe_float λν
safe_expires_in = int(self._safe_float(data.get('expires_in', 86400)))
expire_str = (datetime.datetime.now(est).replace(tzinfo=None) + datetime.timedelta(seconds=safe_expires_in)).strftime('%Y-%m-%d %H:%M:%S')
dir_name = os.path.dirname(self.token_file)
if dir_name:
try: os.makedirs(dir_name, exist_ok=True)
except OSError: pass
# π¨ MODIFIED: [Case 16 & μ 4νλ² μ€μ] μμμ μ°κΈ°(Atomic Write) κ°μ λ° POSIX νμ€ os.replace μ£Όμ
fd = None
temp_path = None
try:
fd, temp_path = tempfile.mkstemp(dir=dir_name or '.', text=True)
with os.fdopen(fd, 'w', encoding='utf-8') as f:
fd = None
json.dump({'token': self.token, 'expire': expire_str}, f)
f.flush()
os.fsync(f.fileno())
os.replace(temp_path, self.token_file)
temp_path = None
except Exception as inner_e:
if fd is not None:
try: os.close(fd)
except OSError: pass
if temp_path:
try: os.remove(temp_path)
except OSError: pass
raise inner_e
break # μ±κ³΅ μ 루ν νμΆ
else:
if attempt == 2:
# π¨ MODIFIED: [λ‘κΉ
μ¦λ° λ°©μ΄] print() μκ° λ° logging.error λ½μ¨
logging.error(f"β [Broker] ν ν° λ°κΈ μ€ν¨: {data.get('error_description') or 'μ μ μλ μ€λ₯'}")
time.sleep(1.0 * (2 ** attempt))
except Exception as e:
if attempt == 2:
# π¨ MODIFIED: [λ‘κΉ
μ¦λ° λ°©μ΄] print() μκ° λ° logging.error λ½μ¨
logging.error(f"β [Broker] ν ν° ν΅μ μλ¬: {e}")
time.sleep(1.0 * (2 ** attempt))
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"
}
# π¨ MODIFIED: [Case 32 & 33] 3λ¨ μ§μ λ°±μ€ν λ° TPS μ΄κ³Ό λ°©μ΄ λ‘μ§ μ£Όμ
def _api_request(self, method, url, headers, params=None, data=None):
TOKEN_EXPIRY_KEYWORDS = frozenset([
'expired', 'μΈμ¦', 'authorization', 'egt0001', 'egt0002', 'oauth',
'μ κ·Όν ν°μ΄ λ§λ£', 'ν ν°μ΄ μ ν¨νμ§'
])
for attempt in range(3):
try:
# π¨ NEW: [Case 32] κ³ μ±λ₯ μΈμ€ν΄μ€ TPS μ΄κ³Ό λ°©μ΄ (KIS μλ² κ±°μ μ°¨λ¨)
time.sleep(0.06)
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)
if res.status_code == 429 or res.status_code >= 500:
raise Exception(f"HTTP Error {res.status_code}")
resp_json = res.json()
# π¨ MODIFIED: [AttributeError λΆκ΄΄ λ°©μ΄] JSON μλ΅μ΄ λμ
λλ¦¬κ° μλ κ²½μ° λΉ λμ
λλ¦¬λ‘ ν΄λ°±
if not isinstance(resp_json, dict):
resp_json = {}
if resp_json.get('rt_cd') != '0':
# π¨ MODIFIED: [AttributeError κΆκ·Ή μμ ] msg1, msg_cdκ° NoneμΌ κ²½μ° λ°μνλ .lower() μ¦μ¬ λ²κ·Έ λ°©μ΄ μ΄λ
msg1_lower = str(resp_json.get('msg1') or '').lower()
msg_cd = str(resp_json.get('msg_cd') or '').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
# π¨ MODIFIED: [λ‘κΉ
μ¦λ° λ°©μ΄] print() μκ° λ° logging.warning λ½μ¨
logging.warning(f"π¨ [μμ μ₯μΉ κ°λ] API ν ν° λ§λ£ κ°μ§! : {msg1_lower}")
self._get_access_token(force=True)
if self.token == old_token or self.token is None:
logging.error("π¨ [Broker] ν ν° κ°±μ μ€ν¨. μ¬μλ μ€λ¨.")
return res, resp_json
headers["authorization"] = f"Bearer {self.token}"
time.sleep(1.0)
continue
return res, resp_json
except Exception as e:
logging.debug(f"β οΈ [Broker] API ν΅μ μ€ μμΈ λ°μ (μλ {attempt+1}/3): {e}")
if attempt == 2: return None, {}
# π¨ NEW: [Case 33] 3λ¨ μ§μ λ°±μ€ν μ μ©
time.sleep(1.0 * (2 ** attempt))
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(round(self._safe_float(value) * 100, 4)) / 100.0)
# π¨ MODIFIED: [Insight 14 & 25] NaN, Infinity λ° String-Comma λ§Ήλ
μ± λ°μ΄ν° μ λ° νν°λ§ μ λ μ΄λ
def _safe_float(self, value):
try:
f_val = float(str(value 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
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
for attempt in range(3):
try:
for prdt_type in ["512", "513", "529"]:
# π¨ NEW: [Case 32] λμ μ€μΊ μμλ TPS μΊ‘ν κ°μ
time.sleep(0.06)
params = {"PRDT_TYPE_CD": prdt_type, "PDNO": ticker}
res = self._call_api("CTPF1702R", "/uapi/overseas-price/v1/quotations/search-info", "GET", params=params)
# π¨ MODIFIED: [AttributeError λΆκ΄΄ λ°©μ΄] output κ²°μΈ‘ λλ νμ
μ€μΌ μ μμ μ°ν
if res.get('rt_cd') == '0':
out = res.get('output')
if isinstance(out, dict):
excg_name = str(out.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
if dynamic_success: break
except Exception as e:
if attempt == 2:
# π¨ MODIFIED: [λ‘κΉ
μ¦λ° λ°©μ΄] print() μκ° λ° logging.warning λ½μ¨
logging.warning(f"β οΈ [Broker] κ±°λμ λμ νλ μ€ν¨: {ticker} - {e}")
time.sleep(1.0 * (2 ** attempt))
if not dynamic_success:
if ticker == "SOXL": 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