/// <summary> 매수 주문 </summary> private void ProcessBuyByRealData(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e, string code, int firstPrice, int price) { if (_processErrorFlag) { return; } if (IsDelay() == false) { //매수정보 저장 BoughtEventData temp = new BoughtEventData(); string log = temp.SettingBoughtPrice(firstPrice, price, code); _logManager.AddLog(code, log); if (_boughtDataDict.ContainsKey(code) == false) { _boughtDataDict.Add(code, temp); } else { Console.WriteLine("Error On Add Buy Dict"); } TODAY_LIST_BUY_PRICE[code] = float.MaxValue; //매수 주문 //axKHOpenAPI2.SendOrder(ORDER_NAME, ORDER_NO, MY_ACCOUNT, 1, code, temp.boughtCount, 0, "03", string.Empty); ++_tickProcessCount; } }
private void axKHOpenAPI2_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { if (e.sRealType == "주식체결") { if (_lastProcessTicks == DateTime.Now.Ticks) { return; } _lastProcessTicks = DateTime.Now.Ticks; string code = e.sRealKey; int price = int.Parse(axKHOpenAPI2.GetCommRealData(code, 10).Trim().Replace("-", "")); if (_boughtDataDict.ContainsKey(code)) { //매수 후 종목 CheckSellProcessByRealData(e, code, price); } else { //매수 전 종목 CheckBuyProcessByRealData(e, code, price); } } }
// Open API 실시간데이터 수신 이벤트 private void axKHOpenAPI_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { string item = e.sRealKey; Logger(Log.실시간, "====실시간 수신 시작===="); Logger(Log.실시간, "종목코드 : {0} | RealType : {1} | RealData : {2}", item, e.sRealType, e.sRealData); if ("09".Equals(item) && "장시작시간".Equals(e.sRealType)) { string realData = e.sRealData; if (realData.Contains("085900")) { //string today = System.DateTime.Now.ToString("yyyyMMdd") + "085900"; //DateTime sysDate = DateTime.ParseExact(today, "yyyyMMddHHmmss", null); //DateTime now = DateTime.Now; //TimeSpan span = sysDate.Subtract(now); //DateTime.Now.Add(span); // 장 개시가 확실할 경우, 값 변경 _operTime = true; Logger(Log.실시간, "[시간변경] : " + DateTime.Now.ToString()); } } Logger(Log.실시간, "====실시간 수신 끝===="); }
public void onReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { if (e.sRealType == "주식체결") { if (e.sRealKey == currentStockCode) { long stockPrice = long.Parse(axKHOpenAPI1.GetCommRealData(currentStockCode, 10)); long upDown = long.Parse(axKHOpenAPI1.GetCommRealData(currentStockCode, 11)); string upDownRate = axKHOpenAPI1.GetCommRealData(currentStockCode, 12); long volume = long.Parse(axKHOpenAPI1.GetCommRealData(currentStockCode, 15)); stockPriceTxt.Text = String.Format("{0:#,###}", stockPrice); stockUpDownTxt.Text = String.Format("{0:#,###}", upDown); stockVolumeTxt.Text = String.Format("{0:#,###}", volume); if (upDown == 0) { stockUpDownTxt.Text = "0"; } if (volume == 0) { stockVolumeTxt.Text = "0"; } stockUpDownRateTxt.Text = upDownRate + "%"; } } }
public void GetMarketState(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { /* * 장운영구분: 215 * 시간: 20 * 장시작예상잔여시간: 214 */ int value = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, 215)); if (value == 0) { // 장 시작 전 } else if (value == 3) { // 장 시작 } else if (value == 2) { // 장 종료, 동시호가 } else if (value == 4) { // 3시 30분 장 종료 } }
private void axKHOpenAPI_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { if (e.sRealType == "주식체결") { // TODO } }
public void runReceiveRealData(AxKHOpenAPILib.AxKHOpenAPI axKHOpenAPI, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { ReceiveRealData rt = getReceiveRealData(e.sRealType); if (rt != null) { rt.ReceivedData(axKHOpenAPI, e); } }
/// <summary> 매수 후 종목 </summary> private void CheckSellProcessByRealData(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e, string code, int price) { if (_processErrorFlag) { return; } if (_boughtDataDict.ContainsKey(code)) { if (_boughtDataDict[code].IsSell(price) && IsDelay() == false) { if (_boughtDataDict[code].processCount > 1) { //익절이라면 최종 목표가로 TODAY_LIST_BUY_PRICE[code] = _boughtDataDict[code].gainPrice; } else { ////손절이라면 첫 목표가로 //TODAY_LIST_BUY_PRICE[code] = _boughtDataDict[code].boughtPrice; //손절이라면 제거 TODAY_LIST_BUY_PRICE.Remove(code); TODAY_LIST_FIRST_PRICE.Remove(code); axKHOpenAPI2.SetRealRemove(REAL_DATA_NO, code); } //매도 주문 //axKHOpenAPI2.SendOrder(ORDER_NAME, ORDER_NO, MY_ACCOUNT, 2, code, _boughtDataDict[code].boughtCount, 0, "03", string.Empty); float gapMoney = (price - _boughtDataDict[code].boughtPrice) * _boughtDataDict[code].boughtCount; string priceLog = string.Format("Sell -- Bought : {1}, Now : {0}, ProcessCount : {2}, Gap : {3}, Margine : {4}", price, _boughtDataDict[code].boughtPrice, _boughtDataDict[code].processCount, price - _boughtDataDict[code].boughtPrice, gapMoney); if (gapMoney > 0) { _logManager.AddGainMoney(gapMoney); } else { _logManager.AddLossMoney(Math.Abs(gapMoney)); } Console.WriteLine(); Console.WriteLine(priceLog); Console.WriteLine(); _logManager.AddLog(code, priceLog); _boughtDataDict.Remove(code); ++_tickProcessCount; } } else { string log = string.Format("Error On CheckSellProcessByRealData.\nCode : {0}", code); Console.WriteLine(log); _processErrorFlag = true; } }
private void kiwoomApi_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { //Console.WriteLine("[DEBUG] OnReceiveRealData - e.sRealKey : " + e.sRealKey + ", e.sRealType : " + e.sRealType + ", e.sRealData : " + e.sRealData); // 보유 종목에 있을 경우 값 업데이트 string market = kiwoomApi.GetCommRealData(e.sRealKey, 290).Trim(); if (market.Equals("2")) { Holding holding = holdings.SingleOrDefault(item => item.StockNo.Contains(e.sRealKey)); if (holding != null) { long currentPrice = long.Parse(Regex.Replace(kiwoomApi.GetCommRealData(e.sRealKey, 10).Trim(), @"[^0-9]", "")); holding.CurrentPrice = String.Format("{0:#,###0}", currentPrice); if (float.Parse(holding.ProfitRate) < -1) { Console.WriteLine("손절 " + holding.StockName + " " + holding.ProfitRate); order(ORDER_TYPE_SELL, holding.StockNo, int.Parse(holding.Qty, System.Globalization.NumberStyles.AllowThousands), 0, ORDER_HOGA_MARKET); // 시장가 손절 } else if (float.Parse(holding.ProfitRate) > 1) { Console.WriteLine("익절 " + holding.StockName + " " + holding.ProfitRate); order(ORDER_TYPE_SELL, holding.StockNo, int.Parse(holding.Qty, System.Globalization.NumberStyles.AllowThousands), int.Parse(currentPrice.ToString()), ORDER_HOGA_LIIMIT); // 시장가 손절 } } ConditionStock conditionStock = conditionStocks.SingleOrDefault(item => item.StockNo.Contains(e.sRealKey)); if (conditionStock != null) { long currentPrice = long.Parse(Regex.Replace(kiwoomApi.GetCommRealData(e.sRealKey, 10).Trim(), @"[^0-9]", "")); conditionStock.CurrentPrice = String.Format("{0:#,###0}", currentPrice); if (string.IsNullOrEmpty(conditionStock.TransferPrice) || long.Parse(conditionStock.TransferPrice, System.Globalization.NumberStyles.AllowThousands) < 1) { conditionStock.TransferPrice = conditionStock.CurrentPrice; } float fluctuationRate = float.Parse(kiwoomApi.GetCommRealData(e.sRealKey, 12).Trim()); conditionStock.FluctuationRate = String.Format("{0:f2}", fluctuationRate); // 주문 목록에 없고, 보유종목에 없으면 매수 // 주문이 들어가기 전에 한번 더 요청이 오면? 안되겠군.. // 조건 검색에 편입되는 순간 확인하고..큐에 넣고 큐를 뒤져야하나? // 편입, 이탈이 반복되는 경우는 어떻게 하지? if (conditionStock.Status.Equals("편입") && !conditionStock.Ordered.Equals("주문") && long.Parse(conditionStock.TransferPrice, System.Globalization.NumberStyles.AllowThousands) < currentPrice) { conditionStock.Ordered = "주문"; order(ORDER_TYPE_BUY, conditionStock.StockNo, 1, int.Parse(currentPrice.ToString()), ORDER_HOGA_LIIMIT); } } } }
private void axKHOpenAPI_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { Logger(Log.실시간, "종목코드 : {0} | RealType : {1} | RealData : {2}", e.sRealKey, e.sRealType, e.sRealData); if (e.sRealType == "주식시세") { Logger(Log.실시간, "종목코드 : {0} | 현재가 : {1:C} | 등락율 : {2} | 누적거래량 : {3:N0} ", e.sRealKey, Int32.Parse(axKHOpenAPI.GetCommRealData(e.sRealType, 10).Trim()), axKHOpenAPI.GetCommRealData(e.sRealType, 12).Trim(), Int32.Parse(axKHOpenAPI.GetCommRealData(e.sRealType, 13).Trim())); } }
public void axKHOpenAPI_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent apiEvent) { try { if (apiEvent.sRealType == "주식시세") { Logger.getInstance.print(Log.StockAPI콜백, "종목코드 : {0} | 현재가 : {1:C} | 등락율 : {2} | 누적거래량 : {3:N0} ", apiEvent.sRealKey, Int32.Parse(khOpenApi_.GetCommRealData(apiEvent.sRealType, 10).Trim()), khOpenApi_.GetCommRealData(apiEvent.sRealType, 12).Trim(), Int32.Parse(khOpenApi_.GetCommRealData(apiEvent.sRealType, 13).Trim())); } } catch (AccessViolationException execption) { Logger.getInstance.print(Log.에러, "[주식 데이터 콜백 에러] {0}\n{1}\n{2}", execption.Message, execption.StackTrace, execption.InnerException); } this.runNextOrderFlag(); }
public static void AxKH_OnReceiveRealData(Object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { switch (e.sRealKey.ToString().Trim()) { case "주식시세": break; case "주식체결": break; case "주식우선호가": break; case "주식호가잔량": break; case "주식시간외호가": break; case "주식당일거래원": break; case "주식예상체결": break; case "주식종목정보": break; case "주식거래원": break; default: break; } }
public void onReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { if (registered) { if (e.sRealType == "장시작시간") { GetMarketState(e); } if ((e.sRealType == "주식호가잔량") || (e.sRealType == "주식선물호가잔량") || (e.sRealType == "선물호가잔량")) { GetHoga(e); } if ((e.sRealType == "주식체결") || (e.sRealType == "선물시세")) { GetTick(e); } } }
// =====================================================<< 3. 실시간 데이터(OnReceiveRealData) 수신부 >>===================================================// // << 실시간 데이터 수신부 : 장중에만 신호 발생한다. 휴일엔 수신 불가 >> // 실시간 주식시세 수신하여 데이터그리드뷰에 직접 출력 // ========================================================================================================================================================// private void axKHOpenAPI_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { //logger.Write(LOGTYPE.C, string.Format("[{0}][{1}]", e.sRealKey, e.sRealType)); string stCode = e.sRealKey; if (e.sRealType == "주식체결") { UpdateDataGridViewData(실시간검색뷰, "종목코드", stCode, "종목코드", stCode, DATATYPE.STR); UpdateDataGridViewData(실시간검색뷰, "종목코드", stCode, "현재가", axKHOpenAPI.GetCommRealData(e.sRealType, 10).Trim(), DATATYPE.ABSINT); UpdateDataGridViewData(실시간검색뷰, "종목코드", stCode, "전일대비", axKHOpenAPI.GetCommRealData(e.sRealType, 11).Trim(), DATATYPE.INT); UpdateDataGridViewData(실시간검색뷰, "종목코드", stCode, "등락율", axKHOpenAPI.GetCommRealData(e.sRealType, 12).Trim(), DATATYPE.STR); UpdateDataGridViewData(실시간검색뷰, "종목코드", stCode, "거래량", axKHOpenAPI.GetCommRealData(e.sRealType, 13).Trim(), DATATYPE.ABSINT); UpdateDataGridViewData(실시간검색뷰, "종목코드", stCode, "구분", 구분모양(axKHOpenAPI.GetCommRealData(e.sRealType, 25).Trim()), DATATYPE.STR); } else if (e.sRealType == "잔고") { UpdateDataGridViewData(단기계좌보유현황뷰, "단기종목코드", stCode, "단기종목코드", stCode, DATATYPE.STR); UpdateDataGridViewData(단기계좌보유현황뷰, "단기종목코드", stCode, "단기현재가", axKHOpenAPI.GetCommRealData(e.sRealType, 10).Trim(), DATATYPE.ABSINT); UpdateDataGridViewData(단기계좌보유현황뷰, "단기종목코드", stCode, "단기보유수량", axKHOpenAPI.GetCommRealData(e.sRealType, 930).Trim(), DATATYPE.ABSINT); UpdateDataGridViewData(단기계좌보유현황뷰, "단기종목코드", stCode, "단기매입금액", axKHOpenAPI.GetCommRealData(e.sRealType, 932).Trim(), DATATYPE.STR); UpdateDataGridViewData(단기계좌보유현황뷰, "단기종목코드", stCode, "단기수익율", axKHOpenAPI.GetCommRealData(e.sRealType, 8019).Trim(), DATATYPE.ABSINT); UpdateDataGridViewData(단기계좌보유현황뷰, "단기종목코드", stCode, "구분", 구분모양(axKHOpenAPI.GetCommRealData(e.sRealType, 25).Trim()), DATATYPE.STR); } }
private void axKHOpenAPI_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { if (e.sRealType == "주식체결") { int rowCount = getRowIndex(e.sRealKey); //종목데이터 수정 ViewList[rowCount].setCurrentData(Utility.getInstance.separateStringWithComma(API.getInstance.getAPI().GetCommRealData(e.sRealType, 10).Trim().ToString()) , API.getInstance.getAPI().GetCommRealData(e.sRealType, 12).Trim().ToString() , Utility.getInstance.separateStringWithComma(API.getInstance.getAPI().GetCommRealData(e.sRealType, 13).Trim().ToString())); Utility.getInstance.Logger(this, Log.실시간, "종목코드 : {0} | RealType : {1} | RealData : {2}", e.sRealKey, e.sRealType, e.sRealData); //Data목록 수정 stockInfoView.Rows[rowCount].SetValues(ViewList[rowCount].getStockName() , ViewList[rowCount].getCurrentPrice() , ViewList[rowCount].getRateOfUpDown() , ViewList[rowCount].getAmountOfVolume()); } }
public void GetHoga(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { string code = e.sRealKey; string hogaDate = axKHOpenAPI1.GetCommRealData(e.sRealType, 21); string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss.fff"); string hogaDataString = $"hoga;{code};{hogaDate};{timestamp}"; for (int i = 0; i < 10; i++) { string sellHoga = axKHOpenAPI1.GetCommRealData(e.sRealType, 50 - i); string sellAmt = axKHOpenAPI1.GetCommRealData(e.sRealType, 70 - i); hogaDataString += $"{sellHoga};{sellAmt};"; } for (int i = 0; i < 10; i++) { string buyHoga = axKHOpenAPI1.GetCommRealData(e.sRealType, 51 + i); string buyAmt = axKHOpenAPI1.GetCommRealData(e.sRealType, 71 + i); hogaDataString += $"{buyHoga};{buyAmt};"; } string totalBuyHogaAmt = axKHOpenAPI1.GetCommRealData(e.sRealType, 125); // 매수호가총잔량 string totalSellHogaAmt = axKHOpenAPI1.GetCommRealData(e.sRealType, 121); // 매도호가총잔량 string netBuyHogaAmt = axKHOpenAPI1.GetCommRealData(e.sRealType, 128); // 순매수잔량 string netSellHogaAmt = axKHOpenAPI1.GetCommRealData(e.sRealType, 138); //순매도잔량 string ratioBuyHogaAmt = axKHOpenAPI1.GetCommRealData(e.sRealType, 129); // 매수비율 string ratioSellHogaAmt = axKHOpenAPI1.GetCommRealData(e.sRealType, 139); // 매도비율 string agentTicker = axKHOpenAPI1.GetCommRealData(e.sRealType, 216); // 투자자별 ticker (제공해주면) hogaDataString += $"{totalBuyHogaAmt};{totalSellHogaAmt};{netBuyHogaAmt};{netSellHogaAmt};{ratioBuyHogaAmt};{ratioSellHogaAmt};{agentTicker};"; //StreamWriter sw = new StreamWriter("C:\\Users\\simpl\\OneDrive\\바탕 화면\\Projects\\tests\\files\\hogatest.txt", append: true); //sw.WriteLine(hogaDataString); //sw.Flush(); //sw.Close(); Kafka.Produce("kiwoom-data", new Message <Null, string> { Value = hogaDataString }, KafkaErrorHandler); Rabbit.BasicPublish(exchange: "", routingKey: "kiwoom-data", basicProperties: null, body: Encoding.UTF8.GetBytes(hogaDataString)); }
public void GetTick(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { /* * 체결시간: 20 * 현재가: 10 * (최우선)매도호가: 27 * (최우선) 매수호가: 28 * 거래량: 15 * 누적거래량: 13 * 고가: 17 * 시가: 16 * 저가: 18 * 거래회전율: 31 * 거래비용: 32 */ string code = e.sRealKey; string tradeDate = axKHOpenAPI1.GetCommRealData(e.sRealType, 20); string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss.fff"); string currentPrice = axKHOpenAPI1.GetCommRealData(e.sRealType, 10); string openPrice = axKHOpenAPI1.GetCommRealData(e.sRealType, 16); string high = axKHOpenAPI1.GetCommRealData(e.sRealType, 17); string low = axKHOpenAPI1.GetCommRealData(e.sRealType, 18); string volume = axKHOpenAPI1.GetCommRealData(e.sRealType, 15); string cumVolume = axKHOpenAPI1.GetCommRealData(e.sRealType, 13); string tradeSellHoga1 = axKHOpenAPI1.GetCommRealData(e.sRealType, 27); string tradeBuyHoga1 = axKHOpenAPI1.GetCommRealData(e.sRealType, 28); string tickDataString = $"tick;{code};{tradeDate};{timestamp};"; tickDataString += $"{currentPrice};{openPrice};{high};{low};{volume};{cumVolume};{tradeSellHoga1};{tradeBuyHoga1};"; //StreamWriter sw = new StreamWriter("C:\\Users\\simpl\\OneDrive\\바탕 화면\\Projects\\tests\\files\\ticktest.txt", append: true); //sw.WriteLine(tickDataString); //sw.Flush(); //sw.Close(); Kafka.Produce("kiwoom-data", new Message <Null, string> { Value = tickDataString }, KafkaErrorHandler); Rabbit.BasicPublish(exchange: "", routingKey: "kiwoom-data", basicProperties: null, body: Encoding.UTF8.GetBytes(tickDataString)); }
void OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { if (e.sRealType == "주식호가잔량") { priceListBox.Items.Clear(); volumeListBox.Items.Clear(); if (e.sRealKey.Equals(currentItemCode)) { for (int i = 50; i >= 41; i--) { int 매도호가 = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, i)); priceListBox.Items.Add(매도호가); } for (int i = 70; i >= 61; i--) { int 매도잔량 = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, i)); volumeListBox.Items.Add(매도잔량); } for (int i = 51; i <= 60; i++) { int 매수호가 = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, i)); priceListBox.Items.Add(매수호가); } for (int i = 71; i <= 80; i++) { int 매수잔량 = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, i)); volumeListBox.Items.Add(매수잔량); } } } if (e.sRealType == "주식체결") { currentPriceLabel.Text = axKHOpenAPI1.GetCommRealData(e.sRealType, 10).ToString(); fluctuationLabel.Text = axKHOpenAPI1.GetCommRealData(e.sRealType, 12).ToString() + "%"; } }
private void axKHOPenAPI_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { this.list_realtime.Items.Add(e.sRealData); this.list_realtime.Items.Add(e.sRealKey); this.list_realtime.Items.Add(e.sRealType); this.list_realtime.Items.Add(axKHOpenAPI1.GetCommRealData(e.sRealData, 10).Trim()); if (e.sRealType == "주식시세") { this.list_realtime.Items.Add("현재가 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 10).Trim()); this.list_realtime.Items.Add("전일대비 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 11).Trim()); this.list_realtime.Items.Add("등락율 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 12).Trim()); this.list_realtime.Items.Add("(최우선)매도호가 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 27).Trim()); this.list_realtime.Items.Add("(최우선)매수호가 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 28).Trim()); this.list_realtime.Items.Add("누적 거래량 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 13).Trim()); this.list_realtime.Items.Add("누적 거래대금 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 14).Trim()); this.list_realtime.Items.Add("시가 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 16).Trim()); this.list_realtime.Items.Add("고가 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 17).Trim()); this.list_realtime.Items.Add("저가 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 18).Trim()); this.list_realtime.Items.Add("전일대비기호 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 25).Trim()); this.list_realtime.Items.Add("전일거래량대비(계약,주) = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 26).Trim()); this.list_realtime.Items.Add("거래다금 증감 = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 27).Trim()); this.list_realtime.Items.Add("전일 거래량댜비(비율) = " + axKHOpenAPI1.GetCommRealData(e.sRealData, 30).Trim()); } }
public abstract void ReceivedData(AxKHOpenAPILib.AxKHOpenAPI axKHOpenAPI, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e);
private void kiwoomApi_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { if (!isRunning) { return; } if (DateTime.Now.Hour > 13) { buttonStop.PerformClick(); } //Console.WriteLine("[DEBUG] OnReceiveRealData - e.sRealKey : " + e.sRealKey + ", e.sRealType : " + e.sRealType + ", e.sRealData : " + e.sRealData); // 보유 종목에 있을 경우 값 업데이트 string market = kiwoomApi.GetCommRealData(e.sRealKey, 290).Trim(); if (market.Equals("2")) { if (orders.Count > 0) { foreach (OrderStock order in orders) { if (order.AfterOrder > ORDER_TIMEOUT && !order.Canceled) { log(LogMode.TRADE, "주문번호 " + order.OrderNo + "의 주문이 오래되어 해당 주문을 취소합니다. (" + order.AfterOrder + "초)"); order.Canceled = true; cancelOrder(order.OrderType.Equals("매수") ? ORDER_TYPE_BUY_CANCEL : ORDER_TYPE_SELL_CANCEL, order.StockNo, order.OrderNo); } } } HoldStock holding = holdings.SingleOrDefault(item => item.StockNo.Contains(e.sRealKey)); if (holding != null) { long currentPrice = long.Parse(Regex.Replace(kiwoomApi.GetCommRealData(e.sRealKey, 10).Trim(), @"[^0-9]", "")); holding.CurrentPrice = String.Format("{0:#,###0}", currentPrice); long dayHighPrice = long.Parse(Regex.Replace(kiwoomApi.GetCommRealData(e.sRealKey, 17).Trim(), @"[^0-9]", "")); holding.DayHighPrice = String.Format("{0:#,###0}", dayHighPrice); long dayLowPrice = long.Parse(Regex.Replace(kiwoomApi.GetCommRealData(e.sRealKey, 18).Trim(), @"[^0-9]", "")); holding.DayLowPrice = String.Format("{0:#,###0}", dayLowPrice); if (holding.isProfit) { log(LogMode.TRADE, holding.StockName + "(" + holding.StockNo + ") 종목이 익절가(" + holding.TargetLine + ")에 도달하여 익절 합니다. (매수가 : " + holding.BuyPrice + ", 매수 횟수 : " + holding.BuyCnt + ", 수익 : " + float.Parse(holding.ProfitRate) + "%)"); holding.Ordered = "주문"; if (!order(ORDER_TYPE_SELL, holding.StockNo, int.Parse(holding.Qty, System.Globalization.NumberStyles.AllowThousands), int.Parse(currentPrice.ToString()), ORDER_HOGA_MARKET)) { holding.Ordered = "대기"; } } else if (holding.Ordered.Equals("대기") && long.Parse(holding.SecondBuyPrice, System.Globalization.NumberStyles.AllowThousands) > currentPrice && holding.BuyCnt == 1) { // 2차 매수가에 도달하면 손절 log(LogMode.TRADE, holding.StockName + "(" + holding.StockNo + ") 종목이 손절가(" + holding.SecondBuyPrice + ")에 도달하여 손절 합니다. (매수가 : " + holding.BuyPrice + ", 손익 : " + float.Parse(holding.ProfitRate) + "%)"); holding.Ordered = "주문"; if (!order(ORDER_TYPE_SELL, holding.StockNo, int.Parse(holding.Qty, System.Globalization.NumberStyles.AllowThousands), int.Parse(currentPrice.ToString()), ORDER_HOGA_MARKET)) { holding.Ordered = "대기"; } /*} else if (holding.Ordered.Equals("대기") && long.Parse(holding.SecondBuyPrice, System.Globalization.NumberStyles.AllowThousands) > currentPrice && holding.BuyCnt == 1) * { * // 2차 매수가 주문 * holding.Ordered = "주문"; * holding.BuyCnt = holding.BuyCnt + 1; * log(LogMode.TRADE, holding.StockName + "(" + holding.StockNo + ") 종목이 2차 매수가에 도달하여 주문 합니다. (" + holding.CurrentPrice + "원)"); * if(!order(ORDER_TYPE_BUY, holding.StockNo, (oneTimeAmount / int.Parse(currentPrice.ToString())), int.Parse(currentPrice.ToString()), ORDER_HOGA_LIIMIT)) * { * holding.BuyCnt = holding.BuyCnt - 1; * } * } else if (holding.Ordered.Equals("대기") && long.Parse(holding.ThirdBuyPrice, System.Globalization.NumberStyles.AllowThousands) > currentPrice && holding.BuyCnt == 2) * { * // 3차 매수가 주문. 기본 2배 물량 * holding.Ordered = "주문"; * holding.BuyCnt = holding.BuyCnt + 1; * log(LogMode.TRADE, holding.StockName + "(" + holding.StockNo + ") 종목이 3차 매수가에 도달하여 주문 합니다. (" + holding.CurrentPrice + "원)"); * if(!order(ORDER_TYPE_BUY, holding.StockNo, (oneTimeAmount / int.Parse(currentPrice.ToString())) * 2, int.Parse(currentPrice.ToString()), ORDER_HOGA_LIIMIT)) * { * holding.Ordered = "대기"; * holding.BuyCnt = holding.BuyCnt - 1; * }*/ } } DetectionStock conditionStock = conditionStocks.SingleOrDefault(item => item.StockNo.Contains(e.sRealKey)); if (conditionStock != null) { long currentPrice = long.Parse(Regex.Replace(kiwoomApi.GetCommRealData(e.sRealKey, 10).Trim(), @"[^0-9]", "")); conditionStock.CurrentPrice = String.Format("{0:#,###0}", currentPrice); //conditionStock.NewTransferPrice = String.Format("{0:#,###0}", currentPrice); long dayHighPrice = long.Parse(Regex.Replace(kiwoomApi.GetCommRealData(e.sRealKey, 17).Trim(), @"[^0-9]", "")); conditionStock.DayHighPrice = String.Format("{0:#,###0}", dayHighPrice); long dayLowPrice = long.Parse(Regex.Replace(kiwoomApi.GetCommRealData(e.sRealKey, 18).Trim(), @"[^0-9]", "")); conditionStock.DayLowPrice = String.Format("{0:#,###0}", dayLowPrice); if (string.IsNullOrEmpty(conditionStock.TransferPrice) || long.Parse(conditionStock.TransferPrice, System.Globalization.NumberStyles.AllowThousands) < 1) { conditionStock.TransferPrice = conditionStock.CurrentPrice; } float fluctuationRate = float.Parse(kiwoomApi.GetCommRealData(e.sRealKey, 12).Trim()); conditionStock.FluctuationRate = String.Format("{0:f2}", fluctuationRate); // 1차 매수가에 도달하면 매수 -> 1차 매수 도달 시 매수 대기했다가 돌파하면 매수하는 방식은? if (currentPrice < oneTimeAmount && !conditionStock.Status.Equals("이탈") && conditionStock.Ordered.Equals("대기") && long.Parse(conditionStock.TargetPrice, System.Globalization.NumberStyles.AllowThousands) > 0 && long.Parse(conditionStock.TargetPrice, System.Globalization.NumberStyles.AllowThousands) > currentPrice && long.Parse(conditionStock.TargetPrice, System.Globalization.NumberStyles.AllowThousands) < long.Parse(conditionStock.TransferPrice, System.Globalization.NumberStyles.AllowThousands)) { /*if (long.Parse(conditionStock.TransferPrice, System.Globalization.NumberStyles.AllowThousands) > long.Parse(conditionStock.NewTransferPrice, System.Globalization.NumberStyles.AllowThousands)) * { * return; * }*/ log(LogMode.TRADE, conditionStock.StockName + "(" + conditionStock.StockNo + ")의 1차 매수가에 도달하여 매수 합니다. (1차 매수가 : " + conditionStock.TargetPrice + ", 진입횟수 : " + conditionStock.TransferCnt + ")"); conditionStock.Ordered = "주문"; //if (!order(ORDER_TYPE_BUY, conditionStock.StockNo, (oneTimeAmount / int.Parse(currentPrice.ToString())), int.Parse(currentPrice.ToString()), ORDER_HOGA_LIIMIT)) // 시장가로 매수 if (!order(ORDER_TYPE_BUY, conditionStock.StockNo, (oneTimeAmount / int.Parse(currentPrice.ToString())), 0, ORDER_HOGA_MARKET)) { conditionStock.Ordered = "대기"; } } } } }
public void onReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { if (e.sRealType == "주식체결") { #region FID //[20] = 체결시간 //[10] = 현재가 //[11] = 전일대비 //[12] = 등락율 //[27] = (최우선) 매도호가 //[28] = (최우선)매수호가 //[15] = 거래량 //[13] = 누적거래량 //[14] = 누적거래대금 //[16] = 시가 //[17] = 고가 //[18] = 저가 //[25] = 전일대비기호 //[26] = 전일거래량대비(계약, 주) //[29] = 거래대금증감 //[30] = 전일거래량대비(비율) //[31] = 거래회전율 //[32] = 거래비용 //[228] = 체결강도 //[311] = 시가총액(억) //[290] = 장구분 //[691] = KO접근도 //[567] = 상한가발생시간 //[568] = 하한가발생시간 #endregion stockInfo stock = CodeManager.Instance.GetCodeFromInfo(e.sRealKey); DateTime stockTime = DateTime.ParseExact(axKHOpenAPI1.GetCommRealData(e.sRealKey, 20), "HHmmss", System.Globalization.CultureInfo.InvariantCulture); // 체결시간 long stockPrice = long.Parse(axKHOpenAPI1.GetCommRealData(e.sRealKey, 10)); // 현재가 long volume = long.Parse(axKHOpenAPI1.GetCommRealData(e.sRealKey, 15)); // 거래량 StringBuilder sb = new StringBuilder(); //sb.AppendFormat("{0} ", stockTime.ToString("HH:mm:ss")); //sb.AppendFormat("현재가 : {0}, ", String.Format("{0:#,###}", stockPrice)); //sb.AppendFormat("거래량 : {0}, ", String.Format("{0:#,###}", volume)); //Console.WriteLine(sb.ToString()); try { sb.Clear(); sb.Append("select * from LiveTable where "); sb.AppendFormat("SignTime = '{0}' ", stockTime.ToString("HH:mm:ss")); sb.AppendFormat("and SignCode = '{0}' ", e.sRealKey); sb.AppendFormat("and SignCodeName = '{0}' ", stock.stockName); DataTable dt = ADBEngine.Instance.fc_SqlDataAdapterQuery(sb.ToString()); int Cnt = 0; if (dt != null) { Cnt = dt.Rows.Count; if (Cnt >= 2) // 2개 이상은 저장안함 { return; } } sb.Clear(); sb.Append("insert into LiveTable "); sb.Append("(SignTime, SignCode, SignCodeName, SignPrice, SignPriceValue, SignPriceIdx,SignDate) VALUES("); sb.AppendFormat("'{0}', ", stockTime.ToString("HH:mm:ss")); sb.AppendFormat("'{0}', ", e.sRealKey); sb.AppendFormat("'{0}', ", stock.stockName); sb.AppendFormat("'{0}', ", String.Format("{0:#,###}", stockPrice)); sb.AppendFormat("'{0}', ", String.Format("{0:#,###}", volume)); sb.AppendFormat("{0}, ", Cnt); sb.AppendFormat("'{0}') ", sDateTime); ADBEngine.Instance.ExecuteNoneQuery(sb.ToString()); List <string> Data = new List <string>(); string[] row = new string[] { stockTime.ToString("HH:mm:ss"), e.sRealKey, stock.stockName, String.Format("{0:#,###}", stockPrice), String.Format("{0:#,###}", volume) }; ds1(row); if (String.IsNullOrEmpty(SelectName)) { return; } if (SelectName != stock.stockName) { return; } row = new string[] { stockTime.ToString("HH:mm:ss"), e.sRealKey, stock.stockName, String.Format("{0:#,###}", stockPrice), String.Format("{0:#,###}", volume) }; ds2(row); } catch (Exception ex) { Console.WriteLine("DB 관련 에러 남"); } } }
private void axKHOpenAPI1_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { }
public void onReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { Console.WriteLine(e.sRealType); }
public void onReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { DateTime currentTime = DateTime.Now; for (int i = 0; i < autoTradingRuleList.Count; i++) { if (autoRuleDataGridView.SelectedCells.Count > 0) { //예외처리해야함 v0.1 int rowIndex = autoRuleDataGridView.SelectedCells[0].RowIndex; autoRuleDataGridView["거래규칙_상태", rowIndex].Value = "시작"; autoTradingRuleList[rowIndex].상태 = "시작"; } if (autoTradingRuleList[i].상태 == "시작") { double profitRate = autoTradingRuleList[i].이익률 * 0.01; double lossRate = autoTradingRuleList[i].손절률 * 0.01; for (int j = 0; j < autoTradingRuleList[i].autoTradingPurchaseStockList.Count; j++) { if (e.sRealType == "주식체결") { string test = axKHOpenAPI1.GetCommRealData(e.sRealType, 10).Replace("+", ""); int matchTime = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, 20)); int compareTime = int.Parse(currentTime.ToString("HHmmss")); // string test2 = axKHOpenAPI1.GetCommRealData(e.sRealType, 930); // string testJango = axKHOpenAPI1.GetChejanData(e.sRealKey, 930); try { autoTradingRuleList[i].autoTradingPurchaseStockList[j].currentPrice = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, 10).Replace("+", "")); } catch { } // autoTradingRuleList[i].autoTradingPurchaseStockList[j].boughtCount = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealKey, 930)); // autoTradingRuleList[i].autoTradingPurchaseStockList[j].boughtCount = int.Parse(testJango); string stockCode = autoTradingRuleList[i].autoTradingPurchaseStockList[j].stockCode; int currentPrice = autoTradingRuleList[i].autoTradingPurchaseStockList[j].currentPrice; int boughtPrice = autoTradingRuleList[i].autoTradingPurchaseStockList[j].boughtPrice; int boughtCount = autoTradingRuleList[i].autoTradingPurchaseStockList[j].boughtCount; string orderType = autoTradingRuleList[i].매도_거래구분; string[] orderTypeArray = orderType.Split(':'); if (compareTime > matchTime && e.sRealKey == stockCode) { if (currentPrice >= (boughtPrice + (boughtPrice * profitRate))) { axKHOpenAPI1.SendOrder("이익율매도주문", "8889", ACCOUNT_NUMBER, 2, stockCode, boughtCount, currentPrice, orderTypeArray[0], ""); } else if (currentPrice <= (boughtPrice - (boughtPrice * profitRate))) { axKHOpenAPI1.SendOrder("손절율매도주문", "8789", ACCOUNT_NUMBER, 2, stockCode, boughtCount, currentPrice, orderTypeArray[0], ""); } } } } } } }
public void onReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { if (e.sRealType == "주식체결") { } }
/// <summary> 매수 전 종목 </summary> private void CheckBuyProcessByRealData(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e, string code, int price) { //장외 if (DateTime.Now.Hour < 9 || (DateTime.Now.Hour >= 15 && DateTime.Now.Minute >= 19)) { return; } if (_processErrorFlag) { return; } if (TODAY_LIST_BUY_PRICE.ContainsKey(code)) { if (price > 0) { float targetPrice = TODAY_LIST_BUY_PRICE[code]; if (price >= targetPrice) { //매수 ProcessBuyByRealData(e, code, TODAY_LIST_FIRST_PRICE[code], price); _logManager.AddBuyCount(); } } else { string log = string.Format("Error On Find Now Price.\nCode : {0}\n", code); Console.WriteLine(log); _processErrorFlag = true; } } else { //targetPRice 등록 //TODO : 시가 또는 price 파라미터값으로 int startPrice = int.Parse(axKHOpenAPI2.GetCommRealData(code, 16).Trim().Replace("-", "")); if (startPrice != 0) { float targetPrice = startPrice * TARGET_PRICE_RATE; string log = string.Format("Init TargetPrice.\nName : {0}\nNow Price : {1}\nTarget Price : {2}", code, startPrice, targetPrice); Console.WriteLine("\n"); Console.WriteLine(log); Console.WriteLine("\n"); if (TODAY_LIST_BUY_PRICE.ContainsKey(code) == false) { TODAY_LIST_BUY_PRICE.Add(code, targetPrice); } else { Console.WriteLine("Error On Add Dict"); _processErrorFlag = true; return; } if (TODAY_LIST_FIRST_PRICE.ContainsKey(code) == false) { TODAY_LIST_FIRST_PRICE.Add(code, startPrice); } else { Console.WriteLine("Error On Add Dict"); _processErrorFlag = true; return; } CheckBuyProcessByRealData(e, code, price); } else { string log = string.Format("Error On Init TargetPrice.\nCode : {0}", code); Console.WriteLine(log); _processErrorFlag = true; } } }
/* chap 4.2 */ /* chap 5.1 */ public void onReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e) { Console.WriteLine(e.sRealType); /* chap 4.2 */ if (e.sRealData == "주식체결") { if (e.sRealKey == currentStockCode) { long stockPrice = long.Parse(axKHOpenAPI1.GetCommRealData(currentStockCode, 10)); long upDown = long.Parse(axKHOpenAPI1.GetCommRealData(currentStockCode, 11)); string upDownRate = axKHOpenAPI1.GetCommRealData(currentStockCode, 12); long volume = long.Parse(axKHOpenAPI1.GetCommRealData(currentStockCode, 15)); stockPriceLabel.Text = String.Format("{0:#,###}", stockPrice); stockUpDownLabel.Text = String.Format("{0:#,###}", upDown); stockVolumeLabel.Text = String.Format("{0:#,###}", volume); if (upDown == 0) { stockUpDownLabel.Text = "0"; } if (volume == 0) { stockVolumeLabel.Text = "0"; } stockUpDownRateLabel.Text = upDownRate + "%"; } } /* chap 5.1 */ if (e.sRealType == "주식호가잔량") { Console.WriteLine(currentStockCode + "------------------------------------------"); if (e.sRealKey.Equals(currentStockCode)) { try { for (int i = 0; i < 10; i++) { int 매도호가 = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, 50 - i)); int 매도잔량 = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, 70 - i)); priceListBox.Items[i] = 매도호가 + " / " + (10 - i) + "차선"; volumeListBox.Items[i] = 매도잔량; if (i == 9) { priceListBox.Items[i] = 매도호가 + " / 매도최우선호가"; } } for (int i = 0; i < 10; i++) { int 매수호가 = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, 51 + i)); int 매수잔량 = int.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, 71 + i)); priceListBox.Items[10 + i] = 매수호가 + " / " + (i + 1) + "차선"; volumeListBox.Items[10 + i] = 매수잔량; if (i == 0) { priceListBox.Items[10 + i] = 매수호가 + " / 매수최우선호가"; } } } catch (Exception exception) { Console.WriteLine(exception.Message.ToString()); } } } else if (e.sRealType == "주식체결") { if (e.sRealKey.Equals(currentStockCode)) { long stockPrice = long.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, 10).Replace("-", "")); priceLabel.Text = String.Format("{0:#,###}", stockPrice); upDownRateLabel.Text = double.Parse(axKHOpenAPI1.GetCommRealData(e.sRealType, 12)) + "%"; } } }