コード例 #1
0
 def bbtInit(self):
   self.api = cl.bbCCXTInit(n=self.n)
   riskDf = cl.bbtGetRiskDf(self.api, self.spotDict)
   for ccy in self.validCcys:
     if ccy in riskDf.index:
       self.futures.loc[ccy, 'FutDelta']=cl.bbtGetFutPos(self.api,ccy)
       self.liqDict[ccy] = riskDf.loc[ccy,'liq']
     else:
       self.liqDict[ccy] = 0
   self.calcFuturesDeltaUSD()
   #####
   if self.n>=2: # trim list for auxiliary BBTs
     self.validCcys=list(self.futures.index[self.futures['FutDelta'] != 0])
   #####
   self.oneDayIncome = 0
   self.prevIncome = 0
   if CR_CONFIGS_DICT['IS_CALC_PAYMENTS']:
     pmts=pd.DataFrame()
     for ccy in self.validCcys:
       data = cl.bbtGetTradeExecutionList(self.api,ccy)
       if not data is None:
         pmts = pmts.append(pd.DataFrame(data).set_index('symbol', drop=False))
     if len(pmts)>0:
       cl.dfSetFloat(pmts, ['fee_rate', 'exec_fee'])
       pmts.loc[['Sell' in z for z in pmts['order_id']],'fee_rate']*=-1 # Correction for fee_rate signs
       pmts['incomeUSD'] = -pmts['exec_fee'] * self.spotDict['USDT']
       pmts['date'] = [datetime.datetime.fromtimestamp(int(ts) / 1000) for ts in pmts['trade_time_ms']]
       pmts = pmts.set_index('date').sort_index()
       #####
       self.oneDayIncome = pmts['incomeUSD'].sum()
       self.prevIncome = pmts.loc[pmts.index[-1]]['incomeUSD'].sum()
   self.setAnnRets()
   #####
   usdtDict=self.api.v2_private_get_wallet_balance({'coin': 'USDT'})['result']['USDT']
   equity = float(usdtDict['equity'])
   self.nav = equity * self.spotDict['USDT']
   self.spots.loc['USDT', 'SpotDelta'] = equity
   self.calcSpotDeltaUSD()
   #####
   for ccy in self.validCcys:
     oneDayFunding = 0
     prevFunding = 0
     estFunding=0
     estFunding2=0
     if CR_CONFIGS_DICT['IS_CALC_PAYMENTS']:
       if len(pmts)>0:
         df=pmts.loc[pmts['symbol']==ccy+'USDT','fee_rate']
         if len(df) > 0:
           oneDayFunding = df.mean() * 3 * 365
           prevFunding = df[df.index[-1]].mean() * 3 * 365
     #####
     if CR_CONFIGS_DICT['IS_CALC_ESTS']:
       estFunding, estFunding2 = self.bbtGetEstFundings_fast(ccy)
     self.makeFundingStr(ccy, oneDayFunding, prevFunding, estFunding, estFunding2)
   #####
   self.makeIncomesStr()
   self.makeLiqStr(riskDf=riskDf,availableBalance=float(usdtDict['available_balance']))
   self.isDone = True
コード例 #2
0
 def makeFlows(ccy):
   start_time = cl.getYest()
   borrows = cleanBorrows(ccy, pd.DataFrame(self.api.private_get_spot_margin_borrow_history({'limit': 1000, 'start_time': start_time})['result']))
   loans = cleanBorrows(ccy, pd.DataFrame(self.api.private_get_spot_margin_lending_history({'limit': 1000, 'start_time': start_time})['result']))
   cl.dfSetFloat(borrows, ['cost','rate'])
   cl.dfSetFloat(loans, 'proceeds')
   prevBorrow = borrows.iloc[-1]['cost'] if borrows.index[-1] == self.payments.index[-1] else 0
   prevLoan = loans.iloc[-1]['proceeds'] if loans.index[-1] == self.payments.index[-1] else 0
   absBalUSD = abs(self.wallet.loc[ccy, 'total']*self.spotDict[ccy])
   d=dict()
   d['oneDayFlows'] = (loans['proceeds'].sum() - borrows['cost'].sum()) * self.spotDict[ccy]
   d['oneDayFlowsAnnRet'] = d['oneDayFlows'] * 365 / absBalUSD
   d['oneDayBorrowRate'] = borrows['rate'].mean() * 24 * 365
   d['prevFlows']=(prevLoan - prevBorrow) * self.spotDict[ccy]
   d['prevFlowsAnnRet']=d['prevFlows'] * 24 * 365 / absBalUSD
   d['prevBorrowRate'] = borrows.iloc[-1]['rate'] * 24 * 365 if borrows.index[-1] == self.payments.index[-1] else 0
   return d
