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분
글쎄요, 말로만 설명해서 정확히 어떤 상황인지 잘 모르겠습니다.

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

... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13223정성태1/20/20234285오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20233936개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234167Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234320오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20233882Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233813VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234406디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234658디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236184Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235743.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235274오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235037기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235113웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234135Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234040Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20233985.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224289.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
13206정성태12/24/20224502.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [3]파일 다운로드1
13205정성태12/24/20224888.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)파일 다운로드1
13204정성태12/22/20224170.NET Framework: 2082. C# - (LSA_UNICODE_STRING 예제로) CustomMarshaler 사용법파일 다운로드1
13203정성태12/22/20224329.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/20224714기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
13201정성태12/20/20225331오류 유형: 835. PyCharm 사용 시 C 드라이브 용량 부족
13200정성태12/19/20224208오류 유형: 834. 이벤트 로그 - SSL Certificate Settings created by an admin process for endpoint
13199정성태12/19/20224495개발 환경 구성: 656. Internal Network 유형의 스위치로 공유한 Hyper-V의 VM과 호스트가 통신이 안 되는 경우
13198정성태12/18/20224376.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?파일 다운로드1
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...