AutoTrade Bot

한국 주식 AI 자동매매 — 단타 + 장기 듀얼 파이프라인, 실계좌 운영 중
Korean equities AI auto-trading — dual pipeline (DayTrade + Long-term), live in production
2026-04-20 실전 운영 중 Live in Production Railway · Vercel · PostgreSQL

개요Overview

한국투자증권(KIS) Open API를 통해 실계좌에서 운영 중인 AI 기반 주식 자동매매 시스템입니다. 단타(DayTrade)장기(Kostolany) 두 개의 독립 파이프라인이 각자의 전략·예산·계좌로 병렬 운영됩니다.

A production AI auto-trading system running on a live brokerage account via the Korea Investment & Securities (KIS) Open API. Two independent pipelines — DayTrade and Kostolany (long-term) — run in parallel with separate strategies, budgets, and accounts.

예측 정확도보다 리스크 관리와 운영 안정성을 우선합니다. 손절·익절·일일 손실 한도, 강제청산, 장애 복구, DB/KIS 정합성 검증이 모두 자동화되어 있습니다.

Risk management and operational stability take priority over prediction accuracy. Stop-loss, take-profit, daily loss limits, force-close, fault recovery, and DB/KIS reconciliation are all automated.

🔒

소스 저장소는 비공개입니다. 대시보드 URL은 인증 필요.

Source repository is private. Dashboard requires authentication.

듀얼 파이프라인Dual Pipeline

⚡ DayTrade Pipeline 당일 청산

  • 매수 허용: 09:05–11:30, 13:00–13:45 KST
  • 5분 사이클 — 후보 선정 → 매수·매도 병렬 실행
  • 종가마감 3단계: 15:10 최유리지정가 → 15:20 시장가 → 15:25 DB정합
  • 신호: 변동성 돌파, 5분봉 브레이크아웃
  • SL −1.2% / TP +2.5% / 분할익절 +1.5%
  • Gemini 뉴스 감성분석 + ML 확률 게이트
  • 별도 계좌·별도 APP KEY 격리
  • DTManager — circuit breaker (3회 실패 → 차단 + 알림)
  • Buy windows: 09:05–11:30, 13:00–13:45 KST
  • 5-min cycle — candidate select → parallel buy + sell
  • 3-phase close: 15:10 best-bid → 15:20 market → 15:25 reconcile
  • Signals: volatility breakout, 5-min breakout
  • SL −1.2% / TP +2.5% / partial TP +1.5%
  • Gemini news sentiment + ML probability gate
  • Isolated account & APP KEY
  • DTManager — circuit breaker (3 fails → block + alert)

📈 Kostolany Pipeline 장기 보유

  • 월 1회 유니버스 선정 (PER·PBR·재무 기반)
  • 월요일 08:30 주간 매수 체크
  • 평일 16:00 일간 매도 체크
  • 매크로 지표 매일 20:00 갱신
  • 분기 1회 포트폴리오 재검토
  • 펀더멘털 + 거시경제 지표 기반 판단
  • KostManager — circuit breaker + 파이프라인 싱글턴
  • Monthly universe selection (PER/PBR/financials)
  • Weekly buy check every Monday 08:30
  • Daily sell check weekdays 16:00
  • Macro indicator refresh daily 20:00
  • Quarterly portfolio review
  • Fundamental + macro-driven decisions
  • KostManager — circuit breaker + pipeline singleton

모듈 구조Module Structure

단타 파이프라인 모듈

DayTrade Pipeline Modules

