Esempio n. 1
0
def login(
    server=None,
    username=None,
    password=None,
):
    """ 로그인
    """
    # 기존에 연결되어 있는 서버가 있으면, 연결을 끊는다
    if _session.IsConnected():
        _session.DisconnectServer()
    
    # 로그인 시 필요한 정보를 입력받는다
    login_server = (server or input('[*] 접속 서버 ((r)eal / (D)emo / (a)ce) : ')).lower()[:1]
    login_server = {
        'r': 'hts.ebestsec.co.kr',
        'd': 'demo.ebestsec.co.kr',
        'a': '127.0.0.1'
    }.get(login_server, 'demo.ebestsec.co.kr')
    login_port = 20001
    login_id = username or input('[*] 아이디 : ')
    login_pw = password or getpass('[*] 패스워드 : ')
    login_cert = '' if login_server == 'demo.ebestsec.co.kr' else getpass('[*] 공인인증서 암호 : ')
    
    # 로그인 요청을 보낸다
    _session.waiting = True
    _session.ConnectServer(login_server, login_port)
    _session.Login(login_id, login_pw, login_cert, 0, 0)
    while _session.waiting:
        PumpWaitingMessages()
        time.sleep(0.05)
 def pump():
     # Prevent application from exiting and allow for handling of GlobalDictionary events
     while True:
         for chg in facade.get_changes():
             GD[chg['key']] = chg['value']
         PumpWaitingMessages()
         time.sleep(
             0.01)  # Avoids high CPU usage by not checking constantly
Esempio n. 3
0
 def _worker(self):
     CoInitializeEx(COINIT_MULTITHREADED)
     handler = WithEvents(self.client, EventHandler)
     handler.setExchange(self)
     while not self._termination.isSet():
         PumpWaitingMessages()
         self._termination.wait(0.001)
     CoUninitialize()
Esempio n. 4
0
    def go(self, blp):

        blp.AutoRelease = True
        blp.Flush()

        end_time = time() + 1

        while 1:
            PumpWaitingMessages()
            if end_time < time():
                print 'completed symbol...'
                break
Esempio n. 5
0
File: bbg.py Progetto: ychaim/pybbg
    def execute_request(request):
        session = DispatchWithEvents('blpapicom.ProviderSession.1', ResponseHandler)
        session.Start()
        try:
            svcname = request.get_bbg_service_name()
            if not session.OpenService(svcname):
                raise Exception('failed to open service %s' % svcname)

            svc = session.GetService(svcname)
            asbbg = request.get_bbg_request(svc, session)
            session.SendRequest(asbbg)
            session.do_init(request)
            while session.waiting:
                PumpWaitingMessages()
            session.has_deferred_exception and session.raise_deferred_exception()
            request.has_exception and request.raise_exception()
            return request
        finally:
            session.Stop()
            session.do_cleanup()
Esempio n. 6
0
    def __init__(self):
        if utils.is_admin():
            CoInitialize()
            self.handler = win32com.client.Dispatch(
                'YFExpertPlus.YFRequestData')
            self.event_handler = win32com.client.WithEvents(
                self.handler, RequestEventHandler)
            self.event_handler.client = self.handler

            self.handler.ComInit()
            self.handler.GSComInit(0)

            print('Start Init request data handler!')
            while not self.event_handler.is_connect:
                PumpWaitingMessages()
                time.sleep(0.5)

            self.hts_result = HTSResult()
            print('Init request data handler!')

        else:
            raise ValueError('Not Admin')
Esempio n. 7
0
    def waitForEvents(self, timeout):
        from win32api import GetCurrentThreadId
        from win32event import INFINITE
        from win32event import MsgWaitForMultipleObjects, \
            QS_ALLINPUT, WAIT_TIMEOUT, WAIT_OBJECT_0
        from pythoncom import PumpWaitingMessages
        import types

        if not isinstance(timeout, int):
            raise TypeError("The timeout argument is not an integer")
        if self.tid != GetCurrentThreadId():
            raise Exception("wait for events from the same thread you inited!")

        if timeout < 0:
            cMsTimeout = INFINITE
        else:
            cMsTimeout = timeout
        rc = MsgWaitForMultipleObjects(self.handles, 0, cMsTimeout,
                                       QS_ALLINPUT)
        if WAIT_OBJECT_0 <= rc < WAIT_OBJECT_0 + len(self.handles):
            # is it possible?
            rc = 2
        elif rc == WAIT_OBJECT_0 + len(self.handles):
            # Waiting messages
            PumpWaitingMessages()
            rc = 0
        else:
            # Timeout
            rc = 1

        # check for interruption
        self.oIntCv.acquire()
        if self.fInterrupted:
            self.fInterrupted = False
            rc = 1
        self.oIntCv.release()

        return rc
