취미 및 과정/주식

[주식]자동매매 코드 수정

mabb 2022. 1. 6. 10:39
반응형

 안녕하세요. 삶의 질을 높이기 위해 노력하는 영차영차입니다.
프로그램이 저 대신 단타를 실행해 준다면 삶의 질이 좋아지겠죠?
부족한 실력이지만 저만의 주식 자동봇을 열심히 만들어보고 있습니다.

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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import win32com.client
import time
from datetime import datetime
 
 
# 인스턴스
instCpCybos = win32com.client.Dispatch('CpUtil.CpCybos')  #사이보스플러스 연결 상태를 확인하는 인스턴스
instStockChart = win32com.client.Dispatch("CpSysDib.StockChart")  #차트데이터를 수신하는 인스턴스
instCpStockCode = win32com.client.Dispatch("CpUtil.CpStockCode")  #주식 종목명 및 코드를 조회하는 인스턴스
instCpCodeMgr = win32com.client.Dispatch(("CpUtil.CpCodeMgr"))  #각종 코드정보 및 코드리스트를 얻는 인스턴스
instMarketEye = win32com.client.Dispatch("CpSysDib.MarketEye")  # 여러종목의 필요항목을 한번에 수신하는 인스턴스
instCpTdUtil = win32com.client.Dispatch("CpTrade.CpTdUtil")  # 계좌정보
instCpTd0311 = win32com.client.Dispatch("CpTrade.CpTd0311")  # 매수 매도 주문 인스턴스
instCpTdNew5331A = win32com.client.Dispatch("CpTrade.CpTdNew5331A")  # 계좌별 매수 가능 금액/ 수량 데이터
instCpTdNew5331B = win32com.client.Dispatch("CpTrade.CpTdNew5331B")  # 계좌별 매도 가능 수량데이터
instCpTd6033 = win32com.client.Dispatch("CpTrade.CpTd6033")  # 계좌별 잔고 및 주문체결 평가현황데이터를 요청하고 수신한다
instStockMst = win32com.client.Dispatch("Dscbo1.StockMst")  # 현재가, 호가 관련
instCpConclusion = win32com.client.Dispatch("Dscbo1.CpCOnclusion")  # 주식 체결 실시간
 
# 계좌정보
instCpTdUtil.TradeInit()
accountNumber = instCpTdUtil.AccountNumber[0]  # 계좌번호
accFlag = instCpTdUtil.GoodsList(accountNumber,1)  #거래구분 코드
 
# 시간 정보
now = int(datetime.now().strftime('%H%M'))
 
#print(hour)
 
# 매도 셋팅 / 손절선 0.95 / 익절선 1.05
 
# 연결 확인
def connect_check():
    print('사이보스플러스 연결를 체크합니다. 주인님')
    bConnect = instCpCybos.IsConnect
    if (bConnect == 0):
        print("PLUS가 정상적으로 연결되지 않았습니다요. ")
        exit() # 프로그램 종료
    elif (bConnect == 1):
        print('접속 성공입니다요. 주인님')
 
 
# target_list 필터링 / save / read 함수
def target_list_save_txt():  #target_list.txt 저장 / target_list_save.txt 함수는 장 전에 미리 수동실행 또는 자동실행 조건 설정
    f = open('C:\\Users\\Administrator\\Desktop\\target_list.txt''wt')
    target_list = cap_filter(instStockChart)
    for code in target_list:
        f.writelines('%s\n' %code)
    f.close()
    print('target_list.txt 저장 완료입니다요')
 
def target_list_read_txt(): # 저장된 target_list.txt 를 읽어오는 함수
    target_list = []
    f = open('C:\\Users\\Administrator\\Desktop\\target_list.txt''rt')
    target_list_a = f.readlines()
    for i in target_list_a:
        a = i.split('\n')[0]
        target_list.append(a)
    return target_list
 
def market_stock():  #target_list_save_txt함수 호출 시 연동됨 / 코스피,코스닥 중 주권 종목의 코드를 리스트로 추출함
    kospilist = instCpCodeMgr.GetStockListByMarket(1)   #코스피 코드리스트
    kosdaqlist = instCpCodeMgr.GetStockListByMarket(2)  #코스닥 코드리스트
    market = kospilist + kosdaqlist  # 코스피 + 코스닥 코드리스트
    market_stock = []
    for code in market:
        check = instCpCodeMgr.GetStockSectionKind(code)
        if check == 1:
            market_stock.append(code)
    return market_stock
 
