KHOpenApi.NET 1.5.7

dotnet add package KHOpenApi.NET --version 1.5.7                
NuGet\Install-Package KHOpenApi.NET -Version 1.5.7                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="KHOpenApi.NET" Version="1.5.7" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add KHOpenApi.NET --version 1.5.7                
#r "nuget: KHOpenApi.NET, 1.5.7"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install KHOpenApi.NET as a Cake Addin
#addin nuget:?package=KHOpenApi.NET&version=1.5.7

// Install KHOpenApi.NET as a Cake Tool
#tool nuget:?package=KHOpenApi.NET&version=1.5.7                

NuGet version KHOpenApi.NET (영웅문-Hero, 영웅문-Global)

  • 키움증권 OpenApi C# wrapper class
  • 개발환경: Visual Studio 2022, netstandard2.0
  • WinUI3, WPF, Winforms 지원
  • 비동기 로그인, TR 요청 지원 (CommConnectAsync, CommRqDataAsync, CommKwRqDataAsync, GetConditionLoadAsync, SendConditionAsync)
  • 비동기 주문 지원 (SendOrderAsync, SendOrderFOAsync, SendOrderCreditAsync)
  • 비동기 간편 TR 요청 지원 (RequestTrAsync)


1. WPF

MainWindow.xaml.cs
    public partial class MainWindow : Window
    {
        // ocx인터페이스 추가
        private AxKHOpenAPI axKHOpenAPI; // 국내 (영웅문)
        private AxKFOpenAPI axKFOpenAPI; // 해외 (영웅문 글로벌)

        public MainWindow()
        {
            InitializeComponent();
            // ActiveX 세팅
            var Handle = new WindowInteropHelper(Application.Current.MainWindow).EnsureHandle();

            axKHOpenAPI = new AxKHOpenAPI(Handle);
            button_login_KH.IsEnabled = axKHOpenAPI.Created;

            axKFOpenAPI = new AxKFOpenAPI(Handle);
            button_login_KF.IsEnabled = axKFOpenAPI.Created;
        }

        private async void button_login_KH_Click(object sender, RoutedEventArgs e)
        {
            // 국내 로그인 요청
            log_list.Items.Add("국내 로그인 요청중...");
            var (ret, msg) = await axKHOpenAPI.CommConnectAsync();
            if (ret == 0)
            {
                log_list.Items.Add("국내 로그인 성공");
            }
            else
            {
                log_list.Items.Add("국내 로그인 실패: " + msg);
            }
        }

        private async void button_login_KF_Click(object sender, RoutedEventArgs e)
        {
            // 해외 로그인 요청
            log_list.Items.Add("해외 로그인 요청중...");
            var (ret, msg) = await axKFOpenAPI.CommConnectAsync(1);
            if (ret == 0)
            {
                log_list.Items.Add("해외 로그인 성공");
            }
            else
            {
                log_list.Items.Add("해외 로그인 실패: " + msg);
            }
        }

비동기 함수 지원
        // 로그인, 조건식 로딩 (CommConnectAsync, GetConditionLoadAsync)
        // TR 요청 (CommRqDataAsync, CommKwRqDataAsync, SendConditionAsync)
        // 간편요청 (RequestTrAsync)
        // 주문 (SendOrderAsync, SendOrderFOAsync, SendOrderFOAsync, SendOrderCreditAsync)

        // 비동기 로그인, 조건식 로딩 (nuget 버전 1.5.0 이상 지원)
        async Task TestLoginAsync()
        {
            var (nRet, sMsg) = await axKHOpenAPI.CommConnectAsync();
            if (0 != nRet)
            {
                OutLog($"로그인 실패: {sMsg}");
                return;
            }
            (nRet, sMsg) = await axKHOpenAPI.GetConditionLoadAsync();
            if (1 != nRet)
            {
                OutLog($"사용자 조건검색리스트요청 실패: {sMsg}");
                return;
            }

            var cond_list = sMsg.Split(';', StringSplitOptions.RemoveEmptyEntries).ToList();
            OutLog($"조건검색식 개수: {cond_list.Count}");

            // DoWork...
        }

        // 비동기 요청 (nuget 버전 1.5.0 이상 지원)
        async Task TestRequestAsync()
        {
            // 국내 종목정보 가져오기
            string itemCode = "005930";
            axKHOpenAPI.SetInputValue("종목코드", itemCode);
            string 종목명 = string.Empty;
            var (nRet, sMsg) = await axKHOpenAPI.CommRqDataAsync("주식기본정보요청", "OPT10001", 0, "1000", e =>
            {
                종목명 = axKHOpenAPI.GetCommData(e.sTrCode, e.sRQName, 0, "종목명").Trim();
            });
            // nRet: 0 성공, 음수 실패(sMsg에 오류내용)
            if (nRet == 0)
                log_list.Items.Add(종목명);
            else
                log_list.Items.Add($"비동기 요청실패: {sMsg}");
        }

        // 비동기 간편요청 (nuget 버전 1.5.3 이상 지원)
        async Task TestSimpleRequestAsync()
        {
            // 샘플 1: 주식기본정보요청
            var response = await api.RequestTrAsync(
                "OPT10001" // TR코드
                , [("종목코드", "005930")] // 입력데이터, 또는 Dictionary<string, string> 형태로 입력
                , ["종목명", "액면가", "영업이익", "시가", "고가", "저가", "현재가", "거래량"] // 가져올 싱글데이터
                , [] // 가져올 멀티데이터
                );
            
            // 샘플 2: 주식일봉차트조회요청
            var indatas = new Dictionary<string, string> 
            {
                { "종목코드", "005930" },
                { "기준일자", "20240704" },
                { "수정주가구분", "1" }
            };
            var response = await axKHOpenAPI.RequestTrAsync("OPT10081", indatas, ["종목코드"], ["일자", "현재가", "거래량"]);
            
            // 샘플 3: 관심종목정보요청
            var response = await axKHOpenAPI.RequestTrAsync("OPTKWFID", [("종목코드", "005930")], [], ["종목명", "현재가", "기준가", "시가", "고가", "저가"]);
            
            // 샘플 4: 거래대금상위요청
            var response = await api.RequestTrAsync(
                "OPT10032" // 거래대금상위요청
                , [
                    ("시장구분", "000"), // 000:전체, 001:코스피, 101:코스닥
                    ("관리종목포함", "0"), // 0:관리종목 미포함, 1:관리종목 포함
                    ]
                , [] // 가져올 싱글데이터
                , ["종목코드", "종목명", "현재순위", "전일순위", "현재가", "전일대비", "등락률", "현재거래량", "전일거래량", "거래대금"] // 가져올 멀티데이터
                );
            
            // 결과처리
            if (response.nErrCode == 0)
            {
                // 요청성공, response.OutputSingleDatas, response.OutputMultiDatas 에 결과가 있음
            }
            else
            {
                // 요청실패, response.rsp_msg 에 오류메시지가 있음
            }
        }

        // 비동기 조건검색 (nuget 버전 1.5.3 이상 지원)
        async Task TestConditionAsync()
        {
            var (nRet, sMsg) = await api.SendConditionAsync("8001", conditionInfo.Name, conditionInfo.Code, 0);
            if (nRet != 1)
            {
                print($"검색식 요청실패: {sMsg}");
                return;
            }
            // sMsg 에 검색된 종목코드가 있음 (세미콜론으로 구분 종목코드1;종목코드2..., 또는 현재가 포함 설정시 종목코드1^현재가1;종목코드2^현재가2 ...로 구분))
        }

        // 비동기 주문 (nuget 버전 1.5.3 이상 지원)
        async Task TestOrderAsync()
        {
            // 삼성전자 주식 1주, 80000원 지정가 매수주문
            string itemCode = "005930";
            int qty = 1;
            int price = 80000;
            var (nRet, sMsg) = await axKHOpenAPI.SendOrderAsync("매수주문", "0101", 계좌번호, 1, itemCode, qty, price, "00", string.Empty);

            // 결과처리
            if (nRet != 0)
            {
                print($"주문 요청실패: {sMsg}"); // 실패사유 출력
                return;
            }

            // 주문성공, 서버까지 주문 전달이 확실히 성공 되었음
        }
    }


