본문 바로가기

Dev/Python

대신증권 CYBOS plus 자동 접속하기

CYBOS API를 이용한 주식종목 가져오기나 해당 종목의 차트 정보를 가져오는 python 코드 예제들은 검색하면 많이 나오지만, 프로그램을 어느정도 완성 후에 daemon으로 띄우기 위해 필수적인 자동 로그인과 관련된 코드들은 검색을 해도 잘 나오지 않는다. 처음엔 방법이 없는줄 알았는데, 그래도 구글링을 하니 안되는건 없더라..

자동 실행을 위한 패키지를 설치해준다.

# 참고로 CYBOS Plus api가 윈도우만 지원하므로, 해당 패키지 인스톨도 윈도우에서밖에 실행되지 않는다.
> pip install pywin32 pywinauto

cybos 접속 관련 클래스는 다음과 같이 선언하였다.

import win32com.client
from pywinauto import application
import locale
import os
import time
locale.setlocale(locale.LC_ALL, 'ko_KR')

class Cybos:
  g_objCpStatus = None

  def __init__(self):
    self.g_objCpStatus = win32com.client.Dispatch('CpUtil.CpCybos')

  def kill_client(self):
    print("########## 기존 CYBOS 프로세스 강제 종료")
    os.system('taskkill /IM ncStarter* /F /T')
    os.system('taskkill /IM CpStart* /F /T')
    os.system('taskkill /IM DibServer* /F /T')
    os.system('wmic process where "name like \'%ncStarter%\'" call terminate')
    os.system('wmic process where "name like \'%CpStart%\'" call terminate')
    os.system('wmic process where "name like \'%DibServer%\'" call terminate')

  def connect(self, id_, pwd):
    if not self.connected():
      self.disconnect()
      self.kill_client()
      print("########## CYBOS 프로세스 자동 접속")
      app = application.Application()
      # cybos plus를 정보 조회로만 사용했기 때문에 인증서 비밀번호는 입력하지 않았다.
      app.start(
        'C:\Daishin\Starter\\ncStarter.exe /prj:cp /id:{id} /pwd:{pwd} /autostart'.format(id=id_, pwd=pwd)
      )
    while not self.connected():
      time.sleep(1)
    return True

  def connected(self):
    b_connected = self.g_objCpStatus.IsConnect
    if b_connected == 0:
      return False
    return True

  def disconnect(self):
    if self.connected():
      self.g_objCpStatus.PlusDisconnect()

  def waitForRequest(self):
    remainCount = self.g_objCpStatus.GetLimitRemainCount(1)
    if remainCount <= 0:
      time.sleep(self.g_objCpStatus.LimitRequestRemainTime / 1000)

if __name__ == '__main__':
  cybos = Cybos()
  cybos.connect(id, password)