コード例 #3
0
ファイル: BBTr.py プロジェクト: eonsmile/CryptoTools
#####
riskDfs = []
for i in range(SHARED_EXCH_DICT['bbt']):
  riskDfs.append(cl.bbtGetRiskDfs(i + 1, spotDict))
cl.parallelRun(riskDfs)
#####
ccys=[]
for i in range(SHARED_EXCH_DICT['bbt']):
  ccys.extend(list(riskDfs[i].riskDf.index))
#####
tickersDf = pd.DataFrame(apiDict['bb'].v2PublicGetTickers()['result']).set_index('symbol')
tickersDf = tickersDf[['USDT' in symbol for symbol in tickersDf.index]]
myList=[ticker[:len(ticker)-4] for ticker in tickersDf.index]
if 'SHIB1000' in myList: myList[myList.index('SHIB1000')]='SHIB' # Special fix for SHIB
tickersDf.index=myList
cl.dfSetFloat(tickersDf, 'turnover_24h')
#####
if isFullUniverse: ccys.extend(tickersDf[tickersDf['turnover_24h']>(AUTO_DICT['TURN_THRESHOLD'] * 1e6)].index)
ccys = [ccy for ccy in ccys if ccy not in AUTO_DICT['EXCLUSIONS']]
ccys=list(set(ccys))
#####
ccyData = []
for ccy in ccys:
  ccyData.append(bbtGetCcyDataPlus(ccy, apiDict, riskDfs, tickersDf))
if isDebug:
  cl.serialRun(ccyData)
else:
  cl.parallelRun(ccyData)