def cap_filter(instStockChart):   #market_stock을 시가총액으로 필터링 / market_stock()을 호출하여 시가총액으로 필터링
    market_code = market_stock()  #target_list_save_txt함수 호출 시 연동됨 /
    target_list = []
    print('시가총액 300억~1000억 종목을 찾고 있습니다. 주인님')
    for code in market_code:
        instStockChart.SetinputValue(0,code)
        instStockChart.SetinputValue(1,ord('2'))
        instStockChart.SetinputValue(4,1)
        instStockChart.SetinputValue(5,13)
        instStockChart.SetinputValue(6,ord('D'))
        instStockChart.SetinputValue(9,ord('1'))
        instStockChart.BlockRequest()
        time.sleep(1.02)
 
        cap =  instStockChart.GetDataValue(0,0)
 
        if (cap >= 30000000000and (cap <= 100000000000):
            target_list.append(code)
            print(len(target_list),'/',len(market_code))
 
    print('타겟 리스트는',len(target_list),'개 입니다. 주인님')
    return target_list
 
 
# 보유종목 반환 함수
def bought_item():  # 보유종목 정보를 반환하는 함수  -> 종목보유여부 체크 및 매도 감시 시 활용
    instCpTdNew5331B.SetInputValue(0,accountNumber)
    instCpTdNew5331B.SetInputValue(1,accFlag[0])
    instCpTdNew5331B.SetInputValue(3,ord('1'))
    instCpTdNew5331B.SetInputValue(4,ord('1'))
    instCpTdNew5331B.BlockRequest()
 
    try:
        savestock_code = instCpTdNew5331B.GetDataValue(0,0)  # 보유종목 코드
        savestock_name = instCpTdNew5331B.GetDataValue(1,0)  # 보유종목 이름
        savestock_quant = instCpTdNew5331B.GetDataValue(12,0#보유종목 매도 가능 수량
        return (savestock_name,savestock_quant,savestock_code)
    except:
        savestock_code = 'none'
        savestock_name = 'none'
        savestock_quant = 0
        return (savestock_name,savestock_quant,savestock_code)
 
def bought_check(): # 보유종목이 있는지 체크하는 함수
    instCpTdNew5331B.SetInputValue(0, accountNumber)
    instCpTdNew5331B.SetInputValue(1, accFlag[0])
    instCpTdNew5331B.SetInputValue(3, ord('1'))
    instCpTdNew5331B.SetInputValue(4, ord('1'))
    instCpTdNew5331B.BlockRequest()
 
    try:
        balance = instCpTdNew5331B.GetDataValue(120)  # 매도가능수량
        if balance != 0:
            return 1  #매도가능 수량이 있음
    except:
        return 0  #매도가능 수량이 없음 / 없으면 에러가 남
 
 
# 종목 선정 함수
def buy_observer(instStockChart,target_list):  # target_list를 서치하여 1개의 종목을 찾아냄
    check = 0
    will_buy_item = []
    while check == 0:
        time.sleep(1.02)
        for code in target_list:   # tqrget_list의 종목 별 0~11봉 거래량 값을 입력값으로 설정
            instStockChart.SetInputValue(0, code)   #종목 코드
            instStockChart.SetInputValue(1, ord('2'))   #'1' 날짜구간 , '2' 갯수
            instStockChart.SetInputValue(411)   # 11개 값 수신 요청  0봉(현재봉) ~ 10봉 까지 11개 값
            instStockChart.SetInputValue(58)    # 거래량
            instStockChart.SetInputValue(6, ord('D'))   # 일봉
            instStockChart.SetInputValue(9, ord('1'))   # 수정주가
            instStockChart.BlockRequest()   #입력값을 api 요청
 
            volumes = []
            numData = instStockChart.GetHeaderValue(3)   # 수신 값의 갯수, 11봉을 요청했으므로 11이 수신됨
            for i in range(numData): # 0~10까지 반복하며 0봉부터 10봉까지의 거래량을 volumes 에 리스트로 저장함
                volume = instStockChart.GetDataValue(0, i)
                volumes.append(volume)
 
            averageVolume = (sum(volumes) - volumes[0]) / (len(volumes) - 1)  # 1~10봉 거래량 평균
 
            if (volumes[0> averageVolume * 2): #0봉(현재봉)과 1~10봉 평균 거래량으로 조건을 설정하여 will_buy_item에 바인딩
                will_buy_item.append(code)
                print('종목을 찾았습니다요. 주인님. 종목코드는',code,'입니다요')
                check = 1   # while 문 탈출
                break  # for문 탈출 순차 탐색 중 먼저 조건에 부합하는 종목을 발견하면 탐색을 종료하는 방식이므로
                       # for문의 속도가 느릴 경우 target_list의 순서 영향을 많이 받을 것임. 종목 탐색의 시간 설정이 중요함
    return will_buy_item
 
 
def buy_observer2(instStockChart,target_list):  # target_list를 서치하여 1개의 종목을 찾아냄
    check = 0
    will_buy_item = []
    while check == 0:
        time.sleep(1.02)
 
        #for code in target_list:
         #   print('종목탐색시작')
 
          #  instMarketEye.SetInputValue(0, (12, '0'))
           # instMarketEye.SetInputValue(0, 68)
            #instMarketEye.SetInputValue(1, code)
            #instMarketEye.BlockRequest()
 
            #buy_rest = instMarketEye.GetDataValue(0, 0)
            #print(buy_rest)
 
            #if buy_rest > 100:
 
        for code in target_list:
                instStockChart.SetInputValue(0, code)  # 종목 코드
                instStockChart.SetInputValue(1, ord('2'))  # '1' 날짜구간 , '2' 갯수
                instStockChart.SetInputValue(411)  # 11개 값 수신 요청  0봉(현재봉) ~ 10봉 까지 11개 값
                instStockChart.SetInputValue(5, [258])  # 시가, 종가, 거래량
                instStockChart.SetInputValue(6, ord('D'))  # 일봉
                instStockChart.SetInputValue(9, ord('1'))  # 수정주가
                instStockChart.BlockRequest()  # 입력값을 api 요청
                #양봉인지 체크, 종가 - 시가
                start = instStockChart.GetDataValue(00)
                end = instStockChart.GetDataValue(10)
                gap = end - start
                # 종가 - 시가가 0보다 크면 거래량 조건을 체크함
                print(code,'시가종가차이',gap)
                if gap > 0:
                    volumes = []
                    for i in range(11):  # 0~10까지 반복하며 0봉부터 10봉까지의 거래량을 volumes 에 리스트로 저장함
                        volume = instStockChart.GetDataValue(2, i)
                        volumes.append(volume)
 
                    averageVolume = (sum(volumes) - volumes[0]) / (len(volumes) - 1)  # 1~10봉 거래량 평균
                    # 지난 10일 평균 거래량의 1.5배를 달성하면 60분선 이격도를 체크함
                    print('현재거래량',volumes[0],'10일평균거래량1.5',averageVolume*1.5)
                    if (volumes[0> averageVolume * 1.5):  # 0봉(현재봉)과 1~10봉 평균 거래량으로 조건을 설정하여 will_buy_item에 바인딩
                        instStockChart.SetInputValue(0, code)  # 종목 코드
                        instStockChart.SetInputValue(1, ord('2'))  # '1' 날짜구간 , '2' 갯수
                        instStockChart.SetInputValue(460)  # 11개 값 수신 요청  0봉(현재봉) ~ 10봉 까지 11개 값
                        instStockChart.SetInputValue(55)  # 종가
                        instStockChart.SetInputValue(6, ord('m'))  # 일봉
                        instStockChart.SetInputValue(9, ord('1'))  # 수정주가
                        instStockChart.BlockRequest()  # 입력값을 api 요청
                        time.sleep(1)
 
                        end_min_aver = []
                        for j in range(60):
                            end_min = instStockChart.GetDataValue(0, j)
                            end_min_aver.append(end_min)
                        # 60분선 이동평균값을 구함
                        average_end_min = sum(end_min_aver) / 60
                        # 60분선 이동평균값와 현재가의 이격도가 102 미만인 경우 will_buy_item에 추가
                        print('60분선평균',average_end_min)
                        print(end_min_aver[0],average_end_min)
                        if float(end_min_aver[0/ average_end_min) < 1.02:
 
                            will_buy_item.append(code)
                            print('주인님 종목을 찾았습니다요!! 양봉/ 거래량 1.5배돌파 / 60분선 이격도 102 이하')
                            check = 1
                            break
    return will_buy_item
 
 
# will_buy_item 호가 출력 및 반환 함수
def item_hoga_data(will_buy_item):   # 호가 정보를 출력하는 함수 / 매수 주문 시 단가로 활용/ 1차 호가주문으로 활용해보자
    instStockMst.SetInputValue(0,will_buy_item)
    instStockMst.BlockRequest()
 
    item_buy_hoga_1 = instStockMst.GetDataValue(1,0)  # 매수 1차 호가 // 매수 주문 시 활용
    item_buy_hoga_2 = instStockMst.GetDataValue(11)
    item_buy_hoga_3 = instStockMst.GetDataValue(12)
    item_sell_hoga_1 = instStockMst.GetDataValue(00)  # 매도 1차 호가
    item_sell_hoga_2 = instStockMst.GetDataValue(01)
    item_sell_hoga_3 = instStockMst.GetDataValue(02)
 
    print('호가정보입니다요.')
    print(instStockMst.GetDataValue(0,2))
    print(instStockMst.GetDataValue(0,1))
    print(instStockMst.GetDataValue(0,0))
    print('--------------------')
    print(instStockMst.GetDataValue(1,0))
    print(instStockMst.GetDataValue(1,1))
    print(instStockMst.GetDataValue(1,2))
 
    return (item_buy_hoga_1,item_buy_hoga_2,item_buy_hoga_3,
            item_sell_hoga_1,item_sell_hoga_2,item_sell_hoga_3)
 
#매수 정보 반환 함수
def buy_possible(will_buy_item,buy_hoga):  # 매수를 위한 정보 / 호가 정보를 인수롤 받아오도록 수정해야함.
    instCpTdNew5331A.SetInputValue(0, accountNumber) # 계좌번호
    instCpTdNew5331A.SetInputValue(1, accFlag[0]) # 상품관리 구분 코드
    instCpTdNew5331A.SetInputValue(2, will_buy_item) # 2 - (string) 종목코드[default:""]- 수량조회시입력
    instCpTdNew5331A.SetInputValue(3'01'#일반/ fok로 주문하면될듯
    instCpTdNew5331A.SetInputValue(4, buy_hoga) # 4 - (long) 주문단가[default:0] - 수량조회시입력
    instCpTdNew5331A.SetInputValue(5'Y'# 5 - Y:증거금 100 %
    instCpTdNew5331A.SetInputValue(6, ord('2')) # 6 - (char)조회구분코드; '1'=금액조회[default], '2'=수량조회
    instCpTdNew5331A.BlockRequest()
 
    possible_amount = int(instCpTdNew5331A.GetHeaderValue(9)) # 증거금 100% 가능 금액 조회
    possible_quant = int(instCpTdNew5331A.GetHeaderValue(17)) # 증거금 100% 주문 가능 수량 조회
 
    print('주문가능금액과',possible_amount)
    print('주문가능수량',possible_quant,'입니다요')
    return (possible_quant,possible_amount)
 
#매수 주문 함수
def buy_order(item,quant,hoga): # 매수주문
    instCpTd0311.SetInputValue(0,'2')
    instCpTd0311.SetInputValue(1,accountNumber)
    instCpTd0311.SetInputValue(2,accFlag[0])
    instCpTd0311.SetInputValue(3,item)
    instCpTd0311.SetInputValue(4,quant)
    instCpTd0311.SetInputValue(5,hoga)
    instCpTd0311.SetInputValue(7,'2'#FOK
    instCpTd0311.SetInputValue(8,'01'#01보통 03시장가 13최우선지정가
    instCpTd0311.BlockRequest()
 
#계좌 수익률 반환 함수
def benefit_ratio():  # 계좌 수익률을 출력하는 함수 / 매도 감시 시 활용
 
    instCpTd6033.SetInputValue(0,accountNumber)
    instCpTd6033.SetInputValue(1,accFlag[0])
    instCpTd6033.SetInputValue(3,'1')
    instCpTd6033.BlockRequest()
 
    #print(instCpTd6033.GetHeaderValue(8))  # 수익률 / 수익률을 기준으로 손절 익절 매도주문을 진행 / 수수료 감안해야함
    ratio = instCpTd6033.GetHeaderValue(8)
    return ratio
 
#호가 출력 및 반환 함수
def save_hoga_data(savestock_code):  # 호가 정보를 출력하는 함수 / 매도 주문 시 단가로 활용/ 1차 호가주문으로 활용해보자
 
    instStockMst.SetInputValue(0, savestock_code)
    instStockMst.BlockRequest()
 
    save_buy_hoga_1 = instStockMst.GetDataValue(10)  # 매수 1차 호가 // 매수 주문 시 활용
    save_buy_hoga_2 = instStockMst.GetDataValue(11)
    save_buy_hoga_3 = instStockMst.GetDataValue(12)
    save_sell_hoga_1 = instStockMst.GetDataValue(00)  # 매도 1차 호가
    save_sell_hoga_2 = instStockMst.GetDataValue(01)
    save_sell_hoga_3 = instStockMst.GetDataValue(02)
 
    print('호가정보입니다요.')
    print(instStockMst.GetDataValue(0,2))
    print(instStockMst.GetDataValue(0,1))
    print(instStockMst.GetDataValue(0,0))
    print('--------------------')
    print(instStockMst.GetDataValue(1,0))
    print(instStockMst.GetDataValue(1,1))
    print(instStockMst.GetDataValue(1,2))
 
    return (save_buy_hoga_1,save_buy_hoga_2,save_buy_hoga_3,
            save_sell_hoga_1,save_sell_hoga_2,save_sell_hoga_3)
 
# 매도감시 함수 / 수익률이 익절선, 손절선 만족 시 매도 주문 실행 / 장중에만 실행시키려면?
def sell_obsever():
    print('매도 감시중입니다요. 주인님')
    check = 0
    #ratio_count = 0  # 임시로 무한루프를 종료하기 위한 기능
    while check == 0:
        time.sleep(1)
        ratio = benefit_ratio()
        print('현재수익률입니다요:',ratio)
        #ratio_count += 1
        #if ratio_count == 10:
         #   print('종료처리합니다요')
          #  check = 1
           # return 1
        if ratio > 103# 익절
            print('얏호 익절 신호입니다요')
            check = 1
            return 1
        elif ratio < 97# 손절
            print('손절입니다 도망치십시요~!')
            check = 1
            return 0
 
 
#매도주문 함수
def sell_order(item,quant,hoga):  # 매도주문
    instCpTd0311.SetInputValue(0,'1'# 매도
    instCpTd0311.SetInputValue(1,accountNumber)
    instCpTd0311.SetInputValue(2,accFlag[0])
    instCpTd0311.SetInputValue(3,item)
    instCpTd0311.SetInputValue(4,quant)
    instCpTd0311.SetInputValue(5,hoga)
    instCpTd0311.SetInputValue(7,'2')
    instCpTd0311.SetInputValue(8,'01')
    instCpTd0311.BlockRequest()
 
 
 
#프로그램 실행
 
#연결 여부 체크
connect_check()
 
#타겟 리스트 셋팅
#target_list_save_txt()
target_list = target_list_read_txt()  # target_list 호출 //
 
#현재 시간 호출
now = int(datetime.now().strftime('%H%M'))
 
 
 
 
 
# 시간이  9시00분 전이거나 15시30분 이후면 장외 대기
while now > 1530 or now < 900:
    now = int(datetime.now().strftime('%H%M'))
    print('장외 입니다요.')
    time.sleep(20)
 
# 시간이 9시 이상이거나 15시 30분보다 작으면 장 중으로 코드 수행
print('장이 열립니다요!')
while now >= 900 and now < 1530:  #장 중에만 반복   # 테스트시 1
    now = int(datetime.now().strftime('%H%M'))
    # 보유종목 체크
    boughtcheck = bought_check()  # 0:미보유중 1:보유중
    #보유 종목이 있을 경우 매도감시 및 매도주문
    if boughtcheck == 1:
        print('보유종목 정보를 가져와보겠습니다요')
        savestock_name,savestock_quant,savestock_code = bought_item()
        print(savestock_name,'종목을',savestock_quant,'주 보유중입니다요')
 
        #sell_check로 익절 및 손절 반복 감시 수행
        sell_check = sell_obsever()
        if sell_check == 1 : #익절 신호 확인 시 매도 정보 추출
            print('익절 신호입니다요!!'# 매수 1호가에 익절
            save_buy_hoga_1, save_buy_hoga_2, save_buy_hoga_3,\
            save_sell_hoga_1, save_sell_hoga_2, save_sell_hoga_3\
            = save_hoga_data(savestock_code)
            print(savestock_name,'종목',savestock_quant,'주를',save_buy_hoga_1,
                  '원에 매도 주문 신청합니다요')
            instCpTdUtil.TradeInit()
            sell_order(savestock_code,savestock_quant,save_buy_hoga_1)
            print('매도 주문 완료입니다 주인님')
            print('매도 체결 대기 중입니다요.')
            # savestock_name이 none이 되면 보유 종목이 없는 것.
            while savestock_name != 'none':
                savestock_name,savestock_quant,savestock_code = bought_item()
                time.sleep(1)
            print('익절 완료입니다요')
            # 재진입 지양
            target_list.remove(savestock_code)
            print('새로운 종목을 찾습니다요')
            boughtcheck = bought_check()
            continue
 
        elif sell_check == 0# 손절 신호 확인 시 매도 정보 추출
            print('손실입니다요!!')
            save_buy_hoga_1, save_buy_hoga_2, save_buy_hoga_3, \
            save_sell_hoga_1, save_sell_hoga_2, save_sell_hoga_3 \
            = save_hoga_data(savestock_code)
            print(savestock_name, '종목', savestock_quant, '주를', save_buy_hoga_1,
                  '원에 매도 주문 신청합니다요')
            instCpTdUtil.TradeInit()
            sell_order(savestock_code,savestock_quant,save_buy_hoga_1)
            print('매도 주문 완료입니다요 주인님')
 
            print('매도 체결 대기 중입니다요.')
            while savestock_name != 'none':
                savestock_name, savestock_quant, savestock_code = bought_item()
                time.sleep(1)
            print('손절 완료입니다요')
            # 재진입 지양
            target_list.remove(savestock_code)
            print('새로운 종목을 찾습니다요')
            boughtcheck = bought_check()
            continue
 
    # 보유종목이 없을 경우 매수 종목 탐색
    if boughtcheck == 0 :
        will_buy_item = buy_observer2(instStockChart,target_list)
        will_buy_item_name = instCpStockCode.CodeToName(will_buy_item[0])
        item_buy_hoga_1, item_buy_hoga_2, item_buy_hoga_3,\
        item_sell_hoga_1, item_sell_hoga_2, item_sell_hoga_3\
        =item_hoga_data(will_buy_item[0])
        possible_quant,possible_amount = buy_possible(will_buy_item[0],item_sell_hoga_1)
 
        if possible_quant == 0:
            print('총알이 부족합니다요,')
            print('다른 종목을 찾습니다요')
            target_list.remove(will_buy_item[0])
            if len(target_list) == 0:
                print('살 수 있는 종목이 없습니다요')
                quit()
            continue
 
        if possible_quant > 0:
            print('매수를 진행합니다요')
            print(will_buy_item_name,'종목',possible_quant,'주를',
                  item_sell_hoga_1,'원에 매수합니다요')
            buy_order(will_buy_item[0],possible_quant,item_sell_hoga_1)
            print('매수주문을 완료하였습니다요')
 
            print('체결 완료 대기중입니다요')
            buy_complete_check = 0
            time_check_a = int(datetime.now().strftime('%H%M'))
            while buy_complete_check == 0 :
                savestock_name, savestock_quant, savestock_code\
                =bought_item()
                time.sleep(1)
                # 매수 주문 완료 후 시간 체크
                time_check_b =int(datetime.now().strftime('%H%M'))
                if time_check_b - time_check_a > 3:
                    print('3분 초과하여 매수주문 취소합니다요')
                    print('종목 재검색을 합니다요.')
                    target_list.remove(will_buy_item[0])
                    buy_complete_check = 1
                    continue
 
                if possible_quant == savestock_quant:
                    buy_complete_check = 1
                    print('매수 체결 완료입니다요.')
                    continue
 
 
cs
반응형