관리자 0 1,438 0 0

지금까지 작업한 내용정리

1. 키움증권 API를 이용하여 키움증권 로그인 처리완료.

2. 로그인 후 주식(코스닥, 코스피) 리스트 가져오기 완료.

3. Access Database 를 이용하여 관심종목 리스트 저장하기 완료.

4. 실시간 체결정보 가져오기까지는 완료했으며, 관심종목 리스트만 체결정보 가져오기는 아직 구현안함.

 

다음과제는 체결정보 가져온 데이터로 체결정보 패턴분석 알고리즘 만들기! 

외롭고 힘들고 고단한 작업이네요. 하지만 재미가 없지는 않습니다. 그렇지만 php 하다가 C# 만지니깐 적응이 안되네요;;;

 


 

 

 

 

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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
 
namespace Auto_Stock
{
    public partial class MainForm : Form
    {
        private string LoginName;
        private string LoginId;
 
        private string accFileName = "stock_db.accdb";
        private string dbPasswd = "admin";
 
        public MainForm()
        {
            InitializeComponent();
 
            /*
            OleDbConnection conn = new OleDbConnection();
            OleDbCommand connCmd = new OleDbCommand();
            Console.WriteLine("mainform start");
            try
            {
                Console.WriteLine("db access start");
                conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + this.accFileName + ";Mode=ReadWrite;Jet OLEDB:Database Password=" + this.dbPasswd;
                conn.Open();
                connCmd.Connection = conn;
                connCmd.CommandText = "INSERT INTO favorite(usr_id) VALUES(@usr_id)";
                connCmd.Parameters.Add(new OleDbParameter("@usr_id", "test"));
                connCmd.ExecuteNonQuery();    // 입력
                connCmd.CommandText = "SELECT * FROM favorite";
                OleDbDataReader oleData = connCmd.ExecuteReader(CommandBehavior.CloseConnection);
                while (oleData.Read())
                {
                    Console.WriteLine(oleData["userId"].ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            */
        }
 
        private void database_proc(string sql, Dictionary<stringstring> param)
        {
            OleDbConnection conn = new OleDbConnection();
            OleDbCommand connCmd = new OleDbCommand();
            try
            {
                conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + accFileName + ";Mode=ReadWrite;Jet OLEDB:Database Password=" + dbPasswd;
                conn.Open();
                connCmd.Connection = conn;
 
                //connCmd.CommandText = "INSERT INTO favorite(usr_id) VALUES(@usr_id)";
                connCmd.CommandText = sql;
                foreach (KeyValuePair<stringstring> row in param)
                {
                    //connCmd.Parameters.Add(new OleDbParameter("@usr_id", "test"));
                    connCmd.Parameters.Add(new OleDbParameter(row.Key, row.Value));
                }
                connCmd.ExecuteNonQuery();    // 입력
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception 에러발생 : " + ex.Message);
            }
            finally
            {
                conn.Close();
            }
        }
 