모듈Module 역할Role
daytrade/selector.py 아침 후보 선정 — fpool 스캔 후 스코어 정렬 Morning candidate selection — fpool scan + score sort
daytrade/buy_agent.py 매수 에이전트 — 진입 시그널 체크, 지정가 주문, 실체결가 확인 Buy agent — entry signal check, limit order, fill price verification
daytrade/sell_agent.py 매도 에이전트 — TP/SL/분할익절/트레일링 스탑 체크 Sell agent — TP/SL/partial-TP/trailing stop checks
daytrade/close_agent.py 종가마감 에이전트 — 3단계 청산, 중복방지 lock, 시장가 폴백 EOD close agent — 3-phase liquidation, dedup lock, market-order fallback
daytrade/strategy.py 진입·청산 시그널 계산 — ATR, RSI, 5분봉 브레이크아웃 Entry/exit signal logic — ATR, RSI, 5-min breakout
daytrade/risk.py 일일 손실 한도, 포지션 사이즈, 매수 허용 여부 판단 Daily loss limit, position sizing, buy eligibility
daytrade/news_analyzer.py Gemini API 뉴스 감성분석 — 후보 스코어 조정 (±0.2) Gemini news sentiment — candidate score adjustment (±0.2)
daytrade/ml_model.py 단타 전용 ML — 진입 확률 게이트 (임계값 0.60) DT-only ML — entry probability gate (threshold 0.60)
daytrade/analysis.py 인디케이터 계산 — MA, ATR, RSI, 볼린저밴드 Indicator builder — MA, ATR, RSI, Bollinger Bands
daytrade/kis_dt.py DT 전용 KIS 클라이언트 — 별도 계좌 격리, 토큰 독립 DT-only KIS client — isolated account, independent token

공통 인프라 모듈

Shared Infrastructure Modules

모듈Module 역할Role
agents/guard_agent.py 장애 모니터링 — 2분 간격, KIS 토큰 갱신, API 헬스체크 Fault monitoring — 2-min interval, KIS token refresh, API health
core/ledger.py 체결 기록 + KIS 실거래 대조 — 슬리피지·미체결 감지 Fill ledger + KIS reconciliation — detects slippage and unfilled orders
core/ws_manager.py WebSocket 실시간 시세 — REST 폴링 폴백 WebSocket real-time prices — REST polling fallback
kis_client/ KIS API 클라이언트 패키지 — 토큰·dedup·레이트리밋 전담 KIS API client package — token management, dedup, rate limiting
models/gemini_analyst.py Gemini Flash API — 뉴스 감성분석, 일일 사용량 추적·DB 플러시 Gemini Flash API — news sentiment, daily usage tracking + DB flush
data/db.py PostgreSQL CRUD — 종목·캔들·포지션·거래내역·설정 PostgreSQL CRUD — symbols, candles, positions, trades, config
utils/market_hours.py KRX 개장 여부 — 2026 공휴일 포함 KRX market hours — including 2026 public holidays
core/finance_agent.py 통합 잔고 관리 — TTL 캐시, pending 예약, DT/Kost 손익 추적 Unified balance manager — TTL cache, pending reservation, DT/Kost P&L tracking
daytrade/dt_manager.py DT 파이프라인 관리자 — circuit breaker, 매수·매도 병렬 실행, 강제청산 조율 DT pipeline manager — circuit breaker, parallel buy/sell execution, force-close coordination
core/kost_manager.py Kostolany 파이프라인 관리자 — circuit breaker, 파이프라인 싱글턴, EOD 리셋 Kostolany pipeline manager — circuit breaker, pipeline singleton, EOD reset

일일 운영 스케줄 (KST)Daily Schedule (KST)

