class GDAX: def __init__(self, key, secret, passphrase): self.logger = Logger(__name__) try: self.client = Client(key, secret, passphrase) except Exception as e: self.logger.log(e) raise ExchangeException(self.__class__.__name__, e) def getBalances(self): try: result = self.client.get_accounts() balances = {} if 'message' in result: raise Exception(result['message']) for currency in result: name = currency["currency"].upper() value = float(currency["balance"]) if value > Config.BALANCE_ZERO: balances[name] = value return balances except Exception as e: self.logger.log(e) raise ExchangeException(self.__class__.__name__, e)
class Trader(object): def __init__(self, market='BTC-USD', live=True): self.product = market if live: url = "https://api.gdax.com" else: url = "https://api-public.sandbox.gdax.com" self.auth_client = AuthenticatedClient( *SecretsManager.get_value('gdax'), api_url=url) @property def is_authenticated(self): try: return self.auth_client.get_accounts() except Exception as e: print(e, 'Failed to retrieve account information') def post_buy(self, price, size): self.auth_client.buy( price=str(price), # USD size=str(size), # BTC product_id=self.product) def post_sell(self, price, size): self.auth_client.sell( price=str(price), # USD size=str(size), # BTC product_id=self.product)
class AsyncStatisticsManager(AsyncTaskManager): def __init__(self, dbReference, connection, authData, logger): super().__init__(dbReference, connection, logger) from gdax import AuthenticatedClient self.gdaxAuthClient = AuthenticatedClient(*authData) self.CapitalStatsRef = self.dbReference.table('CapitalData') self.RiskStatsRef = self.dbReference.table('RiskData') self.riskProfile = None #not permanent async def updateRiskStatistics(self): analyticsDict = self.riskProfile.getAnalytics() self.RiskStatsRef.update(analyticsDict).run(self.connection) await asyncio.sleep(0) async def updateCapitalStatistics(self, logCapital=False): try: accountData = list(self.gdaxAuthClient.get_accounts()) acctDataUSD = list( filter(lambda x: x['currency'] == "USD", accountData)) availibleCapitalUSD = float(acctDataUSD[0]['available']) printCapitalValid = bool(logCapital == True) capitalDict = { 'capital': availibleCapitalUSD, "commission": 'None', "return": 'None' } if (printCapitalValid): capitalCheck = "Current Capital: " + str(availibleCapitalUSD) self.logger.addEvent('statistics', capitalCheck) self.CapitalStatsRef.update(capitalDict).run(self.connection) except BaseException as e: self.logger.addEvent( 'trading', ('GDAX_AUTHCLIENT_GET_ACCOUNTS_ERROR: ' + str(e))) await asyncio.sleep(0) async def pullRiskStatistics(self): RiskStats = self.pullTableContents(self.RiskStatsRef) await asyncio.sleep(0) return RiskStats[0] async def pullCapitalStatistics(self): CapitalStats = self.pullTableContents(self.CapitalStatsRef) await asyncio.sleep(0) return CapitalStats[0]
class AsyncStatisticsManager(AsyncTaskManager): def __init__(self, dbReference, connection, authData, logger): super().__init__(dbReference, connection, logger) from gdax import AuthenticatedClient self.gdaxAuthClient = AuthenticatedClient(*authData) from .Constants import DEFAULT_CAPITAL_DICT self.capitalStats = DEFAULT_CAPITAL_DICT self.riskStats, self.riskProfile = {'FUNDS': None}, None self.positionBookRef = self.dbReference.table('PositionBook') def getReturns(self): positionBook = self.pullTableContents(self.positionBookRef) positionBook = positionBook[1:] return [p.returns for p in positionBook if p.returns != None] async def updateRiskStatistics(self): from .Pipeline import getRiskFreeRate self.riskProfile.updateRiskFreeRate(getRiskFreeRate()) self.riskProfile.updateReturns(self.getReturns()) self.riskStats = self.riskProfile.getAnalytics() await asyncio.sleep(0) async def updateCapitalStatistics(self, logCapital=False): try: accountData = list(self.gdaxAuthClient.get_accounts()) acctDataUSD = list( filter(lambda x: x['currency'] == "USD", accountData)) availibleCapitalUSD = float(acctDataUSD[0]['available']) printCapitalValid = bool(logCapital == True) if (printCapitalValid): capitalCheck = "Current Capital: " + str(availibleCapitalUSD) self.logger.addEvent('statistics', capitalCheck) self.capitalStats['capital'] = availibleCapitalUSD except BaseException as e: self.logger.addEvent( 'trading', ('GDAX_AUTHCLIENT_GET_ACCOUNTS_ERROR: ' + str(e))) await asyncio.sleep(0) def getRiskStats(self, availibleFunds, pullRiskParams=False): self.riskStats['FUNDS'] = availibleFunds if pullRiskParams: return self.riskStats, self.riskProfile.parameters else: return self.riskStats def getCapitalStats(self): return self.capitalStats def getReturnsCount(self): return len(self.riskProfile.analyticsObj.returns)