Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 6개 있습니다.)

C# - 키움 Open API+ 사용 시 Registry 등록 없이 KHOpenAPI.ocx 사용하는 방법

아래의 글을 보고,

한 권으로 끝내는 주식 자동매매 프로그램 만들기
; https://wikidocs.net/book/1930

2.2 API 설치하기 환경설정
; https://wikidocs.net/17635

3.1 프로그램에서 HTS처럼 로그인하기
; https://wikidocs.net/17646

실습하는 중에 키움 증권 웹 사이트의,

키움 Open API+
; https://www1.kiwoom.com/nkw.templateFrameSet.do?m=m1408000000

"키움 Open API+ 모듈 다운로드" 링크를 통해 설치를 하게 되면 KHOpenAPI.ocx가 레지스트리에 등록됩니다. 그리고 그것을 사용해 Windows Forms 응용 프로그램을 구성하는 실습을 하게 되는데요. 혹시 이번에도 레지스트리 등록 없이,

Registry 등록 없이 COM 개체 사용
; https://www.sysnet.pe.kr/2/1/262

파일 복사 만으로 실행할 수도 있지 않을까 싶어서 시도를 해봤습니다. ^^




이전에도 설명했지만,

Registry 등록 과정 없이 COM 개체 사용 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/1167

ocx 파일을 레지스트리에 등록하지 않으려면 이를 서술하는 manifest 파일이 있어야 합니다. 그리고 해당 파일에 기술할 정보는 oleview.exe를 이용하면 쉽게 구할 수 있습니다.

khopenapi_regfree_1.png

이를 바탕으로 다음과 같은 2개의 manifest 파일을 만들 수 있고,

[KHOpenAPI.ocx.manifest 파일]
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">

  <assemblyIdentity version="1.0.0.1" processorArchitecture="x86" name="KHOpenAPI.ocx" type="win32">
  </assemblyIdentity>
  
  <file name="KHOpenAPI.ocx">
    <comClass clsid="{a1574a0d-6bfa-4bd7-9020-ded88711818d}" threadingModel="Apartment" tlbid="{6d8c2b4d-ef41-4750-8ad4-c299033833fb}" progid="KHOPENAPI.KHOpenAPICtrl.1" />
    <typelib tlbid="{6d8c2b4d-ef41-4750-8ad4-c299033833fb}" version="1.2" helpdir="" resourceid="0" flags="CONTROL,HASDISKIMAGE" />
  </file>
  <comInterfaceExternalProxyStub name="_DKHOpenAPI" 
                                 iid="{CF20FBB6-EDD4-4BE5-A473-FEF91977DEB6}" 
                                 proxyStubClsid32="{00020424-0000-0000-C000-000000000046}" 
                                 baseInterface="{00000000-0000-0000-C000-000000000046}" 
                                 tlbid="{6d8c2b4d-ef41-4750-8ad4-c299033833fb}">
  </comInterfaceExternalProxyStub>
</assembly>

[WindowsFormsApp1.exe.manifest 파일]
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="asInvoker" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
  
  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
    </application>
  </compatibility>
  
  <dependency>
    <dependentAssembly asmv2:dependencyType="install" asmv2:codebase="KHOpenAPI.ocx.manifest" asmv2:size="1058">
      <assemblyIdentity name="KHOpenAPI.ocx" version="1.0.0.1" processorArchitecture="x86" type="win32" />
    </dependentAssembly>
  </dependency>

</asmv1:assembly>

이 2개의 파일을 프로젝트에 추가 후 "Copy if newer" 옵션으로 설정합니다. 마지막으로 프로젝트 설정 창에서 Application / Resources 영역의 "Manifest" 값을 "Create application without a manifest"로 맞춘 후,

mage_command_line_6.png

빌드하면 됩니다. 물론, "키움 Open API+ 모듈 다운로드"로 설치한 "OpenAPI" 폴더의 모든 파일을 Windows Forms EXE 파일이 있는 폴더에 그대로 복사해줘야 합니다. 이후부터는 해당 폴더를 원하는 PC에 그대로 XCopy(Robocopy) 배포를 하면 끝!

실제로 다음과 같이 로그인 테스트를 호출한 코드 실행 시,

using System;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.axKHOpenAPI1.OnEventConnect += AxKHOpenAPI1_OnEventConnect;
        }

        private void AxKHOpenAPI1_OnEventConnect(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnEventConnectEvent e)
        {
            if (e.nErrCode != 0)
            {
                MessageBox.Show(e.nErrCode.ToString());
            }
            else
            {
                string userId = axKHOpenAPI1.GetLoginInfo("USER_ID");
                this.Text = userId;                
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.axKHOpenAPI1.CommConnect() < 0)
            {
                MessageBox.Show("Failed to call CommConnect API");
            }
        }
    }
}

이렇게 잘 실행되는 것을 확인할 수 있습니다.

khopenapi_regfree_2.png

(이 글의 예제 코드는 github에 등록해 두었으니 참고하세요.)




제가 증권 쪽 API는 처음 보는 것인데, 다소 Legacy스러운 면이 있더군요. 일례로 Unicode를 제대로 지원하지 않아 "Use Unicode UTF-8 for worldwide language support" 옵션이 설정된 윈도우에서는,

cmd_support_han_4.png

다음과 같이 KOA Studio 등의 UI 중 한글이 완전히 깨져나오는 문제가 있습니다.

khopenapi_regfree_3.png