2. WinForms

Form1.cs
    public partial class Form1 : Form
    {
        // ocx인터페이스 추가
        private AxKHOpenAPI axKHOpenAPI; // 국내 (영웅문)
        private AxKFOpenAPI axKFOpenAPI; // 해외 (영웅문 글로벌)

        public Form1()
        {
            InitializeComponent();

            // ActiveX 세팅
            axKHOpenAPI = new AxKHOpenAPI(Handle);

            // WPF샘플과 동일
            ...
        }
        ...
    }


3. WinUI3 (target platforms: x86/x64, UnPackaged)

*WinuUI3 x86모드에서 글로벌OpenApi는 오류발생, x64모드에서는 오류없음

MainWindow.xaml.cs
    public sealed partial class MainWindow : Window
    {
        // ocx인터페이스 추가
        private AxKHOpenAPI axKHOpenAPI; // 국내 (영웅문)
        private AxKFOpenAPI axKFOpenAPI; // 해외 (영웅문 글로벌)

        public MainWindow()
        {
            this.InitializeComponent();
            // ActiveX 세팅
            System.IntPtr Handle = WinRT.Interop.WindowNative.GetWindowHandle(this);

            axKHOpenAPI = new AxKHOpenAPI(Handle);

            // WPF샘플과 동일
            ...
        }
        ...
    }

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.5.7 34 11/1/2024
1.5.6 93 10/2/2024
1.5.4 132 8/12/2024
1.5.3 168 7/21/2024
1.5.2 211 3/31/2024
1.5.1 306 2/18/2024
1.5.0 385 1/9/2024
1.4.0 473 11/5/2023
1.3.0 669 1/14/2023
1.1.0 721 9/21/2022
1.0.4 822 8/23/2022
1.0.3 711 8/22/2022
1.0.2 706 8/20/2022
1.0.1 679 8/19/2022