예제 #1
0
        private void OpenApi_Connected(string[] accounts, string userId, string server)
        {
            comboBox_Account.Items.AddRange(accounts);
            comboBox_Account.SelectedIndex = 0;

            label_UserId.Text = userId;
            label_Server.Text = server;

            UpdateBalances();

            var etfs = OpenApi.GetETFs();

            foreach (var etf in etfs)
            {
                if (etf.Name.Contains("200") || etf.Name.Contains("150") || etf.Name.Contains("인버스"))
                {
                    comboBox_Stock1.Items.Add(etf);
                    comboBox_Stock2.Items.Add(etf);
                    comboBox_Stock3.Items.Add(etf);
                }
            }

            comboBox_Stock1.SelectedItem = etfs.FirstOrDefault(x => x.Name == "KODEX 코스닥 150");
            comboBox_Stock2.SelectedItem = etfs.FirstOrDefault(x => x.Name == "TIGER 코스닥150");
            comboBox_Stock3.SelectedItem = etfs.FirstOrDefault(x => x.Name == "KODEX 코스닥150선물인버스");

            Show();
        }
예제 #2
0
        private void OnBalance()
        {
            _wait = true;

            OpenApi.UpdateBalances(_account, delegate(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveTrDataEvent e)
            {
                int count = OpenApi.GetRepeatCnt(e);
                for (int i = 0; i < count; ++i)
                {
                    string 종목명  = OpenApi.GetTrData(e, "종목명", i);
                    string 보유수량 = OpenApi.GetTrData(e, "보유수량", i);
                    foreach (var stock in _stockInfos)
                    {
                        if (stock.Stock.ToString() == 종목명)
                        {
                            int quantity;
                            if (int.TryParse(보유수량, out quantity))
                            {
                                stock.Quantity = quantity;
                            }
                            else
                            {
                                // something wrong;
                                Error = "보유수량 오류: " + 보유수량;
                                return;
                            }
                            break;
                        }
                    }
                }

                _wait = false;
                MoveState(EPhase.Price);
            });
        }
예제 #3
0
        private void button_CollectData_Click(object sender, EventArgs e)
        {
            OpenApi.Clear();

            const string end        = "수집 종료";
            var          collecting = button_CollectData.Text != end;

            button_CollectData.Text = collecting ? end : "데이터 수집";
            EnableTradeControls(!collecting);
            button_Start.Enabled = !collecting;

            if (!collecting)
            {
                return;
            }

            var etfs = OpenApi.GetETFs();

            string[] names =
            {
                "KODEX 200",
                "TIGER 200",
                "KBSTAR 200",
                "KODEX 인버스",
                "KODEX 코스닥 150",
                "TIGER 코스닥150",
                "KODEX 코스닥150선물인버스"
            };

            var stocks = etfs.Where(x => names.Contains(x.Name));

            OpenApi.SetRealReg(stocks.Select(x => x.Code));
        }
예제 #4
0
        private void UpdateBalances()
        {
            OpenApi.UpdateBalances(GetAccount(), delegate(_DKHOpenAPIEvents_OnReceiveTrDataEvent e)
            {
                string 예수금     = OpenApi.GetTrNum(e, "예수금");
                string D2추정예수금 = OpenApi.GetTrNum(e, "D+2추정예수금");
                string 가잔고평가액  = OpenApi.GetTrNum(e, "유가잔고평가액");
                string 예탁자산평가액 = OpenApi.GetTrNum(e, "예탁자산평가액");
                string 총매입금액   = OpenApi.GetTrNum(e, "총매입금액");

                var row = dataGridView_Balance.Rows[0];
                row.SetValues(예수금, D2추정예수금, 가잔고평가액, 예탁자산평가액, 총매입금액);


                int count = OpenApi.GetRepeatCnt(e);
                dataGridView_Stocks.RowCount = count;

                for (int i = 0; i < count; ++i)
                {
                    string 종목명  = OpenApi.GetTrData(e, "종목명", i);
                    string 보유수량 = OpenApi.GetTrNum(e, "보유수량", i);
                    string 평균단가 = OpenApi.GetTrNum(e, "평균단가", i);
                    string 현재가  = OpenApi.GetTrNum(e, "현재가", i);
                    string 평가금액 = OpenApi.GetTrNum(e, "평가금액", i);
                    string 손익금액 = OpenApi.GetTrNum(e, "손익금액", i);

                    row = dataGridView_Stocks.Rows[i];
                    row.SetValues(종목명, 보유수량, 평균단가, 현재가, 평가금액, 손익금액);
                }
            });
        }