그래도 KOA Studio는 실행이라도 되지만, 영웅문 HTS 프로그램은 아예 실행 도중 비정상 종료를 해버립니다. 심지어 Open API를 사용하는 Windows Forms 응용 프로그램도 로그인하자마자 다음과 같은 이벤트 로그를 남기며,

Log Name:      Application
Source:        .NET Runtime
Date:          2020-01-27 오전 12:16:58
Event ID:      1026
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      TESTPC
Description:
Application: WindowsFormsApp1.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: exception code e06d7363, exception address 761F35D2

비정상 종료를 합니다.

또 하나 Legacy스러운 면이 있다면 x86 32비트만 지원할 뿐 64비트는 지원하지 않는다는 것입니다. 그리고 꽤나 결정적인 문제점인데, 우리가 일반적으로 알고 있는 "Open API"라는 성격에는 맞지 않게 INITECH이나 AhnLab 모듈에 엮어있다는 점과 "로그인"을 하는 방식이 CommConnect 호출 후 별도 프로세스(opstarter.exe)에서 뜬 "로그인 창"을 반드시 거쳐야 한다는 점에서 "서비스화"된 응용 프로그램에서는 사용할 수 없다는 점입니다. (혹시, 이런 제약이 없는 증권사의 OpenAPI를 알고 계신 분은 덧글 부탁드립니다. ^^)




참고로, OCX 컨트롤을 Windows Form에 둔 후 실행했을 때 "((System.ComponentModel.ISupportInitialize)(this.axKHOpenAPI1)).EndInit();" 코드에서 다음과 같은 오류가 발생한다면?

System.Runtime.InteropServices.COMException
  HResult=0x80040154
  Message=Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  Source=System.Windows.Forms
  StackTrace:
   at System.Windows.Forms.UnsafeNativeMethods.CoCreateInstance(Guid& clsid, Object punkOuter, Int32 context, Guid& iid)
   at System.Windows.Forms.AxHost.CreateWithLicense(String license, Guid clsid)
   at System.Windows.Forms.AxHost.CreateInstanceCore(Guid clsid)
   at System.Windows.Forms.AxHost.CreateInstance()
   at System.Windows.Forms.AxHost.GetOcxCreate()
   at System.Windows.Forms.AxHost.TransitionUpTo(Int32 state)
   at System.Windows.Forms.AxHost.CreateHandle()
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.AxHost.EndInit()
   at WindowsFormsApp1.Form1.InitializeComponent() in c:\temp\WindowsFormsApp1\WindowsFormsApp1\Form1.Designer.cs:line 53
   at WindowsFormsApp1.Form1..ctor() in c:\temp\WindowsFormsApp1\WindowsFormsApp1\Form1.cs:line 16
   at WindowsFormsApp1.Program.Main() in c:\temp\WindowsFormsApp1\WindowsFormsApp1\Program.cs:line 18

또는 디버그 없이 실행했다면 이벤트 로그에 이런 오류가 남을 수 있는데,

Log Name:      Application
Source:        .NET Runtime
Date:          1/26/2020 8:15:45 PM
Event ID:      1026
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      TESTPC
Description:
Application: WindowsFormsApp1.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Runtime.InteropServices.COMException
   at System.Windows.Forms.UnsafeNativeMethods.CoCreateInstance(System.Guid ByRef, System.Object, Int32, System.Guid ByRef)
   at System.Windows.Forms.AxHost.CreateWithLicense(System.String, System.Guid)
   at System.Windows.Forms.AxHost.CreateInstanceCore(System.Guid)
   at System.Windows.Forms.AxHost.CreateInstance()
   at System.Windows.Forms.AxHost.GetOcxCreate()
   at System.Windows.Forms.AxHost.TransitionUpTo(Int32)
   at System.Windows.Forms.AxHost.CreateHandle()
   at System.Windows.Forms.Control.CreateControl(Boolean)
   at System.Windows.Forms.Control.CreateControl(Boolean)
   at System.Windows.Forms.AxHost.EndInit()
   at WindowsFormsApp1.Form1.InitializeComponent()
   at WindowsFormsApp1.Form1..ctor()
   at WindowsFormsApp1.Program.Main()

Windows Forms 프로젝트의 출력을 "Any CPU" 또는 "x64"로 한 경우입니다. 즉, (위에서도 언급했지만) "키움 Open API+"는 64비트 환경을 지원하지 않으므로 명시적으로 "x86"으로 설정하고 빌드해야 합니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/20/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2020-07-03 05시39분
[Castiel] 감사합니다. 덕분에 해결하였습니다.
[guest]
2022-10-12 05시04분
[여요] 안녕하세요...글 잘 보았습니다.
c# 키움 api에서요 TR 데이타를 엑셀에 넣으려면 에러가 나는데요
제가 만든 메서드에서는 잘 넣어지는데 이상하게도
증권사에서 받은 데이타는 안넣어지네요.....
c# 윈폼에서 그리드뷰를 안쓰고 엑셀을 쓰려고 하는데요
왜 안될까요?
[guest]
2022-10-12 11시12분
글쎄요, 말로만 설명해서 정확히 어떤 상황인지 잘 모르겠습니다.

최소한의 재현 코드를 담은 프로젝트를 첨부해 다시 질문해 주세요
정성태

1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13372정성태6/15/20233110개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233132개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233295개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233092개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233224개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233328오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233130.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232895오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233677.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233240스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233163.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233638오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233034오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233352오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233659.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233464.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233769DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233684.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20233954.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233567.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234068VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233318오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233645.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233568.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20233929.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233775오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...