Esempio n. 8
0
def Demo( prog_id ):
    # First create the object
    object = Dispatch(prog_id)
    print "Thread", GetCurrentThreadId(), "creating object"
    created_id = object.GetCreatedThreadId()
    print "Object reports it was created on thread", created_id
    # Now create the threads, remembering the handles.
    handles = []
    for i in range(3):
        # As we are not allowed to pass the object directly between
        # apartments, we need to marshal it.
        object_stream = CoMarshalInterThreadInterfaceInStream(
                          IID_IDispatch, object )
        # Build an argument tuple for the thread.
        args = (object_stream,)
        handle, id = beginthreadex(None, 0, WorkerThread, args, 0)
        handles.append(handle)
    # Now we have all the threads running, wait for them to terminate.
    # also remember how many times we are asked to pump messages.
    num_pumps = 0
    while handles:
        # A quirk in MsgWaitForMultipleObjects means we must wait
        # for each event one at at time
        rc = MsgWaitForMultipleObjects(handles, 0, 5000, QS_ALLINPUT)
        if rc >= WAIT_OBJECT_0 and rc < WAIT_OBJECT_0+len(handles):
            # A thread finished - remove its handle.
            del handles[rc-WAIT_OBJECT_0]
        elif rc==WAIT_OBJECT_0 + len(handles):
            # Waiting message
            num_pumps = num_pumps + 1
            PumpWaitingMessages()
        else:
            print "Nothing seems to be happening",
            print "but I will keep waiting anyway..."
    print "Pumped messages", num_pumps, "times"
    print "Demo of", prog_id, "finished."
Esempio n. 9
0
ofname = str(sys.argv[2])

# The caller needs to make sure
# the file exists. However, the PDFCreator
# is going to determine if the file is actually
# printable

if not PDFCreator.cIsPrintable(ifname):
    exit()

ReadyState = 0

# setup output directory and filename

options.AutosaveDirectory = os.path.dirname(ofname)
options.AutosaveFilename = os.path.splitext(os.path.basename(ofname))[0]
PDFCreator.cSaveOptions(options)
PDFCreator.cPrintFile(ifname)

c = 0
while (ReadyState == 0) and (c < (maxTime / sleepTime)):
	c = c + 1
	sleep(sleepTime)
	PumpWaitingMessages()
#if ReadyState == 0:
#	exit()

PDFCreator.cOptions = options
PDFCreator.cSaveOptions(oldOptions)
PDFCreator.cClose
PDFCreator = None
    def algorithm_4__buy_yesterday_low_price__sell_today_high_price(self):
##########
        __기대수익률 = 1.1 # %

        __bDBG = True

        __bExit = False
        __bIsStockMarketOpen = False

        __time_table = {
            ''
        }

        # hard coding
        매도_원주문_번호_리스트 = []
        매도_종목_리스트 = [] # 원주문번호랑 매도 종목이랑 matching 하기위해 사용.

        __stCpStockConclusion = creon_1_SB_PB.CpPBConclusion()

        while True:
            print('******************************************!!!!!!')
# 장 중인지 확인
            __bIsStockMarketOpen = self.stUtils.장_중인지_확인()
            connect = self.stInit.is_creon_connected_as_admin() # NOTE: always return True.
            if __bDBG == True:
                __bIsStockMarketOpen = True
                print('__bIsStockMarketOpen: %s, connect: %s' % (__bIsStockMarketOpen, connect))

# >> [1] 장 열릴 때까지 대기
            if (connect == False) | (__bIsStockMarketOpen == False):
                print('# >> [1] 장 열릴 때까지 대기')
                while True:
                    sleep(5)
                    # connect = self.stInit.do_creon_connect() # NOTE: always return True. 

                    print('현재 시간 : %s' % (self.stUtils.현재_시간()))
                    if self.stUtils.장_중인지_확인() == True:
                        print('주식 장 시작!!!!!!!!!!!!!!!!!!!')
                        break
            else:                
# 장 열림!
                print('# [2] 장 열림!')
                # sleep(30) # 바로 시작하면, 계쏙 "크레온 보안카드 비밀번호 입력" 요청 하는 듯?
                bTradeInit = self.stTrading.do_trade_init()
                if bTradeInit == False:
                    exit()
# >> 어제 매수한 종목 있으면, 수익률(ex. 2%) 에 맞춰 매도 걸어놓음
# >>> 매도 시, 가격 최소 단위? 맞춰서 매도 걸어야 함.;;


                return connect # for DBG

                
                # 잔고 확인 (보유 주식)
                주식_잔고_리스트 = self.stTrading.주식_잔고_조회(bPrint=False)

                #NOTE: *.json 에서 구매 목록 가져오도록 수정 필요
                # json_utils.json_write('purchase_list_0301.json', 'test', Algorithm.current_purchase_stock_list)
                # test = json_utils.json_read('purchase_list_0301.json', 'test')

                # 매수_목록_0218
                # 매수_목록_0220 로 갈아끼우자,
                # 매도 <-- 어제 매수한 종목에 대한 매도 주문

                __subscribe_code_list = []
                for i in range(len(self.current_purchase_stock_list)):
                    __code = self.stUtils.get_code_from_name(self.current_purchase_stock_list[i])
                    __subscribe_code_list.append(__code)
                __stCpStockConclusion.subscribe(__subscribe_code_list, __stCpStockConclusion)
                
                for i in range(len(주식_잔고_리스트)):
                    for j in range(len(self.current_purchase_stock_list)):
                        if 주식_잔고_리스트[i]['종목명'] == self.current_purchase_stock_list[j] :
                            __주문수량 = 1
                            # 매도 수행
                            # if (self.current_purchase_stock_list[j] == '인프라웨어') | (self.current_purchase_stock_list[j] == '에이치엘비파워'):
                            #     __주문수량 = 2

                            __매도_원주문번호 = self.stTrading.주식_주문( # *** 매수/매도 주문은 정상 동작함
                                매매 = 1, # 1: 매도, 2: 매수
                                stockName=self.current_purchase_stock_list[j],
                                주문단가=self.stUtils.get_trade_price((주식_잔고_리스트[i]['손익단가'] * (1 + (__기대수익률/100)))), # 손익단가 * 1.02 == 2 % 높게 매도
                                # 주문 단가 자리 수 맞춰야 함.
                                주문수량=__주문수량,
                                bPrint=False,
                                bTest=False
                            )
                            if __매도_원주문번호 != 0: # 0: 매도 주문 실패
                                매도_원주문_번호_리스트.append(__매도_원주문번호)
                                매도_종목_리스트.append(self.current_purchase_stock_list[j])
                print('매도_원주문_번호_리스트: %s' % (매도_원주문_번호_리스트))

                __bCalculate = False
                if __bDBG == True:
                    __bCalculate = True
                __계산_타이밍 = 1800 # 장 마감 30 분 전에 계산
                while __bCalculate == False:
                    __마감까지_남은시간 = self.stUtils.마감_까지_남은_시간().total_seconds()
                    __bCalculate = (__마감까지_남은시간 <= __계산_타이밍) # 장 중이지 않을 경우, __마감까지_남은시간 는 음수
                    # if __bDBG == True:
                    #     __bBuyStock = True

                    __log = '장 마감까지 %s 초 남음 (%s) (계산 타이밍: %s 초 전)' % (round(__마감까지_남은시간, 2), __bCalculate, __계산_타이밍)
                    print(__log)
                    # log.log_write(__log)
                    sleep(5)

