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)
13473정성태12/5/20232307닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232134C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232163Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232475닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232186닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232172닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232166오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232376닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232108개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232212닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232115오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232188오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232246닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232208닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232192닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232197닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232149VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232442닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232329닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232675닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232211오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232294닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232425닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232251닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232347개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232620닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...