Coverage for view / web / routes / order.py: 96%
32 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-04 15:08 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-04 15:08 +0000
1"""
2주문 관련 API 엔드포인트 (order.html).
3"""
4from fastapi import APIRouter, HTTPException
5from view.web.api_common import _get_ctx, _serialize_response, OrderRequest
7router = APIRouter()
10@router.post("/order")
11async def place_order(req: OrderRequest):
12 """매수/매도 주문 (성공 시 가상 매매 기록에도 '수동매매'로 저장)"""
13 ctx = _get_ctx()
14 t_start = ctx.pm.start_timer()
16 # 1. 실제/모의 투자 주문 전송
17 if req.side == "buy":
18 resp = await ctx.order_execution_service.handle_buy_stock(req.code, req.qty, req.price)
19 elif req.side == "sell":
20 resp = await ctx.order_execution_service.handle_sell_stock(req.code, req.qty, req.price)
21 else:
22 raise HTTPException(status_code=400, detail="side는 'buy' 또는 'sell'이어야 합니다.")
24 # 2. [추가됨] 주문 성공 시 가상 매매 장부에도 기록 (전략명: "수동매매")
25 if resp and resp.rt_cd == "0":
26 # virtual_trade_service가 초기화되어 있는지 확인
27 if hasattr(ctx, 'virtual_trade_service') and ctx.virtual_trade_service: 27 ↛ 52line 27 didn't jump to line 52 because the condition on line 27 was always true
28 try:
29 # 가격 형변환 (문자열 -> 숫자)
30 price_val = int(req.price) if req.price and req.price.isdigit() else 0
32 # 시장가 주문(price=0)인 경우 현재가를 조회하여 사용
33 if price_val == 0 and getattr(ctx, 'stock_query_service', None):
34 try:
35 price_resp = await ctx.stock_query_service.handle_get_current_stock_price(req.code)
36 if price_resp and price_resp.rt_cd == "0" and isinstance(price_resp.data, dict):
37 price_str = str(price_resp.data.get('price', '0'))
38 price_val = int(price_str) if price_str.isdigit() else 0
39 except Exception:
40 pass
42 if req.side == "buy":
43 # 매수 기록 (전략명: 수동매매)
44 ctx.virtual_trade_service.log_buy("수동매매", req.code, price_val)
45 elif req.side == "sell": 45 ↛ 52line 45 didn't jump to line 52 because the condition on line 45 was always true
46 # 매도 기록 (수익률 계산됨)
47 ctx.virtual_trade_service.log_sell(req.code, price_val)
49 except Exception as e:
50 print(f"[WebAPI] 수동매매 기록 중 오류 발생: {e}")
52 ctx.pm.log_timer("place_order", t_start)
53 return _serialize_response(resp)