open_api.py 25.6 KB
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 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
from PyQt5.QtCore import *
from PyQt5.QAxContainer import *
from PyQt5.QtWidgets import *
import pymysql
import datetime
from sqlalchemy import *
from collections import defaultdict
from pandas import DataFrame

from Logger import *
import config
from Simulator_Api import *

pymysql.install_as_MySQLdb()

class Open_Api(QAxWidget):
    def __init__(self):
        super().__init__()

        # event_loop list
        self.login_event_loop=QEventLoop()
        self.tr_event_loop=QEventLoop()

        # open_api 호출 횟수를 저장f
        self.rq_count=0
        self.set_date()
        self.tr_loop_count=0
        self.call_time=datetime.datetime.now()

        # open_api 연동
        self._create_instance()
        self._set_signal_slots()
        self.comm_connect()

        # 계좌정보 출력
        self.get_account_info()

        # 변수 설정
        self.set_variable()

        self.simul_api=Simulator_Api(self.simul_num,"real",self.db_name)
        logger.debug("알고리즘 번호 : %s",self.simul_api.simul_num)
        logger.debug("매수 알고리즘 번호 : %s",self.simul_api.buy_algorithm)
        logger.debug("매도 알고리즘 번호 : %s",self.simul_api.sell_algorithm)

        if not self.simul_api.is_table_exist(self.db_name,"setting_data"):
            self.create_setting_data()

        self.set_simul_variable()
        self.ohlcv=defaultdict(list)

    # 날짜 설정
    def set_date(self):
        self.today=datetime.datetime.today().strftime("%Y%m%d")
        self.today_time=datetime.datetime.today().strftime("%Y%m%d%H%M")

    # 키움 open_api 를 사용하기 위한 ocx controller 생성
    def _create_instance(self):
        try:
            self.setControl("KHOPENAPI.KHOpenAPICtrl.1")
        except Exception as e:
            logger.critical(e)

    # 이벤트 처리를 위한 slots
    def _set_signal_slots(self):
        try:
            # 로그인 처리 이벤트
            self.OnEventConnect.connect(self._login_slot)
            # 조회요청 처리 이벤트
            self.OnReceiveTrData.connect(self._receive_tr_data)
            # 서버 통신 후 수신메세지 처리 이벤트
            self.OnReceiveMsg.connect(self._receive_msg)
            # 주문요청 처리 이벤트
            self.OnReceiveChejanData.connect(self._receive_chejan_data)
        except Exception as e:
            logger.critical(e)

    # 로그인 이벤트 처리 slot
    # param : code - 로그인 성공 시 0
    #                      실패 시 에러코드 출력
    def _login_slot(self,code):
        try:
            if code==0:
                logger.debug("connected")
            else:
                logger.debug("connection failed...")
            self.login_event_loop.exit()
        except Exception as e:
            logger.critical(e)

    # 수동 로그인설정인 경우 로그인창을 출력해서 로그인을 시도
    # 자동로그인 설정인 경우 로그인창 출력없이 로그인을 시도
    def comm_connect(self):
        try:
            self.dynamicCall("CommConnect()")
            self.login_event_loop.exec_()
        except Exception as e:
            logger.critical(e)

    # TR 요청을 처리하는 slot
    # param sScrNo      : 스크린번호
    #       sRQName     : 요청했을 때 지은 이름
    #       sTrCode     : 요청 id, tr코드
    #       sRecordName : 레코드 이름
    #       sPrevNext   : 다음 페이지가 있는지 여부. "2" : 다음페이지 존재, "0" or "" : 다음페이지 없음
    def _receive_tr_data(self,sScrNo,sRQName,sTrCode,sRecordName,sPrevNext):
        if sPrevNext=='2':
            self.remained_data=True
        else:
            self.remained_data=False

        # Request 요청에 따른 함수 처리
        if sRQName == "opt10081_req" and self.purpose == "trader":
            logger.debug("주식일봉차트조회요청")
            self._opt10081(sRQName,sTrCode)
        elif sRQName == "opt10081_req" and self.purpose == "collector":
            logger.debug("주식일봉차트조회요청")
            self.collector_opt10081(sRQName,sTrCode)
        elif sRQName == "opw00001_req":
            logger.debug("예수금상세현황요청")
            self._opw00001(sRQName,sTrCode)
        elif sRQName == "opw00018_req":
            logger.debug("계좌평가잔고내역요청")
            self._opw00018(sRQName,sTrCode)
        elif sRQName == "opt10074_req":
            logger.debug("일자별실현손익요청")
            self._opt10074(sRQName,sTrCode)
        elif sRQName == "opw00015_req":
            logger.debug("위탁종합거래내역요청")
            self._opw00015(sRQName,sTrCode)
        elif sRQName == "opt10076_req":
            logger.debug("실시간체결요청")
            self._opt10076(sRQName,sTrCode)
        elif sRQName == "opt10073_req":
            logger.debug("일자별종목별실현손익요청")
            self._opt10073(sRQName,sTrCode)
        elif sRQName == "opt10080_req":
            logger.debug("주식분봉차트조회요청")
            self._opt10080(sRQName,sTrCode)
        elif sRQName == "send_order_req":
            pass
        else:
            logger.debug("Invalid Request Code...")

        # 다음 페이지가 존재할 경우 처리
        # 다음 페이지가 존재하지 않을 경우 event loop를 종료
        if sRQName!="send_order_req":
            self.tr_loop_count-=1
        try:
            if self.tr_loop_count<=0:
                self.tr_event_loop.exit()
                self.tr_loop_count=0
        except AttributeError:
            pass

    # 서버통신 후 수신한 메시지를 알려주는 slot
    def _receive_msg(self,sScrNo,sRQName,sTrCode,sMsg):
        logger.debug(sMsg)

    # 주문요청후 주문접수, 체결통보, 잔고통보를 수신할 때 마다 호출
    # GetChejanData()함수를 이용해서 상세한 정보를 얻을 수 있다
    # param     :   sGubun  -   체결구분. 접수와 체결시 '0'값, 국내주식 잔고전달은 '1'값, 파생잔고 전달은 '4'
    def _receive_chejan_data(self,sGubun,nItemCnt,sFIdList):
        # 현재 체결 진행 중인 코드
        print("주분번호 : ",self.get_chejan_data(9023))
        print("종목명 : ",self.get_chejan_data(302))
        print("주문수량 : ",self.get_chejan_data(900))
        print("주문가격 : ",self.get_chejan_data(901))

    # OnReceiveChejan()이벤트가 호출될때 체결정보나 잔고정보를 얻어오는 함수
    # param     :   nFid    -   실시간 타입에 포함된 FID
    def get_chejan_data(self,nFid):
        try:
            ret=self.dynamicCall("GetChejanData(int)",nFid)
            return ret
        except Exception as e:
            logger.critical(e)

    # 사용자의 계좌정보 저장 및 출력
    def get_account_info(self):
        account_no=self.get_login_info("ACCNO")
        self.account_no=account_no.split(";")[0]
        logger.debug(self.account_no)

    # 원하는 사용자 정보 반환
    # param     :   tag - ACCNO - 보유계좌리스트
    #                     ACCOUNT_CNT - 보유계좌 수
    #                     USER_ID - 사용자 ID
    #                     USER_NAME - 사용자 이름
    #                     KEY_BSECGB - 키보드 보안 해제 여부 (0 : 정상, 1: 해지)
    #                     FIREW_SECGB - 방화벽 설정여부 (0 : 미설정, 1: 설정, 2 : 해지)
    #                     GetServerGubun - 접속서버 구분 (1 : 모의투자, 나머지 : 실서버)
    # return    :   tag를 통해 요청한 정보(ret) 반환
    def get_login_info(self,tag):
        try:
            ret=self.dynamicCall("GetLoginInfo(QString)",tag)
            return ret
        except Exception as e:
            logger.critical(e)

    # 조회요청시 TR의 Input값을 지정하는 함수
    # param : sId       -   TR에 명시된 Input이름
    #         svalue    -   Input이름으로 지정한 값
    def set_input_value(self,sId,sValue):
        try:
            self.dynamicCall("SetInputValue(QString, QString)", sId, sValue)
        except Exception as e:
            print(e)
            sys.exit()

    # 조회요청함수
    # param : sRQName       -   사용자 구분명
    #         sTrCode       -   조회하려는 TR이름
    #         nPrevNext     -   연속조회여부
    #         sScreenNo     -   화면번호
    def comm_rq_data(self,sRQName,sTrData,nPrevNext,sScrNo):
        self.dynamicCall("CommRqData(QString, QString, int, QString", sRQName, sTrData, nPrevNext, sScrNo)
        self.tr_event_loop.exec_()

    # OnReceiveTRData()이벤트가 호출될때 조회데이터를 얻어오는 함수
    # param : sTrCode       -   TR 이름
    #         sRecordName   -   레코드이름
    #         nIndex        -   TR반복부
    #         sItemName     -   TR에서 얻어오려는 출력항목이름
    def _get_comm_data(self,sTrCode,sRecordName,nIndex,sItemName):
        ret = self.dynamicCall("GetCommData(QString, QString, int, QString", sTrCode, sRecordName, nIndex, sItemName)
        return ret.strip()

    # 조회수신한 멀티데이터의 갯수(반복)을 얻는다
    # param : sTrCode       -   tr이름
    #         sRecordName   -   레코드 이름
    def _get_repeat_cnt(self,sTrCode,sRecordName):
        try:
            ret=self.dynamicCall("GetRepeatCnt(QString, QString)",sTrCode,sRecordName)
            return ret
        except Exception as e:
            print(e)
            sys.exit()

    # 변수 설정
    # 실전투자인지 모의투자인지 여부를 확인하고 그에 해당하는 데이터베이스를 생성하는 함수
    def set_variable(self):
        self.config=config
        self.reset_opw00018_output()

        if self.account_no==self.config.real_account_no:
            logger.debug("실전투자")
            self.simul_num=self.config.real_num
            self.set_database(self.config.real_bot_name)
            self.mod_classify=100

        elif self.account_no==self.config.test_account_no:
            logger.debug("모의투자")
            self.simul_num=self.config.test_num
            self.set_database(self.config.test_bot_name)
            self.mod_classify=1

        else:
            logger.debug("Invalid Account Number. Check the Config.py")
            exit(1)

        self.is_balance_null=True
        self.use=False

    # 데이터베이스 생성 및 엔진 설정
    def set_database(self,db_name):
        self.db_name=db_name
        conn=pymysql.connect(
            host=config.db_ip,
            port=int(config.db_port),
            user=config.db_id,
            password=config.db_pw,
            charset='utf8'
        )
        cursor=conn.cursor()
        if not self.is_database_exist(cursor):
            self.create_database(cursor)
        self.engine_bot=create_engine("mysql+pymysql://"+self.config.db_id+":"+self.config.db_pw+"@"+
                                      self.config.db_ip + ":" + self.config.db_port+"/"+db_name,encoding='utf-8')
        self.create_info_database(cursor)

        conn.commit()
        cursor.close()
        conn.close()

        self.engine_daily=create_engine("mysql+pymysql://"+self.config.db_id+":"+self.config.db_pw+"@"+
                                        self.config.db_ip + ":" + self.config.db_port+"/daily_info",encoding='utf-8')
        self.engine_stock=create_engine("mysql+pymysql://"+self.config.db_id+":"+self.config.db_pw+"@"+
                                        self.config.db_ip + ":" + self.config.db_port+"/stock_info",encoding='utf-8')
        self.engine_minute=create_engine("mysql+pymysql://"+self.config.db_id+":"+self.config.db_pw+"@"+
                                         self.config.db_ip + ":" + self.config.db_port+"/minute_info",encoding='utf-8')

    # Bot Database가 존재하는지 확인하는 함수
    def is_database_exist(self,cursor):
        query="select 1 from information_schema.schemata where schema_name='{}'"
        result=cursor.execute(query.format(self.db_name))
        if result:
            return True
        else:
            return False

    # Bot Database를 생성하는 함수
    def create_database(self,cursor):
        query="create database {}"
        cursor.execute(query.format(self.db_name))

    # information 데이터베이스가 존재하는지 확인
    # 존재하지 않는다면 새로 생성
    def create_info_database(self,cursor):
        info_list=['daily_info','stock_info','minute_info']
        query="select schema_name from information_schema.schemata"
        cursor.execute(query)
        result=cursor.fetchall()
        print(result)
        exist_list=[item[0].lower() for item in result]
        create_query="create database {}"
        has_created=False
        for db in info_list:
            if db not in exist_list:
                has_created=True
                logger.debug(db,"Database not exist. Create the Database.")
                cursor.execute(create_query.format(db))
                logger.debug(db,"Creation Completed!")

        if has_created and self.engine_bot.has_table('setting_data'):
            print("exist")
            self.engine_bot.execute("update setting_data set code_update='0")

    def create_setting_data(self):
        df_data={"limit_money":[],"per_invest":[],"max_per_invest":[],"min_per_invest":[],"set_per_invest":[],
                 "code_update":[],"today_finish":[],"balance_to_db":[],"posses_stocks":[],"today_profit":[],
                 "contract_check":[],"db_to_daily_info":[],"today_buy_list":[],"stock_info":[],"min_info":[],
                 "daily_info":[]}
        df_setting_data=DataFrame(df_data,
                                  columns=['limit_money','per_invest','max_per_invest','min_per_invest','set_per_invest',
                                           'code_update','today_finish','balance_to_db','posses_stocks','today_profit',
                                           'contract_check','db_to_daily_info','today_buy_list','stock_info','min_info',
                                           'daily_info'])

        df_setting_data.loc[0,'limit_money']=int(0)
        df_setting_data.loc[0,'per_invest']=int(0)
        df_setting_data.loc[0,'max_per_invest']=int(0)
        df_setting_data.loc[0,'min_per_invest']=int(0)
        df_setting_data.loc[0,'set_per_invest']=str(0)

        df_setting_data.loc[0,'code_update']=str(0)
        df_setting_data.loc[0,'today_finish']=str(0)
        df_setting_data.loc[0,'balance_to_db']=str(0)
        df_setting_data.loc[0,'posses_stocks']=str(0)
        df_setting_data.loc[0,'today_profit']=float(0)

        df_setting_data.loc[0,'contract_check']=str(0)
        df_setting_data.loc[0,'db_to_daily_info']=str(0)
        df_setting_data.loc[0,'today_buy_list']=str(0)
        df_setting_data.loc[0,'stock_info']=str(0)
        df_setting_data.loc[0,'min_info']=str(0)

        df_setting_data.loc[0,'daily_info']=str(0)

        df_setting_data.to_sql("setting_data",self.engine_bot,if_exists="replace")

    # 시뮬레이터에서 사용할 변수들을 설정
    def set_simul_variable(self):
        self.latest_date=self.simul_api.get_latest_date()
        if not self.simul_api.is_table_exist(self.db_name,"transaction_history"):
            logger.debug("create transaction_history table")
            self.per_invest=0
            self.create_transaction_history(0,0,0,0,0)
            self.delete_item_by_code(0)

        if not self.check_per_invest():
            self.set_per_invest()
        else:
            self.per_invest=self.get_per_invest()
            self.simul_api.per_invest=self.per_invest

    # transaction_history 테이블 생성 및 column 설정
    def create_transaction_history(self,order_num,code,contract_check,purchase_price,rate):
        logger.debug("creating transaction_history table")
        self.set_date()
        self.simul_api.df_transaction_history()
        self.simul_api.df_th.loc[0,'order_num']=order_num
        self.simul_api.df_th.loc[0,'code']=str(code)
        self.simul_api.df_th.loc[0,'reate']=float(rate)
        self.simul_api.df_th.loc[0,'buy_date']=self.today_time
        self.simul_api.df_th.loc[0,'contract_check']=contract_check
        self.simul_api.df_th.loc[0,'per_invest']=self.per_invest
        self.simul_api.df_th.loc[0,'purchase_price']=purchase_price

        self.simul_api.df_th=self.simul_api.df_th.fillna(0)
        self.simul_api.df_th.to_sql('transaction_history',self.engine_bot,if_exists='append')

    def delete_item_by_code(self,code):
        query="delete from transaction_history where code='%s'"
        self.engine_bot.execute(query%code)

    # setting_data에 per_invest항목이 설정되어 있는지 확인하는 함수
    def check_per_invest(self):
        query="select per_invest, set_per_invest from setting_data"
        result=self.engine_bot.execute(query).fetchall()
        if result[0][1]==self.today:
            self.per_invest=result[0][0]
            return True
        else:
            return False

    # 데이터베이스에서 per_invest항목을 반환
    def get_per_invest(self):
        query="select per_invest from setting_data"
        result=self.engine_bot.execute(query).fetchall()
        return result[0][0]

    # per_invest 항목 설정
    # per_ invest : 한 종목 당 투자할 금액
    def set_per_invest(self):
        self.get_deposit()
        self.get_balance()
        self.total_invest=self.deposit+self.total_purchase

        self.per_invest=self.simul_api.per_invest
        query="update setting_data set per_invest='%s', set_per_invest='%s'"
        self.engine_bot.execute(query%(self.per_invest,self.today))

    # 예수금 조회 및 저장
    def get_deposit(self):
        self.set_input_value("계좌번호",self.account_no)
        self.set_input_value("비밀번호입력매체구분",00)
        self.set_input_value("조회구분",1)
        self.comm_rq_data("opw00001_req","opw00001",0,"2000")

    # 예수금 상세현황요청 함수
    def _opw00001(self,sRQName,sTrCode):
        self.deposit=self._get_comm_data(sTrCode,sRQName,0,"d+2출금가능금액")
        self.deposit=int(self.deposit)

    # 잔고 조회 및 저장
    def get_balance(self):
        self.reset_opw00018_output()
        self.set_input_value("계좌번호",self.account_no)
        self.comm_rq_data("opw00018_req","opw00018",0,"2000")
        # 다음페이지가 존재할 경우 계속해서 조회
        while self.remained_data:
            self.set_input_value("계좌번호",self.account_no)
            self.comm_rq_data("opw00018_req","opw00018",2,"2000")

    # 계좌평가 잔고내역을 저장하는 변수 초기화
    def reset_opw00018_output(self):
        self.opw00018_output={'single':[],'multi':[]}


    # 계좌평가 잔고내역 요청
    # 싱글데이터를 통해 계좌에 대한 평가 잔고 데이터를 제공
    # 멀티데이터를 통해 보유 종목별 평가 잔고 데이터를 제공
    def _opw00018(self,sRQName,sTrCode):
        # 계좌평가 잔고 데이터 - 싱글데이터 저장
        self.total_purchase=self._get_comm_data(sTrCode,sRQName,0,"총매입금액")
        self.total_evaluated_price=self._get_comm_data(sTrCode,sRQName,0,"총평가금액")
        self.total_valuation=self._get_comm_data(sTrCode,sRQName,0,"총평가손익금액")
        self.earning_rate=self._get_comm_data(sTrCode,sRQName,0,"총수익률(%)")
        self.estimated_deposit=self._get_comm_data(sTrCode,sRQName,0,"추정예탁자산")

        self.total_purchase=int(self.total_purchase)
        self.total_evaluated_price=int(self.total_evaluated_price)
        self.total_valuation=int(self.total_valuation)
        self.earning_rate=float(self.earning_rate)
        self.estimated_deposit=int(self.estimated_deposit)

        self.opw00018_output['single'].append(self.total_purchase)
        self.opw00018_output['single'].append(self.total_evaluated_price)
        self.opw00018_output['single'].append(self.total_valuation)
        self.opw00018_output['single'].append(self.earning_rate)
        self.opw00018_output['single'].append(self.estimated_deposit)

        # 종목별 평가 잔고 데이터 - 멀티데이터 저장
        rows=self._get_repeat_cnt(sTrCode,sRQName)

        for i in range(rows):
            code=self._get_comm_data(sTrCode,sRQName,i,"종목번호")
            name=self._get_comm_data(sTrCode,sRQName,i,"종목명")
            quantity=self._get_comm_data(sTrCode,sRQName,i,"보유수량")
            purchase_price=self._get_comm_data(sTrCode,sRQName,i,"매입가")
            current_price=self._get_comm_data(sTrCode,sRQName,i,"현재가")
            total_valuation=self._get_comm_data(sTrCode,sRQName,i,"평가손익")
            earning_rate=self._get_comm_data(sTrCode,sRQName,i,"수익률(%)")
            total_purchase=self._get_comm_data(sTrCode,sRQName,i,"매입금액")

            code=code[1:]
            quantity=int(quantity)
            purchase_price=int(purchase_price)
            current_price=int(current_price)
            total_valuation=int(total_valuation)
            earning_rate=float(earning_rate)
            total_purchase=int(total_purchase)

            self.opw00018_output['multi'].append(
                [name,quantity,purchase_price,current_price,total_valuation,earning_rate,total_purchase,code]
            )

    # 일자별 실현 손익 요청
    def _opt10074(self,sRQName,sTrCode):
        self.total_profit=self._get_comm_data(sTrCode,sRQName,0,"실현손익")
        self.today_profit=self._get_comm_data(sTrCode,sRQName,0,"당일매도손익")

    # open_api를 통해 보유한 종목을 가져오는 함수
    # 가져온 정보를 posses_item이라는 테이블에 저장
    def get_posses_item(self):
        item_count=len(self.opw00018_output['multi'])
        posses_item_data={'date':[],'code':[],'code_name':[],'holding_amount':[],'purchase_price':[],
                          'present_price':[],'valuation_profit':[],'rate':[],'item_total_purchase':[]}

        posses_item=DataFrame(posses_item_data,
                              columns=['date','code','code_name','holding_amount','purchase_price',
                                       'present_price','valuation_profit','rate','item_total_purchase'])

        for i in range(item_count):
            item=self.opw00018_output['multi'][i]

            posses_item.loc[i,'date']=self.today
            posses_item.loc[i,'code']=item[7]
            posses_item.loc[i,'code_name']=item[0]
            posses_item.loc[i,'holding_amount']=int(item[1])
            posses_item.loc[i,'purchase_price']=int(item[2])
            posses_item.loc[i,'present_price']=int(item[3])
            posses_item.loc[i,'valuation_profit']=int(item[4])
            posses_item.loc[i,'rate']=float(item[5])
            posses_item.loc[i,'item_total_purchase']=int(item[6])

        posses_item.to_sql("posses_item",self.engine_bot,if_exists='replace')
        self.contract_sync()

    # 현재 소유하고 있는 종목에 대해 transaction_history 테이블을 업데이트
    def contract_sync(self):
        query="select code,code_name,rate from posses_item p" \
              "where p.code not in (select a.code from transaction_history a" \
              "where a.sell_date='0' group by a.code)" \
              "group by p.code"
        result=self.engine_bot.execute(query).fetchall()

        for item in result:
            self.set_input_value("종목코드",item.code)
            self.set_input_value("조회구분",1)
            self.set_input_value("계좌번호",self.account_no)
            self.comm_rq_data("opt10076_req","opt10076",0,"0350")

            if self.not_contract['주문구분']=="+매수":
                if self.not_contract['미체결수량']==0:
                    contract_check=0
                else:
                    contract_check=1
            elif self.not_contract['주문구분']=='':
                self.create_transaction_history(self.today,item.code,0,0,item.rate)
                continue
            else:
                continue

            self.create_transaction_history(self.not_contract['주문번호'],item.code,contract_check,self.not_contract['체결가'],item.rate)

    def _opt10076(self,sRQName,sTrCode):
        outputs=['주문번호','종목명','주문구분','주문가격','주문수량','체결가','체결량','미체결수량',
                 '당일매매수수료','당일매매세금','주문상태','매매구분','원주문번호','주문시간','종목코드']
        self.not_contract={}

        for key in outputs:
            if key not in ['주문번호','원주문번호','주문시간','종목코드']:
                self.not_contract[key]=int(self._get_comm_data(sTrCode,sRQName,0,key))
            self.not_contract[key]=self._get_comm_data(sTrCode,sRQName,0,key)

    # posses_item 테이블을 업데이트 했을 경우 setting data 테이블에 업데이트 한 날짜를 표시
    def setting_data_posses_stock(self):
        query="update setting_data set posses_stocks='%s'"
        self.engine_bot.execute(query%self.today)

    def reset_opt10073_output(self):
        self.opt10073_output={'single':[],'multi':[]}

    def _opt10073(self,sRQName,sTrCode):
        rows=self._get_repeat_cnt(sTrCode,sRQName)

        for i in range(rows):
            date=self._get_comm_data(sTrCode,sRQName,i,"일자")
            code=self._get_comm_data(sTrCode,sRQName,i,"종목코드")
            code_name=self._get_comm_data(sTrCode,sRQName,i,"종목명")
            amount=self._get_comm_data(sTrCode,sRQName,i,"체결량")
            today_profit=self._get_comm_data(sTrCode,sRQName,i,"당일매도손익")
            earning_rate=self._get_comm_data(sTrCode,sRQName,i,"손익율")

            code=code.lstrip('A')

            self.opt10073_output['multi'].append([date,code,code_name,amount,today_profit,earning_rate])






if __name__=="__main__":
    app=QApplication(sys.argv)
    a=Open_Api()