        private Dictionary<intDictionary<stringstring>> database_select(string sql, Dictionary<intstring> columns)
        {
            OleDbConnection conn = new OleDbConnection();
            OleDbCommand connCmd = new OleDbCommand();
            Dictionary<intDictionary<stringstring>> list = new Dictionary<intDictionary<stringstring>>();
            try
            {
                Console.WriteLine("select start");
                conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + this.accFileName + ";Mode=ReadWrite;Jet OLEDB:Database Password=" + this.dbPasswd;
                conn.Open();
                connCmd.Connection = conn;
 
                //connCmd.CommandText = "SELECT * FROM favorite";
                connCmd.CommandText = sql;
                OleDbDataReader oleData = connCmd.ExecuteReader(CommandBehavior.CloseConnection);
                int i = 0;
                while (oleData.Read())
                {
                    //Console.WriteLine("usr_id = " + oleData["usr_id"].ToString());
                    Dictionary<stringstring> list_row = new Dictionary<stringstring>();
                    foreach(KeyValuePair<intstring> row in columns)
                    {
                        string column = row.Value;
                        list_row[column] = oleData[column].ToString();
                    }
                    list[i++= list_row;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }
 
            return list;
        }
 
        //로그인 버튼 클릭
        private void ButtonLogin_Click(object sender, EventArgs e)
        {
            if(LoginName != null)
            {
                MessageBox.Show("이미 로그인 하셨습니다.");
                return;
            }
 
            long Result;
            Result = axKHOpenAPI1.CommConnect();
            if (Result != 0)
            {
                Console.WriteLine("로그인창 열기 실패!");
            }
            else
            {
                Console.WriteLine("로그인창 열기 성공!");
            }
        }
 
        //로그인 후 개인정보 가져오기
        private void axKHOpenAPI1_OnEventConnect(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnEventConnectEvent e)
        {
            Console.WriteLine("개인정보 가져오기 성공!");
            string UserName = axKHOpenAPI1.GetLoginInfo("USER_NAME");
            string UserId = axKHOpenAPI1.GetLoginInfo("USER_ID");
            ButtonLogin.Text = UserName + "(" + axKHOpenAPI1.GetLoginInfo("USER_ID"+  ")";
            LoginName = UserName;
            LoginId = UserId;
        }
 
        //전체종목리스트에서 주식 row를 클릭하면 실행
        private void listBoxStock_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
 
        //종목리스트 불러오기
        bool IsListCall = false;
        bool 전체종목리스트_초기체크 = true;
        private void ButtonListCall_Click(object sender, EventArgs e)
        {
            if (LoginName == null)
            {
                MessageBox.Show("로그인이 필요합니다.");
            }
            else
            {
                if(IsListCall == true)
                {
                    //MessageBox.Show("이미 호출된 상태입니다.");
                    //return;
                }
 
                Dictionary<stringstring> favorite_list = listVIew1_select();
                //Console.WriteLine(favorite_list);
 
                IsListCall = true;
 
                전체종목리스트_초기체크 = true;
                listView1.Items.Clear();
                ListViewStock.Items.Clear();
                ListViewStock.CheckBoxes = true// 항목옆에 확인란을 표시할지 여부를 선택합니다.
                //ListViewStock.Click += new EventHandler(ListViewCheckClick);
                //ListViewStock.OwnerDraw = true;
 
                //GetCodeListByMarket 메소드는 메소드의 인자로 시장 구분 코드를 문자열로 넘겨주면 메소드의 리턴 값으로 해당 시장에 속해 있는 종목들의 종목 코드 목록을 리턴
                //sMarket – 0:장내, 3:ELW, 4:뮤추얼펀드, 5:신주인수권, 6:리츠, 8:ETF, 9:하이일드펀드, 10:코스닥, 30:제3시장
                Console.WriteLine("종목 불러오기 시작");
                string[] marketList = { "0""10" };
                int InCnt = 0;
                int OutCnt = 0;
                int i = 0;
                foreach (string MNumber in marketList)
                {
                    string result = axKHOpenAPI1.GetCodeListByMarket(MNumber);
                    string[] stockList = result.Split(';');
 
                    if (MNumber == "0")
                    {
                        InCnt = stockList.Count();
                    }
                    else
                    {
                        OutCnt = stockList.Count();
                    }
 
                    int listView1_cnt = 0;
                    foreach (string code in stockList)
                    {
                        if (code != "")
                        {
                            string StockName = axKHOpenAPI1.GetMasterCodeName(code);
 
                            //전체종목리스트 ListView row 만들자
                            ListViewItem item = new ListViewItem(""0);
                            item.Checked = false// 체크박스는 일단 false
                            if (favorite_list.ContainsKey(code))
                            {
                                item.Checked = true;
                                listView1_add(listView1_cnt.ToString(), code, favorite_list[code]); //관심종목추가
                                listView1_cnt++;
                            }
                            else
                            {
                                item.Checked = false;
                            }
 
                            //SubItem
                            item.SubItems.Add(i.ToString());
                            item.SubItems.Add(StockName);
                            item.SubItems.Add(code);
 
                            ListViewStock.Items.Add(item);
                            i++;
                        }
                    }
                }
 
                전체종목리스트_초기체크 = false;
 
                //axKHOpenAPI1.SetInputValue("종목코드", 000030.ToString());
                //axKHOpenAPI1.CommRqData("000030_주식기본정보", "opt10001", 0, "0101");
                //axKHOpenAPI1.SetRealReg("0120", "000030", "9001;302;10;11;25;12;13", "1");  // 000030 종목을 실시간 추가등록
                axKHOpenAPI1.SetRealReg("0120""000030""20;15""1");
            }
        }
 
        //ListView의 이벤트는 [디자인]창에서 속성모드에서 function 명을 추가해서 사용하자.
        //[전체종목리스트] 체크박스 클릭시 발생
        private void ListViewStock_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            //Console.WriteLine("ListViewStock_ItemChecked");
            //Console.WriteLine(e.Item.Checked); //true or false
            if(전체종목리스트_초기체크 == false//초기로딩시에는 실행이 되면 안됨!
            {
                //Console.WriteLine(e.Item.SubItems.Count); //라인의 컬럼개수(4개)
                //Console.WriteLine(e.Item.Index); //라인 row index 번호
                //Console.WriteLine(e.Item.SubItems[2].Text); //유한양행
                if (e.Item.Checked == true)
                {
                    string sql = "INSERT INTO favorite(usr_id, stock_code, stock_name) VALUES(@usr_id, @stock_code, @stock_name)";
                    Dictionary<stringstring> param = new Dictionary<stringstring>();
                    param["@usr_id"= LoginId;
                    param["@stock_code"= e.Item.SubItems[3].Text; //000060
                    param["@stock_name"= e.Item.SubItems[2].Text; //하이트진로
                    database_proc(sql, param);
                }
                else
                {
                    string sql = "DELETE FROM favorite WHERE usr_id = @usr_id AND stock_code = @stock_code";
                    Dictionary<stringstring> param = new Dictionary<stringstring>();
                    param["@usr_id"= LoginId;
                    param["@stock_code"= e.Item.SubItems[3].Text; //000060
                    database_proc(sql, param);
                }
 
                listView1_loading();
            }
        }
 
        private Dictionary<stringstring> listVIew1_select()
        {
            Dictionary<intstring> columns = new Dictionary<intstring>();
            int ci = 0;
            columns[ci++= "stock_code";
            columns[ci++= "stock_name";
            Dictionary<intDictionary<stringstring>> list = database_select("SELECT * FROM favorite WHERE usr_id = '" + LoginId + "'", columns);
            Dictionary<stringstring> favorite_list = new Dictionary<stringstring>();
            foreach (KeyValuePair<intDictionary<stringstring>> row in list)
            {
                Console.WriteLine(row.Value["stock_code"+ " => " + row.Value["stock_name"]);
                favorite_list[row.Value["stock_code"]] = row.Value["stock_name"];
            }
 
            return favorite_list;
        }
 
        private void listView1_loading()
        {
            listView1.Items.Clear();
            Dictionary<stringstring> favorite_list = listVIew1_select();
            int i = 0;
            foreach (KeyValuePair<stringstring> row in favorite_list)
            {
                string number = i.ToString();
                listView1_add(number, row.Key, row.Value);
                i++;
            }
        }
 
        //관심종목 추가
        private void listView1_add(string number, string code, string codeString)
        {
            ListViewItem item2 = new ListViewItem(number, 0);
            item2.SubItems.Add(code);
            item2.SubItems.Add(codeString);
 
            listView1.Items.Add(item2);
        }
 
        //실시간 시세 이벤트라는데 뭔지 잘 몰겠다.
        //이게 보니깐 주기적으로 호출이 된다... 아마도 특정초단위로 알아서 호출되는 건가보다...
        private void axKHOpenAPI1_OnReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e)
        {
            //Console.WriteLine("sRealKey : " + e.sRealKey);
            //Console.WriteLine("sRealType : " + e.sRealType);
            //Console.WriteLine("sRealData : " + e.sRealData);
 
            //e.sRealKey = 종목코드
            //e.sRealType = 리얼타입 (주식시세, 주식체결 등)
            //e.sRealData = 실시간 데이터 전문
 
            if (e.sRealType == "주식체결")
            {
                Console.WriteLine("===============================================================");
                Console.WriteLine("현재가" + axKHOpenAPI1.GetCommRealData(e.sRealKey, 10));       // 현재가
                Console.WriteLine("체결시간" + axKHOpenAPI1.GetCommRealData(e.sRealKey, 20));     // 체결시간
                Console.WriteLine("체결량" + axKHOpenAPI1.GetCommRealData(e.sRealKey, 15));       // 체결량
                //Console.WriteLine("누적거래량" + axKHOpenAPI1.GetCommRealData(e.sRealKey, 13));   // 누적거래량
                //Console.WriteLine("체결강도" + axKHOpenAPI1.GetCommRealData(e.sRealKey, 228));    // 체결강도
            }
        }
    }
}
 
cs

 

Comments


카테고리