Files
auto-stock/backend/app/realtime/examples.py

239 lines
7.4 KiB
Python

"""
Realtime Module Usage Examples
Realtime 모듈 사용 예시
"""
import asyncio
import logging
from typing import Dict, Any
from app.realtime import KISWebSocketClient, event_handler, EventType, market_scheduler
from app.realtime.websocket_client import create_websocket_client
from app.strategy import strategy_manager
from app.trading import order_manager, market_data_provider
logger = logging.getLogger(__name__)
# ── 예시 1: 기본 실시간 시세 수신 ────────────────────────
async def example_basic_price_stream():
"""기본 실시간 시세 수신 예시"""
# 핸들러 등록
async def on_price_update(event_data: Dict[str, Any]):
stock_code = event_data['stock_code']
price = event_data['current_price']
print(f"💰 {stock_code}: {price}원")
event_handler.register(EventType.PRICE_UPDATE, on_price_update)
# WebSocket 연결
ws_client = create_websocket_client()
await ws_client.connect()
# 종목 구독
await ws_client.subscribe_price("005930") # 삼성전자
await ws_client.subscribe_price("000660") # SK하이닉스
# 메시지 수신 (무한 루프)
await ws_client.listen()
# ── 예시 2: 실시간 전략 실행 ───────────────────────────
async def example_realtime_strategy():
"""실시간 시세로 전략 실행"""
from app.strategy.strategies import DayTradingStrategy
# 전략 등록
strategy = DayTradingStrategy()
strategy_manager.register_strategy(strategy)
# 실시간 시세 수신 시 전략 실행
async def on_price_update(event_data: Dict[str, Any]):
stock_code = event_data['stock_code']
current_price = event_data['current_price']
# 시장 데이터 구성
market_data = {
"current_price": current_price,
"minute_chart": await market_data_provider.get_minute_chart(stock_code),
}
# 전략 실행
signal = await strategy_manager.run_strategy(
"DayTrading",
stock_code=stock_code,
market_data=market_data
)
# 신호 발생 시 주문
if signal:
logger.info(f"📡 신호 발생: {signal}")
result = await order_manager.place_order(
stock_code=signal.stock_code,
order_type=signal.signal_type.value,
quantity=10,
price=signal.price
)
logger.info(f"📤 주문 결과: {result}")
event_handler.register(EventType.PRICE_UPDATE, on_price_update)
# WebSocket 실행
ws_client = create_websocket_client()
await ws_client.run() # 자동 재연결 포함
# ── 예시 3: 장 스케줄러 활용 ───────────────────────────
async def example_market_scheduler():
"""장 스케줄러 활용 예시"""
ws_client = None
# 장 시작 콜백
async def on_market_open():
nonlocal ws_client
logger.info("🔔 장 시작 - WebSocket 연결 및 구독")
ws_client = create_websocket_client()
await ws_client.connect()
# 관심 종목 구독
watch_list = ["005930", "000660", "035420"]
for stock_code in watch_list:
await ws_client.subscribe_price(stock_code)
# 수신 시작
asyncio.create_task(ws_client.listen())
# 장 종료 콜백
async def on_market_close():
logger.info("🔕 장 종료 - WebSocket 연결 해제")
if ws_client:
await ws_client.disconnect()
# 콜백 등록
market_scheduler.register_callbacks(
on_open=on_market_open,
on_close=on_market_close
)
# 스케줄러 실행
await market_scheduler.run()
# ── 예시 4: 복합 예시 (전체 시스템) ──────────────────────
async def example_full_system():
"""전체 자동매매 시스템 예시"""
from app.strategy.strategies import DayTradingStrategy
# 1. 전략 등록
strategy = DayTradingStrategy(
config={
"max_positions": 3,
"stop_loss_pct": 0.025
}
)
strategy_manager.register_strategy(strategy, priority=10)
# 2. 이벤트 핸들러 등록
async def on_price_update(event_data: Dict[str, Any]):
"""실시간 시세 → 전략 실행 → 주문"""
stock_code = event_data['stock_code']
current_price = event_data['current_price']
# 시장 데이터 수집
market_data = {
"current_price": current_price,
"minute_chart": await market_data_provider.get_minute_chart(stock_code),
}
# 포트폴리오 데이터
balance = await order_manager.get_balance()
# ... 보유 종목 파싱
# 전략 실행
signal = await strategy_manager.run_strategy(
"DayTrading",
stock_code=stock_code,
market_data=market_data
)
if signal:
# 주문 실행
from app.strategy.signal import SignalType
if signal.signal_type == SignalType.BUY:
await order_manager.place_order(
stock_code=signal.stock_code,
order_type="BUY",
quantity=10,
price=signal.price
)
elif signal.signal_type in [SignalType.SELL, SignalType.STOP_LOSS, SignalType.TAKE_PROFIT]:
await order_manager.place_order(
stock_code=signal.stock_code,
order_type="SELL",
quantity=signal.quantity,
price=signal.price
)
event_handler.register(EventType.PRICE_UPDATE, on_price_update)
# 3. 장 스케줄러 설정
ws_client = None
async def on_market_open():
nonlocal ws_client
logger.info("🔔 장 시작")
# WebSocket 연결
ws_client = create_websocket_client()
await ws_client.connect()
# 관심 종목 구독
watch_list = ["005930", "000660", "035420", "005380"]
for code in watch_list:
await ws_client.subscribe_price(code)
# 수신 시작
asyncio.create_task(ws_client.listen())
async def on_market_close():
logger.info("🔕 장 종료")
# WebSocket 연결 해제
if ws_client:
await ws_client.disconnect()
market_scheduler.register_callbacks(
on_open=on_market_open,
on_close=on_market_close
)
# 4. 시스템 실행
logger.info("🚀 자동매매 시스템 시작")
await market_scheduler.run()
# ── 메인 함수 ─────────────────────────────────────────
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
# 예시 선택 실행
# asyncio.run(example_basic_price_stream())
# asyncio.run(example_realtime_strategy())
# asyncio.run(example_market_scheduler())
asyncio.run(example_full_system())