티스토리 뷰

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

* 특정 종목의 현재 시세와 잔고 데이터를 활용하여,

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

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

 

[Source Code]

    def TreatSellingProcess(self, itemParam):
        # itemParam = {'ItemCode', 'PurchaseAmount', 'EvaluatedAmount', 'HoldQuantity', 'CurrentPrice'}

        itemCode = itemParam.get("ItemCode")
        mustBeSold = False
        if not self.BoughtItemDF.empty:
            self.BoughtItemDF = self.BoughtItemDF.sort_values(by=['ITime'], axis=0, ascending=False)
            index1 = self.BoughtItemDF[(self.BoughtItemDF['ItemCode']==itemCode)&(self.BoughtItemDF['AccountType']==self.AccountType)].index
            if not index1.empty:
                itemData1 = self.BoughtItemDF.loc[index1[0]].to_dict()
                boughtTime = itemData1.get('ITime')
                timeD1 = bTime.GetTimeDifference(boughtTime)
                dayD1 = timeD1.get('Day')
                if dayD1>self.HoldDaysLimit: mustBeSold = True
            else: mustBeSold = True
        else:
            mustBeSold = True

        if not itemCode: return;
        #balanceStatus = itemParam.get('Status')
        buyCost = itemParam.get('BuyCost')
        purchaseAmount = itemParam.get('PurchaseAmount')
        evaluatedAmount = itemParam.get('EvaluatedAmount')
        holdQty = int(itemParam.get('HoldQuantity'))
        itemData = self.GetItemPrice_Now(itemParam)
        priceNow = int(itemData.get('CurrentPrice'))
        benefitRatio = evaluatedAmount/purchaseAmount
        referenceBenefit = (100+(self.DefaultEarningRatio*1.1))/100
        if benefitRatio > referenceBenefit: orderPrice = priceNow
        elif mustBeSold: orderPrice = priceNow
        else: orderPrice = buyCost*referenceBenefit
        if orderPrice>100000: orderPrice = round(orderPrice/100)*100
        elif orderPrice>10000: orderPrice = round(orderPrice/50)*50
        else:  orderPrice = round(orderPrice/10)*10
        orderParam = {
            'ItemCode': itemCode,
            'OrderQuantity': str(holdQty),
            'OrderType': "Sell",
            'ItemPrice': str(orderPrice)
        }
        itemParam['Status'] = "Ordered"
        res1 = self.OrderItem(orderParam)
        if res1:
            msgCode = res1.get('MessageCode')
            if msgCode == "APBK0400": print("[!] Re-writing for ", str(orderParam))
            orderParam.update(itemParam)
            orderParam['ItemStatus'] = "SELL"
            orderParam['AccountType'] = self.AccountType
            orderParam['SellTime'] = bTime.GetTimeString()
            orderParam['ITime'] = bTime.GetTimeString()
            orderParam['DateString'] = bTime.GetDateString()
            if self.SellingItems:
                sellingItem = self.SellingItems.get(itemCode)
            else: sellingItem = None
            if not sellingItem:
                self.TradeNo += 1
                orderParam['TradeNo'] = str(self.TradeNo)
                self.SellingItems[itemCode] = orderParam
                self.ItemTradeDF = pd.concat([self.ItemTradeDF, DataFrame([orderParam])], axis=0, ignore_index=True)
                message1 = "[!-KISPy233-21] Selling ... Item with " + str(orderParam)
                message1 += "\n @ " + bTime.GetTimeString()
                bDiscordManager.SendMessage2BST(message1)
            return "Selling ..."
        else:
            print("[Fail to SELL] ", str(orderParam))
반응형