왜: 체결이 없어도 마지막가는 유지인데, TTL로 None 만들고 매도/EOD를 건너뛰어 8/5 돌파·금요일 leftover가 남음. 호가필터 TTL 구멍과 같은 병. 넣을 파일 신규: kis_trader/engine/live_sell_price.py kis_trader/strategies/base.py (_ws_last_quote, _resolve_sell_price) 전략: momentum.py scalping.py tail_catch.py breakout.py range_break.py dart_strategy.py updow_strategy.py updown_feed.py us_momentum.py WS: ws_manager.py kis_ws.py kiwoom_ws.py ls_ws.py kis_ws_overseas.py kis_trader/web/live_config_schema.py (WS_PRICE_MAX_AGE_SEC 기본 0) database.py (키 주석 + legacy/ sys.path) kis_trader/execution/order_manager.py (잔고 있는데 40240000 ghost_purge 금지 — 같은 EOD 사고) EOD가 min_hold에 안 막히게 손본 momentum_hts_logic.py / scalping_engine.py / tail_engine.py (이 대화에서 손본 부분만 확인 후) 문서: docs/like_mcp.md/db_erd.md code_architecture.md (가격 TTL 문구) 메시지 초안 fix: 매수·매도 현재가를 TTL로 버리지 않음 (마지막 RAM) 횡보·체결 공백을 죽은 캐시로 오인해 None 처리하면 손절·EOD가 스킵된다. 호가필터와 같이 나이는 무시하고 마지막 체결가를 유지한다. EOD는 매수가 폴백. 영향: 실매 O / 백테·옵투나 봉 경로 거의 무관 (엔진 식 변경 아님) 커밋 2 — 루트 정리 (remove/ vs legacy/) 왜: 루트 단독봇·테스트는 지울 보관함으로. 웹·알람이 아직 쓰는 모듈은 remove에 두면 나중에 폴더째 삭제 때 깨짐. 넣을 파일 이동: 미사용 → remove/legacy_root/ (래퍼, ETF/키움 옛봇, 테스트, kiwoom_rest_api 등) 이동: 사용 중 → legacy/ (holding_bot kis_holding_ver1 news_analyzer kis_long_ver1/2) 신규: kis_trader/utils/legacy_root.py legacy/README.md remove/README.md import 경로: backtest_web.py mm_butler.py mm_remote.py updow_holding_cfg.py dbband_stock_cfg.py param_search_updow*.py dbband_param_search.py param_search_apply_snapshot.py verify_three_paths.py docs/like_mcp.md/code_architecture.md 수동 노트 메시지 초안 chore: 미사용 루트는 remove/, 웹·알람 구모듈은 legacy/ remove는 나중에 통째 삭제 예정. holding_bot·news_analyzer·kis_long은 ensure_legacy_root로 legacy/만 본다. 빼기: scratch/set_ws_price_max_age_zero.py (일회성)
304 lines
8.2 KiB
Python
304 lines
8.2 KiB
Python
from PySide2.QtWidgets import QApplication,QMainWindow
|
|
from PySide2.QtUiTools import QUiLoader
|
|
from PySide2.QtCore import QObject, QEvent, QTimer, QCoreApplication
|
|
|
|
import sys
|
|
# from button_holder import ButtonHolder
|
|
# from slider import SliderHolder
|
|
# from rockwidget import RockWidget
|
|
from main_window import Main_window
|
|
from balance_window import Balance_window
|
|
# from test import Test
|
|
# from ui.ui_test import Ui_Test
|
|
# from second_window import Second_Window
|
|
import time
|
|
from threading import Thread
|
|
|
|
from tr.tr_master import Tr_master
|
|
# from tr.tr_sc0 import Tr_sc0
|
|
# from tr.tr_sc1 import Tr_sc1
|
|
from tr.tr_0424 import Tr_0424
|
|
from tr.tr_pending import Tr_pending
|
|
|
|
import win32com.client #이베스트 관련
|
|
import pythoncom #이베스트 관련
|
|
|
|
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
|
|
|
from apscheduler.schedulers.qt import QtScheduler
|
|
|
|
from dotenv import load_dotenv
|
|
import os
|
|
|
|
# load .env
|
|
load_dotenv()
|
|
|
|
loader=QUiLoader()
|
|
|
|
app=QApplication(sys.argv)
|
|
|
|
the_path=os.path.dirname(__file__)
|
|
os.environ['ROOT_FILE_PATH'] = the_path
|
|
|
|
|
|
|
|
#meta class conflict 나서 서브클래스로 하면 안 됨 미리 선언하고 생성자로 넘겨야됨
|
|
# class XReal_S3_:
|
|
# def __init__(self):
|
|
# super().__init__()
|
|
# self.count = 0
|
|
|
|
# def OnReceiveRealData(self, tr_code): # event handler
|
|
# """
|
|
# 이베스트 서버에서 ReceiveRealData 이벤트 받으면 실행되는 event handler
|
|
# """
|
|
# self.count += 1
|
|
# shcode = self.GetFieldData("OutBlock", "shcode")
|
|
# # price = self.GetFieldData("OutBlock", "price")
|
|
# # chetime = self.GetFieldData("OutBlock", "chetime")
|
|
|
|
# if shcode is
|
|
|
|
|
|
# #print('shcode: ',shcode)
|
|
# #print('price: ',price)
|
|
# #print('chetime: ',chetime)
|
|
# # window.set_the_stock_code(price)
|
|
|
|
# def start(self,stock_code):
|
|
# """
|
|
# 이베스트 서버에 실시간 data 요청함.
|
|
# """
|
|
# self.ResFileName = "C:\\eBEST\\xingAPI\\Res\\S3_.res" # RES 파일 등록
|
|
# self.SetFieldData("InBlock", "shcode", stock_code)
|
|
# self.AdviseRealData() # 실시간데이터 요청
|
|
|
|
# def add_item(self, stockcode):
|
|
# # 실시간데이터 요청 종목 추가
|
|
# self.SetFieldData("InBlock", "shcode", stockcode)
|
|
# self.AdviseRealData()
|
|
|
|
# def remove_item(self, stockcode):
|
|
# # stockcode 종목만 실시간데이터 요청 취소
|
|
# self.UnadviseRealDataWithKey(stockcode)
|
|
|
|
# def end(self):
|
|
# self.UnadviseRealData() # 실시간데이터 요청 모두 취소
|
|
|
|
|
|
#meta class conflict 나서 서브클래스로 하면 안 됨 미리 선언하고 생성자로 넘겨야됨 끝
|
|
|
|
SHUT_DOWN_FLAG=False
|
|
|
|
# def set_shut_down_flag():
|
|
# SHUT_DOWN_FLAG=True
|
|
# #print('SHUT_DOWN_FLAG: ',SHUT_DOWN_FLAG)
|
|
|
|
|
|
|
|
tr_pending=win32com.client.DispatchWithEvents("XA_DataSet.XAQuery",Tr_pending)#미체결티알
|
|
tr_0424=win32com.client.DispatchWithEvents("XA_DataSet.XAQuery",Tr_0424)#계좌티알
|
|
|
|
|
|
balance_window=Balance_window(tr_pending)
|
|
#이베스트 로그인
|
|
STAND_BY = 0
|
|
RECEIVED = 1
|
|
|
|
class XASessionEvents:
|
|
login_state = STAND_BY
|
|
|
|
login_cnt=0
|
|
|
|
def OnLogin(self, code, msg):
|
|
XASessionEvents.login_state = RECEIVED
|
|
# time.sleep(5)
|
|
# print('로그인 결과: ',msg)
|
|
# print('로그인 결과 code: ',code)
|
|
if code=='0000':
|
|
query.single_request(tr_0424,balance_window,tr_pending)
|
|
res=self.account_info()
|
|
if res is not None:
|
|
window.show_buttons()
|
|
window.set_status_label('로그인 성공')
|
|
|
|
# tr_0424.init_get_account()
|
|
else:
|
|
self.login_cnt+=1
|
|
if self.login_cnt <5:
|
|
window.set_status_label(f'로그인 실패. 남은 회수 {self.login_cnt} / 5')
|
|
else:
|
|
window.set_status_label(f'로그인 실패. 재시도 회수를 초과했습니다')
|
|
|
|
if self.login_cnt >5:
|
|
pass
|
|
|
|
|
|
|
|
|
|
# window.set_the_text(msg)
|
|
def OnDisconnect(self, code, msg):
|
|
pass
|
|
|
|
def account_info(self):
|
|
"""
|
|
계좌 정보 조회
|
|
"""
|
|
|
|
account_no = self.GetAccountListCount()
|
|
|
|
if account_no is not None:
|
|
|
|
# print("계좌 갯수 = {0}".format(account_no))
|
|
|
|
# for i in range(account_no):
|
|
# account = self.GetAccountList(i)
|
|
# #print("계좌번호 = {0}".format(account))
|
|
|
|
|
|
self.account = self.GetAccountList(0)
|
|
os.environ['ACCOUNT'] = self.GetAccountList(0)
|
|
return 1
|
|
|
|
else:
|
|
return None
|
|
|
|
class XAQueryEvents:
|
|
query_state = STAND_BY
|
|
def OnReceiveData(self, code):
|
|
XAQueryEvents.query_state = RECEIVED
|
|
def OnReceiveMessage(self, error, nMessageCode, szMessage):
|
|
#print(szMessage)
|
|
pass
|
|
|
|
session=win32com.client.DispatchWithEvents("XA_Session.XASession",XASessionEvents)
|
|
|
|
url=os.environ.get('URL')
|
|
port=os.environ.get('PORT')
|
|
server_type=os.environ.get('SERVER_TYPE')
|
|
|
|
id=os.environ.get('ID')
|
|
pw=os.environ.get('PW')
|
|
cert=os.environ.get('CERT')
|
|
account = os.environ.get('ACCOUNT')
|
|
|
|
|
|
window=Main_window(session,balance_window)
|
|
window.show()
|
|
|
|
|
|
|
|
result=session.ConnectServer(url,port)
|
|
|
|
#이베스트 로그인 끝
|
|
|
|
|
|
#마스터 테스트
|
|
|
|
query=win32com.client.DispatchWithEvents("XA_DataSet.XAQuery",Tr_master)
|
|
|
|
|
|
|
|
# while Tr_master.query_state == False:
|
|
# pythoncom.PumpWaitingMessages()
|
|
|
|
|
|
|
|
#마스터 테스트 끝
|
|
|
|
|
|
#데몬쓰레드 테스트
|
|
|
|
|
|
|
|
#데몬쓰레드 테스트 끝
|
|
|
|
|
|
|
|
|
|
#리얼 테스트
|
|
|
|
# class XReal_S3_:
|
|
# def __init__(self):
|
|
# super().__init__()
|
|
# self.count = 0
|
|
|
|
# def OnReceiveRealData(self, tr_code): # event handler
|
|
# """
|
|
# 이베스트 서버에서 ReceiveRealData 이벤트 받으면 실행되는 event handler
|
|
# """
|
|
# self.count += 1
|
|
# shcode = self.GetFieldData("OutBlock", "shcode")
|
|
# price = self.GetFieldData("OutBlock", "price")
|
|
# chetime = self.GetFieldData("OutBlock", "chetime")
|
|
# #print('shcode: ',shcode)
|
|
# #print('price: ',price)
|
|
# #print('chetime: ',chetime)
|
|
# window.set_the_stock_code(price)
|
|
|
|
# def start(self,stock_code):
|
|
# """
|
|
# 이베스트 서버에 실시간 data 요청함.
|
|
# """
|
|
# self.ResFileName = "C:\\eBEST\\xingAPI\\Res\\S3_.res" # RES 파일 등록
|
|
# self.SetFieldData("InBlock", "shcode", stock_code)
|
|
# self.AdviseRealData() # 실시간데이터 요청
|
|
|
|
# def add_item(self, stockcode):
|
|
# # 실시간데이터 요청 종목 추가
|
|
# self.SetFieldData("InBlock", "shcode", stockcode)
|
|
# self.AdviseRealData()
|
|
|
|
# def remove_item(self, stockcode):
|
|
# # stockcode 종목만 실시간데이터 요청 취소
|
|
# self.UnadviseRealDataWithKey(stockcode)
|
|
|
|
# def end(self):
|
|
# self.UnadviseRealData() # 실시간데이터 요청 모두 취소
|
|
|
|
# xreal = win32com.client.DispatchWithEvents("XA_DataSet.XAReal", XReal_S3_)
|
|
|
|
# xreal.start('005930')
|
|
|
|
# # for i in range(100):
|
|
# # #print('try: {}'.format(i))
|
|
# # pythoncom.PumpWaitingMessages()
|
|
# # await asyncio.sleep(0)
|
|
|
|
# while True:
|
|
# pythoncom.PumpWaitingMessages()
|
|
# # if xreal.count == 5:
|
|
# # xreal.add_item("003490") # 대한항공 추가
|
|
|
|
# # if xreal.count == 20:
|
|
# # xreal.remove_item("005930")
|
|
# #000660
|
|
|
|
# # if xreal.count == 30:
|
|
# # xreal.end()
|
|
# # time.sleep(10)
|
|
# # #print("---- end -----")
|
|
# # break
|
|
|
|
# # await asyncio.sleep(0)
|
|
|
|
|
|
# @app.on_event('startup')
|
|
# def init_data():
|
|
|
|
# async_scheduler = AsyncIOScheduler()
|
|
# async_scheduler.add_job(spider_batch.ping_to_db, 'cron', second='*/15',args=[app])
|
|
# async_scheduler.start()
|
|
|
|
|
|
# def yeah():
|
|
# #print('YEAH!!!!')
|
|
|
|
# scheduler = QtScheduler()
|
|
# scheduler.add_job(yeah, 'interval', seconds=5)
|
|
# scheduler.start()
|
|
|
|
|
|
app.exec_()
|
|
|