티스토리 뷰

<한국투자증권의 OpenAPI를 활용한 주식 자동 주문 프로그램 만들기>

* 특정 종목의 현재 시세와 과거 데이터 분석 자료를 활용하여,

* 지금 이 종목을 매수할 지 여부를 판단하고,

* 판단 결과에 따라 특정 가격에 매수 주문을 발생시킴.

 

 

[Source Code]

    def TreatBuyingProcess(self, itemInfo, preInfo):
        itemCode = itemInfo.get('ItemCode')
        priceAvg = int(itemInfo.get("Average"))
        itemData = None
        try:
            itemData = self.GetItemPrice_Now(itemInfo)
        except Exception as e:
            print("[??] Exception of itemData for ", itemCode, " with ", str(e))
        if not itemData:
            #print("[??] None of Data for ", str(itemInfo))
            return;
        priceNow = int(itemData.get('CurrentPrice'))
        try:
            if preInfo: 
                previousPrice = int(preInfo.get('BuyCost'))
                if priceNow > previousPrice: return;
        except: pass
        if priceNow<1000: return;
        if priceNow > (1.2*priceAvg): return;
        if priceNow < (0.8*priceAvg) : return;
        refPriceRatio = (100 - (self.DefaultEarningRatio*0.75))/100
        if priceNow > (refPriceRatio*priceAvg): return;
        try:
            diffYesterday = int(itemData.get('DiffPreviousDay'))
        except: return;
        if diffYesterday>0: return;
        high250 = int(itemData.get('High250'))
        if priceNow > (0.9*high250): return;
        low250 = int(itemData.get('Low250'))
        if priceNow < (1.1*low250): return;
        orderQuanity = (self.CAPITAL/(2*self.ItemLimit))/priceNow
        if orderQuanity<1: return;
        #*****
        orderParam = {
            'ItemCode': itemCode,
            'OrderQuantity': int(orderQuanity),
            'OrderType': "Buy",
            'ItemPrice': priceNow
        }
        res1 = self.OrderItem(orderParam)
        #*****
        if res1:
            orderParam.update(itemInfo)
            orderParam['ItemStatus'] = "BUY"
            orderParam['AccountType'] = self.AccountType
            #orderParam['TradeTime'] = bTime.GetTimeString()
            orderParam['ITime'] = bTime.GetTimeString()
            orderParam['DateString'] = bTime.GetDateString()
            self.TradeNo += 1
            orderParam['TradeNo'] = str(self.TradeNo)
            self.BuyingItems[itemCode] = orderParam
            self.ItemTradeDF = pd.concat([self.ItemTradeDF, DataFrame([orderParam])], axis=0, ignore_index=True)
            comName1 = itemInfo.get('CompanyName')
            message1 = "[!-KISPy233-21] Buying ... " + comName1 + " with " + str(orderParam)
            message1 += "\n @ " + bTime.GetTimeString()
            bDiscordManager.SendMessage2BST(message1)
            itemInfo['Status'] = bTime.GetTimeString()
            print("Buying ......")
            return itemInfo
        else:
            print("[?] Fail to BUY : ", str(orderParam))
반응형