######
# Main
コード例 #4
0
 def kutInit(self):
   self.api = cl.kuCCXTInit(n=self.n)
   self.usdtDict = cl.kuGetAccountOverview(self.api,'USDT')
   self.availableBalance = float(self.usdtDict['availableBalance'])
   self.riskDf=cl.kutGetRiskDf(self.api,self.availableBalance)
   #####
   positions=cl.kuGetPositions(self.api)
   for ccy in self.validCcys:
     ccy2 = cl.kuGetTicker(ccy, isKUT=True)
     if ccy2 in positions.index:
       self.futures.loc[ccy, 'FutDelta']=positions.loc[ccy2,'currentQty']*cl.kutGetMult(self.api, ccy)
   self.calcFuturesDeltaUSD()
   #####
   if self.n >= 2:  # trim list for auxiliary KUTs
     self.validCcys = list(self.futures.index[self.futures['FutDelta'] != 0])
   #####
   for ccy in self.validCcys:
     ccy2= cl.kuGetTicker(ccy, isKUT=True)
     if ccy2 in positions.index:
       self.liqDict[ccy] = self.riskDf.loc[ccy2,'liq']
     else:
       self.liqDict[ccy] = 0
   #####
   self.oneDayIncome=0
   self.prevIncome=0
   if CR_CONFIGS_DICT['IS_CALC_PAYMENTS']:
     pmts=pd.DataFrame()
     startAt = cl.getYest() * 1000
     for ccy in self.validCcys:
       df=pd.DataFrame(cl.kuGetFundingHistory(self.api,self.name,ccy,startAt,isKUT=True))
       if len(df)>0: pmts=pmts.append(df[['symbol','timePoint','fundingRate','funding']])
     if len(pmts)>0:
       cl.dfSetFloat(pmts, ['timePoint', 'fundingRate', 'funding'])
       pmts['fundingUSD'] = pmts['funding'] * self.spotDict['USDT']
       pmts=pmts.set_index('timePoint').sort_index()
       self.oneDayIncome=pmts['fundingUSD'].sum()
       self.prevIncome=pmts.loc[pmts.index[-1]]['fundingUSD'].sum()
   self.setAnnRets()
   #####
   equity = float(self.usdtDict['accountEquity'])
   self.nav = equity * self.spotDict['USDT']
   self.spots.loc['USDT', 'SpotDelta'] = equity
   self.calcSpotDeltaUSD()
   #####
   for ccy in self.validCcys:
     oneDayFunding = 0
     prevFunding = 0
     estFunding=0
     estFunding2=0
     if CR_CONFIGS_DICT['IS_CALC_PAYMENTS']:
       if len(pmts)>0:
         df=pmts.loc[pmts['symbol'] == cl.kuGetTicker(ccy,isKUT=True), 'fundingRate']
         if len(df) > 0:
           oneDayFunding = df.mean() * 3 * 365
           prevFunding = df[df.index[-1]].mean() * 3 * 365
     #####
     if CR_CONFIGS_DICT['IS_CALC_ESTS']:
       estFunding,estFunding2 = self.kutGetEstFundings_fast(ccy)
     self.makeFundingStr(ccy, oneDayFunding, prevFunding, estFunding, estFunding2)
   #####
   self.makeIncomesStr()
   self.makeLiqStr(riskDf=self.riskDf, availableBalance=self.availableBalance)
   self.isDone = True
コード例 #5
0
 def kuInit(self):
   self.api = cl.kuCCXTInit(n=self.n)
   positions = cl.kuGetPositions(self.api)
   for ccy in self.validCcys:
     coinDict=cl.kuGetAccountOverview(self.api, ccy)
     accountEquity = coinDict['accountEquity']
     availableBalance = coinDict['availableBalance']
     self.spots.loc[ccy, 'SpotDelta'] = accountEquity
     ccy2=cl.kuGetTicker(ccy,isKUT=False)
     if ccy2 in positions.index:
       currentQty=positions.loc[ccy2,'currentQty']
       liquidationPrice=positions.loc[ccy2,'liquidationPrice']
       markPrice=positions.loc[ccy2,'markPrice']
       self.futures.loc[ccy, 'FutDelta'] = currentQty / self.spotDict[ccy]
       self.liqDict[ccy] = liquidationPrice / markPrice - (availableBalance * markPrice / currentQty)
     else:
       self.liqDict[ccy] = 0
   self.calcSpotDeltaUSD()
   self.calcFuturesDeltaUSD()
   #####
   self.oneDayIncome = 0
   self.prevIncome = 0
   if CR_CONFIGS_DICT['IS_CALC_PAYMENTS']:
     pmts = pd.DataFrame()
     startAt = cl.getYest() * 1000
     for ccy in self.validCcys:
       df = pd.DataFrame(cl.kuGetFundingHistory(self.api, self.name, ccy, startAt, isKUT=False))
       if len(df) > 0:
         pmts = pmts.append(df[['symbol', 'timePoint', 'fundingRate', 'funding', 'settleCurrency']])
     ##### Convert to USD #####
     spots=[]
     for i in range(len(pmts)):
       ccy=pmts['settleCurrency'].iloc[i]
       ccy = 'BTC' if ccy=='XBT' else ccy
       spots.append(self.spotDict[ccy])
     pmts['funding']*=spots
     ##########################
     cl.dfSetFloat(pmts, ['timePoint', 'fundingRate', 'funding'])
     pmts = pmts.set_index('timePoint').sort_index()
     self.oneDayIncome = pmts['funding'].sum()
     self.prevIncome = pmts.loc[pmts.index[-1]]['funding'].sum()
   self.setAnnRets()
   #####
   self.nav=self.spots['SpotDeltaUSD'].sum()
   #####
   for ccy in self.validCcys:
     oneDayFunding=0
     prevFunding=0
     estFunding=0
     estFunding2=0
     if CR_CONFIGS_DICT['IS_CALC_PAYMENTS']:
       if len(pmts) > 0:
         df = pmts.loc[pmts['symbol'] == cl.kuGetTicker(ccy,isKUT=False), 'fundingRate']
         if len(df) > 0:
           oneDayFunding = df.mean() * 3 * 365
           prevFunding = df[df.index[-1]].mean() * 3 * 365
     #####
     if CR_CONFIGS_DICT['IS_CALC_ESTS']:
       estFunding, estFunding2 = self.kuGetEstFundings_fast(ccy)
     self.makeFundingStr(ccy, oneDayFunding, prevFunding, estFunding, estFunding2)
   #####
   self.makeIncomesStr()
   self.isDone = True
