■ 키움증권의 OpenAPI를 사용하는 방법을 보여준다. (기능 개선)
▶ TimeSleepManager.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
using System; using System.Threading; namespace TestProject { /// <summary> /// 시간 휴지 관리자 /// </summary> public static class TimeSleepManager { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 마지막 틱 카운트 /// </summary> public static long LastTickCount; #endregion //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 전체 시간 1 /// </summary> private static int _totalTime1 = 0; /// <summary> /// 카운트 1 /// </summary> private static int _count1; /// <summary> /// 전체 시간 2 /// </summary> private static int _totalTime2 = 0; /// <summary> /// 카운트 2 /// </summary> private static int _count2; /// <summary> /// 전체 시간 3 /// </summary> private static int _totalTime3 = 0; /// <summary> /// 카운트 3 /// </summary> private static int _count3; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 시작하기 - Start() /// <summary> /// 시작하기 /// </summary> public static void Start() { LastTickCount = DateTime.Now.Ticks; } #endregion #region 휴지하기 - Sleep() /// <summary> /// 휴지하기 /// </summary> public static void Sleep() { long currentTickCount = DateTime.Now.Ticks; int deltaTime = (int)((currentTickCount - LastTickCount) / 10000d); //Console.WriteLine($"작업 시간 : {deltaTime}"); LastTickCount = currentTickCount; _count1++; _totalTime1 += deltaTime; int sleep1; if(_count1 == 5) // 5번 { if(_totalTime1 >= 1000) // 1초 { sleep1 = 0; } else { sleep1 = 1000 - _totalTime1; } _count1 = 0; _totalTime1 = 0; } else { sleep1 = 0; } _count3++; _totalTime3 += deltaTime; int sleep3; if(_count3 == 100) // 200번 { if(_totalTime3 >= 30000) // 30초 { sleep3 = 0; } else { sleep3 = 30000 - _totalTime1; } _count3 = 0; _totalTime3 = 0; } else { sleep3 = 0; } _count2++; _totalTime2 += deltaTime; int sleep2; if(_count2 == 1000) // 1,000번 { if(_totalTime2 >= 3600000) // 60분 { sleep2 = 0; } else { sleep2 = 3600000 - _totalTime2; } _count2 = 0; _totalTime2 = 0; } else { sleep2 = 0; } int finalSleep; if(sleep1 > sleep2 && sleep1 > sleep3) { finalSleep = sleep1; } else if(sleep2 > sleep1 && sleep2 > sleep3) { finalSleep = sleep2; } else { finalSleep = sleep3; } if(finalSleep > 0) { Thread.Sleep(finalSleep); LastTickCount = DateTime.Now.Ticks; } } #endregion } } |
▶ TransactionDataType.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
namespace TestProject { /// <summary> /// 트랜잭션 데이터 타입 /// </summary> public enum TransactionDataType { /// <summary> /// 단일 /// </summary> Single, /// <summary> /// 복수 /// </summary> Multiple, /// <summary> /// 복수 (첫번째 페이지만) /// </summary> MultipleFirstPage } } |
▶ IMessageForm.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
namespace TestProject { /// <summary> /// 메시지 폼 인터페이스 /// </summary> public interface IMessageForm { //////////////////////////////////////////////////////////////////////////////////////////////////// Method #region 메시지 추가하기 - AddMessage(formatString, argumentArray) /// <summary> /// 메시지 추가하기 /// </summary> /// <param name="formatString">포맷 문자열</param> /// <param name="argumentArray">인자 배열</param> void AddMessage(string formatString, params object[] argumentArray); #endregion } } |
▶ TransactionDataRequest.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 |
using System; using System.Collections.Generic; using System.Threading; using System.Windows.Forms; namespace TestProject { /// <summary> /// 트랜잭션 데이터 요청 /// </summary> /// <typeparam name="TItem">항목 타입</typeparam> public class TransactionDataRequest<TItem> : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Protected #region Field /// <summary> /// 메시지 폼 /// </summary> private IMessageForm messageForm; /// <summary> /// HTS /// </summary> protected AxKHOpenAPILib.AxKHOpenAPI hts; /// <summary> /// 요청명 /// </summary> protected string requestName; /// <summary> /// 트랜잭션 코드 /// </summary> protected string transactionCode; /// <summary> /// 화면 번호 /// </summary> protected string screenNumber; /// <summary> /// 리소스 해제 여부 /// </summary> protected bool disposed = false; /// <summary> /// 작업 여부 /// </summary> protected bool isWorking = false; /// <summary> /// 입력값 딕셔너리 /// </summary> protected Dictionary<string, string> inputValueDictionary = new Dictionary<string, string>(); /// <summary> /// 결과 리스트 /// </summary> protected List<TItem> resultList = new List<TItem>(); /// <summary> /// 트랜잭션 데이터 타입 /// </summary> protected TransactionDataType dataType; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 입력값 딕셔너리 - InputValueDictionary /// <summary> /// 입력값 딕셔너리 /// </summary> public Dictionary<string, string> InputValueDictionary { get { return this.inputValueDictionary; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - TransactionDataRequest(messageForm, hts, requestName, transactionCode, screenNumber, dataType) /// <summary> /// 생성자 /// </summary> /// <param name="messageForm">메시지 폼</param> /// <param name="hts">HTS</param> /// <param name="requestName">요청명</param> /// <param name="transactionCode">트랜잭션 코드</param> /// <param name="screenNumber">화면 번호</param> /// <param name="dataType">트래잭션 데이터 타입</param> public TransactionDataRequest ( IMessageForm messageForm, AxKHOpenAPILib.AxKHOpenAPI hts, string requestName, string transactionCode, string screenNumber, TransactionDataType dataType ) { this.messageForm = messageForm; this.hts = hts; this.requestName = requestName; this.transactionCode = transactionCode; this.screenNumber = screenNumber; this.dataType = dataType; this.hts.OnReceiveTrData += hts_OnReceiveTrData; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public //////////////////////////////////////////////////////////////////////////////// Function #region 리스트 구하기 - GetList() /// <summary> /// 리스트 구하기 /// </summary> /// <returns>리스트</returns> public List<TItem> GetList() { try { this.isWorking = true; foreach(KeyValuePair<string, string> keyValuePair in this.inputValueDictionary) { this.hts.SetInputValue(keyValuePair.Key, keyValuePair.Value); } TimeSleepManager.Start(); int returnCode = this.hts.CommRqData(this.requestName, this.transactionCode, 0, this.screenNumber); if(returnCode == 0) { while(this.isWorking) { Thread.Sleep(300); Application.DoEvents(); } return this.resultList; } else { return null; } } finally { this.isWorking = false; } } #endregion #region (IDisposable) 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected //////////////////////////////////////////////////////////////////////////////// Function #region 항목 구하기 - GetItem(e, index) /// <summary> /// 항목 구하기 /// </summary> /// <param name="e">이벤트 인자</param> /// <param name="index">인덱스</param> /// <returns>항목</returns> protected virtual TItem GetItem(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveTrDataEvent e, int index) { return default(TItem); } #endregion #region 리소스 해제하기 - Dispose(disposing) /// <summary> /// 리소스 해제하기 /// </summary> /// <param name="disposing">리소스 해제 여부</param> protected virtual void Dispose(bool disposing) { if(!this.disposed) { if(disposing) { this.hts.OnReceiveTrData -= hts_OnReceiveTrData; if(this.resultList != null) { this.resultList.Clear(); this.resultList = null; } this.disposed = true; } } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region HTS 트랜잭션 데이터 수신시 처리하기 - hts_OnReceiveTrData(sender, e) /// <summary> /// HTS 트랜잭션 데이터 수신시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void hts_OnReceiveTrData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveTrDataEvent e) { if(e.sRQName != this.requestName && e.sTrCode != this.transactionCode && e.sScrNo != this.screenNumber) { return; } if(this.dataType == TransactionDataType.Single) { TItem item = GetItem(e, 0); this.resultList.Add(item); } else { int itemCount = this.hts.GetRepeatCnt(e.sTrCode, e.sRQName); for(int i = 0; i < itemCount; i++) { TItem item = GetItem(e, i); this.resultList.Add(item); } } if((this.dataType != TransactionDataType.Single) && (this.dataType != TransactionDataType.MultipleFirstPage) && (e.sPrevNext == "2")) { foreach(KeyValuePair<string, string> keyValuePair in this.inputValueDictionary) { this.hts.SetInputValue(keyValuePair.Key, keyValuePair.Value); } TimeSleepManager.Sleep(); this.messageForm?.AddMessage($"{DateTime.Now.ToString("HH:mm:ss")} : 후속 데이터를 호출합니다."); int returnCode = this.hts.CommRqData(this.requestName, this.transactionCode, 2, this.screenNumber); if(returnCode != 0) { this.resultList.Clear(); this.resultList = null; this.isWorking = false; } } else { this.isWorking = false; } } #endregion } } |
▶ 일별거래상세항목.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
namespace TestProject { /// <summary> /// 일별거래상세항목 /// </summary> public class 일별거래상세항목 { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public public string 일자 { get; set; } public string 종가 { get; set; } public string 전일대비기호 { get; set; } public string 전일대비 { get; set; } public string 등락율 { get; set; } public string 거래량 { get; set; } public string 거래대금 { get; set; } public string 장전거래량 { get; set; } public string 장전거래비중 { get; set; } public string 장중거래량 { get; set; } public string 장중거래비중 { get; set; } public string 합계3 { get; set; } public string 기간중거래량 { get; set; } public string 체결강도 { get; set; } public string 외인보유 { get; set; } public string 외인비중 { get; set; } public string 외인순매수 { get; set; } public string 기관순매수 { get; set; } public string 개인순매수 { get; set; } public string 외국계 { get; set; } public string 신용잔고율 { get; set; } public string 프로그램 { get; set; } public string 장전거래대금 { get; set; } public string 장전거래대금비중 { get; set; } public string 장중거래대금 { get; set; } public string 장중거래대금비중 { get; set; } public string 장후거래대금 { get; set; } public string 장후거래대금비중 { get; set; } } } |
▶ 일별거래상세요청.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
namespace TestProject { /// <summary> /// 일별거래상세요청 /// </summary> public class 일별거래상세요청 : TransactionDataRequest<일별거래상세항목> { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - 일별거래상세요청(messageForm, hts, dataType) /// <summary> /// 생성자 /// </summary> /// <param name="messageForm">메시지 폼</param> /// <param name="hts">HTS</param> /// <param name="dataType">트랜잭션 데이터 타입</param> public 일별거래상세요청 ( IMessageForm messageForm, AxKHOpenAPILib.AxKHOpenAPI hts, TransactionDataType dataType ) : base(messageForm, hts, "일별거래상세", "OPT10015", "0001", dataType) { } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected //////////////////////////////////////////////////////////////////////////////// Function #region 항목 구하기 - GetItem(e, index) /// <summary> /// 항목 구하기 /// </summary> /// <param name="e">이벤트 인자</param> /// <param name="index">인덱스</param> /// <returns>항목</returns> protected override 일별거래상세항목 GetItem(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveTrDataEvent e, int index) { string 일자 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "일자" ).Trim(); string 종가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "종가" ).Trim(); string 전일대비기호 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "전일대비기호" ).Trim(); string 전일대비 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "전일대비" ).Trim(); string 등락율 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "등락율" ).Trim(); string 거래량 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "거래량" ).Trim(); string 거래대금 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "거래대금" ).Trim(); string 장전거래량 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "장전거래량" ).Trim(); string 장전거래비중 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "장전거래비중" ).Trim(); string 장중거래량 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "장중거래량" ).Trim(); string 장중거래비중 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "장중거래비중" ).Trim(); string 합계3 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "합계3" ).Trim(); string 기간중거래량 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "기간중거래량" ).Trim(); string 체결강도 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "체결강도" ).Trim(); string 외인보유 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "외인보유" ).Trim(); string 외인비중 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "외인비중" ).Trim(); string 외인순매수 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "외인순매수" ).Trim(); string 기관순매수 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "기관순매수" ).Trim(); string 개인순매수 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "개인순매수" ).Trim(); string 외국계 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "외국계" ).Trim(); string 신용잔고율 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "신용잔고율" ).Trim(); string 프로그램 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "프로그램" ).Trim(); string 장전거래대금 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "장전거래대금" ).Trim(); string 장전거래대금비중 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "장전거래대금비중").Trim(); string 장중거래대금 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "장중거래대금" ).Trim(); string 장중거래대금비중 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "장중거래대금비중").Trim(); string 장후거래대금 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "장후거래대금" ).Trim(); string 장후거래대금비중 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "장후거래대금비중").Trim(); 일별거래상세항목 item = new 일별거래상세항목(); item.일자 = 일자; item.종가 = 종가; item.전일대비기호 = 전일대비기호; item.전일대비 = 전일대비; item.등락율 = 등락율; item.거래량 = 거래량; item.거래대금 = 거래대금; item.장전거래량 = 장전거래량; item.장전거래비중 = 장전거래비중; item.장중거래량 = 장중거래량; item.장중거래비중 = 장중거래비중; item.합계3 = 합계3; item.기간중거래량 = 기간중거래량; item.체결강도 = 체결강도; item.외인보유 = 외인보유; item.외인비중 = 외인비중; item.외인순매수 = 외인순매수; item.기관순매수 = 기관순매수; item.개인순매수 = 개인순매수; item.외국계 = 외국계; item.신용잔고율 = 신용잔고율; item.프로그램 = 프로그램; item.장전거래대금 = 장전거래대금; item.장전거래대금비중 = 장전거래대금비중; item.장중거래대금 = 장중거래대금; item.장중거래대금비중 = 장중거래대금비중; item.장후거래대금 = 장후거래대금; item.장후거래대금비중 = 장후거래대금비중; return item; } #endregion } } |
▶ 주식기본정보항목.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
namespace TestProject { /// <summary> /// 주식기본정보항목 /// </summary> public class 주식기본정보항목 { public string 종목코드 { get; set; } public string 종목명 { get; set; } public string 결산월 { get; set; } public string 액면가 { get; set; } public string 자본금 { get; set; } public string 상장주식 { get; set; } public string 신용비율 { get; set; } public string 연중최고 { get; set; } public string 연중최저 { get; set; } public string 시가총액 { get; set; } public string 시가총액비중 { get; set; } public string 외인소진률 { get; set; } public string 대용가 { get; set; } public string PER { get; set; } public string EPS { get; set; } public string ROE { get; set; } public string PBR { get; set; } public string EV { get; set; } public string BPS { get; set; } public string 매출액 { get; set; } public string 영업이익 { get; set; } public string 당기순이익 { get; set; } public string D250최고 { get; set; } // 250최고 public string D250최저 { get; set; } // 250최저 public string 시가 { get; set; } public string 고가 { get; set; } public string 저가 { get; set; } public string 상한가 { get; set; } public string 하한가 { get; set; } public string 기준가 { get; set; } public string 예상체결가 { get; set; } public string 예상체결수량 { get; set; } public string D250최고가일 { get; set; } // 250최고가일 public string D250최고가대비율 { get; set; } // 250최고가대비율 public string D250최저가일 { get; set; } // 250최저가일 public string D250최저가대비율 { get; set; } // 250최저가대비율 public string 현재가 { get; set; } public string 대비기호 { get; set; } public string 전일대비 { get; set; } public string 등락율 { get; set; } public string 거래량 { get; set; } public string 거래대비 { get; set; } public string 액면가단위 { get; set; } } } |
▶ 주식기본정보요청.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
namespace TestProject { /// <summary> /// 주식기본정보요청 /// </summary> public class 주식기본정보요청 : TransactionDataRequest<주식기본정보항목> { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - 주식기본정보요청(messageForm, hts) /// <summary> /// 생성자 /// </summary> /// <param name="messageForm">메시지 폼</param> /// <param name="hts">HTS</param> public 주식기본정보요청 ( IMessageForm messageForm, AxKHOpenAPILib.AxKHOpenAPI hts ) : base(messageForm, hts, "주식기본정보", "OPT10001", "0001", TransactionDataType.Single) { } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected //////////////////////////////////////////////////////////////////////////////// Function #region 항목 구하기 - GetItem(e, index) /// <summary> /// 항목 구하기 /// </summary> /// <param name="e">이벤트 인자</param> /// <param name="index">인덱스</param> /// <returns>항목</returns> protected override 주식기본정보항목 GetItem(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveTrDataEvent e, int index) { string 종목코드 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "종목코드" ).Trim(); string 종목명 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "종목명" ).Trim(); string 결산월 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "결산월" ).Trim(); string 액면가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "액면가" ).Trim(); string 자본금 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "자본금" ).Trim(); string 상장주식 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "상장주식" ).Trim(); string 신용비율 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "신용비율" ).Trim(); string 연중최고 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "연중최고" ).Trim(); string 연중최저 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "연중최저" ).Trim(); string 시가총액 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "시가총액" ).Trim(); string 시가총액비중 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "시가총액비중" ).Trim(); string 외인소진률 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "외인소진률" ).Trim(); string 대용가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "대용가" ).Trim(); string PER = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "PER" ).Trim(); string EPS = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "EPS" ).Trim(); string ROE = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "ROE" ).Trim(); string PBR = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "PBR" ).Trim(); string EV = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "EV" ).Trim(); string BPS = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "BPS" ).Trim(); string 매출액 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "매출액" ).Trim(); string 영업이익 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "영업이익" ).Trim(); string 당기순이익 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "당기순이익" ).Trim(); string D250최고 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "250최고" ).Trim(); string D250최저 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "250최저" ).Trim(); string 시가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "시가" ).Trim(); string 고가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "고가" ).Trim(); string 저가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "저가" ).Trim(); string 상한가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "상한가" ).Trim(); string 하한가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "하한가" ).Trim(); string 기준가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "기준가" ).Trim(); string 예상체결가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "예상체결가" ).Trim(); string 예상체결수량 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "예상체결수량" ).Trim(); string D250최고가일 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "250최고가일" ).Trim(); string D250최고가대비율 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "250최고가대비율").Trim(); string D250최저가일 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "250최저가일" ).Trim(); string D250최저가대비율 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "250최저가대비율").Trim(); string 현재가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "현재가" ).Trim(); string 대비기호 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "대비기호" ).Trim(); string 전일대비 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "전일대비" ).Trim(); string 등락율 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "등락율" ).Trim(); string 거래량 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "거래량" ).Trim(); string 거래대비 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "거래대비" ).Trim(); string 액면가단위 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, 0, "액면가단위" ).Trim(); 주식기본정보항목 item = new 주식기본정보항목(); item.종목코드 = 종목코드; item.종목명 = 종목명; item.결산월 = 결산월; item.액면가 = 액면가; item.자본금 = 자본금; item.상장주식 = 상장주식; item.신용비율 = 신용비율; item.연중최고 = 연중최고; item.연중최저 = 연중최저; item.시가총액 = 시가총액; item.시가총액비중 = 시가총액비중; item.외인소진률 = 외인소진률; item.대용가 = 대용가; item.PER = PER; item.EPS = EPS; item.ROE = ROE; item.PBR = PBR; item.EV = EV; item.BPS = BPS; item.매출액 = 매출액; item.영업이익 = 영업이익; item.당기순이익 = 당기순이익; item.D250최고 = D250최고; item.D250최저 = D250최저; item.시가 = 시가; item.고가 = 고가; item.저가 = 저가; item.상한가 = 상한가; item.하한가 = 하한가; item.기준가 = 기준가; item.예상체결가 = 예상체결가; item.예상체결수량 = 예상체결수량; item.D250최고가일 = D250최고가일; item.D250최고가대비율 = D250최고가대비율; item.D250최저가일 = D250최저가일; item.D250최저가대비율 = D250최저가대비율; item.현재가 = 현재가; item.대비기호 = 대비기호; item.전일대비 = 전일대비; item.등락율 = 등락율; item.거래량 = 거래량; item.거래대비 = 거래대비; item.액면가단위 = 액면가단위; return item; } #endregion } } |
▶ 주식일봉차트항목.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
namespace TestProject { /// <summary> /// 주식일봉차트항목 /// </summary> public class 주식일봉차트항목 { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public public string 현재가 { get; set; } public string 거래량 { get; set; } public string 거래대금 { get; set; } public string 일자 { get; set; } public string 시가 { get; set; } public string 고가 { get; set; } public string 저가 { get; set; } } } |
▶ 주식일봉차트조회요청.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
namespace TestProject { /// <summary> /// 주식일봉차트조회요청 /// </summary> public class 주식일봉차트조회요청 : TransactionDataRequest<주식일봉차트항목> { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - 주식일봉차트조회요청(messageForm, hts, dataType) /// <summary> /// 생성자 /// </summary> /// <param name="messageForm">메시지 폼</param> /// <param name="hts">HTS</param> /// <param name="dataType">트랜잭션 데이터 타입</param> public 주식일봉차트조회요청 ( IMessageForm messageForm, AxKHOpenAPILib.AxKHOpenAPI hts, TransactionDataType dataType ) : base(messageForm, hts, "주식일봉차트조회", "OPT10081", "0001", dataType) { } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected //////////////////////////////////////////////////////////////////////////////// Function #region 항목 구하기 - GetItem(e, index) /// <summary> /// 항목 구하기 /// </summary> /// <param name="e">이벤트 인자</param> /// <param name="index">인덱스</param> /// <returns>항목</returns> protected override 주식일봉차트항목 GetItem(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveTrDataEvent e, int index) { string 현재가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "현재가" ).Trim(); string 거래량 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "거래량" ).Trim(); string 거래대금 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "거래대금").Trim(); string 일자 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "일자" ).Trim(); string 시가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "시가" ).Trim(); string 고가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "고가" ).Trim(); string 저가 = this.hts.CommGetData(e.sTrCode, string.Empty, e.sRQName, index, "저가" ).Trim(); 주식일봉차트항목 item = new 주식일봉차트항목(); item.현재가 = 현재가; item.거래량 = 거래량; item.거래대금 = 거래대금; item.일자 = 일자; item.시가 = 시가; item.고가 = 고가; item.저가 = 저가; return item; } #endregion } } |
▶ MainForm.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
using System; using System.Collections.Generic; using System.Windows.Forms; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form, IMessageForm { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 로그인 여부 /// </summary> private bool isLogIn = false; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); FormClosing += Form_FormClosing; this.loginButton.Click += loginButton_Click; this.logoutButton.Click += logOutButton_Click; this.주식기본정보요청Button.Click += 주식기본정보요청Button_Click; this.주식일봉차트조회요청Button.Click += 주식일봉차트조회요청Button_Click; this.일별거래상세요청Button.Click += 일별거래상세요청Button_Click; this.종목코드Button.Click += 종목코드Button_Click; this.hts.OnEventConnect += hts_OnEventConnect; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 폼 닫을 경우 처리하기 - Form_FormClosing(sender, e) /// <summary> /// 폼 닫을 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_FormClosing(object sender, FormClosingEventArgs e) { if(this.isLogIn) { LogOut(); } } #endregion #region HTS 이벤트 연결시 처리하기 - hts_OnEventConnect(sender, e) /// <summary> /// HTS 이벤트 연결시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void hts_OnEventConnect(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnEventConnectEvent e) { if(e.nErrCode == 0) // 성공시 { AddMessage("CONNECT - 로그인 처리 성공"); } else { AddMessage("CONNECT - 로그인 처리 실패 : {0}", e.nErrCode); } } #endregion #region 로그인 버튼 클릭시 처리하기 - loginButton_Click(sender, e) /// <summary> /// 로그인 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void loginButton_Click(object sender, EventArgs e) { if(this.hts.CommConnect() == 0) { AddMessage("로그인 창 열기를 성공했습니다."); this.isLogIn = true; } else { AddMessage("로그인 창 열기를 실패했습니다."); } } #endregion #region 로그아웃 버튼 클릭시 처리하기 - logOutButton_Click(sender, e) /// <summary> /// 로그아웃 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void logOutButton_Click(object sender, EventArgs e) { LogOut(); AddMessage("로그아웃 했습니다."); } #endregion #region 주식기본정보요청 버튼 클릭시 처리하기 - 주식기본정보요청Button_Click(sender, e) /// <summary> /// 주식기본정보요청 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void 주식기본정보요청Button_Click(object sender, EventArgs e) { AddMessage("주식기본정보요청을 시작합니다."); using(var request = new 주식기본정보요청(this, this.hts)) { request.InputValueDictionary.Add("종목코드", "105560"); // KB금융지주 List<주식기본정보항목> resultList = request.GetList(); if(resultList != null) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(resultList[0]); this.resultRichTextBox.Text = json; AddMessage("주식기본정보요청을 종료합니다."); } else { AddMessage("주식기본정보요청을 실패했습니다."); } } } #endregion #region 주식일봉차트조회요청 버튼 클릭시 처리하기 - 주식일봉차트조회요청Button_Click(sender, e) /// <summary> /// 주식일봉차트조회요청 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void 주식일봉차트조회요청Button_Click(object sender, EventArgs e) { AddMessage("주식일봉차트조회요청을 시작합니다."); using(var request = new 주식일봉차트조회요청(this, this.hts, TransactionDataType.MultipleFirstPage)) { request.InputValueDictionary.Add("종목코드" , "105560" ); // KB금융지주 request.InputValueDictionary.Add("기준일자" , "20220204"); request.InputValueDictionary.Add("수정주가구분", "1" ); List<주식일봉차트항목> resultList = request.GetList(); if(resultList != null) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(resultList); this.resultRichTextBox.Text = json; AddMessage("주식일봉차트조회요청을 종료합니다."); } else { AddMessage("주식일봉차트조회요청을 실패했습니다."); } } } #endregion #region 일별거래상세요청 버튼 클릭시 처리하기 - 일별거래상세요청Button_Click(sender, e) /// <summary> /// 일별거래상세요청 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void 일별거래상세요청Button_Click(object sender, EventArgs e) { AddMessage("일별거래상세요청을 시작합니다."); using(var request = new 일별거래상세요청(this, this.hts, TransactionDataType.MultipleFirstPage)) { request.InputValueDictionary.Add("종목코드", "105560" ); // KB금융지주 request.InputValueDictionary.Add("시작일자", "20220113"); List<일별거래상세항목> resultList = request.GetList(); if(resultList != null) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(resultList); this.resultRichTextBox.Text = json; AddMessage("일별거래상세요청을 종료합니다."); } else { AddMessage("일별거래상세요청을 실패했습니다."); } } } #endregion #region 종목코드 버튼 클릭시 처리하기 - 종목코드Button_Click(sender, e) /// <summary> /// 종목코드 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void 종목코드Button_Click(object sender, EventArgs e) { string result = this.hts.GetCodeListByMarket("0"); this.resultRichTextBox.Text = result; } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 메시지 지우기 - ClearMessage() /// <summary> /// 메시지 지우기 /// </summary> private void ClearMessage() { this.messageListBox.Items.Clear(); } #endregion #region 메시지 추가하기 - AddMessage(formatString, argumentArray) /// <summary> /// 메시지 추가하기 /// </summary> /// <param name="formatString">포맷 문자열</param> /// <param name="argumentArray">인자 배열</param> public void AddMessage(string formatString, params object[] argumentArray) { string source = string.Format("[{0}] {1}", DateTime.Now.ToString("HH:mm:ss"), string.Format(formatString, argumentArray)); Invoke(new MethodInvoker(() => { this.messageListBox.Items.Insert(0, source); })); } #endregion #region 로그 아웃 하기 - LogOut() /// <summary> /// 로그 아웃 하기 /// </summary> private void LogOut() { this.hts.DisconnectRealData("0001"); this.hts.CommTerminate(); this.isLogIn = false; } #endregion } } |