# 장 마감? 1분 전, 현재 주가로 1 주 씩 매수 # 이 것도 딜레이 걸어야 함..
                __top = 5 # 5 개 회사 추천

                print('현재 시간 : %s' % (self.stUtils.현재_시간()))
                __추천_종목_리스트, __투자_후보_이름, __투자_후보_예상수익 = self.algorithm_3__stock_purchase_recommandation(전체기간=1, marketType='코스닥', top=__top, 기대수익률=__기대수익률, 비교횟수=100, bPrint=False) # marketType(0: 코스피, 1: 코스닥)
                print('현재 시간 : %s' % (self.stUtils.현재_시간()))
                
                print('** 추천 종목:', __투자_후보_이름, __투자_후보_예상수익)

# >> 장 마감 1분 전인지 확인 (1분 이상 남았다면 대기)
                # sleep(2)
                __투자_후보_현재_정보_리스트 = []
                __bBuyStock = False
                if __bDBG == True:
                    __bBuyStock = True
                # 0 원에 걸면? -> 바로 사지거나 팔릴 수 있음
                __매수_타이밍 = 240 # 2 분 30 초 전,,
                while __bBuyStock == False:
                    __마감까지_남은시간 = self.stUtils.마감_까지_남은_시간().total_seconds()
                    __bBuyStock = (__마감까지_남은시간 <= __매수_타이밍) # 장 중이지 않을 경우, __마감까지_남은시간 는 음수
                    # if __bDBG == True:
                    #     __bBuyStock = True

                    print('장 마감까지 %s 초 남음 (%s) (매수 타이밍: %s 초 전)' % (round(__마감까지_남은시간, 2), __bBuyStock, __매수_타이밍))
                    sleep(2)
                    
# 매도 실패에 대한 예외처리 필요.
                print('******************매도 실패에 대한 예외 처리******************')
                # 현재가로 매도 필요한 종목 목록..!
                for i in range(len(매도_종목_리스트)):
                    __stockConclusion = False # TODO: need to fix
                    print('__stockConclusion: %s' % (__stockConclusion))
                    if __stockConclusion == False: # 매도 안된 경우
                        # [TODO] 매도 주문 취소
                        # 기존 매도 주문 일괄 취소
                        __종목명 = self.current_purchase_stock_list[i]

                        # def 주식_주문_취소(self, 원주문번호, 종목이름, 취소수량=0, bPrint=False):
                        self.stTrading.주식_주문_취소(
                            원주문번호=매도_원주문_번호_리스트[i], # 원래 다 0 인지 확인 필요
                            종목이름=매도_종목_리스트[i], # 원주문번호랑 매도 종목이랑 순서 맞춰져 있음
                            취소수량=0, # 0: 전부
                            bPrint=True)

                        sleep(1) # 혹시 몰라서 delay
                        ## 현재가 매도 주문
                        print(__종목명)
                        __stockInfo = self.stStockInfo.getInfoDetail(__종목명, bPrint=True)
                        __현재가 = __stockInfo[0]

                        __주문수량 = 1
                        # if (__종목명 == '인프라웨어') | (__종목명 == '에이치엘비파워'):
                        #     __주문수량 = 2

                        self.stTrading.주식_주문( # *** 매수/매도 주문은 정상 동작함
                            매매 = 1, # 1: 매도, 2: 매수
                            stockName=__종목명,
                            # 주문단가=self.stUtils.get_trade_price(__현재가, 호가=-5),
                            주문단가=__현재가,
                            주문수량=__주문수량, # 0 이라고 전량 아님,,!!
                            주문호가구분코드='03', # 시장가로 매도
                            bPrint=False,
                            bTest=False)
                print('************************************************************************')

