"백엔드_핵심_로직_구현_프론트엔드_연동_및_도커_배포_최적화_완료"

This commit is contained in:
2026-02-03 00:52:54 +09:00
parent ed8fc0943b
commit eeddc62089
32 changed files with 1287 additions and 318 deletions

View File

@@ -3,6 +3,7 @@ import json
import websockets
import logging
from typing import Dict, Set, Callable, Optional
from datetime import datetime
from app.services.kis_auth import kis_auth
from app.core.crypto import aes_cbc_base64_dec
@@ -21,134 +22,113 @@ class RealtimeManager:
def __init__(self):
self.ws: Optional[websockets.WebSocketClientProtocol] = None
self.approval_key: Optional[str] = None
self.subscribed_codes: Set[str] = set()
self.running = False
self.data_map: Dict[str, Dict] = {} # Store IV/Key for encrypted TRs
async def start(self):
"""
Main loop: Connect -> Authenticate -> Listen
"""
self.running = True
while self.running:
try:
# 1. Get Approval Key
self.approval_key = await kis_auth.get_approval_key()
logger.info(f"Connecting to KIS WS: {self.WS_URL_REAL}")
async with websockets.connect(self.WS_URL_REAL, ping_interval=None) as websocket:
self.ws = websocket
logger.info("Connected.")
# 2. Resubscribe if recovering connection
if self.subscribed_codes:
await self._resubscribe_all()
# 3. Listen Loop
await self._listen()
except Exception as e:
logger.error(f"WS Connection Error: {e}. Retrying in 5s...")
await asyncio.sleep(5)
async def stop(self):
self.running = False
if self.ws:
await self.ws.close()
async def subscribe(self, stock_code: str, type="price"):
"""
Subscribe to a stock.
type: 'price' (H0STCNT0 - 체결가)
"""
if not self.ws or not self.approval_key:
logger.warning("WS not ready. Adding to pending list.")
self.subscribed_codes.add(stock_code)
return
# Domestic Realtime Price TR ID: H0STCNT0
tr_id = "H0STCNT0"
tr_key = stock_code
# Reference Counting: Code -> Set of Sources
# e.g. "005930": {"HOLDING", "FRONTEND_DASHBOARD"}
self.subscriptions: Dict[str, Set[str]] = {}
self.running = False
self.data_map: Dict[str, Dict] = {}
# Realtime Data Cache (Code -> DataDict)
# Used by Scheduler to persist data periodically
self.price_cache: Dict[str, Dict] = {}
async def add_subscription(self, code: str, source: str):
"""
Request subscription. Increments reference count for the code.
"""
if code not in self.subscriptions:
self.subscriptions[code] = set()
if not self.subscriptions[code]:
# First subscriber, Send WS Command
await self._send_subscribe(code, "1") # 1=Register
self.subscriptions[code].add(source)
logger.info(f"Subscribed {code} by {source}. RefCount: {len(self.subscriptions[code])}")
async def remove_subscription(self, code: str, source: str):
"""
Remove subscription. Decrements reference count.
"""
if code in self.subscriptions and source in self.subscriptions[code]:
self.subscriptions[code].remove(source)
logger.info(f"Unsubscribed {code} by {source}. RefCount: {len(self.subscriptions[code])}")
if not self.subscriptions[code]:
# No more subscribers, Send WS Unsubscribe
await self._send_subscribe(code, "2") # 2=Unregister
del self.subscriptions[code]
async def _send_subscribe(self, code: str, tr_type: str):
if not self.ws or not self.approval_key:
return # Will resubscribe on connect
payload = {
"header": {
"approval_key": self.approval_key,
"custtype": "P",
"tr_type": "1", # 1=Register, 2=Unregister
"tr_type": tr_type,
"content-type": "utf-8"
},
"body": {
"input": {
"tr_id": tr_id,
"tr_key": tr_key
"tr_id": "H0STCNT0",
"tr_key": code
}
}
}
await self.ws.send(json.dumps(payload))
self.subscribed_codes.add(stock_code)
logger.info(f"Subscribed to {stock_code}")
async def _resubscribe_all(self):
for code in self.subscribed_codes:
await self.subscribe(code)
for code in list(self.subscriptions.keys()):
await self._send_subscribe(code, "1")
async def _listen(self):
async for message in self.ws:
try:
# Message can be plain text provided by library, or bytes
if isinstance(message, bytes):
message = message.decode('utf-8')
# KIS sends data in specific formats.
# 1. JSON (Control Messages, PINGPONG, Subscription Ack)
# 2. Text/Pipe separated (Real Data) - Usually starts with 0 or 1
if isinstance(message, bytes): message = message.decode('utf-8')
first_char = message[0]
if first_char in ['{', '[']:
# JSON Message
data = json.loads(message)
header = data.get('header', {})
tr_id = header.get('tr_id')
if tr_id == "PINGPONG":
await self.ws.send(message) # Echo back
logger.debug("PINGPONG handled")
elif 'body' in data:
# Subscription Ack
# Store IV/Key if encryption is enabled (msg1 often contains 'ENCRYPT')
# But for Brokerage API, H0STCNT0 is usually plaintext unless configured otherwise.
# If encrypted, 'iv' and 'key' are in body['output']
pass
elif first_char in ['0', '1']:
# Real Data: 0|TR_ID|DATA_CNT|DATA...
if first_char in ['0', '1']:
# Real Data
parts = message.split('|')
if len(parts) < 4:
continue
if len(parts) < 4: continue
tr_id = parts[1]
raw_data = parts[3]
# Decryption Check
# If this tr_id was registered as encrypted, decrypt it.
# For now assuming Plaintext for H0STCNT0 as per standard Personal API.
# Parse Data
if tr_id == "H0STCNT0": # Domestic Price
# Data format: TIME^PRICE^...
# We need to look up format spec.
# Simple implementation: just log or split
fields = raw_data.split('^')
if len(fields) > 2:
current_price = fields[2] # Example index
# TODO: Update DB
# print(f"Price Update: {current_price}")
pass
if tr_id == "H0STCNT0":
await self._parse_domestic_price(raw_data)
elif first_char == '{':
data = json.loads(message)
if data.get('header', {}).get('tr_id') == "PINGPONG":
await self.ws.send(message)
except Exception as e:
logger.error(f"Error processing WS message: {e}")
logger.error(f"WS Error: {e}")
async def _parse_domestic_price(self, raw_data: str):
# Format: MKSC_SHRN_ISCD^EXEC_TIME^CURRENT_PRICE^...
fields = raw_data.split('^')
if len(fields) < 3: return
code = fields[0]
curr_price = fields[2]
change = fields[4]
change_rate = fields[5]
# Create lightweight update object (Dict)
update_data = {
"code": code,
"price": curr_price,
"change": change,
"rate": change_rate,
"timestamp": datetime.now().isoformat()
}
# Update Cache
self.price_cache[code] = update_data
# logger.debug(f"Price Update: {code} {curr_price}")
realtime_manager = RealtimeManager()