왜: 체결이 없어도 마지막가는 유지인데, 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 (일회성)
327 lines
12 KiB
Python
327 lines
12 KiB
Python
|
|
from dotenv import load_dotenv
|
|
import os
|
|
from tr.tr_0424 import Tr_0424
|
|
from PySide2 import QtTest
|
|
from PySide2 import QtCore
|
|
import json
|
|
|
|
# from order_window import Order_window
|
|
|
|
from balance_window import Balance_window
|
|
import win32com.client #이베스트 관련
|
|
import pythoncom #이베스트 관련
|
|
load_dotenv()
|
|
|
|
from tr.tr_master import Tr_master
|
|
tr_master=Tr_master()
|
|
|
|
|
|
from tr.tr_sc0 import Tr_sc0
|
|
|
|
|
|
class Tr_pending:
|
|
# class Worker(QtCore.QThread):
|
|
# # def __init__(self,tr_0424):
|
|
# # self.tr_0424=tr_0424
|
|
|
|
# def call(self,tr_0424):
|
|
# self.tr_0424=tr_0424
|
|
|
|
# def run(self):
|
|
# while True:
|
|
# self.sleep(2)
|
|
# self.tr_0424.get_account(Balance_window)
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.account=os.environ.get('ACCOUNT')
|
|
self.pw=os.environ.get('PW')
|
|
# self.tr_0424=win32com.client.DispatchWithEvents("XA_DataSet.XAQuery",Tr_0424)#계좌티알
|
|
# self.tr_0424.get_account(Balance_window)
|
|
|
|
# self.worker = self.Worker()
|
|
# self.worker.call(self.tr_0424)
|
|
# self.worker.start()
|
|
|
|
# self.order_window=Order_window()
|
|
|
|
# self.the_pending={}#미체결
|
|
self.the_pending_list=[]
|
|
# self.the_pending_temp={}#오더 에코 떨어지기 전에 메모리에 올려놓는 미체결
|
|
|
|
|
|
# self.sc0_real = win32com.client.DispatchWithEvents("XA_DataSet.XAReal", Tr_sc0)
|
|
# self.sc0_real.start(self.process_pending_change_echo)
|
|
|
|
def init_set_text(self,func):
|
|
self.set_status_label=func
|
|
|
|
|
|
# def process_pending_change_echo(self,ord_no, ord_qty, ord_price, stock_code, stock_name):
|
|
# print('process_pending_change_echo: ',self.the_pending_list)
|
|
|
|
|
|
def get_pending(self,balance_window):
|
|
# print('펜딩부름')
|
|
|
|
self.balance_window=balance_window
|
|
|
|
# self.ResFileName = "C:\\eBEST\\xingAPI\\Res\\t0424.res"
|
|
|
|
|
|
the_path=os.environ.get('ROOT_FILE_PATH')
|
|
self.ResFileName = the_path+"\\Res\\CSPAQ13700.res"
|
|
|
|
self.SetFieldData("CSPAQ13700InBlock1", "RecCnt", 0, "00001")
|
|
self.SetFieldData("CSPAQ13700InBlock1", "AcntNo", 0, os.environ.get('ACCOUNT'))
|
|
self.SetFieldData("CSPAQ13700InBlock1", "InptPwd", 0, os.environ.get('PW'))
|
|
self.SetFieldData("CSPAQ13700InBlock1", "OrdMktCode", 0, '00')
|
|
self.SetFieldData("CSPAQ13700InBlock1", "BnsTpCode", 0, '0') #0 결제기준, 2 체결기준
|
|
self.SetFieldData("CSPAQ13700InBlock1", "IsuNo", 0, '')
|
|
self.SetFieldData("CSPAQ13700InBlock1", "ExecYn", 0, '3')
|
|
|
|
self.SetFieldData("CSPAQ13700InBlock1", "OrdDt", 0, '')
|
|
|
|
self.SetFieldData("CSPAQ13700InBlock1", "SrtOrdNo2", 0, '999999999')
|
|
self.SetFieldData("CSPAQ13700InBlock1", "BkseqTpCode", 0, '0')
|
|
self.SetFieldData("CSPAQ13700InBlock1", "OrdPtnCode", 0, '00')
|
|
|
|
#print('계좌 불러옴')
|
|
|
|
|
|
|
|
|
|
err_code = self.Request(False)
|
|
if err_code < 0:
|
|
#print("error... {0}".format(err_code))
|
|
|
|
pass
|
|
|
|
def init_draw_pending_table(self):
|
|
# self.balance_window.insert_row_on_pending_table()
|
|
# self.balance_window.set_value_on_pending_table(0,0,'stock_name')
|
|
# self.balance_window.set_value_on_pending_table(1,0,'stock_code')
|
|
|
|
|
|
for i,obj in enumerate( self.the_pending_list):
|
|
try:
|
|
|
|
self.balance_window.insert_row_on_pending_table()
|
|
|
|
self.balance_window.set_value_on_pending_table(0,i,obj['ord_no'] )
|
|
self.balance_window.set_value_on_pending_table(1,i,obj['stock_name'] )
|
|
self.balance_window.set_value_on_pending_table(2,i,obj['side'])
|
|
self.balance_window.set_value_on_pending_table(3,i,obj['stock_code'])
|
|
self.balance_window.set_value_on_pending_table(4,i,obj['ord_qty'])
|
|
self.balance_window.set_value_on_pending_table(5,i,obj['ord_price'])
|
|
self.balance_window.set_value_on_pending_table(6,i,obj['OrgOrdNo'])
|
|
self.balance_window.set_value_on_pending_table(7,i,obj['OrdTrxPtnNm'])
|
|
|
|
|
|
|
|
|
|
except:
|
|
pass
|
|
|
|
def OnReceiveData(self, tr_code):
|
|
|
|
# self.tr_0424.get_account(Balance_window)
|
|
block_count=self.GetBlockCount("CSPAQ13700OutBlock3")
|
|
self.the_pending_list=[]
|
|
os.environ['the_pending_list_length']=str(len(self.the_pending_list))
|
|
os.environ['the_pending_list']=json.dumps(self.the_pending_list)
|
|
# if len(self.the_pending_list)>0:
|
|
# self.the_pending_list=[]
|
|
|
|
|
|
if block_count is not None:
|
|
# print('미체결 block_count: ',block_count)
|
|
|
|
|
|
for i in range(block_count):
|
|
|
|
OrgOrdNo = self.GetFieldData("CSPAQ13700OutBlock3", "OrgOrdNo",i).strip()
|
|
ord_no = self.GetFieldData("CSPAQ13700OutBlock3", "OrdNo",i).strip()
|
|
ord_qty = self.GetFieldData("CSPAQ13700OutBlock3", "OrdQty",i).strip()
|
|
ExecQty = self.GetFieldData("CSPAQ13700OutBlock3", "ExecQty",i).strip()#체결수량
|
|
ord_price = self.GetFieldData("CSPAQ13700OutBlock3", "OrdPrc",i).strip()
|
|
stock_code = self.GetFieldData("CSPAQ13700OutBlock3", "shcode",i).strip()
|
|
stock_name = self.GetFieldData("CSPAQ13700OutBlock3", "IsuNm",i).strip()
|
|
BnsTpCode = self.GetFieldData("CSPAQ13700OutBlock3", "BnsTpCode",i).strip()#매매구분 1 매도 2 매수
|
|
|
|
BnsTpNm = self.GetFieldData("CSPAQ13700OutBlock3", "BnsTpNm",i).strip()
|
|
OrdTrxPtnCode = self.GetFieldData("CSPAQ13700OutBlock3", "OrdTrxPtnCode",i).strip()
|
|
OrdTrxPtnNm = self.GetFieldData("CSPAQ13700OutBlock3", "OrdTrxPtnNm",i).strip()
|
|
# MrcTpCode = self.GetFieldData("CSPAQ13700OutBlock3", "MrcTpCode",i).strip()
|
|
# MrcTpNm = self.GetFieldData("CSPAQ13700OutBlock3", "MrcTpNm",i).strip()
|
|
|
|
side=''
|
|
|
|
if BnsTpCode=='1':
|
|
side='매도'
|
|
else:
|
|
side='매수'
|
|
|
|
actual_qty=int(ord_qty)-int(ExecQty)#미체결량 구하기
|
|
|
|
# print('미체결 MrcTpCode: ',MrcTpCode)
|
|
# print('미체결 MrcTpNm: ',MrcTpNm)
|
|
|
|
the_dict_from_master=tr_master.master_dict.get(stock_name,{})
|
|
|
|
|
|
stock_code_from_master=the_dict_from_master.get('shcode',"")
|
|
|
|
obj={
|
|
"ord_no":ord_no,
|
|
"ord_qty":actual_qty,
|
|
"ord_price":int(float(ord_price)),
|
|
"stock_code":stock_code_from_master,
|
|
"stock_name":stock_name,
|
|
'side':side,
|
|
'OrgOrdNo':OrgOrdNo,
|
|
'OrdTrxPtnNm':OrdTrxPtnNm
|
|
}
|
|
self.the_pending_list.append(obj)
|
|
|
|
os.environ['the_pending_list_length']=str(len(self.the_pending_list))
|
|
os.environ['the_pending_list']=json.dumps(self.the_pending_list)
|
|
|
|
# print('tr_pending의 the_pending_list: ',json.loads(os.environ['the_pending_list']) )
|
|
# print('tr_pending의 the_pending_list 길이: ',os.environ['the_pending_list_length'])
|
|
self.init_draw_pending_table()
|
|
|
|
# if tr_code=='CSPAT00600':
|
|
# df,df1=result
|
|
|
|
|
|
# XAQueryEvents.query_state = True
|
|
# block_count=self.GetBlockCount("t8430OutBlock")
|
|
# #print('block_count: ',block_count)
|
|
|
|
|
|
# for i in range(block_count):
|
|
# hname = self.GetFieldData("t8430OutBlock", "hname", i).strip()
|
|
# shcode = self.GetFieldData("t8430OutBlock", "shcode", i).strip()
|
|
# gubun = self.GetFieldData("t8430OutBlock", "gubun", i).strip() #1은 코스피, 2는 코스닥
|
|
|
|
# master_dict[shcode]={
|
|
# 'hname':hname,
|
|
# 'gubun':gubun
|
|
# }
|
|
|
|
# #print('master_dict: ',master_dict['005930'])
|
|
# query_1857.set_master(master_dict)
|
|
|
|
|
|
# hname = self.GetFieldData("t8430OutBlock", "hname", 0)
|
|
# shcode = self.GetFieldData("t8430OutBlock", "shcode", 0)
|
|
# #print('tr_code: ',tr_code)
|
|
# #print('hname: ',hname)
|
|
# #print('shcode: ',shcode)
|
|
|
|
# param['hname']=hname
|
|
# param['shcode']=shcode
|
|
pass
|
|
def OnReceiveMessage(self, error, nMessageCode, szMessage):
|
|
|
|
if nMessageCode=='00040':
|
|
#미체결 obj 메모리에 올리는 부분
|
|
self.the_pending=self.the_pending_temp
|
|
# self.set_status_label(szMessage)
|
|
|
|
|
|
|
|
# def shoot_order(self,stock_code,how_many,price,open,order_price,order_style,order_type):
|
|
# #order_style이 매수인지 매도인지 그거 말하는거임
|
|
# #order_type은 지정가인지 시장가인지 그거임
|
|
|
|
# # 00@지정가
|
|
# # 03@시장가
|
|
# is_market='00'
|
|
|
|
# if order_type=='market':
|
|
# is_market='03'
|
|
# order_price=0
|
|
|
|
# is_ask='1'
|
|
|
|
|
|
# if order_style=='bid':
|
|
# is_ask='2'
|
|
|
|
|
|
# order_dict={
|
|
# 'account':self.account,
|
|
# 'stock_code':stock_code,
|
|
# 'how_many':how_many,
|
|
# 'order_price':order_price,
|
|
# 'is_ask':is_ask,
|
|
# 'is_market':is_market,
|
|
# 'order_type':order_type
|
|
# }
|
|
|
|
# #미체결에 넣는다 같은 스톡코드라도 리스트로 뿌려야되는거 아님?
|
|
# #걍 미체결 리얼에서 떨어지는거 찍어볼까
|
|
# # pending_stock=self.the_pending_temp.get(stock_code,None)
|
|
|
|
# # self.the_pending_list.append({
|
|
|
|
# # })
|
|
|
|
|
|
# # if pending_stock is None:
|
|
|
|
# # self.the_pending_temp[stock_code]={
|
|
# # 'stock_code':stock_code,
|
|
# # 'how_many':how_many,
|
|
# # 'order_price':order_price,
|
|
# # }
|
|
# # else:
|
|
# # self.the_pending_temp[stock_code]['how_many']=how_many
|
|
|
|
# #미체결에 넣는다 끝
|
|
|
|
|
|
# stock_code="A"+stock_code#모투라 이렇게 해놈
|
|
|
|
# the_path=os.environ.get('ROOT_FILE_PATH')
|
|
# self.ResFileName = the_path+"\\Res\\CSPAT00600.res"
|
|
|
|
# self.ResFileName = "C:\\eBEST\\xingAPI\\Res\\CSPAT00600.res"
|
|
# self.SetFieldData("CSPAT00600InBlock1", "AcntNo", 0, self.account)
|
|
# self.SetFieldData("CSPAT00600InBlock1", "InptPwd", 0, "0000") #모투는 0000임
|
|
# self.SetFieldData("CSPAT00600InBlock1", "IsuNo", 0, stock_code) #모투는 앞에 A 더하래
|
|
# self.SetFieldData("CSPAT00600InBlock1", "OrdQty", 0, how_many) #얘네 왜 스트링임?
|
|
# self.SetFieldData("CSPAT00600InBlock1", "OrdPrc", 0, str(order_price))#얘네 왜 스트링임?
|
|
# self.SetFieldData("CSPAT00600InBlock1", "BnsTpCode", 0, is_ask)#1이 매도 2가 매수
|
|
# # 00@지정가
|
|
# # 03@시장가
|
|
# # 05@조건부지정가
|
|
# # 06@최유리지정가
|
|
# # 07@최우선지정가
|
|
# # 61@장개시전시간외종가
|
|
# # 81@시간외종가
|
|
# # 82@시간외단일가
|
|
# self.SetFieldData("CSPAT00600InBlock1", "OrdprcPtnCode", 0, is_market)
|
|
# # 000:보통
|
|
# # 003:유통/자기융자신규
|
|
# # 005:유통대주신규
|
|
# # 007:자기대주신규
|
|
# # 101:유통융자상환
|
|
# # 103:자기융자상환
|
|
# # 105:유통대주상환
|
|
# # 107:자기대주상환
|
|
# # 180:예탁담보대출상환(신용)
|
|
# self.SetFieldData("CSPAT00600InBlock1", "MgntrnCode", 0, '000')
|
|
# self.SetFieldData("CSPAT00600InBlock1", "LoanDt", 0, '')#대출일이라는데 일단 비워둠
|
|
# self.SetFieldData("CSPAT00600InBlock1", "OrdCndiTpCode", 0, '0') #0:없음,1:IOC,2:FOK 주문조건구분
|
|
|
|
# #print('ORDER!!!!!')
|
|
|
|
|
|
# err_code = self.Request(False)
|
|
# if err_code < 0:
|
|
# pass
|
|
# #print("error... {0}".format(err_code))
|