예제 #5
0
        private void OnOrderConfirm()
        {
            _wait = true;

            OpenApi.SetInputValue("계좌번호", _account);
            OpenApi.SetInputValue("전체종목구분", "0");
            OpenApi.SetInputValue("매매구분", "0");
            OpenApi.SetInputValue("체결구분", "1");
            OpenApi.CommRqData("실시간미체결요청", "opt10075", delegate(_DKHOpenAPIEvents_OnReceiveTrDataEvent e)
            {
                int count      = OpenApi.GetRepeatCnt(e);
                bool hasRemain = false;
                for (int i = 0; i < count; ++i)
                {
                    var name   = OpenApi.GetTrData(e, "종목명", i);
                    var remain = OpenApi.GetTrData(e, "미체결수량", i).ToInt();
                    if (remain > 0)
                    {
                        hasRemain = true;
                        break;
                    }
                }

                _wait = false;
                MoveState(hasRemain ? EPhase.Begin : EPhase.Balance);
            });
        }
예제 #6
0
        private void ProcessPhase()
        {
            if (_wait || !OpenApi.IsTradeable())
            {
                return;
            }

            switch (Phase)
            {
            case EPhase.OrderConfirm:
                OnOrderConfirm();
                break;

            case EPhase.Balance:
                OnBalance();
                break;

            case EPhase.Price:
                OnPrice();
                break;

            case EPhase.Order:
                OnOrder();
                break;
            }
        }
예제 #7
0
        public BackTestForm()
        {
            InitializeComponent();

            var etfs = OpenApi.GetETFs();

            foreach (var etf in etfs)
            {
                if (etf.Name.Contains("200") || etf.Name.Contains("150") || etf.Name.Contains("인버스"))
                {
                    comboBox_Stock1.Items.Add(etf);
                    comboBox_Stock2.Items.Add(etf);
                    comboBox_Stock3.Items.Add(etf);
                }
            }

            comboBox_Stock1.SelectedItem = etfs.FirstOrDefault(x => x.Name == "KODEX 200");
            comboBox_Stock2.SelectedItem = etfs.FirstOrDefault(x => x.Name == "TIGER 200");
            comboBox_Stock3.SelectedItem = etfs.FirstOrDefault(x => x.Name == "KBSTAR 200");

            foreach (var interval in Intervals)
            {
                comboBox_Interval.Items.Add(interval);
            }
            comboBox_Interval.SelectedIndex = 0;
            comboBox_Interval.Enabled       = false;
        }
예제 #8
0
        private void OpenApi_ReceivedRealData(_DKHOpenAPIEvents_OnReceiveRealDataEvent real)
        {
            if (real.sRealType == "ETF NAV")
            {
                var nav = OpenApi.GetRealData(real.sRealKey, 36);
                _navs[real.sRealKey] = Math.Abs(nav.ToFloat());
                return;
            }

            DateTime now = DateTime.Now;

            //DateTime time;
            //var strTime = OpenApi.GetRealData(real.sRealKey, 21);
            //if (DateTime.TryParseExact(strTime,
            //    "HHmmss", CultureInfo.CurrentCulture, DateTimeStyles.None, out time))
            //{
            //    now = new DateTime(now.Year, now.Month, now.Day, time.Hour, time.Minute, time.Second);
            //}

            var askingPrice = new AskingPrice(now);

            for (int i = 0; i < OpenApi.RealPriceCount; ++i)
            {
                askingPrice.Sell.Add(new Asking
                {
                    Price    = Math.Abs(OpenApi.GetRealData(real.sRealKey, i + 41).ToInt()),
                    Quantity = OpenApi.GetRealData(real.sRealKey, i + 61).ToInt(),
                });

                askingPrice.Buy.Add(new Asking
                {
                    Price    = Math.Abs(OpenApi.GetRealData(real.sRealKey, i + 51).ToInt()),
                    Quantity = OpenApi.GetRealData(real.sRealKey, i + 71).ToInt(),
                });
            }

            _navs.TryGetValue(real.sRealKey, out askingPrice.Nav);

            if (_trader != null)
            {
                _trader.SetAskingPrice(real.sRealKey, askingPrice);
            }

            WriteAskingPrice(real.sRealKey, askingPrice);
        }
