티스토리 뷰

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

* 보유 계좌에 대한 잔고 조회 기능 활용

* 보유 계좌 : 실전투자 계좌, 모의투자 계좌

* 조회 직전에 보유하고 있던 기존 데이터(잔고, 매수, 매도 등)와 조회 데이터를 활용하여 기존 데이터를 갱신

 

[Source Code]

    def InquiryBalance(self, paramIn=None): # 주식 잔고 조회
        # paramIn :
        # max 20 itmes per 1 inquiry
        boughtCount = 0

        if self.ACCOUNTTYPE=="Actual":
            tr_id = "TTTC8434R" # 실전투자 잔고조회
        else:
            tr_id = "VTTC8434R" # 모의투자 잔고조회

        url1 = "/uapi/domestic-stock/v1/trading/inquire-balance"
        acceccURL = self.URL0 + url1
        header1 = {
            'Content-Type': "application/json; chartset=UTF-8",
            'authorization': f"Bearer {self.AccessToken}",
            #'authorization': self.AccessToken,
            'appkey': self.AppKey,
            'appsecret': self.AppSecret,
            'tr_id': tr_id,
            'tr_cont': None, # None, "1", "2", ...
            'custtype': "P",
            'mac_address': None,
            'hashkey': None
        }

        param1 = {
            'CANO': self.AccountNo, # Account No.(8 digits)
            'ACNT_PRDT_CD': cConstants.KIS_ACCOUNTSUB, # Account No. (2 digits)
            'AFHR_FLPR_YN': "N", # 조회시작일자(8, YYYYMMDD)
            'OFL_YN': "", # 조회 종료 일자(8, YYYYMMDD)
            'INQR_DVSN': "01", # 02(대출일별), 02(종목별)
            'UNPR_DVSN': "01",
            'FUND_STTL_ICLD_YN': "N",
            'FNCG_AMT_AUTO_RDPT_YN': "N",
            'PRCS_DVSN': "N",
            'PRCS_DVSN': "00", # 00(전일매매포함), 01(전일매매미포함)
            'CTX_AREA_FK100': "",
            'CTX_AREA_NK100':""
        }

        #res1 = requests.post(acceccURL, data=json.dumps(param1), headers=header1)
        res1 = requests.get(acceccURL, params=param1, headers=header1)
##        print(res1.text)
        try:
            inquiryResults = json.loads(res1.text)
        except:
            print("[?? in ] InquiryBalance()", )
            return;
        success2 = inquiryResults.get('rt_cd') # if "0": SUCCESS
        if success2!="0": 
            print("Inquiry FAILED")
            return;
        responseCode2 = inquiryResults.get('msg_cd')
        message2 = inquiryResults.get('msg1')
        outputs11 = inquiryResults.get('output1')