# >> 매수 종목 정보 검색
                for i in range(len(__투자_후보_이름)):
                    print(__투자_후보_이름[i])
                    __투자_후보_현재_정보_리스트.append(self.stStockInfo.getInfoDetail(__투자_후보_이름[i], bPrint=True)) # 출력되는 정보 순서 참고. 추후 dictionary 로 변경하면 좋을 듯,
                
                __매수_타이밍 = 60 # 1 분 0 초 전,,
                while __bBuyStock == False:
                    __마감까지_남은시간 = self.stUtils.마감_까지_남은_시간().total_seconds()
                    __bBuyStock = (__마감까지_남은시간 <= __매수_타이밍) # 장 중이지 않을 경우, __마감까지_남은시간 는 음수
                    # if __bDBG == True:
                    #     __bBuyStock = True

                    __log = '장 마감까지 %s 초 남음 (%s) (매수 타이밍: %s 초 전)' % (round(__마감까지_남은시간, 2), __bBuyStock, __매수_타이밍)
                    print(__log)
                    # log.log_write(__log)
                    sleep(5)
# >> 매수 수행
                if bTradeInit == True:
# >>> (optional) 실시간 주가 subscribe
                    # subscribe_stockcur_list = []
                    # for i in range(len(__투자_후보_이름)):
                    #     __stCpStockCur = creon_1_SB_PB.CpPBStockCur() # 실시간 주가 변동 확인 위해서 사용 *************** 현재 가격 받아오는건 정상동작 안함..
                    #     __code = self.stUtils.get_code_from_name(__투자_후보_이름[i])
                    #     __stCpStockCur.subscribe(__code, __stCpStockCur) # 실시간 거래 가능시간 이외에는, 현재가 고정이기 때문에 subscribe 해도 받는(receive)게 없다.
                    #     subscribe_stockcur_list.append(__stCpStockCur)

                    for i in range(len(__투자_후보_이름)):
                        __code = self.stUtils.get_code_from_name(__투자_후보_이름[i])
                        __stCpStockConclusion.subscribe(__code, __stCpStockConclusion)

                        __현재가 = __투자_후보_현재_정보_리스트[i][0]
                        self.stTrading.주식_주문( # *** 매수 주문은 정상 동작함
                            매매 = 2, # 2: 매수
                            stockName=__투자_후보_이름[i],
                            # 주문단가=self.stUtils.get_trade_price(__투자_후보_현재_정보_리스트[i][0], 호가=+5), # 현재가 ** 높은 가격 걸면?
                            주문단가=__현재가, # 현재가 ** 높은 가격 걸면?
                            주문수량=1,
                            주문호가구분코드='03', # 시장가로 매수
                            bPrint=False,
                            bTest=False
                        )
                
                    __bBuyComplete = False
                    __bSellComplete = False
# >>> 매수 성공 확인
                    __timeout = 100
                    __timeout_count = 0
                    while True:
                        PumpWaitingMessages() # https://ko.wikipedia.org/wiki/이벤트_루프
                        sleep(2)
                        if __stCpStockConclusion.get_buy_count() == len(__투자_후보_이름):
                            __bBuyComplete = True
                        if __stCpStockConclusion.get_sell_count() == len(self.current_purchase_stock_list):
                            __bSellComplete = True

                        print('[%s]' % (self.stUtils.현재_시간()))
                        __log = '매도 (%s/%s), 매수 (%s/%s)' % (__stCpStockConclusion.get_sell_count(), len(self.current_purchase_stock_list),
                        __stCpStockConclusion.get_buy_count(), len(__투자_후보_이름))
                        print(__log)
                        log.log_write(__log)

                        __timeout_count+=1
                        if __timeout_count > __timeout:
                            __bExit = True
                            break
                        if (__bBuyComplete == True) & (__bSellComplete == True):
                            __bExit = True
                            break

# >>> 모든 subscribe 해제
                    # __stCpStockConclusion.unsubscribe()
                    # 매도 종목 unsubscribe
                    # for i in range(len(self.current_purchase_stock_list)):
                    #     __code = self.stUtils.get_code_from_name(self.current_purchase_stock_list[i])
                    #     __stCpStockConclusion.unsubscribe(__code, __stCpStockConclusion)
                    # # 매수 종목 unsubscribe
                    # for i in range(len(__투자_후보_이름)):
                    #     __code = self.stUtils.get_code_from_name(__투자_후보_이름[i])
                    #     __stCpStockConclusion.unsubscribe(__code, __stCpStockConclusion)

                if __bDBG == True:
                    __bExit = True


            if __bExit == True:
                break