예제 #9
0
        private void button_Start_Click(object sender, EventArgs e)
        {
            var stocks = new[]
            {
                comboBox_Stock1.SelectedItem as Stock,
                comboBox_Stock2.SelectedItem as Stock,
                comboBox_Stock3.SelectedItem as Stock,
            };

            if (_trader == null)
            {
                float margin = textBox_Margin.Text.ToFloat();
                margin /= 100;
                margin += 1.0f;

                _trader = new Trader(GetAccount(), textBox_Quantity.Text.ToInt(), margin,
                                     stocks[0], stocks[1], stocks[2]);
            }
            else
            {
                _trader = null;
            }

            // 현재 시작여부
            var started = _trader != null;

            button_Start.Text = started ? "거래 종료" : "거래 시작";
            EnableTradeControls(!started);
            button_CollectData.Enabled = !started;

            OpenApi.Clear();

            if (_trader == null)
            {
                return;
            }

            OpenApi.SetRealReg(stocks.Select(x => x.Code));
            OpenApi.RegisterAction(1000, delegate()
            {
                _trader.Process();
            });
        }
예제 #10
0
        private void OnOrder()
        {
            for (int i = _sellOrders.Count - 1; i >= 0; --i)
            {
                var order  = _sellOrders[i];
                var result = OpenApi.Sell(_account, order.Stock.Code, order.Quantity);
                Debug.Warn("Sell: {0}, {1}, Result: {2}", order.Stock, order.Quantity, result);
            }

            for (int i = _buyOrders.Count - 1; i >= 0; --i)
            {
                var order  = _buyOrders[i];
                var result = OpenApi.Buy(_account, order.Stock.Code, order.Quantity);
                Debug.Warn("Buy: {0}, {1}, Result: {2}", order.Stock, order.Quantity, result);
            }

            _sellOrders.Clear();
            _buyOrders.Clear();
            MoveState(EPhase.OrderConfirm);
        }
예제 #11
0
        private void Request(string code, DateTime begin, DateTime end, StockPriceCollection collection, string interval,
                             IProgress <int> progress, int seq = 0)
        {
            _code     = code;
            _begin    = begin;
            _end      = end;
            _progress = progress;
            _interval = interval;

            OpenApi.SetInputValue("종목코드", code);
            if (IsDaily())
            {
                OpenApi.SetInputValue("기준일자", _end.ToString("yyyyMMdd"));
            }
            else
            {
                OpenApi.SetInputValue("틱범위", interval);
            }

            OpenApi.SetInputValue("수정주가구분", "0");
            OpenApi.CommRqData("차트구하기", IsDaily() ? "opt10081" : "opt10080", collection.PriceCallback, seq);
        }
예제 #12
0
 protected override void OnVisibleChanged(EventArgs e)
 {
     base.OnVisibleChanged(e);
     Visible = OpenApi.IsConnected();
 }