08:55 DT 아침 종목 선정 — fpool 스캔, RSI 프리워밍, WS 구독 시작 DT morning selection — fpool scan, RSI pre-warm, WS subscribe
09:05~ DT 5분 사이클 시작 — buy_agent + sell_agent 병렬 실행 (DTManager) DT 5-min cycles begin — buy_agent + sell_agent parallel (DTManager)
15:05 마지막 일반 사이클 (이후 종가마감 모듈 전용 구간) Last regular cycle (close agent takes over after this)
15:10 Phase 1 — 최유리지정가 강제청산, 체결 검증 Phase 1 — best-bid force close with fill verification
15:20 Phase 2 — KIS 잔고 재조회, 시장가 sweep (폴백: 지정가×0.97) Phase 2 — KIS balance recheck, market-order sweep (fallback: limit×0.97)
15:25 Phase 3 — DB/KIS 대조, stale 포지션 정리, Telegram 알림 Phase 3 — DB/KIS diff, stale position cleanup, Telegram alert
16:00 DT ML 모델 재학습 (당일 거래 데이터 반영) DT ML model retrain on today's trade data
매시 정각 KIS/DB 정합성 검증 (Reconcile) KIS/DB reconciliation every hour
일 22:00 DT 종목 풀(fpool) 재스캔 — KOSPI+KOSDAQ 전체 DT fpool rescan — full KOSPI+KOSDAQ scan

리스크 관리Risk Management

항목Item 설정값Value 설명Description
손절Stop-Loss −1.2% 진입가 기준From entry
익절Take-Profit +2.5% 전량 청산Full exit
분할 익절Partial TP +1.5% 50% 매도 후 잔량 트레일링50% exit, trailing on rest
트레일링 스탑Trailing Stop −0.5% 세션 고점 대비 낙폭Drop from session high
일일 손실 한도Daily Loss Limit −3% 초과 시 신규 매수 차단Block new buys on breach
매수 슬리피지 상한Buy Slippage Cap +1% 지정가 = 신호가 × 1.01, 미체결 시 스킵Limit = signal × 1.01, skip if unfilled
ML 확률 게이트ML Probability Gate 0.60 임계값 미만 신호 진입 차단Block entry below threshold

시스템 아키텍처System Architecture

KIS API 시세·주문 WebSocket 실시간 시세 DayTrade Pipeline selector buy_agent sell_agent close_agent ×3 news_analyzer ml_model risk / strategy 별도 계좌 격리 5분 사이클 Kostolany Pipeline selector (월1회) weekly_buy_check daily_sell_check macro.refresh fundamentals 장기 보유 전략 Shared Infra FinanceAgent (잔고캐시) GuardAgent (2분) Reconcile (1시간) kis_client pkg gemini_analyst data/db.py market_hours failsafe / notifier Railway (Python) PostgreSQL Dashboard Next.js · Vercel 실시간 포지션 DT 컨트롤 패널
듀얼 파이프라인 + 공유 인프라 + Vercel 대시보드 Dual pipeline + shared infra + Vercel dashboard

기술 스택Tech Stack

기술Tech 용도Purpose
Python 3.11 전체 봇 파이프라인Full bot pipeline
APScheduler 크론 스케줄러 — 각 파이프라인 독립 BackgroundScheduler Cron scheduler — independent BackgroundScheduler per pipeline
KIS Open API 시세 조회 + 실주문 (모의/실전 분리) Market data + live orders (mock/live isolation)
Gemini Flash 뉴스 감성분석, 일일 사용량 DB 추적 News sentiment analysis, daily usage tracking
LightGBM 단타 ML — 진입 확률 예측 (매일 재학습) DT ML — entry probability prediction (daily retrain)
PostgreSQL 거래·포지션·후보·설정 영구 저장 Trades, positions, candidates, config persistent storage
Next.js 15 · Vercel 실시간 대시보드 (인증 필요) Real-time dashboard (authenticated)
Railway Python 봇 호스팅 — GitHub push 자동 배포 Python bot hosting — auto-deploy on GitHub push
Telegram Bot API 거래 알림 + 장애 경고 Trade notifications + fault alerts
⚠️

실계좌 운영 봇은 예측 품질만큼 장애 내성이 중요합니다. 코드 배포 시 Python 문법 검증, import 폴백, 강제청산 이중화가 필수입니다.

For a live-account bot, fault tolerance matters as much as prediction quality. Python syntax validation, import fallback, and redundant force-close are essential before any deployment.

링크Links