Esempio n. 11
0
    def run(self):
        if len(self._accountlist) == 0:
            self.logger.info('fail: no account')
            return

        if self._servername[:3] == 'MIS':
            accountpwd = ['0000', '0000']
        elif self._servername in ['X', 'SERVER']:
            accountpwd = ['0302', '']
        else:
            self.logger.info('servername: ' + self._servername)
            self.logger.info('fail: not available servername')
            accountpwd = []
            return

        while True:
            # data = self.socket.recv_pyobj()
            # logmsg = "Thread_Id: [%d] Recv request: [%s]" % (self.thread_id, data)
            # self.logger.info(logmsg)
            #
            # time.sleep(1)
            #
            # self.socket.send(b"World")

            msg_dict = self.socket_order.recv_pyobj()
            if not self._XASession.IsConnected():
                self.logger.info('fail: disconnect xsession')
                self.socket_order.send_pyobj('fail: disconnect xsession')
                continue

            if type(msg_dict) != dict:
                self.logger.info(str(msg_dict) + 'is not dict')
                self.socket_order.send_pyobj('fail: msg_dict is not dict')
                continue

            nowtime = datetime.now()
            strnowtime = datetime.strftime(nowtime, "%Y-%m-%d %H:%M:%S.%f")
            strnowtime = strnowtime[:-3]
            self.logger.info('-------' * 4)
            self.logger.info('receive_order')

            newamendcancel = msg_dict.get(
                'NewAmendCancel', ' ')  # 'N' = New, 'A' = Amend, 'C' = Cancel
            buysell = msg_dict.get('BuySell', '')  # 'B' = Buy, 'S' = 'Sell'
            shortcd = msg_dict.get('ShortCD', '')
            orderprice = msg_dict.get('OrderPrice', 0)
            orderqty = msg_dict.get('OrderQty', 0)
            ordertype = msg_dict.get('OrderType', 0)  # 1 = Market, 2 = Limit
            timeinforce = msg_dict.get('TimeInForce', 'GFD')  # GFD, IOC, FOK
            autotrader_id = msg_dict.get('AutoTraderID', '0')
            orgordno = msg_dict.get('OrgOrderNo', -1)

            if not isinstance(orderprice, float) and newamendcancel in [
                    'N', 'A'
            ]:
                self.logger.info('fail: ' + str(msg_dict) +
                                 ' orderprice not float')
                self.socket_order.send_pyobj('fail: orderprice not float')
                continue

            logmsg = '%s, %s, %s, %f, %d, %s, %s' % (
                autotrader_id,
                newamendcancel,
                shortcd,
                orderprice,
                int(orderqty),
                buysell,
                orgordno,
            )

            self.logger.info(logmsg)

            if newamendcancel == 'N' and buysell == 'B':
                buysell = '2'
            elif newamendcancel == 'N' and buysell == 'S':
                buysell = '1'
            elif newamendcancel == 'N':
                self.logger.info('invalid newamendcancel, buysell')
                continue

            if newamendcancel == 'N' and shortcd[0] == 'A':
                # equity new order
                self.xaquery_CSPAT00600.SetFieldData(
                    'CSPAT00600InBlock1', 'AcntNo', 0,
                    self._accountlist[self.eq_account_index])
                self.xaquery_CSPAT00600.SetFieldData(
                    'CSPAT00600InBlock1', 'InptPwd', 0,
                    accountpwd[self.eq_account_index])
                self.xaquery_CSPAT00600.SetFieldData('CSPAT00600InBlock1',
                                                     'IsuNo', 0,
                                                     str(shortcd))  # demo
                self.xaquery_CSPAT00600.SetFieldData('CSPAT00600InBlock1',
                                                     'OrdQty', 0,
                                                     int(orderqty))
                self.xaquery_CSPAT00600.SetFieldData('CSPAT00600InBlock1',
                                                     'OrdPrc', 0,
                                                     str(orderprice))
                self.xaquery_CSPAT00600.SetFieldData('CSPAT00600InBlock1',
                                                     'BnsTpCode', 0, buysell)
                self.xaquery_CSPAT00600.SetFieldData('CSPAT00600InBlock1',
                                                     'OrdprcPtnCode', 0, '00')
                self.xaquery_CSPAT00600.SetFieldData('CSPAT00600InBlock1',
                                                     'MgntrnCode', 0, '000')
                self.xaquery_CSPAT00600.SetFieldData('CSPAT00600InBlock1',
                                                     'LoanDt', 0, ' ')
                self.xaquery_CSPAT00600.SetFieldData('CSPAT00600InBlock1',
                                                     'OrdCndiTpCode', 0, '0')
                ret = self.xaquery_CSPAT00600.Request(False)
                if ret is None:
                    while self.xaquery_CSPAT00600.observer.flag:
                        PumpWaitingMessages()
                    self.xaquery_CSPAT00600.observer.flag = True
                    # szMsgCode = self.xaquery_CSPAT00600.data['szMessageCode']
                    # if szMsgCode != '00039' and szMsgCode != '00040':
                    #     self.socket_order.send(str(szMsgCode))
                    # else:
                    #     self.socket_order.send(str(szMsgCode))
                    self.socket_order.send(str(szMsgCode))

            elif newamendcancel == 'C' and shortcd[0] == 'A':
                # equity cancel order
                self.xaquery_CSPAT00800.SetFieldData('CSPAT00800InBlock1',
                                                     'OrgOrdNo', 0,
                                                     int(orgordno))
                self.xaquery_CSPAT00800.SetFieldData(
                    'CSPAT00800InBlock1', 'AcntNo', 0,
                    self._accountlist[self.eq_account_index])
                self.xaquery_CSPAT00800.SetFieldData(
                    'CSPAT00800InBlock1', 'InptPwd', 0,
                    accountpwd[self.eq_account_index])
                self.xaquery_CSPAT00800.SetFieldData('CSPAT00800InBlock1',
                                                     'IsuNo', 0,
                                                     str(shortcd))  # demo
                self.xaquery_CSPAT00800.SetFieldData('CSPAT00800InBlock1',
                                                     'OrdQty', 0,
                                                     int(orderqty))
                ret = self.xaquery_CSPAT00800.Request(False)
                if ret is None:
                    # self.ordno_dict[self.xaquery_CSPAT00800.data['OrdNo']] = autotrader_id
                    # self.redis_client.hset('ordno_dict', self.xaquery_CSPAT00800.data['OrdNo'], autotrader_id)
                    self.socket_order.send('OK')
                    self.logger.info('OK')
                else:
                    self.socket_order.send('Reject')
                    self.logger.info('Reject')

            elif newamendcancel == 'N' and (shortcd[:3]
                                            in ['101', '201', '301', '105']):
                if nowtime.hour >= 6 and nowtime.hour < 16:
                    # KRX Futures, Options new order
                    self.xaquery_CFOAT00100.SetFieldData(
                        'CFOAT00100InBlock1', 'AcntNo', 0,
                        self._accountlist[self.fo_account_index])
                    self.xaquery_CFOAT00100.SetFieldData(
                        'CFOAT00100InBlock1', 'Pwd', 0,
                        accountpwd[self.fo_account_index])
                    self.xaquery_CFOAT00100.SetFieldData(
                        'CFOAT00100InBlock1', 'FnoIsuNo', 0, str(shortcd))
                    self.xaquery_CFOAT00100.SetFieldData(
                        'CFOAT00100InBlock1', 'BnsTpCode', 0, buysell)
                    self.xaquery_CFOAT00100.SetFieldData(
                        'CFOAT00100InBlock1', 'FnoOrdprcPtnCode', 0, '00')
                    self.xaquery_CFOAT00100.SetFieldData(
                        'CFOAT00100InBlock1', 'OrdPrc', 0, str(orderprice))
                    self.xaquery_CFOAT00100.SetFieldData(
                        'CFOAT00100InBlock1', 'OrdQty', 0, int(orderqty))
                    self.xaquery_CFOAT00100.autotrader_id = autotrader_id
                    ret = self.xaquery_CFOAT00100.Request(False)
                    self.logger.info(str(ret))
                    if not ret:
                        while self.xaquery_CFOAT00100.observer.flag:
                            PumpWaitingMessages()
                        self.xaquery_CFOAT00100.observer.flag = True
                        szMsg = self.xaquery_CFOAT00100.data['szMessage']
                        szMsgCode = self.xaquery_CFOAT00100.data[
                            'szMessageCode']
                        self.logger.info(szMsg.strip() + szMsgCode)
                        # if szMsgCode in ['00030', '00040']:
                        # self.ordno_dict[int(self.xaquery_CFOAT00100.data['OrdNo'])] = autotrader_id
                        # self.redis_client.hset('ordno_dict', self.xaquery_CFOAT00100.data['OrdNo'], autotrader_id)

                        # self.socket_order.send(str(szMsgCode))
                    else:
                        self.logger.info('async_ret_error %s' % str(ret))
                        self.socket_order.send_pyobj('async_ret_error %s' %
                                                     str(ret))
                else:
                    if shortcd[:3] in ['105']:
                        self.logger.info('not yet implement... 101, 105')
                        self.socket_order.send_pyobj('not yet implement...')
                        continue
                    elif shortcd[:3] in ['101']:
                        # KRX CME Futures new order
                        self.xaquery_CCEAT00100.SetFieldData(
                            'CCEAT00100InBlock1', 'AcntNo', 0,
                            self._accountlist[self.fo_account_index])
                        self.xaquery_CCEAT00100.SetFieldData(
                            'CCEAT00100InBlock1', 'Pwd', 0,
                            accountpwd[self.fo_account_index])
                        self.xaquery_CCEAT00100.SetFieldData(
                            'CCEAT00100InBlock1', 'FnoIsuNo', 0, str(shortcd))
                        self.xaquery_CCEAT00100.SetFieldData(
                            'CCEAT00100InBlock1', 'BnsTpCode', 0, buysell)
                        self.xaquery_CCEAT00100.SetFieldData(
                            'CCEAT00100InBlock1', 'FnoOrdprcPtnCode', 0, '00')
                        self.xaquery_CCEAT00100.SetFieldData(
                            'CCEAT00100InBlock1', 'OrdPrc', 0, str(orderprice))
                        self.xaquery_CCEAT00100.SetFieldData(
                            'CCEAT00100InBlock1', 'OrdQty', 0, int(orderqty))
                        self.xaquery_CCEAT00100.autotrader_id = autotrader_id
                        ret = self.xaquery_CCEAT00100.Request(False)
                        self.logger.info(str(ret))
                        if not ret:
                            while self.xaquery_CCEAT00100.observer.flag:
                                PumpWaitingMessages()
                            self.xaquery_CCEAT00100.observer.flag = True
                            szMsg = self.xaquery_CCEAT00100.data['szMessage']
                            szMsgCode = self.xaquery_CCEAT00100.data[
                                'szMessageCode']
                            self.logger.info(szMsg.strip() + szMsgCode)
                            # if szMsgCode in ['00030', '00040']:
                            # self.ordno_dict[int(self.xaquery_CFOAT00100.data['OrdNo'])] = autotrader_id
                            # self.redis_client.hset('ordno_dict', self.xaquery_CFOAT00100.data['OrdNo'], autotrader_id)

                            # self.socket_order.send(str(szMsgCode))
                        else:
                            self.logger.info('async_ret_error %s' % str(ret))
                            self.socket_order.send_pyobj('async_ret_error %s' %
                                                         str(ret))
                    else:
                        # Eurex Options new order
                        self.xaquery_CEXAT11100.SetFieldData(
                            'CEXAT11100InBlock1', 'AcntNo', 0,
                            self._accountlist[self.fo_account_index])
                        self.xaquery_CEXAT11100.SetFieldData(
                            'CEXAT11100InBlock1', 'Pwd', 0,
                            accountpwd[self.fo_account_index])
                        self.xaquery_CEXAT11100.SetFieldData(
                            'CEXAT11100InBlock1', 'FnoIsuNo', 0, str(shortcd))
                        self.xaquery_CEXAT11100.SetFieldData(
                            'CEXAT11100InBlock1', 'BnsTpCode', 0, buysell)
                        self.xaquery_CEXAT11100.SetFieldData(
                            'CEXAT11100InBlock1', 'ErxPrcCndiTpCode', 0, '2')
                        self.xaquery_CEXAT11100.SetFieldData(
                            'CEXAT11100InBlock1', 'OrdPrc', 0, str(orderprice))
                        self.xaquery_CEXAT11100.SetFieldData(
                            'CEXAT11100InBlock1', 'OrdQty', 0, int(orderqty))
                        self.xaquery_CEXAT11100.autotrader_id = autotrader_id
                        self.xaquery_CEXAT11100.shortcd = str(shortcd)
                        ret = self.xaquery_CEXAT11100.Request(False)
                        self.logger.info(str(ret))
                        if not ret:
                            while self.xaquery_CEXAT11100.observer.flag:
                                PumpWaitingMessages()
                            self.xaquery_CEXAT11100.observer.flag = True

                            szMsg = self.xaquery_CEXAT11100.data['szMessage']
                            szMsgCode = self.xaquery_CEXAT11100.data[
                                'szMessageCode']
                            self.logger.info(szMsg.strip() + szMsgCode)
                            # if szMsgCode in['00030', '00040']:
                            # self.ordno_dict[int(self.xaquery_CEXAT11100.data['OrdNo'])] = autotrader_id
                            # self.redis_client.hset('ordno_dict', self.xaquery_CEXAT11100.data['OrdNo'], autotrader_id)

                            # self.socket_order.send(str(szMsgCode))

                            # self.socket.send('async_ret_ok')
                        else:
                            self.logger.info('async_ret_error %s' % str(ret))
                            self.socket_order.send_pyobj('async_ret_error %s' %
                                                         str(ret))

            elif newamendcancel == 'C' and (shortcd[:3]
                                            in ['101', '201', '301', '105']):
                if nowtime.hour >= 6 and nowtime.hour < 16:
                    # KRX Futures, Options Cancel Order
                    self.xaquery_CFOAT00300.SetFieldData(
                        'CFOAT00300InBlock1', 'AcntNo', 0,
                        self._accountlist[self.fo_account_index])
                    self.xaquery_CFOAT00300.SetFieldData(
                        'CFOAT00300InBlock1', 'Pwd', 0,
                        accountpwd[self.fo_account_index])
                    self.xaquery_CFOAT00300.SetFieldData(
                        'CFOAT00300InBlock1', 'FnoIsuNo', 0, shortcd)
                    self.xaquery_CFOAT00300.SetFieldData(
                        'CFOAT00300InBlock1', 'OrgOrdNo', 0, int(orgordno))
                    self.xaquery_CFOAT00300.SetFieldData(
                        'CFOAT00300InBlock1', 'CancQty', 0, int(orderqty))
                    self.xaquery_CFOAT00300.autotrader_id = autotrader_id
                    ret = self.xaquery_CFOAT00300.Request(False)
                    if ret is None:
                        # self.ordno_dict[self.xaquery_CFOAT00300.data['OrdNo']] = autotrader_id
                        # self.redis_client.hset('ordno_dict', self.xaquery_CFOAT00300.data['OrdNo'], autotrader_id)
                        self.socket_order.send('OK')
                        self.logger.info('OK')
                    else:
                        self.socket_order.send('Reject')
                        self.logger.info('Reject')
                else:
                    if shortcd[:3] in ['105']:
                        self.logger.info('not yet implement... 101, 105')
                        self.socket.send('not yet implement...')
                        continue
                    elif shortcd[:3] in ['101']:
                        # KRX Futures, Options Cancel Order
                        self.xaquery_CCEAT00300.SetFieldData(
                            'CCEAT00300InBlock1', 'AcntNo', 0,
                            self._accountlist[self.fo_account_index])
                        self.xaquery_CCEAT00300.SetFieldData(
                            'CCEAT00300InBlock1', 'Pwd', 0,
                            accountpwd[self.fo_account_index])
                        self.xaquery_CCEAT00300.SetFieldData(
                            'CCEAT00300InBlock1', 'FnoIsuNo', 0, shortcd)
                        self.xaquery_CCEAT00300.SetFieldData(
                            'CCEAT00300InBlock1', 'OrgOrdNo', 0, int(orgordno))
                        self.xaquery_CCEAT00300.autotrader_id = autotrader_id
                        ret = self.xaquery_CCEAT00300.Request(False)
                        if ret is None:
                            # self.ordno_dict[self.xaquery_CFOAT00300.data['OrdNo']] = autotrader_id
                            # self.redis_client.hset('ordno_dict', self.xaquery_CFOAT00300.data['OrdNo'], autotrader_id)
                            self.socket_order.send('OK')
                            self.logger.info('OK')
                        else:
                            self.socket_order.send('Reject')
                            self.logger.info('Reject')
                    else:
                        # Eurex Options Cancel Order
                        self.xaquery_CEXAT11300.SetFieldData(
                            'CEXAT11300InBlock1', 'OrgOrdNo', 0, int(orgordno))
                        self.xaquery_CEXAT11300.SetFieldData(
                            'CEXAT11300InBlock1', 'AcntNo', 0,
                            self._accountlist[self.fo_account_index])
                        self.xaquery_CEXAT11300.SetFieldData(
                            'CEXAT11300InBlock1', 'Pwd', 0,
                            accountpwd[self.fo_account_index])
                        self.xaquery_CEXAT11300.SetFieldData(
                            'CEXAT11300InBlock1', 'FnoIsuNo', 0, str(shortcd))
                        self.xaquery_CEXAT11300.autotrader_id = autotrader_id
                        ret = self.xaquery_CEXAT11300.Request(False)
                        if ret is None:
                            # self.ordno_dict[autotrader_id] = self.xaquery_CEXAT11300.data['OrdNo']
                            # self.redis_client.hset('ordno_dict', self.xaquery_CEXAT11300.data['OrdNo'], autotrader_id)
                            self.socket_order.send('OK')
                            self.logger.info('OK')
                        else:
                            self.socket_order.send('Reject')
                            self.logger.info('Reject')
            else:
                self.logger.info('not yet implement other case order')
                self.socket.send('not yet implement other case order')
