refactor: enhance Optuna backtesting framework, optimize orderbook filtering, and update database management utilities.
This commit is contained in:
91
scratch/test_kis_hoga_ws.py
Normal file
91
scratch/test_kis_hoga_ws.py
Normal file
@@ -0,0 +1,91 @@
|
||||
import sys
|
||||
import asyncio
|
||||
import json
|
||||
import websockets
|
||||
import logging
|
||||
|
||||
sys.path.insert(0, "/home/hoon/kis_bot")
|
||||
from database import TradeDB
|
||||
import requests
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
async def test_kis_hoga(code="005930"):
|
||||
db = TradeDB()
|
||||
row = db.conn.execute(
|
||||
"SELECT KIS_APP_KEY_REAL, KIS_APP_SECRET_REAL FROM env_config ORDER BY id DESC LIMIT 1"
|
||||
).fetchone()
|
||||
db.close()
|
||||
|
||||
if not row:
|
||||
print("KIS API 설정이 없습니다.")
|
||||
return
|
||||
|
||||
app_key = dict(row).get("KIS_APP_KEY_REAL")
|
||||
app_secret = dict(row).get("KIS_APP_SECRET_REAL")
|
||||
|
||||
# 직접 발급 (테스트용)
|
||||
url_app = "https://openapi.koreainvestment.com:9443/oauth2/Approval"
|
||||
headers = {"content-type": "application/json; utf-8"}
|
||||
body = {
|
||||
"grant_type": "client_credentials",
|
||||
"appkey": app_key,
|
||||
"secretkey": app_secret
|
||||
}
|
||||
|
||||
print(f"DEBUG: appkey length={len(str(app_key))}, appsecret length={len(str(app_secret))}")
|
||||
|
||||
res = requests.post(url_app, headers=headers, json=body)
|
||||
approval_key = res.json().get("approval_key")
|
||||
|
||||
if not approval_key:
|
||||
print(f"❌ Approval Key 발급 실패: {res.text}")
|
||||
return
|
||||
|
||||
print(f"Approval Key 획득: {approval_key[:10]}...")
|
||||
|
||||
url = "ws://ops.koreainvestment.com:21000"
|
||||
|
||||
async with websockets.connect(url, ping_interval=60) as ws:
|
||||
print(f"웹소켓 연결 성공: {url}")
|
||||
|
||||
req = {
|
||||
"header": {
|
||||
"approval_key": approval_key,
|
||||
"custtype": "P",
|
||||
"tr_type": "1", # 1: 등록
|
||||
"content-type": "utf-8"
|
||||
},
|
||||
"body": {
|
||||
"input": {
|
||||
"tr_id": "H0STASP0",
|
||||
"tr_key": code
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await ws.send(json.dumps(req))
|
||||
print(f"{code} 실시간 호가(H0STASP0) 구독 요청 발송")
|
||||
|
||||
count = 0
|
||||
while count < 5:
|
||||
res = await ws.recv()
|
||||
if res.startswith('0') or res.startswith('1'):
|
||||
# 실시간 데이터 스트림
|
||||
parts = res.split('|')
|
||||
if len(parts) >= 4:
|
||||
tr_id = parts[1]
|
||||
raw_data = parts[3]
|
||||
fields = raw_data.split('^')
|
||||
if tr_id == "H0STASP0":
|
||||
ask1 = fields[3]
|
||||
bid1 = fields[13]
|
||||
ask1_vol = fields[23]
|
||||
bid1_vol = fields[33]
|
||||
print(f"🔔 [실시간 호가 수신] {code} - 매도1호가: {ask1}(잔량 {ask1_vol}) | 매수1호가: {bid1}(잔량 {bid1_vol})")
|
||||
count += 1
|
||||
else:
|
||||
print(f"💬 [시스템 메시지] {res}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(test_kis_hoga("005930"))
|
||||
Reference in New Issue
Block a user