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

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

... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11273정성태8/22/201721624오류 유형: 415. 윈도우 업데이트 에러 Error 0x80070643
11272정성태8/21/201724745VS.NET IDE: 120. 비주얼 스튜디오 2017 버전 15.3.1 - C# 7.1 공개 [2]
11271정성태8/19/201719166VS.NET IDE: 119. Visual Studio 2017에서 .NET Core 2.0 프로젝트 환경 구성하는 방법
11270정성태8/17/201730607.NET Framework: 673. C#에서 enum을 boxing 없이 int로 변환하기 [2]
11269정성태8/17/201721414디버깅 기술: 93. windbg - 풀 덤프에서 .NET 스레드의 상태를 알아내는 방법
11268정성태8/14/201720992디버깅 기술: 92. windbg - C# Monitor Lock을 획득하고 있는 스레드 찾는 방법
11267정성태8/10/201725074.NET Framework: 672. 모노 개발 환경
11266정성태8/10/201724862.NET Framework: 671. C# 6.0 이상의 소스 코드를 Visual Studio 설치 없이 명령행에서 컴파일하는 방법
11265정성태8/10/201753124기타: 66. 도서: 시작하세요! C# 7.1 프로그래밍: 기본 문법부터 실전 예제까지 [11]
11264정성태8/9/201724001오류 유형: 414. UWP app을 signtool.exe로 서명 시 0x8007000b 오류 발생
11263정성태8/9/201719471오류 유형: 413. The C# project "..." is targeting ".NETFramework, Version=v4.0", which is not installed on this machine. [3]
11262정성태8/5/201718203오류 유형: 412. windbg - SOS does not support the current target architecture. [3]
11261정성태8/4/201720775디버깅 기술: 91. windbg - 풀 덤프 파일로부터 강력한 이름의 어셈블리 추출 후 사용하는 방법
11260정성태8/3/201718868.NET Framework: 670. C# - 실행 파일로부터 공개키를 추출하는 방법
11259정성태8/2/201718128.NET Framework: 669. 지연 서명된 어셈블리를 sn.exe -Vr 등록 없이 사용하는 방법
11258정성태8/1/201718892.NET Framework: 668. 지연 서명된 DLL과 서명된 DLL의 차이점파일 다운로드1
11257정성태7/31/201719128.NET Framework: 667. bypassTrustedAppStrongNames 옵션 설명파일 다운로드1
11256정성태7/25/201720580디버깅 기술: 90. windbg의 lm 명령으로 보이지 않는 .NET 4.0 ClassLibrary를 명시적으로 로드하는 방법 [1]
11255정성태7/18/201723161디버깅 기술: 89. Win32 Debug CRT Heap Internals의 0xBAADF00D 표시 재현 [1]파일 다운로드3
11254정성태7/17/201719475개발 환경 구성: 322. "Visual Studio Emulator for Android" 에뮬레이터를 "Android Studio"와 함께 쓰는 방법
11253정성태7/17/201719740Math: 21. "Coding the Matrix" 문제 2.5.1 풀이 [1]파일 다운로드1
11252정성태7/13/201718413오류 유형: 411. RTVS 또는 PTVS 실행 시 Could not load type 'Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowFactory2'
11251정성태7/13/201717062디버깅 기술: 88. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 (2)
11250정성태7/13/201720662디버깅 기술: 87. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 [1]
11249정성태7/12/201718453오류 유형: 410. LoadLibrary("[...].dll") failed - The specified procedure could not be found.
11248정성태7/12/201724908오류 유형: 409. pip install pefile - 'cp949' codec can't decode byte 0xe2 in position 208687: illegal multibyte sequence
... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...