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
|
import sys
from PyQt5.QtWidgets import * #pip install PyQt5
from PyQt5.QtGui import *
from PyQt5.QAxContainer import *
from PyQt5.QtCore import *
import yfinance as yf #pip install yfinance
from pandas_datareader import data as pdr #pip install pandas_datareader
yf.pdr_override() #yifannce 오버라이드
import pandas as pd
from pandas import DataFrame
import mplfinance as mpf #pip install mplfinance
from matplotlib.backends.backend_qt5agg import FigureCanvas as FigureCanvas
from matplotlib.ticker import FormatStrFormatter
from datetime import datetime, timedelta
from workalendar.usa import NewYork #pip install tox, pip install workalendar==2.4.0
from pytz import timezone #나스닥 타임존 설정용
from apscheduler.schedulers.background import BackgroundScheduler #pip install apscheduler
from apscheduler.jobstores.base import JobLookupError #특정 시간이나 일정 간격 실행을 위한 모듈
import time
koreanInvest_id = "@"
koreanInvest_account = ""
koreanInvest_account_code = ""
koreanInvest_account_password = ""
koreanInvest_stock_exchange = "NASD"
koreanInvest_stock_code = "TQQQ"
koreanInvest_stock_count = "1"
koreanInvest_stock_price = "6.11"
koreanInvest_stock_type = "00" # 00:지정가, 01:시장가, LOO:32, LOC:34
def job(mainWidget):
print(mainWidget.df)
def ICMK(data, period=26):
period_high = data['High'].rolling(window=period).max()
period_low = data['Low'].rolling(window=period).min()
return (period_high + period_low) / 2
def SMA(data, period=20):
return data.rolling(window=period).mean()
def RSI (data, time_window):
diff = data.diff(1).dropna() # diff in one field(one day)
#this preservers dimensions off diff values
up_chg = 0 * diff
down_chg = 0 * diff
# up change is equal to the positive difference, otherwise equal to zero
up_chg[diff > 0] = diff[ diff>0 ]
# down change is equal to negative deifference, otherwise equal to zero
down_chg[diff < 0] = diff[ diff < 0 ]
# check pandas documentation for ewm
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html
# values are related to exponential decay
# we set com=time_window-1 so we get decay alpha=1/time_window
up_chg_avg = up_chg.ewm(com=time_window-1 , min_periods=time_window).mean()
down_chg_avg = down_chg.ewm(com=time_window-1 , min_periods=time_window).mean()
rs = abs(up_chg_avg/down_chg_avg)
rsi = 100 - 100/(1+rs)
return rsi
class MainWidget(QWidget):
def __init__(self):
super().__init__()
self.nasdaq_calendar = NewYork() #나스닥 워킹 데이 체크
self.summer_time_2022_start_date = datetime(2022, 3, 13, tzinfo = timezone('US/Eastern'))
self.summer_time_2022_end_date = datetime(2022, 11, 5, tzinfo = timezone('US/Eastern'))
self.nasdaq_time = datetime.now(timezone('US/Eastern')) #나스닥 거래소 시간으로 설정
self.isSummertime = False
if self.nasdaq_time - self.summer_time_2022_start_date > timedelta(days = 0) and self.summer_time_2022_end_date - self.nasdaq_time > timedelta(days = 0):
self.isSummertime = True
else:
self.isSummertime = False
self.today_date = self.nasdaq_time.strftime("%Y-%m-%d")
self.start_date = (self.nasdaq_time - timedelta(days=90)).strftime("%Y-%m-%d")
self.df = pdr.get_data_yahoo('TQQQ', start=self.start_date, end=self.today_date) #yfinance 에서 TQQQ 데이터 다운로드
self.df['SMA5'] = SMA(self.df['Close'], 5) #이평선 5
self.df['SMA10'] = SMA(self.df['Close'], 10) #이평선 10
self.df['SMA20'] = SMA(self.df['Close'], 20) #이평선 20
self.df['ICMK'] = ICMK(self.df, 26) # 일목균형표 26일
self.df['RSI'] = RSI(self.df['Close'], 14) #RSI 14 일
self.df_dummy_data = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # 행 하나 추가
self.df_columns = ['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume', 'SMA5', 'SMA10', 'SMA20', 'ICMK', 'RSI']
self.today_date = [self.nasdaq_time.strftime("%Y-%m-%d")]
self.df_today = DataFrame(data=self.df_dummy_data, index=pd.to_datetime(self.today_date), columns=self.df_columns)
self.df = pd.concat([self.df, self.df_today])
#print(self.df)
fig, axlist = mpf.plot(self.df, datetime_format='%b %d', type='candle', volume=True, mav=(20), style='starsandstripes', returnfig=True) # 그래프 그리기
axlist[0].yaxis.set_major_formatter(FormatStrFormatter('$%.0f')) #숫자 뒤에 $ 붙이기
canvas = FigureCanvas(fig)
canvas.draw()
self.label_ID = QLabel("한투 ID:")
self.line_edit_ID = QLineEdit(self)
self.line_edit_ID.setText(koreanInvest_id)
self.label_account_password = QLabel("한투 비번:")
self.line_edit_account_password = QLineEdit(self)
self.line_edit_account_password.setText(koreanInvest_account_password)
self.label_account = QLabel("한투 계좌:")
self.line_edit_account = QLineEdit(self)
self.line_edit_account.setText(koreanInvest_account)
self.label_account_code = QLabel("한투 계좌 코드:")
self.line_edit_account_code = QLineEdit(self)
self.line_edit_account_code.setText(koreanInvest_account_code)
self.label_stock_exchange = QLabel("거래소:")
self.line_edit_stock_exchange = QLineEdit(self)
self.line_edit_stock_exchange.setText("NASD")
self.line_edit_stock_exchange.setEnabled(False)
self.label_stock_code = QLabel("종목:")
self.line_edit_stock_code = QLineEdit(self)
self.line_edit_stock_code.setText(koreanInvest_stock_code)
self.label_stock_count = QLabel("수량:")
self.line_edit_stock_count = QLineEdit(self)
self.line_edit_stock_count.setText(koreanInvest_stock_count)
self.label_stock_price = QLabel("지정가:")
self.line_edit_stock_price = QLineEdit(self)
self.line_edit_stock_price.setText(koreanInvest_stock_price)
self.label_krw = QLabel("KRW(₩):")
self.label_krw_balance = QLabel("0")
self.label_usd = QLabel("USD($):")
self.label_usd_balance = QLabel("0")
self.text_edit = QTextEdit(self)
self.text_edit.setGeometry(0, 0, 1200, 600)
# self.text_edit.setEnabled(False)
# 매수 버튼
self.btn_buy = QPushButton("Buy", self) # 버튼 텍스트
self.btn_buy.clicked.connect(self.btn_buy_clicked) # 클릭 시 실행할
# 매도 버튼
self.btn_sell = QPushButton("Sell", self) # 버튼 텍스트
self.btn_sell.clicked.connect(self.btn_sell_clicked) # 클릭 시 실행할
# 실시간 라이브 on 버튼
self.btn_live_on = QPushButton("Live on", self) # 버튼 텍스트
self.btn_live_on.clicked.connect(self.btn_live_on_clicked) # 클릭 시 실행할
# 실시간 라이브 off 버튼
self.btn_live_off = QPushButton("Live off", self) # 버튼 텍스트
self.btn_live_off.clicked.connect(self.btn_live_off_clicked) # 클릭 시 실행할
# 한국계좌 잔고 체크
self.btn_check_balance = QPushButton("Balance", self) # 버튼 텍스트
self.btn_check_balance.clicked.connect(self.btn_check_balance_clicked) # 클릭 시 실행할
# 미국계좌 잔고 체크
self.btn_check_us_balance = QPushButton("US Balance", self) # 버튼 텍스트
self.btn_check_us_balance.clicked.connect(self.btn_check_us_balance_clicked) # 클릭 시 실행할
mainLayout = QVBoxLayout() #레이아웃 추가
sub1Layout = QHBoxLayout()
sub1_1Layout = QGridLayout()
sub1_2Layout = QVBoxLayout()
sub2Layout = QHBoxLayout()
chartLayout = QVBoxLayout()
sub1Layout.addLayout(sub1_1Layout)
sub1Layout.addLayout(sub1_2Layout)
mainLayout.addLayout(sub1Layout)
mainLayout.addLayout(sub2Layout)
mainLayout.addLayout(chartLayout)
sub1_1Layout.addWidget(self.label_ID, 0, 0)
sub1_1Layout.addWidget(self.line_edit_ID, 0, 1)
sub1_1Layout.addWidget(self.label_account_password, 0, 2)
sub1_1Layout.addWidget(self.line_edit_account_password, 0, 3)
sub1_1Layout.addWidget(self.label_account, 1, 0)
sub1_1Layout.addWidget(self.line_edit_account, 1, 1)
sub1_1Layout.addWidget(self.label_account_code, 1, 2)
sub1_1Layout.addWidget(self.line_edit_account_code, 1, 3)
sub1_1Layout.addWidget(self.label_stock_exchange, 2, 0)
sub1_1Layout.addWidget(self.line_edit_stock_exchange, 2, 1)
sub1_1Layout.addWidget(self.label_stock_code, 2, 2)
sub1_1Layout.addWidget(self.line_edit_stock_code, 2, 3)
sub1_1Layout.addWidget(self.label_stock_count, 3, 0)
sub1_1Layout.addWidget(self.line_edit_stock_count, 3, 1)
sub1_1Layout.addWidget(self.label_stock_price, 3, 2)
sub1_1Layout.addWidget(self.line_edit_stock_price, 3, 3)
sub1_1Layout.addWidget(self.label_krw, 4, 0)
sub1_1Layout.addWidget(self.label_krw_balance, 4, 1)
sub1_1Layout.addWidget(self.label_usd, 4, 2)
sub1_1Layout.addWidget(self.label_usd_balance, 4, 3)
sub1_2Layout.addWidget(self.text_edit)
sub2Layout.addWidget(self.btn_buy)
sub2Layout.addWidget(self.btn_sell)
sub2Layout.addWidget(self.btn_live_on)
sub2Layout.addWidget(self.btn_live_off)
sub2Layout.addWidget(self.btn_check_balance)
sub2Layout.addWidget(self.btn_check_us_balance)
chartLayout.addWidget(canvas)
self.setLayout(mainLayout)
self.setGeometry(0, 0, 1200, 600)
self.btn_check_balance_clicked()
self.btn_check_us_balance_clicked()
def btn_buy_clicked(self):
# 주문 입력 및 전송
self.tran_os_us_buy = QAxWidget("ITGExpertCtl.ITGExpertCtlCtrl.1")
self.tran_os_us_buy.SetSingleData(0, self.line_edit_account.text()) #종합계좌번호 ##계좌일련번호[8],)
self.tran_os_us_buy.SetSingleData(1, self.line_edit_account_code.text()) #계좌상품코드 ##계좌 상품코드, GetAccount() 함수 이용(뒤 2자리)
self.tran_os_us_buy.SetSingleData(2, self.tran_os_us_buy.GetEncryptPassword(self.line_edit_account_password.text())) #계좌비밀번호(반드시 암호화 처리 필요)
self.tran_os_us_buy.SetSingleData(3, self.line_edit_stock_exchange.text()) #해외거래소코드 ##거래소코드 나스닥 NASD 뉴욕 NVSE 아맥스 AMEX
self.tran_os_us_buy.SetSingleData(4, self.line_edit_stock_code.text()) #상품번호 ##종목코드
self.tran_os_us_buy.SetSingleData(5, self.line_edit_stock_count.text()) #주문수량
self.tran_os_us_buy.SetSingleData(6, self.line_edit_stock_price.text()) #해외주문단가 ##주문가격
self.tran_os_us_buy.SetSingleData(7, "") #연락전화번호 #전화번호 필수값 아님
self.tran_os_us_buy.SetSingleData(8, "") #운용사지정주문번호 입력하지 않음
self.tran_os_us_buy.SetSingleData(9, "0") #주문서버구분코드 고정값 0
self.tran_os_us_buy.SetSingleData(10, "00") # 주문구분, 00: 지정가, 01: 시장가 LOO:32 LOC:34
#항목 설정
self.tran_os_us_buy.RequestData("OS_US_BUY")
self.text_edit.append("미국 매수주문 전송 [" + str(self.tran_os_us_buy.GetSendRqID()) + "] ")
self.tran_os_us_buy.ReceiveData.connect(self.tran_os_us_buy_receivedata) #이벤트 연결
def tran_os_us_buy_receivedata(self):
# 주문응답 이벤트
self.text_edit.append("미국 매수주문 응답 [" + str(self.tran_os_us_buy.GetSendRqID()) + "] ")
#결과 메세지
self.text_edit.append("[" + str(self.tran_os_us_buy.GetSendRqID()) + "] " + self.tran_os_us_buy.GetReqMsgCode() + " " + self.tran_os_us_buy.GetReqMessage())
self.text_edit.append("주문번호 : " + self.tran_os_us_buy.GetSingleData(1, 0))
self.text_edit.append("주문시간 : " + self.tran_os_us_buy.GetSingleData(2, 0))
def btn_sell_clicked(self):
self.tran_os_us_sell = QAxWidget("ITGExpertCtl.ITGExpertCtlCtrl.1")
self.tran_os_us_sell.SetSingleData(0, self.line_edit_account.text()) #계좌일련번호[8], GetAccount() 함수 이용(앞 8자리)
self.tran_os_us_sell.SetSingleData(1, self.line_edit_account_code.text()) #계좌 상품코드, GetAccount() 함수 이용(뒤 2자리)
self.tran_os_us_sell.SetSingleData(2, self.tran_os_us_sell.GetEncryptPassword(self.line_edit_account_password.text())) #계좌비밀번호(반드시 암호화 처리 필요)
self.tran_os_us_sell.SetSingleData(3, self.line_edit_stock_exchange.text()) #거래소코드
self.tran_os_us_sell.SetSingleData(4, self.line_edit_stock_code.text()) #종목코드
self.tran_os_us_sell.SetSingleData(5, self.line_edit_stock_count.text()) #주문수량
self.tran_os_us_sell.SetSingleData(6, self.line_edit_stock_price.text()) #주문가격
self.tran_os_us_sell.SetSingleData(7, "") #전화번호
self.tran_os_us_sell.SetSingleData(8, "") #운용사지정주문번호
self.tran_os_us_sell.SetSingleData(9, "0") #주문서버구분코드
self.tran_os_us_sell.SetSingleData(10, "00") # 주문구분, 지정가:00 MOO:31 MOC:33 LOO:32 LOC:34
#항목 설정
self.tran_os_us_sell.RequestData("OS_US_SELL")
self.text_edit.append("미국 매도주문 전송 [" + str(self.tran_os_us_sell.GetSendRqID()) + "] ")
self.tran_os_us_sell.ReceiveData.connect(self.tran_os_us_sell_receivedata) #이벤트 연결
def tran_os_us_sell_receivedata(self):
# 주문응답 이벤트
self.text_edit.append("미국 매도주문 응답 [" + str(self.tran_os_us_sell.GetSendRqID()) + "] ")
#결과 메세지
self.text_edit.append("[" + str(self.tran_os_us_sell.GetSendRqID()) + "] " + self.tran_os_us_sell.GetReqMsgCode() + " " + self.tran_os_us_sell.GetReqMessage())
self.text_edit.append("주문번호 : " + self.tran_os_us_sell.GetSingleData(1, 0))
self.text_edit.append("주문시간 : " + self.tran_os_us_sell.GetSingleData(2, 0))
def btn_live_on_clicked(self):
self.check_os_stcnto_r = QAxWidget("ITGExpertCtl.ITGExpertCtlCtrl.1")
self.check_os_stcnto_r.SetSingleData(0, "DNASTQQQ") #실시간종목코드
self.check_os_stcnto_r.RequestRealData("OS_STCNT0_R", "DNASTQQQ")
self.text_edit.append("미국 실시간 데이터 체결 조회 on [" + str(self.check_os_stcnto_r.GetSendRqID()) + "] ")
self.check_os_stcnto_r.ReceiveRealData.connect(self.check_os_stcnto_r_receiverealdata) #이벤트 연결
def check_os_stcnto_r_receiverealdata(self):
#self.text_edit.append(self.check_os_stcnto_r.GetSingleData(1, 0) + " 현재가: " + self.check_os_stcnto_r.GetSingleData(11, 0))
self.df.loc[self.today_date, 'Open'] = float(self.check_os_stcnto_r.GetSingleData(8, 0))
self.df.loc[self.today_date, 'High'] = float(self.check_os_stcnto_r.GetSingleData(9, 0))
self.df.loc[self.today_date, 'Low'] = float(self.check_os_stcnto_r.GetSingleData(10, 0))
self.df.loc[self.today_date, 'Close'] = float(self.check_os_stcnto_r.GetSingleData(11, 0)) #종가 = 현재가
self.df['SMA5'] = SMA(self.df['Close'], 5) #이평선 5
self.df['SMA10'] = SMA(self.df['Close'], 10) #이평선 10
self.df['SMA20'] = SMA(self.df['Close'], 20) #이평선 20
self.df['ICMK'] = ICMK(self.df, 26) # 일목균형표 26일
self.df['RSI'] = RSI(self.df['Close'], 14) #RSI 14 일
#print(self.df)
def btn_live_off_clicked(self):
self.check_os_stcnto_r.UnRequestRealData("OS_STCNT0_R", "DNASTQQQ")
self.text_edit.append("미국 실시간 데이터 체결 조회 off [" + str(self.check_os_stcnto_r.GetSendRqID()) + "] ")
def btn_check_balance_clicked(self):
self.scap = QAxWidget("ITGExpertCtl.ITGExpertCtlCtrl.1")
self.scap.SetSingleData(0, self.line_edit_account.text()) #계좌일련번호[8], GetAccount() 함수 이용(앞 8자리)
self.scap.SetSingleData(1, self.line_edit_account_code.text()) #계좌 상품코드, GetAccount() 함수 이용(뒤 2자리)
self.scap.SetSingleData(2, self.scap.GetEncryptPassword(self.line_edit_account_password.text())) #계좌비밀번호(반드시 암호화 처리 필요)
self.scap.SetSingleData(3, "036570") #상품번호
self.scap.SetSingleData(4, "0") #주문단가
self.scap.SetSingleData(5, "01") #주문구분 01 시장가
self.scap.SetSingleData(6, "N") #CMA 평가
self.scap.SetSingleData(7, "N") #주문가격
self.scap.RequestData("SCAP")
#self.text_edit.append("한국 계좌 잔고조회 [" + str(self.scap.GetSendRqID()) + "] ")
self.scap.ReceiveData.connect(self.scap_receivedata) #이벤트 연결
def scap_receivedata(self):
"""
# 주문응답 이벤트
self.text_edit.append("한국 계좌 잔고조회 응답 [" + str(self.scap.GetSendRqID()) + "] ")
#결과 메세지
self.text_edit.append("[" + str(self.scap.GetSendRqID()) + "] " + self.scap.GetReqMsgCode() + " " + self.scap.GetReqMessage())
self.text_edit.append("주문가능 현금 : " + self.scap.GetSingleData(0, 0))
self.text_edit.append("가능수량계산단가 : " + self.scap.GetSingleData(4, 0))
self.text_edit.append("미수없는매수금액 : " + self.scap.GetSingleData(5, 0))
self.text_edit.append("매수없는매수수량 : " + self.scap.GetSingleData(6, 0))
self.text_edit.append("최대매수금액 : " + self.scap.GetSingleData(7, 0))
self.text_edit.append("최대매수수량 : " + self.scap.GetSingleData(8, 0))
self.text_edit.append("주문가능외화금액원화 : " + self.scap.GetSingleData(11, 0))
"""
self.label_krw_balance.setText(self.scap.GetSingleData(0, 0))
def btn_check_us_balance_clicked(self):
self.os_us_dncl = QAxWidget("ITGExpertCtl.ITGExpertCtlCtrl.1")
self.os_us_dncl.SetSingleData(0, self.line_edit_account.text()) #종합계좌번호
self.os_us_dncl.SetSingleData(1, self.line_edit_account_code.text()) #계좌 상품코드
self.os_us_dncl.SetSingleData(2, self.scap.GetEncryptPassword(self.line_edit_account_password.text())) #계좌비밀번호(반드시 암호화 처리 필요)
#self.os_us_dncl.SetSingleData(3, "") #통화코드
self.os_us_dncl.RequestData("OS_US_DNCL")
#self.text_edit.append("계좌 잔고조회 [" + str(self.os_us_dncl.GetSendRqID()) + "] ")
self.os_us_dncl.ReceiveData.connect(self.os_us_dncl_receivedata) #이벤트 연결
def os_us_dncl_receivedata(self):
"""
# 주문응답 이벤트
self.text_edit.append("미국 계좌 잔고조회 응답 [" + str(self.os_us_dncl.GetSendRqID()) + "] ")
#결과 메세지
self.text_edit.append("[" + str(self.os_us_dncl.GetSendRqID()) + "] " + self.os_us_dncl.GetReqMsgCode() + " " + self.os_us_dncl.GetReqMessage())
self.text_edit.append("통화코드 : " + self.os_us_dncl.GetSingleData(0, 0))
self.text_edit.append("통화코드명 : " + self.os_us_dncl.GetSingleData(1, 0))
self.text_edit.append("외화예수금액1 : " + self.os_us_dncl.GetSingleData(2, 0))
self.text_edit.append("외화주문가능금액2 : " + self.os_us_dncl.GetSingleData(3, 0))
self.text_edit.append("외화주문가능금액1 : " + self.os_us_dncl.GetSingleData(4, 0))
"""
self.label_usd_balance.setText(self.os_us_dncl.GetSingleData(2, 0))
#print(self.label_usd_balance.text())
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
sched = BackgroundScheduler()
sched.start()
#sched.add_job(job, 'cron', day_of_week='5', hour='19', minute='15', timezone='US/Eastern', id="trading", args=[self.mainWidget])
sched.add_job(job, 'cron', second='*/5', timezone='US/Eastern', id="trading", args=[self.mainWidget])
#0 19 15 ? * MON-FRI *
def initUI(self):
self.setWindowTitle("한국투자증권-API")
self.mainWidget = MainWidget()
self.setCentralWidget(self.mainWidget)
self.setGeometry(0, 0, 1200, 600)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
myWindow = MyWindow()
myWindow.show()
app.exec_()
|
cs |
스레드 갖다 버렸다.
1
2
3
4
5
6
7
8
9
|
def schedule_trading():
schedule.every(10).seconds.do(do_trading)
#schedule.every().day.at("17:00").do(schedule_job)
while True:
schedule.run_pending() # pending된 Job을 실행
def do_trading():
print("a")
|
cs |
대충 위와 같이 작업하였으나
pending 코드에서 sleep을 줘도 저기서 계속 리소스를 잡아먹다보니
프로그램이 극도로 느려졌다.
그래서 다른 것을 찾아봤고 찾은 것이 apscheduler 다.
https://lemontia.tistory.com/508
여기에 잘 나와있으니 참고하시길
추가된 코드는
from apscheduler.schedulers.background import BackgroundScheduler #pip install apscheduler
from apscheduler.jobstores.base import JobLookupError #특정 시간이나 일정 간격 실행을 위한 모듈
import time
def job(mainWidget):
print(mainWidget.df)
sched.add_job(job, 'cron', second='*/5', timezone='US/Eastern', id="trading", args=[self.mainWidget])
정도 되시겠다.
5초마다 백그라운드로 job 함수를 실행한다.
나는 특정 시간에 작동하기 위해
sched.add_job(job, 'cron', day_of_week='5', hour='19', minute='15', timezone='US/Eastern', id="trading", args=[self.mainWidget])
크론을 이렇게 줄 예정이다.
나스닥 휴일은 나중에 생각해보자;;
'미국 주식 프로그램 만들기(eFriend expert)' 카테고리의 다른 글
[중요] KIS Developers로 변경 (0) | 2022.08.14 |
---|---|
19. 미국 주식 자동매매 프로그램 만들기 - 스케쥴러 수정 (0) | 2022.08.06 |
17. 미국 주식 자동매매 프로그램 만들기 - 알고리즘? (0) | 2022.05.30 |
16. 미국 주식 자동매매 프로그램 만들기 - 스레드 추가 (2) | 2022.05.30 |
15. 미국 주식 자동매매 프로그램 만들기 - 나스닥 휴일 확인 (0) | 2022.05.17 |