import os
from PyQt5.QAxContainer import *
from PyQt5.QtCore import *
from config.errorCode import *
from PyQt5.QtTest import *
from config.kiwoomType import *
from datetime import datetime, timedelta
import asyncio
import time
import math
import numpy as np
import copy
class Kiwoom(QAxWidget):
def __init__(self):
super().__init__()
print("Kiwoom() class start.")
self.realType = RealType()
####### event loop를 실행하기 위한 변수 모음
self.login_event_loop = QEventLoop() # 로그인 요청용 이벤트 루프
self.detail_account_info_event_loop = QEventLoop() # 예수금 요청용 이벤트 루프
self.calculator_event_loop = QEventLoop()
self.tmp_event_loop = QEventLoop()
#########################################
####### 계좌 관련된 변수
self.check = 0
self.account_stock_dict = {}
self.account_num = None # 계좌번호 담아줄 변수
self.hesun_account_num = None
self.deposit = 0 # 예수금
self.use_money = 0 # 실제 투자에 사용할 금액
self.use_money_percent = 0.5 # 예수금에서 실제 사용할 비율
self.output_deposit = 0 # 출력가능 금액
self.total_profit_loss_money = 0 # 총평가손익금액
self.total_profit_loss_rate = 0.0 # 총수익률(%)
########################################
######## 종목 정보 가져오기
self.portfolio_stock_dict = {}
self.jango_dict = {}
self.not_account_stock_dict = {}
self.mesu_price = {}
self.medo_price = {}
########################
####### 요청 스크린 번호
self.screen_my_info = "2000" # 계좌 관련한 스크린 번호
self.screen_calculation_stock = "4000" # 계산용 스크린 번호
self.screen_real_stock = 5000 # 종목별 할당할 스크린 번호
self.screen_meme_stock = 6000 # 종목별 할당할 주문용 스크린 번호
self.screen_start_stop_real = "1000" # 장 시작/종료 실시간 스크린 번호
########################################
###*** 2
self.hesun_codes = ["005930", ""]
########### 종목 분석 용
self.calcul_data = []
self.moving_average_price_369 = 0
##########################################
self.is_hesun = 0
# self.is_hesun = 1
self.rqDataCode = "101R6000"
self.rqDataCode2 = "01R6000"
######### 초기 셋팅 함수들 바로 실행
self.get_ocx_instance() # OCX 방식을 파이썬에 사용할 수 있게 반환해 주는 함수 실행
self.event_slots() # 키움과 연결하기 위한 시그널 / 슬롯 모음
self.real_event_slot() # 실시간 이벤트 시그널 / 슬롯 연결
self.signal_login_commConnect() # 로그인 요청 함수 포함
self.get_account_info() # 계좌번호 가져오기
QTest.qWait(15000)
#########################################
self.stop = 0
self.stopCheck = 0
self.high_suick = 0
self.low_suick = 0
self.high_jan = 0
self.susu = 0.0035
# self.susu = 0.01
self.real_susu = 0.00015
self.real_segeum = 0.0015
self.hesun_susu = 0.00995
self.last1SecTime = {}
self.mememoney = {}
self.start1Sec = {}
self.nowHourMin = {}
self.nowSec = {}
self.price_data_min = {}
self.calcul_data_min = {}
self.moving_average_price_min = {}
self.moving_average_price_min_pre = {}
self.moving_average_price_min_pre_2 = {}
self.moving_average_price_min_pre_3 = {}
self.moving_average_price_min_pre_4 = {}
self.moving_average_price_min_pre_5 = {}
self.moving_average_price_min_pre_10 = {}
self.moving_average_price_min_pre_50 = {}
self.moving_average_price_min_pre_100 = {}
self.bollinger_price = {}
self.bollinger_price_min = {}
self.bollinger_price_min_pre = {}
self.b_upper = {}
self.b_center = {}
self.b_lower = {}
self.b_upper_pre = {}
self.b_center_pre = {}
self.b_lower_pre = {}
self.b_upper_pre_2 = {}
self.b_center_pre_2 = {}
self.b_lower_pre_2 = {}
self.b_upper_pre_3 = {}
self.b_center_pre_3 = {}
self.b_lower_pre_3 = {}
self.b_upper_pre_4 = {}
self.b_center_pre_4 = {}
self.b_lower_pre_4 = {}
self.b_upper_pre_5 = {}
self.b_center_pre_5 = {}
self.b_lower_pre_5 = {}
self.current_price3_pre = {}
self.open_price3_pre_2 = {}
self.current_price3_pre_2 = {}
iRet = self.dynamicCall("SetRealReg(QString, QString, QString, QString)", self.screen_start_stop_real, '',
self.realType.REALTYPE['장시작시간']['장운영구분'], "0")
# Thistime = datetime.datetime.strptime(timeStr, '%H:%M:%S')
now = datetime.now()
then = datetime(now.year, now.month, now.day, 9, 0, 0)
delta = now - then
strCode = self.rqDataCode
self.moving_average_price_min[strCode] = {}
self.moving_average_price_min_pre[strCode] = {}
self.moving_average_price_min_pre_2[strCode] = {}
self.moving_average_price_min_pre_3[strCode] = {}
self.moving_average_price_min_pre_4[strCode] = {}
self.moving_average_price_min_pre_5[strCode] = {}
self.moving_average_price_min_pre_10[strCode] = {}
self.moving_average_price_min_pre_50[strCode] = {}
self.moving_average_price_min_pre_100[strCode] = {}
self.bollinger_price[strCode] = []
self.bollinger_price_min[strCode] = []
self.bollinger_price_min_pre[strCode] = []
self.b_upper[strCode] = 0.0
self.b_center[strCode] = 0.0
self.b_lower[strCode] = 0.0
self.b_upper_pre[strCode] = 0.0
self.b_center_pre[strCode] = 0.0
self.b_lower_pre[strCode] = 0.0
self.b_upper_pre_2[strCode] = 0.0
self.b_center_pre_2[strCode] = 0.0
self.b_lower_pre_2[strCode] = 0.0
self.b_upper_pre_3[strCode] = 0.0
self.b_center_pre_3[strCode] = 0.0
self.b_lower_pre_3[strCode] = 0.0
self.b_upper_pre_4[strCode] = 0.0
self.b_center_pre_4[strCode] = 0.0
self.b_lower_pre_4[strCode] = 0.0
self.b_upper_pre_5[strCode] = 0.0
self.b_center_pre_5[strCode] = 0.0
self.b_lower_pre_5[strCode] = 0.0
self.current_price3_pre[strCode] = 0.0
self.open_price3_pre_2[strCode] = 0.0
self.current_price3_pre_2[strCode] = 0.0
self.realCount = 0
self.preRealCount = 0
self.printHourMin = "0000"
self.detail_account_info()
# self.detail_account_mystock() #계좌평가잔고내역 가져오기
if delta.days < 0:
self.tmp_event_loop.exec_()
self.get_condtion_codes()
###################################################################################################
def get_ocx_instance(self):
###*** 1
self.setControl("KHOPENAPI.KHOpenAPICtrl.1") # 레지스트리에 저장된 API 모듈 불러오기
###*** 2
# self.setControl("KFOPENAPI.KFOpenAPICtrl.1") # 레지스트리에 저장된 API 모듈 불러오기
def signal_login_commConnect(self):
###*** 1
self.dynamicCall("CommConnect()") # 로그인 요청 시그널
###*** 2
# self.dynamicCall("CommConnect(int)", 0) # 로그인 요청 시그널
self.login_event_loop.exec_() # 이벤트 루프 실행
###################################################################################################
async def update_condtion(self):
print("update_condtion : ")
for strCode in self.hesun_codes:
if strCode == "":
continue
# self.detail_account_mystock()
# await asyncio.sleep(1)
###################################################################################################
def event_slots(self):
self.OnEventConnect.connect(self.login_slot) # 로그인 관련 이벤트
self.OnReceiveTrData.connect(self.trdata_slot) # 트랜잭션 요청 관련 이벤트
##*** 2
self.OnReceiveConditionVer.connect(self.condition_slot)
self.OnReceiveTrCondition.connect(self.tr_condition_slot)
self.OnReceiveRealCondition.connect(self.real_condition_slot)
def real_event_slot(self):
self.OnReceiveRealData.connect(self.realdata_slot) # 실시간 이벤트 연결
self.OnReceiveChejanData.connect(self.chejan_slot) # 종목 주문체결 관련한 이벤트
def get_account_info(self):
account_list = self.dynamicCall("GetLoginInfo(QString)", "ACCNO") # 계좌번호 반환
# self.account_num = account_list.split(';')[1] # a;b;c [a, b, c]
self.account_num = account_list.split(';')[0]
print("계좌번호 : %s %s" % (self.account_num, self.hesun_account_num))
def detail_account_info(self, sPrevNext="0"):
self.dynamicCall("SetInputValue(QString, QString)", "계좌번호", self.account_num)
self.dynamicCall("SetInputValue(QString, QString)", "비밀번호", "9128")
self.dynamicCall("SetInputValue(QString, QString)", "비밀번호입력매체구분", "0")
self.dynamicCall("SetInputValue(QString, QString)", "조회구분", "1")
self.dynamicCall("CommRqData(QString, QString, int, QString)", "예수금상세현황요청", "opw00001", sPrevNext, self.screen_my_info)
self.detail_account_info_event_loop.exec_()
def detail_account_mystock(self, sPrevNext="0"):
self.dynamicCall("SetInputValue(QString, QString)", "계좌번호", self.account_num)
self.dynamicCall("SetInputValue(QString, QString)", "비밀번호", "9128")
self.dynamicCall("SetInputValue(QString, QString)", "비밀번호입력매체구분", "00")
self.dynamicCall("SetInputValue(QString, QString)", "조회구분", "1")
self.dynamicCall("CommRqData(QString, QString, int, QString)", "계좌평가잔고내역요청", "opw00018", sPrevNext, self.screen_my_info)
self.detail_account_info_event_loop.exec_()
def stop_screen_cancel(self, sScrNo=None):
self.dynamicCall("DisconnectRealData(QString)", sScrNo) # 스크린 번호 연결 끊기
def get_condtion_codes(self):
self.dynamicCall("GetConditionLoad()")
self.login_event_loop.exec_() # 이벤트 루프 실행
###################################################################################################
def condition_slot(self):
condtion_list = self.dynamicCall("GetConditionNameList()")
print("%s" % condtion_list)
# strScrNo : 화면번호
# strConditionName : 조건식 이름
# nIndex : 조건명 인덱스
# nSearch : 조회구분(0:조건검색, 1:실시간 조건검색)
# 1:실시간조회의 화면 개수의 최대는 10개
# 선택한 조건검색을 화면번호 0156 실시간 조건검색 타입으로 호출
# ret 1 성공
# ret = self.dynamicCall("SendCondition(QString,QString, int, int)", "0156", "새조건명222_매도", 6, 1)
# print("SendCondition 새조건명222_매도 6 Ret : %d" % ret)
ret = self.dynamicCall("SendCondition(QString,QString, int, int)", "10000", "새조건명333", 4, 1)
print("SendCondition 새조건명333 4 Ret : %d" % ret)
#ret = self.dynamicCall("SendCondition(QString,QString, int, int)", "10000", "새조건명111", 1, 1)
#print("SendCondition 새조건명111 1 Ret : %d" % ret)
#ret = self.dynamicCall("SendCondition(QString,QString, int, int)", "10000", "새조건명222", 10, 1)
#print("SendCondition 새조건명222 10 Ret : %d" % ret)
def tr_condition_slot(self, sScrNo, strCodeList, strConditionName, nIndex, nNext):
self.login_event_loop.exit()
return
def real_condition_slot(self, strCode, strType, condtionName, conditionIndex):
if strCode == "":
return
now = datetime.now()
nowTime = now.strftime('%H%M%S')
conIndex = int(float(conditionIndex))
if self.stop == 1 and conIndex == 5:
return
if float(nowTime) >= 90300 and conIndex == 5:
return
if float(nowTime) < 90300 and conIndex == 4:
return
#if float(nowTime) < 91500 and conIndex == 12:
# return
if float(nowTime) > 151500:
return
if strType == "I":
if strCode not in self.jango_dict:
self.jango_dict.update({strCode: {}})
self.jango_dict[strCode].update({"매": 0})
self.jango_dict[strCode].update({"매수조건": 0})
then = datetime(now.year, now.month, now.day, 1, 0, 0)
self.jango_dict[strCode].update({"매도완료시간": then})
self.jango_dict[strCode].update({"매도조건통시": "0000"})
self.jango_dict[strCode].update({"매입단가": 0})
self.jango_dict[strCode].update({"매수시간": then})
self.jango_dict[strCode].update({"첫": -1})
self.jango_dict[strCode].update({"조건": -1})
self.jango_dict[strCode].update({"조건1횟수": 0})
self.jango_dict[strCode].update({"조건2횟수": 0})
self.jango_dict[strCode].update({"조건3횟수": 0})
self.jango_dict[strCode].update({"520in": 0})
if self.jango_dict[strCode]["매수조건"] == 0:
delta = now - self.jango_dict[strCode]["매수시간"]
# delta = now - self.jango_dict[strCode]["매도완료시간"]
if delta.seconds > 60 * 0 * 1:
nowSec = now.strftime('%S')
nowSecInt = int(nowSec)
self.jango_dict[strCode].update({"첫": 0})
self.jango_dict[strCode].update({"매": 0})
self.jango_dict[strCode].update({"조건": conIndex})
self.jango_dict[strCode].update({"매수조건": 1})
fids = self.realType.REALTYPE['주식체결']['체결시간']
# self.screen_real_stock += 1
self.portfolio_stock_dict.update({strCode: {"종목명": "", "현재가": "",
"스크린번호": str(self.screen_real_stock),
"주문용스크린번호": str(self.screen_meme_stock)}})
screen_num = self.portfolio_stock_dict[strCode]['스크린번호']
iRet = self.dynamicCall("SetRealReg(QString, QString, QString, QString)", screen_num, strCode,
fids, "1")
print("real_condition Success!!" , iRet, now, strCode, conIndex)
self.last1SecTime[strCode] = "000000"
self.mememoney[strCode] = 0
self.start1Sec[strCode] = 0
self.nowHourMin[strCode] = "0000"
self.nowSec[strCode] = "000000"
self.price_data_min[strCode] = []
self.price_data_min[strCode].append(0.0)
self.price_data_min[strCode].append(0.0)
self.price_data_min[strCode].append(1000000.0)
self.price_data_min[strCode].append(0.0)
self.calcul_data_min[strCode] = []
self.moving_average_price_min[strCode] = {}
self.moving_average_price_min_pre[strCode] = {}
self.moving_average_price_min_pre_2[strCode] = {}
self.moving_average_price_min_pre_10[strCode] = {}
self.moving_average_price_min_pre_50[strCode] = {}
self.moving_average_price_min_pre_100[strCode] = {}
self.jango_dict[strCode].update({"check": 0})
self.jango_dict[strCode].update({"매도조건": 0})
self.jango_dict[strCode].update({"주문수량": 0})
self.jango_dict[strCode].update({"보유수량": 0})
self.jango_dict[strCode].update({"최고수익률": -100})
self.jango_dict[strCode].update({"최저수익률": 100})
self.jango_dict[strCode].update({"수익률": 0})
self.jango_dict[strCode].update({"매수시간": datetime.now()})
self.jango_dict[strCode].update({"매도대기시간": datetime.now()})
self.jango_dict[strCode].update({"매수주문전달성공": "0000"})
self.jango_dict[strCode].update({"최고가": 0})
self.jango_dict[strCode].update({"최저가": 10000000})
self.jango_dict[strCode].update({"매도": 0})
self.jango_dict[strCode].update({"누적거래대금": 0})
def login_slot(self, err_code):
print(errors(err_code)[1])
# 로그인 처리가 완료됐으면 이벤트 루프를 종료한다.
self.login_event_loop.exit()
def trdata_slot(self, sScrNo, sRQName, sTrCode, sRecordName, sPrevNext):
if sRQName == "예수금상세현황요청":
deposit = self.dynamicCall("GetCommData(QString, QString, int, QString)", sTrCode, sRQName, 0, "예수금")
self.deposit = int(deposit)
use_money = float(self.deposit) * self.use_money_percent
self.use_money = int(use_money)
self.use_money = self.use_money / 4
output_deposit = self.dynamicCall("GetCommData(QString, QString, int, QString)", sTrCode, sRQName, 0,
"출금가능금액")
self.output_deposit = int(output_deposit)
print("예수금 : %s %d" % (self.deposit, self.output_deposit))
self.stop_screen_cancel(self.screen_my_info)
self.detail_account_info_event_loop.exit()
def realdata_slot(self, sCode, sRealType, sRealData):
if sRealType == "장시작시간":
fid = self.realType.REALTYPE[sRealType]['장운영구분'] # (0:장시작전, 2:장종료전(20분), 3:장시작, 4,8:장종료(30분), 9:장마감)
value = self.dynamicCall("GetCommRealData(QString, int)", sCode, fid)
if value == '0':
print("장 시작 전")
elif value == '3':
now = datetime.now()
print("장 시작 : %s" % now)
self.tmp_event_loop.exit()
elif value == "2":
print("장 종료, 동시호가로 넘어감")
elif value == "4":
print("3시30분 장 종료")
elif sRealType == "주식체결" or sRealType == "선물시세":
sRealType = "주식체결"
now = datetime.now()
nowHourMin = now.strftime('%H%M')
nowHourMinSec = now.strftime('%H%M%S')
self.check = self.check + 1
# print("realdata_slot", sCode, nowHourMinSec)
is_hesun = 0
if self.rqDataCode == sCode:
is_hesun = 1
b = self.dynamicCall("GetCommRealData(QString, int)", sCode, self.realType.REALTYPE[sRealType]['현재가']) # 출력 : +(-)2520
b = abs(float(b))
e = self.dynamicCall("GetCommRealData(QString, int)", sCode, self.realType.REALTYPE[sRealType]['(최우선)매도호가']) # 출력 : +(-)2520
e = abs(float(e))
# g = 0
g = self.dynamicCall("GetCommRealData(QString, int)", sCode, self.realType.REALTYPE[sRealType]['누적거래대금']) # 출력 : +(-)2520
g = abs(int(g))
tmp = self.dynamicCall("GetCommRealData(QString, int)", sCode, self.realType.REALTYPE[sRealType]['체결시간']) # 출력 : 000070
chegul_time = tmp[0:4]
chegul_time_sec = tmp[4:6]
chegul_time_hour_min_sec = tmp[0:6]
f = self.dynamicCall("GetCommRealData(QString, QString)", sCode, self.realType.REALTYPE[sRealType]['등락율']) # 출력 : +(-)2520
f = abs(float(f))
#######################################
is_mesu = self.jango_dict[sCode]["매수조건"]
is_medo = self.jango_dict[sCode]["매도조건"]
isMinReCalc = 0
if self.nowHourMin[sCode] != chegul_time:
isMinReCalc = 1
self.nowHourMin[sCode] = chegul_time
if isMinReCalc == 1:
tmp = copy.copy(self.price_data_min[sCode])
if len(self.calcul_data_min[sCode]) == 220:
self.calcul_data_min[sCode].pop()
self.calcul_data_min[sCode].insert(0, tmp)
self.price_data_min[sCode][0] = 0.0
self.price_data_min[sCode][1] = 0.0
self.price_data_min[sCode][2] = 1000000.0
self.price_data_min[sCode][3] = 0.0
if self.price_data_min[sCode][0] < b:
self.price_data_min[sCode][0] = b
if self.price_data_min[sCode][2] > b:
self.price_data_min[sCode][2] = b
if self.price_data_min[sCode][3] == 0:
self.price_data_min[sCode][3] = b
self.price_data_min[sCode][1] = b
current_price3 = b
open_price3_min = self.price_data_min[sCode][3]
high_price3_min = self.price_data_min[sCode][0]
low_price3_min = self.price_data_min[sCode][2]
moving_average_price_3 = 0.0
moving_average_price_3_1 = 0.0
moving_average_price_3_2 = 0.0
moving_average_price_10 = 0.0
moving_average_price_20 = 0.0
if len(self.calcul_data_min[sCode]) >= 2 and self.calcul_data_min[sCode][1][1] > 0.0:
moving_average_price_3 = (b + self.calcul_data_min[sCode][0][1] + self.calcul_data_min[sCode][1][1]) / 3
moving_average_price_3_1 = (self.calcul_data_min[sCode][0][1] + self.calcul_data_min[sCode][1][1] + self.calcul_data_min[sCode][2][1]) / 3
if len(self.calcul_data_min[sCode]) >= 9 and self.calcul_data_min[sCode][8][1] > 0.0:
total = 0
for i in range(9):
total += self.calcul_data_min[sCode][i][1]
moving_average_price_10 = (b + total) / 10
if len(self.calcul_data_min[sCode]) >= 19 and self.calcul_data_min[sCode][18][1] > 0.0:
total = 0
for i in range(19):
total += self.calcul_data_min[sCode][i][1]
moving_average_price_20 = (b + total) / 20
# moving_average_price_2 = (b + self.calcul_data_min[sCode][0][1]) / 2
# moving_average_price_2_1 = (self.calcul_data_min[sCode][0][1] + self.calcul_data_min[sCode][1][1]) / 2
# moving_average_price_2_2 = (self.calcul_data_min[sCode][1][1] + self.calcul_data_min[sCode][2][1]) / 2
# print("11111111" , now, sCode, moving_average_price_2_2, moving_average_price_2_1, moving_average_price_2)
if self.jango_dict[sCode]["매수조건"] == 3 and self.jango_dict[sCode]["매도조건"] == 1:
self.jango_dict[sCode].update({"현재가": b})
checkSuccess = 1
total_suik = 0
count_jan = 0
for key, dic in self.not_account_stock_dict.items():
code = dic["코"]
if code == "101R6000":
continue
checkChegual = 0
if "체결가" in dic:
checkChegual = 1
if self.jango_dict[code]["매수조건"] == 3 and self.jango_dict[code]["매도조건"] == 1 and checkChegual == 0:
if "현재가" not in self.jango_dict[code]:
checkSuccess = 0
print("%s no 현재가 %s" % (dic["명"], code))
break
cur_price = self.jango_dict[code]["현재가"]
if cur_price == 0:
checkSuccess = 0
print("%s 현재가 0 %s" % (dic["명"], code))
break
if "매입가" not in dic:
checkSuccess = 0
print("%s no 매입가 %s" % (dic["명"], code))
break
if dic["매"] != self.jango_dict[code]["매"]:
print("11111", key, dic["명"], sCode, dic["매"], self.jango_dict[code]["매"])
continue
tmp_suik = dic["수익"]
if tmp_suik != -1.0:
print("%s 비정상 수익 %s" % (dic["명"], code))
continue
meip = dic["매입가"] * dic["체"]
susu = meip * self.susu
suik = cur_price * dic["체"] - meip - susu
mesu_susu = meip * self.real_susu
medo_susu = (cur_price * dic["체"] * self.real_susu) + (cur_price * dic["체"] * self.real_segeum)
real_suik = (cur_price * dic["체"] - meip) - (mesu_susu + medo_susu)
count_jan += 1
total_suik += real_suik
if isMinReCalc == 1:
print("잔 ", now, key, code, dic["명"], real_suik, suik, cur_price, dic["매입가"], dic["체"])
elif checkChegual == 1:
total_suik += dic["수익"]
if isMinReCalc == 1:
print("완 ", now, key, code, dic["명"], dic["수익"])
else:
# print("%s %d %d %d" % (code, checkChegual, self.jango_dict[code]["매수조건"], self.jango_dict[code]["매도조건"]))
checkSuccess = 0
if checkChegual == 0 and self.jango_dict[code]["매수조건"] == 0 and self.jango_dict[code]["매도조건"] == 0:
del self.not_account_stock_dict[key]
break
if checkSuccess == 0:
total_suik = 0
if checkSuccess == 1: # and self.printHourMin != nowHourMin:
if self.high_jan < count_jan:
self.high_jan = count_jan
print("high_jan %d" % (self.high_jan))
if isMinReCalc == 1 or self.high_suick < total_suik or self.low_suick > total_suik:
print("%s %s %s low_ %f high_ %f total_suik %f" %
(now, self.printHourMin, nowHourMin, self.low_suick, self.high_suick, total_suik))
self.printHourMin = nowHourMin
if self.high_suick < total_suik:
self.high_suick = total_suik
if self.low_suick > total_suik:
self.low_suick = total_suik
if is_mesu == 0:
return
if self.jango_dict[sCode]["최고가"] < b:
self.jango_dict[sCode]["최고가"] = b
if self.jango_dict[sCode]["최저가"] > b:
self.jango_dict[sCode]["최저가"] = b
# bNotAgainMesu = 0
# if self.jango_dict[sCode]["매도조건통시"] == self.nowHourMin[sCode] and self.jango_dict[sCode]['매입단가'] >= b:
# bNotAgainMesu = 1
# ksj
# if bNotAgainMesu == 1:
# print("bNotAgainMesu return!!", sCode, now)
# self.jango_dict[sCode].update({"매수조건": 0})
# screen_num = self.portfolio_stock_dict[sCode]['스크린번호']
# iRet = self.dynamicCall("SetRealRemove(QString, QString)", screen_num, sCode)
# return
if is_mesu == 1 and (f > 27 or e > 400000):
print("f > 27 return!!", sCode, now)
self.jango_dict[sCode].update({"매수조건": 0})
screen_num = self.portfolio_stock_dict[sCode]['스크린번호']
iRet = self.dynamicCall("SetRealRemove(QString, QString)", screen_num, sCode)
return
quantity = 0
if is_hesun == 0:
if is_mesu == 1 and e > 0:
result = 100000 / e
quantity = int(result)
if quantity == 0:
quantity = 1
else:
quantity = 4
if is_mesu == 1:
order_success = -1
if is_hesun == 0:
order_success = self.dynamicCall(
"SendOrder(QString, QString, QString, int, QString, int, int, QString, QString)",
["신규매수", self.portfolio_stock_dict[sCode]["주문용스크린번호"], self.account_num, 1, sCode, quantity, 0,
self.realType.SENDTYPE['거래구분']['시장가'], ""]
)
else:
order_success = self.dynamicCall(
"SendOrderFO(QString, QString, QString, QString, int, QString, QString, int, QString, QString)",
["신규매수", self.portfolio_stock_dict[sCode]["주문용스크린번호"], self.hesun_account_num, sCode, 1, "2",
"3",
quantity, "", ""]
)
if order_success == 0:
print("%s 매수주문 전달 성공 : %s" % (now, sCode))
self.jango_dict[sCode].update({"주문수량": quantity})
self.jango_dict[sCode].update({"매수조건": 2})
self.jango_dict[sCode].update({"매수주문전달성공": nowHourMin})
self.jango_dict[sCode].update({"누적거래대금": g})
self.jango_dict[sCode].update({"수익률": 0})
self.jango_dict[sCode].update({"최고수익률": 0.0})
self.jango_dict[sCode].update({"최저수익률": 1000000.0})
self.nowHourMin[sCode] = nowHourMin
# screen_num = self.portfolio_stock_dict[sCode]['스크린번호']
# iRet = self.dynamicCall("SetRealRemove(QString, QString)", screen_num, sCode)
else:
print("매수주문 전달 실패 : %s" % sCode, order_success)
self.jango_dict[sCode].update({"매수조건": 0})
screen_num = self.portfolio_stock_dict[sCode]['스크린번호']
if is_hesun == 0:
iRet = self.dynamicCall("SetRealRemove(QString, QString)", screen_num, sCode)
return
##########################################
if is_mesu != 3:
return
if self.jango_dict[sCode]["조건"] == 5:
if total_suik < -4000: # -2600
if self.stop == 0:
print("손절!!")
# self.stop = 1
if self.high_suick > 4400 and total_suik < 4100 and total_suik > 0:
if self.stop == 0:
print("4000 달성!!", self.low_suick)
self.stop = 1
if self.high_suick > 8400 and total_suik < 8100 and total_suik > 0:
if self.stop == 0:
print("8000 달성!!", self.low_suick)
self.stop = 1
if self.high_suick > 12400 and total_suik < 12100 and total_suik > 0:
if self.stop == 0:
print("12000 달성!!", self.low_suick)
self.stop = 1
if self.high_suick > 16400 and total_suik < 16100 and total_suik > 0:
if self.stop == 0:
print("16000 달성!!", self.low_suick)
self.stop = 1
# if self.high_suick > 7500 and total_suik < 5500 and total_suik > 0:
# print("4500 달성!!", self.low_suick)
# self.stop = 1
if self.stop == 1 and self.jango_dict[sCode]["조건"] == 5:
self.jango_dict[sCode].update({"매도": 2})
if is_medo == 1:
current_meme_rate = (current_price3 - open_price3_min) / open_price3_min
current_meme_rate = round(current_meme_rate * 100, 5)
suik_rate = round((current_price3 - self.jango_dict[sCode]['매입단가']) / self.jango_dict[sCode]['매입단가'], 5)
suik_rate = round(suik_rate * 100, 5)
if self.jango_dict[sCode]["최고수익률"] < suik_rate:
self.jango_dict[sCode]["최고수익률"] = suik_rate
if self.jango_dict[sCode]["최저수익률"] > suik_rate:
self.jango_dict[sCode]["최저수익률"] = suik_rate
is_time_check_mode_condition = 0
is_medo_condition = 0
delta = now - self.jango_dict[sCode]["매수시간"]
check2 = 0
check3 = 0
check4 = 0
check5 = 0
check6 = 0
check7 = 0
check8 = 0
check9 = 0
check10 = 0
check11 = 0
check12 = 0
check13 = 0
check14 = 0
check15 = 0
check16 = 0
if self.jango_dict[sCode]["조건"] == 1:
check13 = moving_average_price_3_1 > moving_average_price_3 and current_meme_rate < -0.4 and suik_rate < 2.0
check14 = moving_average_price_10 > b * 1.012 and current_meme_rate < -0.4
check15 = suik_rate < -1.5
check16 = moving_average_price_20 > b * 1.0068 and current_meme_rate < -0.3
if self.jango_dict[sCode]["조건"] == 4:
#check2 = moving_average_price_3_1 > moving_average_price_3 and current_meme_rate < -0.2
check3 = moving_average_price_3_1 > moving_average_price_3 and moving_average_price_3 < moving_average_price_10 / 1.001 and current_meme_rate < -0.2
#check6 = self.jango_dict[sCode]["매도"]
check6 = suik_rate < -1.0
# if self.jango_dict[sCode]["check"] == 0 and check16 == 1:
# self.jango_dict[sCode]["check"] = self.check
if float(nowHourMinSec) > 151900:
is_time_check_mode_condition = 1
if delta.seconds > 0 and (
(f > 29.5) or (check2 or check3 or check6) or (check13 or check14 or check15 or check16) or (
check8 or check9 or check10)):
is_medo_condition = 1
print(
"매도조건1 통과 %s %f check(%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d) %d %f %f %f %s" % (
sCode, suik_rate, check2, check3, check4, check5, check6, check7, check8, check9, check10,
check11, check12, check13, check14, check15, self.jango_dict[sCode]["check"], self.check,
current_meme_rate, f, now))
######
if is_time_check_mode_condition == 1 or is_medo_condition == 1:
self.jango_dict[sCode].update({"수익률": suik_rate})
# self.jango_dict[sCode].update({"매도조건통시": nowHourMin})
if is_hesun == 0:
order_success = self.dynamicCall(
"SendOrder(QString, QString, QString, int, QString, int, int, QString, QString)",
["신규매도", self.portfolio_stock_dict[sCode]["주문용스크린번호"], self.account_num, 2, sCode,
self.jango_dict[sCode]['보유수량'], 0, self.realType.SENDTYPE['거래구분']['시장가'], ""]
)
else:
order_success = self.dynamicCall(
"SendOrderFO(QString, QString, QString, QString, int, QString, QString, int, QString, QString)",
["신규매도", self.portfolio_stock_dict[sCode]["주문용스크린번호"], self.hesun_account_num, sCode, 1,
"1", "3",
quantity, "", ""]
)
if order_success == 0:
print("%s 매도주문 전달 성공: %s" % (now, sCode))
self.jango_dict[sCode].update({"매도조건": 2})
else:
print("매도주문 전달 실패: %s" % sCode)
#######################################
def chejan_slot(self, sGubun, nItemCnt, sFidList):
# 주문체결
if int(sGubun) == 0:
account_num = self.dynamicCall("GetChejanData(int)", self.realType.REALTYPE['주문체결']['계좌번호'])
sCode = self.dynamicCall("GetChejanData(int)", self.realType.REALTYPE['주문체결']['종목코드'])[1:]
is_hesun = 0
if self.rqDataCode == sCode or self.rqDataCode2 == sCode:
is_hesun = 1
sCode = self.rqDataCode
# if self.is_hesun == 1:
# sCode = self.rqDataCode
stock_name = self.dynamicCall("GetChejanData(int)", self.realType.REALTYPE['주문체결']['종목명'])
stock_name = stock_name.strip()
origin_order_number = self.dynamicCall("GetChejanData(int)",
self.realType.REALTYPE['주문체결']['원주문번호']) # 출력 : defaluse : "000000"
order_number = self.dynamicCall("GetChejanData(int)",
self.realType.REALTYPE['주문체결']['주문번호']) # 출럭: 0115061 마지막 주문번호
order_status = self.dynamicCall("GetChejanData(int)",
self.realType.REALTYPE['주문체결']['주문상태']) # 출력: 접수, 확인, 체결
order_quan = self.dynamicCall("GetChejanData(int)", self.realType.REALTYPE['주문체결']['주문수량']) # 출력 : 3
order_quan = int(order_quan)
order_price = self.dynamicCall("GetChejanData(int)", self.realType.REALTYPE['주문체결']['주문가격']) # 출력: 21000
# if float(order_price) > 0:
# return
# order_price = int(order_price)
not_chegual_quan = self.dynamicCall("GetChejanData(int)",
self.realType.REALTYPE['주문체결']['미체결수량']) # 출력: 15, default: 0
not_chegual_quan = int(not_chegual_quan)
order_gubun = self.dynamicCall("GetChejanData(int)", self.realType.REALTYPE['주문체결']['주문구분']) # 출력: -매도, +매수
# order_gubun = order_gubun.strip().lstrip('+').lstrip('-')
chegual_time_str = self.dynamicCall("GetChejanData(int)",
self.realType.REALTYPE['주문체결']['주문/체결시간']) # 출력: '151028'
chegual_price = self.dynamicCall("GetChejanData(QString)",
self.realType.REALTYPE['주문체결']['체결가']) # 출력: 2110 default : ''
if chegual_price == '':
chegual_price = 0.0
else:
chegual_price = float(chegual_price)
chegual_quantity = self.dynamicCall("GetChejanData(int)",
self.realType.REALTYPE['주문체결']['체결량']) # 출력: 5 default : ''
if chegual_quantity == '':
chegual_quantity = 0
else:
chegual_quantity = int(chegual_quantity)
# current_price = self.dynamicCall("GetChejanData(int)", self.realType.REALTYPE['주문체결']['현재가']) # 출력: -6000
# current_price = abs(int(current_price))
# first_sell_price = self.dynamicCall("GetChejanData(int)", self.realType.REALTYPE['주문체결']['(최우선)매도호가']) # 출력: -6010
# first_sell_price = abs(int(first_sell_price))
# first_buy_price = self.dynamicCall("GetChejanData(int)", self.realType.REALTYPE['주문체결']['(최우선)매수호가']) # 출력: -6000
# first_buy_price = abs(int(first_buy_price))
######## 새로 들어온 주문이면 주문번호 할당
if order_number not in self.not_account_stock_dict.keys():
self.not_account_stock_dict.update({order_number: {}})
self.not_account_stock_dict[order_number].update({"매": 0})
self.not_account_stock_dict[order_number].update({"분": order_gubun})
self.not_account_stock_dict[order_number].update({"코": sCode})
self.not_account_stock_dict[order_number].update({"시간": chegual_time_str})
self.not_account_stock_dict[order_number].update({"명": stock_name})
self.not_account_stock_dict[order_number].update({"조": self.jango_dict[sCode]["조건"]})
self.not_account_stock_dict[order_number].update({"체": chegual_quantity})
# self.not_account_stock_dict[order_number].update({"주문": order_quan})
self.not_account_stock_dict[order_number].update({"익": round(self.jango_dict[sCode]["수익률"], 5)})
self.not_account_stock_dict[order_number].update({"최고익": round(self.jango_dict[sCode]["최고수익률"], 5)})
self.not_account_stock_dict[order_number].update({"최저익": round(self.jango_dict[sCode]["최저수익률"], 5)})
# self.not_account_stock_dict[order_number].update({"누적": round(self.jango_dict[sCode]["누적거래대금"],5)})
# self.not_account_stock_dict[order_number].update({"최고가": round(self.jango_dict[sCode]["최고가"],5)})
# self.not_account_stock_dict[order_number].update({"최저가": round(self.jango_dict[sCode]["최저가"],5)})
# self.not_account_stock_dict[order_number].update({"체결가": chegual_price})
# self.not_account_stock_dict[order_number].update({"매입가": 0})
self.not_account_stock_dict[order_number].update({"주문상태": order_number})
self.not_account_stock_dict[order_number].update({"수익": -1.0})
print("chejan_slot", order_number, stock_name, sCode, not_chegual_quan)
now = datetime.now()
nowDate = now.strftime('%Y-%m-%d')
nowTime = now.strftime('%H:%M:%S')
if order_gubun == "+매수" and chegual_price > 0:
if sCode not in self.mesu_price.keys():
self.mesu_price.update({sCode: []})
self.mesu_price[sCode].append([chegual_price, chegual_quantity])
if order_gubun == "-매도" and chegual_price > 0:
if sCode not in self.medo_price.keys():
self.medo_price.update({sCode: []})
self.medo_price[sCode].append([chegual_price, chegual_quantity])
self.jango_dict[sCode].update({"현재가": 0})
if order_gubun == "+매수" and not_chegual_quan == 0:
final_price = 0.0
pre_quan = 0
quan = 0
for lst in self.mesu_price[sCode]:
quan = lst[1] - pre_quan
if quan < 0:
break
tmp = lst[0] * quan
final_price += tmp
pre_quan = lst[1]
if quan > 0:
final_price = float(final_price / order_quan)
else:
final_price = chegual_price
self.mesu_price[sCode].clear()
self.jango_dict[sCode].update({"매수오더": order_number})
self.jango_dict[sCode].update({"매도": 0})
self.jango_dict[sCode].update({"매수조건": 3})
self.jango_dict[sCode].update({"매수시간": now})
self.jango_dict[sCode].update({"보유수량": order_quan})
self.jango_dict[sCode].update({"매입단가": final_price})
self.not_account_stock_dict[order_number].update({"매입가": final_price})
self.jango_dict[sCode].update({"매도조건": 1})
self.jango_dict[sCode]["매"] = self.jango_dict[sCode]["매"] + 1
self.not_account_stock_dict[order_number].update({"매": self.jango_dict[sCode]["매"]})
filename = nowDate + ".txt"
f = open(filename, "a", encoding="utf8")
f.write("%s\n" % self.not_account_stock_dict[order_number])
f.close()
if order_gubun == "-매도" and not_chegual_quan == 0:
meip_quan = self.jango_dict[sCode]["보유수량"]
meip = self.jango_dict[sCode]["매입단가"]
mesu = meip * meip_quan
self.jango_dict[sCode].update({"매수조건": 0})
self.jango_dict[sCode].update({"매도조건": 0})
self.jango_dict[sCode].update({"보유수량": 0})
self.jango_dict[sCode].update({"매도완료시간": now})
self.jango_dict[sCode].update({"매입단가": 0})
screen_num = self.portfolio_stock_dict[sCode]['스크린번호']
final_price = 0.0
pre_quan = 0
quan = 0
for lst in self.medo_price[sCode]:
quan = lst[1] - pre_quan
if quan < 0:
break
tmp = lst[0] * quan
final_price += tmp
pre_quan = lst[1]
if quan > 0:
final_price = float(final_price / order_quan)
else:
final_price = chegual_price
self.medo_price[sCode].clear()
self.not_account_stock_dict[order_number].update({"수익": 0.0})
suik_price = 0.0
suik_final = 0.0
if is_hesun == 0:
susu = mesu * self.susu
suik = final_price * meip_quan - mesu - susu
mesu_susu = mesu * self.real_susu
medo_susu = (final_price * meip_quan * self.real_susu) + (
final_price * meip_quan * self.real_segeum)
real_suik = (final_price * meip_quan - mesu) - (mesu_susu + medo_susu)
self.not_account_stock_dict[order_number].update({"수익": real_suik})
else:
susu = mesu * self.hesun_susu
suik = (final_price * meip_quan - mesu) / 0.02
suik_price = suik * 1000
suik_final = suik_price - susu
self.not_account_stock_dict[order_number].update({"수익": suik_final})
# print("%s %s %f %f" % (nowTime, self.not_account_stock_dict[order_number]["명"], suik, real_suik))
self.not_account_stock_dict[order_number].update({"체결가": final_price})
# suik_rate = round((final_price - mesu) / mesu,5)
# suik_rate = round(suik_rate * 100, 5)
# self.not_account_stock_dict[order_number].update({"익": round(suik_rate, 5)})
# ksj
if is_hesun == 0:
iRet = self.dynamicCall("SetRealRemove(QString, QString)", screen_num, sCode)
self.calcul_data_min[sCode].clear()
filename = nowDate + ".txt"
f = open(filename, "a", encoding="utf8")
f.write("%s\n" % self.not_account_stock_dict[order_number])
f.close()
# del self.not_account_stock_dict[self.jango_dict[sCode]["매수오더"]]
ㄹㄴㅇㄹ
반응형