コード例 #6
0
 def bbInit(self):
   def getPayments(ccy):
     n = 0
     df = pd.DataFrame()
     while True:
       n += 1
       tl = self.api.v2_private_get_execution_list({'symbol': ccy + 'USD', 'start_time': cl.getYest() * 1000, 'limit': 1000, 'page': n})['result']['trade_list']
       if tl is None:
         break
       else:
         df = df.append(pd.DataFrame(tl))
     if len(df)==0:
       return None
     else:
       return df.set_index('symbol', drop=False)
   #####
   self.api = cl.bbCCXTInit()
   self.wallet=pd.DataFrame(self.api.v2_private_get_wallet_balance()['result']).transpose()
   cl.dfSetFloat(self.wallet,'equity')
   for ccy in self.validCcys:
     self.spots.loc[ccy,'SpotDelta']=self.wallet.loc[ccy,'equity']
   self.calcSpotDeltaUSD()
   #####
   futs = self.api.v2_private_get_position_list()['result']
   futs = pd.DataFrame([pos['data'] for pos in futs]).set_index('symbol')
   cl.dfSetFloat(futs, ['size','liq_price','position_value','unrealised_pnl'])
   for ccy in self.validCcys:
     ccy2=ccy+'USD'
     mult = -1 if futs.loc[ccy2,'side']=='Sell' else 1
     self.futures.loc[ccy, 'FutDelta'] = futs.loc[ccy2, 'size'] * mult / self.spotDict[ccy]
     self.liqDict[ccy] = futs.loc[ccy2,'liq_price'] / cl.bbGetMid(self.api,ccy)
   self.calcFuturesDeltaUSD()
   #####
   self.oneDayIncome=0
   self.prevIncome=0
   if CR_CONFIGS_DICT['IS_CALC_PAYMENTS']:
     pmts = pd.DataFrame()
     for ccy in self.validCcys:
       pmts = pmts.append(getPayments(ccy))
     if len(pmts)>0:
       pmts = pmts[pmts['exec_type'] == 'Funding'].copy()
       cl.dfSetFloat(pmts, ['fee_rate', 'exec_fee'])
       pmts.loc[['Sell' in z for z in pmts['order_id']],'fee_rate']*=-1 # Correction for fee_rate signs
       for ccy in self.validCcys:
         ccy2=ccy+'USD'
         if ccy2 in pmts.index: pmts.loc[ccy2, 'incomeUSD'] = -pmts.loc[ccy2, 'exec_fee'] * self.spotDict[ccy]
       pmts['date'] = [datetime.datetime.fromtimestamp(int(ts) / 1000) for ts in pmts['trade_time_ms']]
       pmts = pmts.set_index('date')
       #####
       if len(pmts)>0:
         self.oneDayIncome = pmts['incomeUSD'].sum()
         self.prevIncome = pmts.loc[pmts.index[-1]]['incomeUSD'].sum()
   self.setAnnRets()
   #####
   self.nav=self.spots['SpotDeltaUSD'].sum()
   #####
   for ccy in self.validCcys:
     oneDayFunding = 0
     prevFunding = 0
     estFunding = 0
     estFunding2 = 0
     if CR_CONFIGS_DICT['IS_CALC_PAYMENTS']:
       if len(pmts) > 0:
         df = pmts.loc[pmts['symbol'] == ccy + 'USD', 'fee_rate']
         if len(df) > 0:
           oneDayFunding = df.mean() * 3 * 365
           prevFunding = df[df.index[-1]].mean() * 3 * 365
     #####
     if CR_CONFIGS_DICT['IS_CALC_ESTS']:
       estFunding,estFunding2 = cl.bbGetEstFundings(self.api, ccy)
     self.makeFundingStr(ccy, oneDayFunding, prevFunding, estFunding, estFunding2)
   #####
   self.makeIncomesStr()
   self.isDone = True
