프로그래밍/파이썬

4. 파이썬 - 키움API 활용한 주문 체결 확인하기

가카리 2025. 6. 15. 21:51
반응형

 

1. TR  조회 응답 및 주문에 대한 메시지 수신하기

   KOA > 개발 가이드 > 주문과 잔고 처리 > 관련 함수

 

  - Kiwoom.py 파일에  send_order 함수 다음에 작성한 코드이다.

def _on_receive_msg(self, screen_no, rqname, trcode, msg):
    print("[Kiwoom] _on_receive_msg is called {} / {} / {} / {}".format(screen_no, rqname, trcode, msg))
    

 

  - 사실 내용을 뿌려주는 거라서 별 내용은 없다.

 

2. TR  접수/체결 결과를 처리하는 함수

 

  가. sGubun 

  - 하나의 주문이 접수되고 체결될 때까지 _onchejan_slot 함수는 3번 호출됨(접수, 체결, 잔고 이동)

  - 접수 및 체결 : 0

  - 잔고 이동 : 1

 

  나. nItemCnt

  - 매개변수 nItemCnt 는 주문 접수 및 체결이 될 때 얻을 수 있는 정보의 항목 수이다.

  - 주문 접수 시점에 _on_chejan_slot이 호출되면서 확인할 수 있는 정보가 주문가, 주문 번호, 주문 상태, 미체결 수량 항목 총 4개이면  nItemCnt 값은 4이다.

 

  다. sFIdList

  - API에서 데이터를 여러 개 전달할 때는 ";"을 기준으로 연결한 하나의 긴 문자를 사용함

  - sFIdList도 마찬가지로 FID들을 ";"을 기준으로 연결한 하나의 긴 문자이다.
  - FID란 주식, 선물/옵션, 파생, 잔고 처리 등 증권 업무를 처리하는데 사용하는 용어의 고유값이다.

  - 주문 상태는 FID가 913이다.

  - 기타 FID는 KOA 의 실시간 목록에서 확인할 수 있다.

 

_on_chejan_slot을 만들기 전에 

 

  해당 종목의 주문 정보를 담을 딕셔너리(self.order)와 체결이 완료되어 잔고로 이동한 종목들을 저장할 딕셔너리 self.balance를 만든다.

 

def __init__(self):
    super().__init__()
    self._make_kiwoom_instance()
    self._set_signal_slots()
    self._comm_connect()#로그인 요청하는 메소드 시작

    self.account_number = self.get_account_number()#계좌번호 가져옴

    self.tr_event_loop = QEventLoop()#TR 요청에 대한 응답 대기를 위한 변수 데이터가 올 때까지 기다렸다가 처리해!" 하는 용도로 사용하는 이벤트 루프
    
    self.order = {} #종목 코드를 키 값으로 해당 종목의 주문 정보를 담은 딕셔너리
    self.balance = {} #종목 코드를 키 값으로 해당 종목의 매수 정보를 담은 딕셔너리

 

 

  - 다음은 _on_chejan_slot 함수 전체 코드이다.

 

def _on_chejan_slot(self, s_gubun, n_item_cnt, s_fid_list):
    print("[Kiwoom] _on_chejan_slot is called {} / {} / {}".format(s_gubun, n_item_cnt, s_fid_list))

    for fid in s_fid_list.split(";"): # ;로 구분되는 fid 리스트를 ;를 기준으로 구분함
        if fid in FID_CODES:
            code = self.dynamicCall("GetChejanData(int)", '9001')[1:] #종목코드의 앞자리 A를 제거함 9001은 FID가 종목코드임
            data = self.dynamicCall("GetChejanData(int)", fid) #fid를 사용하여 데이터 얻어오기 9203이면 주문번호를 수신하여 data를 저장

            data = data.strip().lstrip('+').lstrip('-') #데이터에 +가 붙어있으면 매수 -면 매도인데 제거함

            if data.isdigit():#수신된 문자형 데이터 중 숫자인 항목을 숫자로 바꿈
                data = int(data)

            item_name = FID_CODES[fid]#fid 코드에 해당하는 항목(item_name)을 찾음
            print("{}: {}".format(item_name, data))#얻어온 데이터 출력(주문가격 30000)

            if int(s_gubun) == 0: #s_gubun이 0이면 접수/체결 시

                if code not in self.order.keys():#아직 order 종목 코드가 없다면 신규 생성하는 과정
                    self.order[code] = {} #빈딕셔너리 생성

                    #예를들어 {'00700' : {'주문상태' : '체결'}} 이런식으로 저장하게됨
                    #접근시 ['00700']['주문상태']로 접근하면 됨
                self.order[code].update({item_name: data})#order 딕셔너리에 데이터 저장

            elif int(s_gubun) == 1:#s_gubun이 1이면 국내 주식 잔고 변경을 함
                #아직 balance에 종목 코드가 없다면 신규 생성하는 과정 
                if code not in self.balance.keys():
                    self.balance[code] = {}

                self.balance[code].update({item_name: data})

    if int(s_gubun) == 0:
        print("* 주문 출력(self.order)")
        print(self.order)
    elif int(s_gubun) == 1:
        print("* 잔고 출력(self.balance)")
        print(self.balance)

 

  - 여기서 fid 값과 GetChejanData 함수를 사용하여 fid에 해당하는 항목 데이터를 얻어온다.

 

 

3. main.py 작성

  - 삼성전자 주식을 60000원에 매수해보는 코드이다.

from api.Kiwoom import *
import sys

app = QApplication(sys.argv)
kiwoom = Kiwoom()

#kiwoom.get_account_number()

#df = kiwoom.get_price_data("005930_AL")
#print(df)

deposit = kiwoom.get_deposit()

order_result = kiwoom.send_order('send_buy_order', '1001', 1, '005930', 1, 60000, '00')

print(order_result)

'''kospi_code_list = kiwoom.get_code_list_by_market("0")
print(len(kospi_code_list))

for code in kospi_code_list:
    code_name = kiwoom.get_master_code_name(code)
    print(code, code_name)

kosdaq_code_list = kiwoom.get_code_list_by_market("10")
print(kosdaq_code_list)
for code in kosdaq_code_list:
    code_name = kiwoom.get_master_code_name(code)
    print(code, code_name)'''

app.exec_()

 

4. 코드 실행결과

 

또 영업시간이 아니라서...회사에서 다시 실행결과를 돌려봐야겠다..

 

5. 소스코드

 

https://github.com/GaKaRi/python_trading

 

GitHub - GaKaRi/python_trading

Contribute to GaKaRi/python_trading development by creating an account on GitHub.

github.com