예제 #13
0
        public MainForm()
        {
            Instance = this;

            InitializeComponent();
            OpenApi.Init(axKHOpenAPI);
            OpenApi.Connected        += OpenApi_Connected;
            OpenApi.ReceivedRealData += OpenApi_ReceivedRealData;

            Debug.Logged += delegate(DateTime time, Debug.LogLevel level, string text)
            {
                try
                {
                    if (!string.IsNullOrEmpty(richTextBox_Logs.Text))
                    {
                        richTextBox_Logs.AppendText(Environment.NewLine);
                    }

                    Color color = Color.Black;
                    switch (level)
                    {
                    case Debug.LogLevel.Warning:
                        color = Color.DarkOrange;
                        break;

                    case Debug.LogLevel.Error:
                        color = Color.DarkRed;
                        break;
                    }

                    var fullText = string.Format("{0}: {1}", time, text);
                    richTextBox_Logs.AppendText(fullText, color);
                    richTextBox_Logs.ScrollToCaret();

                    using (StreamWriter w = File.AppendText("log.txt"))
                    {
                        w.WriteLine(fullText);
                    }
                }
                catch (Exception e)
                {
                    File.WriteAllText("exception.txt", e.ToString());
                }
            };

            dataGridView_Balance.Columns.Add("예수금", "예수금");
            dataGridView_Balance.Columns.Add("D+2추정예수금", "D+2추정예수금");
            dataGridView_Balance.Columns.Add("유가잔고평가액", "유가잔고평가액");
            dataGridView_Balance.Columns.Add("예탁자산평가액", "예탁자산평가액");
            dataGridView_Balance.Columns.Add("총매입금액", "총매입금액");
            dataGridView_Balance.Rows.Add();

            dataGridView_Stocks.Columns.Add("종목명", "종목명");
            dataGridView_Stocks.Columns.Add("보유수량", "보유수량");
            dataGridView_Stocks.Columns.Add("평균단가", "평균단가");
            dataGridView_Stocks.Columns.Add("현재가", "현재가");
            dataGridView_Stocks.Columns.Add("평가금액", "평가금액");
            dataGridView_Stocks.Columns.Add("손익금액", "손익금액");

            _tradeControls.Add(comboBox_Stock1);
            _tradeControls.Add(comboBox_Stock2);
            _tradeControls.Add(comboBox_Stock3);
            _tradeControls.Add(textBox_Quantity);
            _tradeControls.Add(textBox_Margin);
        }
예제 #14
0
        private void PriceCallback(AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveTrDataEvent e)
        {
            bool continued = true;

            int count = OpenApi.GetRepeatCnt(e);

            for (int i = 0; i < count; ++i)
            {
                string date       = OpenApi.GetTrData(e, IsDaily() ? "일자" : "체결시간", i);
                string startPrice = OpenApi.GetTrData(e, "시가", i);
                string highPrice  = OpenApi.GetTrData(e, "고가", i);
                string lowPrice   = OpenApi.GetTrData(e, "저가", i);
                string price      = OpenApi.GetTrData(e, "현재가", i);

                var stock = new StockPrice();

                if (IsDaily())
                {
                    DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out stock.Time);
                }
                else
                {
                    DateTime.TryParseExact(date, "yyyyMMddHHmmss", CultureInfo.CurrentCulture, DateTimeStyles.None, out stock.Time);
                }

                long.TryParse(startPrice, out stock.StartPrice);
                stock.StartPrice = Math.Abs(stock.StartPrice);

                long.TryParse(highPrice, out stock.HighPrice);
                stock.HighPrice = Math.Abs(stock.HighPrice);

                long.TryParse(lowPrice, out stock.LowPrice);
                stock.LowPrice = Math.Abs(stock.LowPrice);

                long.TryParse(price, out stock.Price);
                stock.Price = Math.Abs(stock.Price);

                if (stock.Time < _begin)
                {
                    continued = false;
                    break;
                }

                var nextEnd = _end.AddDays(1);
                if (stock.Time >= nextEnd)
                {
                    continue;
                }

                Items.Add(stock);

                if (_progress != null)
                {
                    _progress.Report(Items.Count);
                }
            }

            int seq;

            int.TryParse(e.sPrevNext, out seq);
            if (seq != 0 && continued)
            {
                Thread.Sleep(300);
                Request(_code, _begin, _end, this, _interval, _progress, seq);
            }
            else
            {
                Items.Reverse();
                _source.SetResult(this);
            }
        }