コード例 #7
0
  def ftxInit(self):
    def cleanBorrows(ccy, df):
      dummy = pd.DataFrame([[0, 0, 0, 0, 0, 0]], columns=['time', 'coin', 'size', 'rate', 'cost', 'proceeds'])
      if len(df) == 0:
        return dummy
      df2 = df.copy()
      df2 = df2[df2['coin'] == ccy]
      if len(df2) == 0:
        return dummy
      df2 = df2.set_index('time').sort_index()
      return df2
    ######
    def makeFlows(ccy):
      start_time = cl.getYest()
      borrows = cleanBorrows(ccy, pd.DataFrame(self.api.private_get_spot_margin_borrow_history({'limit': 1000, 'start_time': start_time})['result']))
      loans = cleanBorrows(ccy, pd.DataFrame(self.api.private_get_spot_margin_lending_history({'limit': 1000, 'start_time': start_time})['result']))
      cl.dfSetFloat(borrows, ['cost','rate'])
      cl.dfSetFloat(loans, 'proceeds')
      prevBorrow = borrows.iloc[-1]['cost'] if borrows.index[-1] == self.payments.index[-1] else 0
      prevLoan = loans.iloc[-1]['proceeds'] if loans.index[-1] == self.payments.index[-1] else 0
      absBalUSD = abs(self.wallet.loc[ccy, 'total']*self.spotDict[ccy])
      d=dict()
      d['oneDayFlows'] = (loans['proceeds'].sum() - borrows['cost'].sum()) * self.spotDict[ccy]
      d['oneDayFlowsAnnRet'] = d['oneDayFlows'] * 365 / absBalUSD
      d['oneDayBorrowRate'] = borrows['rate'].mean() * 24 * 365
      d['prevFlows']=(prevLoan - prevBorrow) * self.spotDict[ccy]
      d['prevFlowsAnnRet']=d['prevFlows'] * 24 * 365 / absBalUSD
      d['prevBorrowRate'] = borrows.iloc[-1]['rate'] * 24 * 365 if borrows.index[-1] == self.payments.index[-1] else 0
      return d
    ######
    self.api = cl.ftxCCXTInit()
    self.wallet = cl.ftxGetWallet(self.api,self.validCcys)
    ccys=self.validCcys.copy()
    cl.appendUnique(ccys,'USDT')
    for ccy in ccys:
      self.spots.loc[ccy,'SpotDelta'] = self.wallet.loc[ccy,'total']
    self.calcSpotDeltaUSD()
    ######
    info = self.api.private_get_account()['result']
    futs = pd.DataFrame(info['positions']).set_index('future')
    cl.dfSetFloat(futs, 'size')
    for ccy in self.validCcys:
      ccy2 = ccy + '-PERP'
      if ccy=='SHIB': ccy2='K'+ccy2 # Special fix for SHIB
      if ccy2 in futs.index:
        mult = -1 if futs.loc[ccy2, 'side']=='sell' else 1
        if ccy == 'SHIB': mult*=1000 # Special fix for SHIB
        self.futures.loc[ccy,'FutDelta']=futs.loc[ccy2,'size']*mult
    self.calcFuturesDeltaUSD()
    ######
    start_time=cl.getYest()
    pmts = pd.DataFrame()
    for ccy in self.validCcys:
      pmts = pmts.append(pd.DataFrame(self.api.private_get_funding_payments({'future':ccy+'-PERP', 'start_time': start_time})['result']))
    pmts = pmts.set_index('time').sort_index()
    cl.dfSetFloat(pmts, 'payment')
    self.payments = pmts
    #####
    self.oneDayIncome = -self.payments['payment'].sum()
    self.prevIncome = -self.payments.loc[self.payments.index[-1]]['payment'].sum()
    self.setAnnRets()
    #####
    flowsCcy=CR_FTX_FLOWS_CCYS.copy()
    cl.appendUnique(flowsCcy,'USD')
    cl.appendUnique(flowsCcy,'USDT')
    for ccy in flowsCcy:
      d=makeFlows(ccy)
      self.oneDayFlows += d['oneDayFlows']
      if d['oneDayFlows']==0 and d['prevFlows']==0 and not ccy in ['USD','USDT']:
        self.flowsDict[ccy]=None
      else:
        z1 = '$' + str(round(d['oneDayFlows'])) + ' (' + str(round(d['oneDayFlowsAnnRet'] * 100)) + '% p.a.)'
        z2 = '$' + str(round(d['prevFlows'])) + ' (' + str(round(d['prevFlowsAnnRet'] * 100)) + '% p.a.)'
        self.flowsDict[ccy]=colored(('FTX 24h/prev ' + ccy + ' flows: ').rjust(37) + z1 + ' / ' + z2, 'blue')
      if ccy in ['USD','USDT']: # Extra info for USD/USDT
        zList = []
        zList.append('na' if d['oneDayBorrowRate'] == 0 else str(round(d['oneDayBorrowRate'] * 100)) + '%')
        zList.append('na' if d['prevBorrowRate'] == 0 else str(round(d['prevBorrowRate'] * 100)) + '%')
        zList.append(str(round(cl.ftxGetEstBorrow(self.api, ccy) * 100)) + '%')
        self.flowsDict[ccy+'2'] = ('FTX ' + ccy + ' 24h/prev/est: ').rjust(37) + '/'.join(zList) + ' p.a. ($' + str(round(self.wallet.loc[ccy, 'usdValue'] / 1000)) + 'K) '
    #####
    self.nav = self.wallet['usdValue'].sum()
    #####
    for ccy in self.validCcys:
      oneDayFunding = 0
      prevFunding = 0
      estFunding = 0
      if CR_CONFIGS_DICT['IS_CALC_PAYMENTS']:
        df = pd.DataFrame(self.api.public_get_funding_rates({'future': ccy + '-PERP', 'start_time': start_time})['result']).set_index('time').sort_index()
        cl.dfSetFloat(df, 'rate')
        oneDayFunding = df['rate'].mean() * 24 * 365
        prevFunding = df['rate'][-1] * 24 * 365
      #####
      if CR_CONFIGS_DICT['IS_CALC_ESTS']:
        estFunding = cl.ftxGetEstFunding(self.api, ccy)
      self.makeFundingStr(ccy, oneDayFunding, prevFunding, estFunding)

    #####
    self.makeIncomesStr()
    #####
    self.mf = float(info['marginFraction'])
    self.mmReq = float(info['maintenanceMarginRequirement'])
    self.freeCollateral = float(info['freeCollateral'])
    totalPositionNotional = self.nav / self.mf
    cushion = (self.mf - self.mmReq) * totalPositionNotional
    delta = self.wallet.loc[self.validCcys, 'usdValue'].sum() + self.futures['FutDeltaUSD'].sum()
    self.makeLiqStr(cushion=cushion,delta=delta)
    #####
    self.isDone=True