Esempio n. 12
0
 def listen(delay=.01):
     while True:
         PumpWaitingMessages()
         time.sleep(delay)
Esempio n. 13
0
def query(res, send, cont=False, timeout=10):
    """ Query 요청

        @arg res[str]`t1102` 사용할 res 파일명
        @arg send[dict] 전송할 데이터
            {
                'Block1': [{'Field1': 'Value1', 'Field2': 'Value2'}, {...}, {...}],
                'Block2': {'Field3': 'Value3', 'Field4': 'Value4'}
            }
    
            단일 InBlock의 경우에는 아래와 같이 간단한 형식도 입력받음
            {'Field1': 'Value1', 'Field2': 'Value2'}
        @arg cont[*bool=False] 연속조회 여부
        @arg timeout[*int=10] 서버 응답 최대 대기 시간, -1인 경우 infinite time
    """
    # res 파일 로드
    _query = DispatchWithEvents('XA_DataSet.XAQuery', _QueryHandler)
    _query.init(res)
    
    if not cont:
        # 전송 현황 업데이트
        if not res in _query_status:
            _query_status[res] = []
        
        while _query_status[res] and _query_status[res][-1] + 1 < time.time():
            _query_status[res].pop()
        
        # 초당 전송 횟수를 고려
        tr_count_per_sec = _query.GetTRCountPerSec(res)
        if len(_query_status[res]) >= tr_count_per_sec:
            delay = max(_query_status[res][-1] + 1.05 - time.time(), 0)
            time.sleep(delay)
        
        # 기간(10분)당 전송 횟수를 고려
        # TODO : 10분 제한이 걸리면 blocking state 진입
        tr_count_limit = _query.GetTRCountLimit(res)
        while tr_count_limit and _query.GetTRCountRequest(res) >= tr_count_limit:
            time.sleep(1)
            _query = DispatchWithEvents('XA_DataSet.XAQuery', _QueryHandler)
            _query.init(res)
    
    # simplified 된 input를 받았을 경우
    send_first_value = list(send.values())[0]
    if not (
        isinstance (send_first_value, list) or
        isinstance (send_first_value, dict)
    ):
        send = { '{}InBlock'.format(res): send }
    
    # 전송할 데이터를 설정
    for block in send.keys():
        if isinstance(send[block], dict):
            for (k, v) in send[block].items():
                _query.set_data(block, k, v)
        elif isinstance(send[block], list):
            for i in range(len(send[block])):
                for (k, v) in send[block][i].items():
                    _query.set_data(block, k, v, i)
        else:
            raise ValueError('알 수 없는 형태의 데이터입니다')
    
    else:
        time.sleep(0.05)
    
    # 데이터 요청
    _query.Request(cont)
    
    now = time.time()
    if not cont:
        _query_status[res].insert(0, now)
    _query.waiting = True
    while _query.waiting:
        if timeout >= 0 and now + timeout < time.time():
            _query.waiting = False
            raise TimeoutError('Query Timeout')
        PumpWaitingMessages()
    
    return _query.response
Esempio n. 14
0
def waitMessage(t):
    end_time = time.clock() + t
    while time.clock() < end_time:
        PumpWaitingMessages()
Esempio n. 15
0
 def __waiting_event(self):
     self.__receive_event = False
     while self.__receive_event is False:
         PumpWaitingMessages()
         sleep(0.001)
Esempio n. 16
0
 def process(self):
     CoInitialize()
     self._running = True
     while self._running:
         time.sleep(0.1)
         PumpWaitingMessages()