#        outputs12 = json.loads(outputs11)
        # pdno(상품번호), prdt_name(상품명), trad_dvsn_name, bfdy_buy_qty, bfdy_sll_qty, 
        # thdt_buyqty, thdt_buyqty, hldg_qty, ord_psbl_qty, pchs_avg_pric, pchs_amt
        # prpr, evlu_amt, evlu_pfls_amt, evlu_pfls_rt, evlu_erng_rt, loan_dt, 
        # loan_amt, loan_amt, loan_amt, fltt_rt, bfdy_cprs_icdc, bfdy_cprs_icdc
        # grta_rt_name, sbst_pric, stck_loan_unpr
        print("보유 종목 현황 =====>")
        #holdItemDF = DataFrame()
        rsts = {}
        capticalAmount = 0
        stockValue = 0
        itemCount = 0
        itemList1 = []
        for output11 in outputs11:
            itemNo = output11.get('pdno')
            itemName = output11.get('prdt_name')
            holdQuantity = int(output11.get('hldg_qty'))
            purchaseAmount = int(output11.get('pchs_amt'))
            avgPrice_ = output11.get('pchs_avg_pric')
            if avgPrice_: avgPrice = round(float(avgPrice_))
            else: avgPrice = None
            evaluatedAmount = int(output11.get('evlu_amt'))
            earnedValue = evaluatedAmount - purchaseAmount
            if purchaseAmount==0: continue;
            earnedRatio = (earnedValue/purchaseAmount)*100
            holdInfo = {
                'ItemNo': itemNo,
                'ItemCode': str(itemNo),
                'ItemName': itemName,
                'HoldQuantity': holdQuantity,
                'BuyCost': avgPrice,
                'PurchaseAmount': purchaseAmount,
                'EvaluatedAmount': evaluatedAmount,
                'EarnedAmount': str(earnedValue),
                'EarnedRatio': str(round(earnedRatio, 2))
            }
            holdInfo['ItemStatus'] = "HOLD"
            holdInfo['ITime'] = bTime.GetTimeString()
            holdInfo['DateString'] = bTime.GetDateString()
            holdInfo['AccountType'] = self.AccountType
            capticalAmount += purchaseAmount
            stockValue += evaluatedAmount
            rsts[itemNo] = holdInfo
            #holdItemDF = pd.concat([holdItemDF, DataFrame([holdInfo])], ignore_index=True, axis=0)
            itemCount += 1
            itemList1.append(itemNo)
            holdItemData = self.HoldItems.get(itemNo)
            sellingItemData = self.SellingItems.get(itemNo)
            if not holdItemData:
                holdInfo['ItemStatus'] = "HOLD"
                self.TradeNo += 1
                holdInfo['TradeNo'] = str(self.TradeNo)
                holdInfo['ITime'] = bTime.GetTimeString()
                holdInfo['DateString'] = bTime.GetDateString()
                self.HoldItems[itemNo] = holdInfo
                if not sellingItemData: self.ItemTradeDF = pd.concat([self.ItemTradeDF, DataFrame([holdInfo])], axis=0, ignore_index=True)
                else: continue;
            buyingItemData = self.BuyingItems.get(itemNo)
            boughtItemData = self.BoughtItems.get(itemNo)
            if buyingItemData: 
                self.BuyingItems.pop(itemNo)
                buyingItemData.update(holdInfo)
                buyingItemData['ItemStatus'] = "BOUGHT"
                buyingItemData['ITime'] = bTime.GetTimeString()
                buyingItemData['DateString'] = bTime.GetDateString()
                self.TradeNo += 1
                buyingItemData['TradeNo'] = str(self.TradeNo)
                self.ItemTradeDF = pd.concat([self.ItemTradeDF, DataFrame([buyingItemData])], axis=0, ignore_index=True)
                boughtCount += 1
                self.BoughtItemDF = pd.concat([self.BoughtItemDF, DataFrame([buyingItemData]) ], axis=0, ignore_index=True)
                self.BoughtItems[itemNo] = holdInfo

        holdItemKeys = self.HoldItems.keys()
        notHolds = []
        for itemCode1 in holdItemKeys:
            holdData = rsts.get(itemCode1)
            if not holdData:
                holdData = self.HoldItems.get(itemCode1)
                holdData['ItemStatus'] = "SOLD"
                holdData['ITime'] = bTime.GetTimeString()
                holdData['DateString'] = bTime.GetDateString()
                self.TradeNo += 1
                holdData['TradeNo'] = str(self.TradeNo)
                self.ItemTradeDF = pd.concat([self.ItemTradeDF, DataFrame([holdData])], axis=0, ignore_index=True)
                print("[Sold-10] ", str(holdData))
                notHolds.append(itemCode1)
        if notHolds:
            for noCode in notHolds:
                self.HoldItems.pop(noCode)

        sellingItemKeys = self.SellingItems.keys()
        soldItemCodes = []
        for itemCode1 in sellingItemKeys:
            holdItemData = self.HoldItems.get(itemCode1)
            if not holdItemData:
                soldItemCodes.append(itemCode1)
                if (notHolds) and (itemCode1 in notHolds): continue;
                soldItemData = self.SellingItems.get(itemCode1)
                soldItemData['ItemStatus'] = "SOLD"
                soldItemData['ITime'] = bTime.GetTimeString()
                soldItemData['DateString'] = bTime.GetDateString()
                self.TradeNo += 1
                soldItemData['TradeNo'] = str(self.TradeNo)
                self.SoldItems[itemCode1] = soldItemData
                self.ItemTradeDF = pd.concat([DataFrame([soldItemData]), self.ItemTradeDF], axis=0, ignore_index=True)
                print("[Sold-11] ", str(soldItemData))
        for itemCode1 in soldItemCodes:
            self.SellingItems.pop(itemCode1)       
            
        if not self.ItemTradeDF.empty:            
            self.ItemTradeDF = self.ItemTradeDF.sort_values(by=['TradeNo'], axis=0, ascending=False)
        '''
        bGoogleSpread.WriteSpread(self.ItemTradeDF, self.Spreadname_DailyTrade, self.Sheetname_Trade)
        bExcel.WriteFile(self.ItemTradeDF, "./Test001.xlsx", self.Sheetname_Trade) ##-
        if boughtCount>0:
            self.BoughtItemDF = self.BoughtItemDF.sort_values(by=['TradeNo'], axis=0, ascending=False) ##-
            bGoogleSpread.WriteSpread(self.BoughtItemDF, self.Spreadname_DailyTrade, self.Sheetname_BoughtItems) ##-
            bExcel.WriteFile(self.BoughtItemDF, "./Test001.xlsx", self.Sheetname_BoughtItems) ##-
        '''


        rsts['CapitalAmount'] = capticalAmount
        rsts['StockValue'] = stockValue
        rsts['ItemNumber'] = itemCount
        rsts['ItemCodeList'] = itemList1

        if rsts: return rsts;

        outputs21 = inquiryResults.get('output2')
#        outputs22 = json.loads(outputs21)
        # dnca_tot_amt, nxdy_excc_amt, prvs_rcdl_excc_amt, cma_evlu_amt, bfdy_buy_amt, 
        # thdt_buy_amt, nxdy_auto_rdpt_amt, nxdy_auto_rdpt_amt, thdt_sll_amt, d2_auto_rdpt_amt, 
        # bfdy_tlex_amt, thdt_tlex_amt, tot_loan_amt, scts_evlu_amt, scts_evlu_amt, 
        # nass_amt, fncg_gld_auto_rdpt_yn, pchs_amt_smtl_amt, pchs_amt_smtl_amt, evlu_pfls_smtl_amt
        # tot_stln_slng_chgs, bfdy_tot_asst_evlu_amt, asst_icdc_amt, asst_icdc_amt
        return inquiryResults
반응형
반응형
250x250
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
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
글 보관함