커밋 1 — 실매 가격 TTL 구멍 (본체)
왜: 체결이 없어도 마지막가는 유지인데, TTL로 None 만들고 매도/EOD를 건너뛰어 8/5 돌파·금요일 leftover가 남음. 호가필터 TTL 구멍과 같은 병. 넣을 파일 신규: kis_trader/engine/live_sell_price.py kis_trader/strategies/base.py (_ws_last_quote, _resolve_sell_price) 전략: momentum.py scalping.py tail_catch.py breakout.py range_break.py dart_strategy.py updow_strategy.py updown_feed.py us_momentum.py WS: ws_manager.py kis_ws.py kiwoom_ws.py ls_ws.py kis_ws_overseas.py kis_trader/web/live_config_schema.py (WS_PRICE_MAX_AGE_SEC 기본 0) database.py (키 주석 + legacy/ sys.path) kis_trader/execution/order_manager.py (잔고 있는데 40240000 ghost_purge 금지 — 같은 EOD 사고) EOD가 min_hold에 안 막히게 손본 momentum_hts_logic.py / scalping_engine.py / tail_engine.py (이 대화에서 손본 부분만 확인 후) 문서: docs/like_mcp.md/db_erd.md code_architecture.md (가격 TTL 문구) 메시지 초안 fix: 매수·매도 현재가를 TTL로 버리지 않음 (마지막 RAM) 횡보·체결 공백을 죽은 캐시로 오인해 None 처리하면 손절·EOD가 스킵된다. 호가필터와 같이 나이는 무시하고 마지막 체결가를 유지한다. EOD는 매수가 폴백. 영향: 실매 O / 백테·옵투나 봉 경로 거의 무관 (엔진 식 변경 아님) 커밋 2 — 루트 정리 (remove/ vs legacy/) 왜: 루트 단독봇·테스트는 지울 보관함으로. 웹·알람이 아직 쓰는 모듈은 remove에 두면 나중에 폴더째 삭제 때 깨짐. 넣을 파일 이동: 미사용 → remove/legacy_root/ (래퍼, ETF/키움 옛봇, 테스트, kiwoom_rest_api 등) 이동: 사용 중 → legacy/ (holding_bot kis_holding_ver1 news_analyzer kis_long_ver1/2) 신규: kis_trader/utils/legacy_root.py legacy/README.md remove/README.md import 경로: backtest_web.py mm_butler.py mm_remote.py updow_holding_cfg.py dbband_stock_cfg.py param_search_updow*.py dbband_param_search.py param_search_apply_snapshot.py verify_three_paths.py docs/like_mcp.md/code_architecture.md 수동 노트 메시지 초안 chore: 미사용 루트는 remove/, 웹·알람 구모듈은 legacy/ remove는 나중에 통째 삭제 예정. holding_bot·news_analyzer·kis_long은 ensure_legacy_root로 legacy/만 본다. 빼기: scratch/set_ws_price_max_age_zero.py (일회성)
This commit is contained in:
122
remove/legacy_root/kiwwom_trader/ws_candle_agg.py
Normal file
122
remove/legacy_root/kiwwom_trader/ws_candle_agg.py
Normal file
@@ -0,0 +1,122 @@
|
||||
# kiwwom_trader/ws_candle_agg.py
|
||||
# 키움 웹소켓 실시간 체결(0B) 수신 → 1분봉 집계 → DB 또는 메모리 버퍼
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from typing import Callable, Dict, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _slot_1m(now: datetime) -> str:
|
||||
"""현재 시각 기준 1분 봉 키 (YYYYMMDDHHMI)."""
|
||||
return now.strftime("%Y%m%d%H%M")
|
||||
|
||||
|
||||
class KiwoomCandleAggregator:
|
||||
"""
|
||||
키움 실시간 타입 0B(주식체결) 수신 시 호출되는 콜백에서
|
||||
종목별·1분봉별 OHLCV를 집계. 확정된 봉은 on_candle 콜백 또는 DB에 전달.
|
||||
"""
|
||||
def __init__(
|
||||
self,
|
||||
on_candle: Optional[Callable[[str, int, str, dict], None]] = None,
|
||||
timeframe_min: int = 1,
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
on_candle: (code, timeframe_min, candle_time, candle_dict) 호출. DB 저장 시 사용.
|
||||
timeframe_min: 봉 간격(분). 1 = 1분봉.
|
||||
"""
|
||||
self.on_candle = on_candle
|
||||
self.timeframe_min = timeframe_min
|
||||
# code -> slot_1m -> { open, high, low, close, volume }
|
||||
self._buf: Dict[str, Dict[str, dict]] = defaultdict(dict)
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
def push_tick(self, code: str, price: float, volume: int, tick_time: Optional[datetime] = None):
|
||||
"""
|
||||
체결 1건 누적. 스레드 세이프하지 않음; 이벤트 루프 한 스레드에서 호출 권장.
|
||||
"""
|
||||
t = tick_time or datetime.now()
|
||||
slot = _slot_1m(t)
|
||||
if slot not in self._buf[code]:
|
||||
self._buf[code][slot] = {
|
||||
"open": price,
|
||||
"high": price,
|
||||
"low": price,
|
||||
"close": price,
|
||||
"volume": volume,
|
||||
}
|
||||
else:
|
||||
c = self._buf[code][slot]
|
||||
c["high"] = max(c["high"], price)
|
||||
c["low"] = min(c["low"], price)
|
||||
c["close"] = price
|
||||
c["volume"] = c.get("volume", 0) + volume
|
||||
|
||||
def flush_slot(self, code: str, slot: str) -> Optional[dict]:
|
||||
"""해당 종목·슬롯 봉을 확정해 반환하고 버퍼에서 제거."""
|
||||
if code not in self._buf or slot not in self._buf[code]:
|
||||
return None
|
||||
c = self._buf[code].pop(slot)
|
||||
if not self._buf[code]:
|
||||
del self._buf[code]
|
||||
return c
|
||||
|
||||
def get_candles(self, code: str, timeframe_min: int, n: int = 50) -> List[dict]:
|
||||
"""
|
||||
메모리 버퍼만 사용하는 경우: 현재 버퍼에 쌓인 봉 반환. 없으면 빈 리스트.
|
||||
DB와 연동 시에는 이 메서드에서 DB를 조회하도록 확장.
|
||||
"""
|
||||
if code not in self._buf:
|
||||
return []
|
||||
slots = sorted(self._buf[code].keys())
|
||||
out = []
|
||||
for slot in slots[-n:]:
|
||||
c = self._buf[code][slot].copy()
|
||||
c["candle_time"] = slot
|
||||
c["volume"] = c.get("volume", 0)
|
||||
out.append(c)
|
||||
return out
|
||||
|
||||
|
||||
def build_ws_client_with_candle_callback(
|
||||
access_token: str,
|
||||
aggregator: KiwoomCandleAggregator,
|
||||
ws_url: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
키움 WebSocketClient에 실시간 0B 수신 시 aggregator.push_tick 호출하도록 연결.
|
||||
kiwoom_rest_api.websocket / websocket_helper 사용.
|
||||
"""
|
||||
try:
|
||||
from kiwoom_rest_api.websocket import WebSocketClient, RealTimeData
|
||||
from kiwoom_rest_api.websocket_constants import STOCK_TRADE_FIELDS, get_field_name
|
||||
except ImportError:
|
||||
logger.warning("kiwoom_rest_api 미설치 또는 경로 미등록 → 웹소켓 캔들 비활성")
|
||||
return None
|
||||
|
||||
client = WebSocketClient(access_token=access_token, ws_url=ws_url)
|
||||
|
||||
async def on_data(realtime_data: RealTimeData):
|
||||
if realtime_data.trnm != "REAL":
|
||||
return
|
||||
for item in realtime_data.data or []:
|
||||
type_code = item.get("type", "")
|
||||
if type_code != "0B":
|
||||
continue
|
||||
item_code = (item.get("item") or [""])[0] if isinstance(item.get("item"), list) else item.get("item", "")
|
||||
if not item_code:
|
||||
continue
|
||||
values = item.get("values") or {}
|
||||
# 10:현재가, 15:거래량 등 (STOCK_TRADE_FIELDS)
|
||||
price = float(values.get("10", 0) or 0)
|
||||
vol = int(values.get("15", 0) or 0)
|
||||
if price > 0:
|
||||
aggregator.push_tick(item_code, price, vol)
|
||||
|
||||
client.on_data = on_data
|
||||
return client
|
||||
Reference in New Issue
Block a user