kiwoompy

조건부 자동 주문

현재가를 조회해서 조건에 맞으면 자동으로 주문을 제출하는 예제입니다.

!!! warning “실계좌 주의” 이 예제를 env="real"로 실행하면 실제 계좌에 주문이 접수됩니다. 반드시 env="demo" (모의투자)로 먼저 충분히 테스트하세요.

목표 가격 도달 시 매수

지정한 종목의 현재가가 목표 가격 이하로 내려오면 매수 주문을 제출합니다.

import time
from kiwoompy import KiwoomClient, KiwoomApiError

client = KiwoomClient(env="demo", appkey="...", secretkey="...")

STOCK_CODE = "005930"   # 삼성전자
TARGET_PRICE = 70000    # 이 가격 이하가 되면 매수
BUY_QUANTITY = "1"
CHECK_INTERVAL = 10     # 10초마다 확인

print(f"{STOCK_CODE} 현재가 모니터링 시작 (목표: {TARGET_PRICE:,}원 이하)")

while True:
    info = client.query.get_stock_info(STOCK_CODE)
    current_price = int(info.cur_prc.replace(",", "").replace("-", "").replace("+", ""))

    print(f"현재가: {current_price:,}원 ({info.flu_rt}%)")

    if current_price <= TARGET_PRICE:
        print(f"목표 가격 도달! {current_price:,}원 ≤ {TARGET_PRICE:,}원 → 매수 주문")
        try:
            result = client.order.buy(
                stock_code=STOCK_CODE,
                quantity=BUY_QUANTITY,
                trade_type="limit",
                price=str(current_price),
            )
            print(f"매수 주문 완료 — 주문번호: {result.ord_no}")
            break
        except KiwoomApiError as e:
            print(f"주문 실패: {e}")
            break

    time.sleep(CHECK_INTERVAL)

수익률 기반 자동 매도

보유 종목의 수익률이 목표치에 도달하면 전량 매도합니다.

import time
from kiwoompy import KiwoomClient, KiwoomApiError

client = KiwoomClient(env="demo", appkey="...", secretkey="...")

TAKE_PROFIT = 5.0    # 수익률 +5% 이상이면 매도
STOP_LOSS = -3.0     # 수익률 -3% 이하면 손절
CHECK_INTERVAL = 30  # 30초마다 확인

print(f"익절: +{TAKE_PROFIT}% / 손절: {STOP_LOSS}%")

while True:
    balance = client.query.get_account_balance()

    for item in balance.holdings:
        profit_rate = float(item.prft_rt)

        if profit_rate >= TAKE_PROFIT:
            print(f"[익절] {item.stk_nm}: {profit_rate:.2f}% → 전량 매도")
            try:
                result = client.order.sell(
                    stock_code=item.stk_cd,
                    quantity=item.trde_able_qty,  # 매도가능수량
                    trade_type="market",
                )
                print(f"  매도 주문 완료 — 주문번호: {result.ord_no}")
            except KiwoomApiError as e:
                print(f"  매도 실패: {e}")

        elif profit_rate <= STOP_LOSS:
            print(f"[손절] {item.stk_nm}: {profit_rate:.2f}% → 전량 매도")
            try:
                result = client.order.sell(
                    stock_code=item.stk_cd,
                    quantity=item.trde_able_qty,
                    trade_type="market",
                )
                print(f"  손절 주문 완료 — 주문번호: {result.ord_no}")
            except KiwoomApiError as e:
                print(f"  손절 실패: {e}")

    time.sleep(CHECK_INTERVAL)

주문 후 미체결 취소

지정가 주문 후 일정 시간 안에 체결되지 않으면 자동으로 취소합니다.

import time
from kiwoompy import KiwoomClient

client = KiwoomClient(env="demo", appkey="...", secretkey="...")

STOCK_CODE = "005930"
WAIT_SECONDS = 60   # 60초 안에 체결 안 되면 취소

# 지정가 매수 주문
result = client.order.buy(
    stock_code=STOCK_CODE,
    quantity="1",
    trade_type="limit",
    price="68000",
)
order_no = result.ord_no
print(f"주문 접수 — 주문번호: {order_no}")

# 체결 대기
time.sleep(WAIT_SECONDS)

# 미체결 확인
unfilled = client.query.get_unfilled_orders(all_stock_type="0", trade_type="buy")
still_unfilled = next((o for o in unfilled if o.ord_no == order_no), None)

if still_unfilled:
    remaining = still_unfilled.oso_qty
    print(f"미체결 {remaining}주 → 취소 주문")
    client.order.cancel(
        original_order_no=order_no,
        stock_code=STOCK_CODE,
        cancel_quantity="0",   # 잔량 전부 취소
    )
    print("취소 완료")
else:
    print("이미 체결됨")

관련 가이드