Exemple #1
0
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)
Exemple #2
0
 def __init__(self, pair):
     Exchange.__init__(self, 'GDAX', pair)
     GDAX_API.__init__(self,
                       key=config.key_pairs[self.name][KEY],
                       b64secret=config.key_pairs[self.name][SECRET],
                       passphrase=config.key_pairs[self.name][PASSPHRASE])
     self.set_order_book()
Exemple #3
0
 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)
Exemple #4
0
 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(**load_conf()['gdax'],
                                            api_url=url)
Exemple #5
0
    def __init__(self, dbReference, connection, authData, logger):
        super().__init__(dbReference, connection, logger)
        self.positionCache = {}
        from .Constants import NOT_SET
        self.symbol, self.quantity, self.riskParams = (NOT_SET, ) * 3

        from gdax import AuthenticatedClient
        self.gdaxAuthClient = AuthenticatedClient(*authData)
Exemple #6
0
    def __init__(self, dbReference, connection, authData, logger):

        super().__init__(dbReference, connection, logger)
        from gdax import AuthenticatedClient

        self.gdaxAuthClient = AuthenticatedClient(*authData)
        self.RiskStatsRef = self.dbReference.table('RiskData')
        self.CapitalStatsRef = self.dbReference.table('CapitalData')
Exemple #7
0
    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')
Exemple #8
0
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)
Exemple #9
0
    def __init__(self, dbReference, connection, authData, logger):

        super().__init__(dbReference, connection, logger)
        from gdax import AuthenticatedClient

        self.pCacheRef = self.dbReference.table('PositionCache')
        self.RiskStatsRef = self.dbReference.table('RiskStats')
        self.CapitalStatsRef = self.dbReference.table('CapitalStats')
        self.gdaxAuthClient = AuthenticatedClient(*authData)

        from .Constants import NOT_SET
        self.symbol, self.quantity, self.tolerance, self.poslimit = (
            NOT_SET, ) * 4

        from .Utilities import getObjectDict
        self.getObjectDict = getObjectDict
Exemple #10
0
    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)
Exemple #11
0
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]
Exemple #12
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)
Exemple #13
0
def client_setup():
    key, secret, phrase = coinbase_pro_key()
    client = AuthenticatedClient(key, secret, phrase)
    return client
Exemple #14
0
class AsyncTradingManager(AsyncTaskManager):
    def __init__(self, dbReference, connection, authData, logger):
        super().__init__(dbReference, connection, logger)
        self.positionCache = {}
        from .Constants import NOT_SET
        self.symbol, self.quantity, self.riskParams = (NOT_SET, ) * 3

        from gdax import AuthenticatedClient
        self.gdaxAuthClient = AuthenticatedClient(*authData)

    def getCacheSize(self):
        return len(list(self.positionCache.keys()))

    def validPosLimitCheck(self):
        return bool(self.positionCache.size() <= self.riskParams['posLimit'])

    async def createOrders(self, stratVerdict):  #read
        entryOrder, validEntryVerdict = 0, (stratVerdict == 1)

        if (validEntryVerdict and self.validPosLimitCheck()):
            from .Order import Order
            entryOrder = Order('ENTRY', 'B', self.symbol, self.quantity)
            orderLog = "Created Order for: " + str(
                self.symbol) + " at size: " + str(self.quantity)
            self.logger.addEvent('trading', orderLog)

        await asyncio.sleep(0)
        return entryOrder

    async def verifyAndEnterPosition(self, entryOrder, currentCapital,
                                     spotPrice):  #read
        newPosition, validEntryConditions = None, (entryOrder is not None
                                                   and currentCapital > 0)

        if validEntryConditions:
            fundToleranceAvailible = currentCapital * self.riskParams[
                'tolerance'] > self.quantity
            if (fundToleranceAvailible and self.validPosLimitCheck()):

                response = dict(
                    self.gdaxAuthClient.buy(product_id=self.symbol,
                                            type='market',
                                            funds=self.quantity))
                orderID = response['id']
                time.sleep(1)
                orderStatus = dict(self.gdaxAuthClient.get_order(orderID))

                if (orderStatus['status'] != 'done'):
                    timedOut = 'TIMED_OUT'
                    self.gdaxAuthClient.cancel_order(orderID)
                    entryOrder.setErrorCode(timedOut)
                    orderTimeOut = 'Order: ' + str(orderID) + ' ' + timedOut
                    self.logger.addEvent('trading', orderTimeOut)
                else:
                    noErrors = 'NO_ERRORS'
                    entryOrder.setOrderID(orderID)
                    entryOrder.setErrorCode(noErrors)
                    orderFillTime = orderStatus['done_at']
                    entryValue = float(response['executed_value'])
                    orderData = (entryOrder.direction, self.symbol,
                                 self.quantity, entryValue, orderFillTime)

                    ### CREATE POSITION OBJECT FROM ORDERDATA AND ADD TO POSTION CACHE
                    from .Position import Position
                    newPosition = Position(orderID, *orderData)
                    self.positionCache.update({orderID: newPosition})
                    positionEntered = noErrors + ', Entered Position: ' + str(
                        orderID)
                    self.logger.addEvent('trading', positionEntered)

            else:
                noFunds = "CAPITAL_TOLERANCE_EXCEEDED"
                entryOrder.setErrorCode(noFunds)
                self.logger.addEvent('trading', noFunds)

        await asyncio.sleep(0)
        return ([entryOrder], newPosition)

    async def exitValidPositions(self, stratVerdict):  #read
        validExitConditions = stratVerdict == -1 and self.getCacheSize() > 0
        completedPositions, exitOrders = [None], [None]

        if validExitConditions:
            self.logger.addEvent('strategy', 'POSITION EXIT CONDITIONS VALID')
            sellResponses, completedPositions, exitOrders, response = [], [], [], None
            self.gdaxAuthClient.cancel_all(product=self.symbol)
            from .Position import Position
            from .Order import Order

            for p in self.positionCache.values():
                from .Constants import GDAX_FUNDS_ERROR
                while (response == GDAX_FUNDS_ERROR or response == None):
                    response = dict(
                        self.gdaxAuthClient.sell(product_id=self.symbol,
                                                 type='market',
                                                 funds=self.quantity))
                    if (response == GDAX_FUNDS_ERROR):
                        self.logger.addEvent(
                            'trading',
                            'INVALID_SELL_RESPONSE: GDAX_FUNDS_ERROR')

                pArgs = (p['entID'], p['direction'], p['ticker'],
                         p['quantity'], p['entryPrice'], p['entryTime'])
                completedPosition = Position(*pArgs)
                completedPosition.setExitID(response['id'])
                completedPositions.append(completedPosition)
                sellResponses.append(response)

                exitOrder = Order('EXIT', 'S', self.symbol, self.quantity)
                exitOrder.setErrorCode("NO_ERRORS")
                exitOrder.setOrderID(response['id'])
                exitOrders.append(exitOrder)
                response = None

            for posit, response in zip(completedPositions, sellResponses):
                exitedPos = "Exited Position:" + posit.exID
                self.logger.addEvent('trading', exitedPos)

                try:
                    orderStatus = dict(
                        self.gdaxAuthClient.get_order(posit.exID))
                    orderExitTime = orderStatus['done_at']
                    posit.setExitParams(float(response['executed_value']),
                                        orderExitTime)
                except BaseException as e:
                    self.logger.addEvent(
                        'trading',
                        ('GDAX_AUTHCLIENT_GETORDER_ERROR: ' + str(e)))

            self.positionCache.clear()

        await asyncio.sleep(0)
        return (exitOrders, completedPositions)
Exemple #15
0
class AsyncTradingManager(AsyncTaskManager):
    def __init__(self, dbReference, connection, authData, logger):

        super().__init__(dbReference, connection, logger)
        from gdax import AuthenticatedClient

        self.pCacheRef = self.dbReference.table('PositionCache')
        self.RiskStatsRef = self.dbReference.table('RiskStats')
        self.CapitalStatsRef = self.dbReference.table('CapitalStats')
        self.gdaxAuthClient = AuthenticatedClient(*authData)

        from .Constants import NOT_SET
        self.symbol, self.quantity, self.tolerance, self.poslimit = (
            NOT_SET, ) * 4

        from .Utilities import getObjectDict
        self.getObjectDict = getObjectDict

    def validPosLimitCheck(self):
        return bool(
            (len(self.pullTableContents(self.pCacheRef)) + 1) <= self.poslimit)

    async def createOrders(self, stratVerdict):  #read

        entryOrder = None
        validEntryVerdict = stratVerdict == 1

        if (validEntryVerdict and self.validPosLimitCheck()):
            from .Order import Order
            entryOrder = Order('ENT', 'B', self.symbol, self.quantity)
            orderLog = "Created Order for: " + str(
                self.symbol) + " at size: " + str(self.quantity)
            self.logger.addEvent('trading', orderLog)

        await asyncio.sleep(0)
        return entryOrder

    async def verifyAndEnterPosition(self, entryOrder, capitalStats,
                                     spotPrice):  #read

        newPosition, currentCapital = None, capitalStats['capital']
        validEntryConditions = entryOrder is not None and currentCapital > 0

        if (validEntryConditions and self.validPosLimitCheck()):

            fundToleranceAvailible = currentCapital * self.tolerance > self.quantity
            #check db for viable kelly criterion values, max draw, etc. (not done)

            if (fundToleranceAvailible):

                response = dict(
                    self.gdaxAuthClient.buy(product_id=self.symbol,
                                            type='market',
                                            funds=self.quantity))
                orderID = response['id']
                time.sleep(1)
                orderStatus = dict(self.gdaxAuthClient.get_order(orderID))

                if (orderStatus['status'] != 'done'):
                    timedOut = 'TIMED_OUT'
                    self.gdaxAuthClient.cancel_order(orderID)
                    entryOrder.setErrorCode(timedOut)
                    orderTimeOut = 'Order: ' + str(orderID) + ' ' + timedOut
                    self.logger.addEvent('trading', orderTimeOut)

                else:
                    noErrors = 'NO_ERRORS'
                    entryOrder.setOrderID(orderID)
                    entryOrder.setErrorCode(noErrors)
                    orderFillTime = orderStatus['done_at']
                    entryValue = float(response['executed_value'])
                    orderData = (entryOrder.direction, self.symbol,
                                 self.quantity, entryValue, orderFillTime)

                    from .Position import Position
                    newPosition = Position(orderID, *orderData)
                    positionEntered = noErrors + ', Entered Position: ' + str(
                        orderID)
                    self.logger.addEvent('trading', positionEntered)

            else:
                noFunds = "CAPITAL_TOLERANCE_EXCEEDED"
                entryOrder.setErrorCode(noFunds)
                self.logger.addEvent('trading', noFunds)

        await asyncio.sleep(0)
        return ([entryOrder], newPosition)

    async def exitValidPositions(self, stratVerdict):  #read

        positionCache = self.pullTableContents(self.pCacheRef)
        validExitConditions = stratVerdict == -1 and positionCache != []
        completedPositions, exitOrders = [None], [None]

        if (validExitConditions):

            sellResponses, completedPositions, exitOrders, response = [], [], [], None
            self.gdaxAuthClient.cancel_all(product=self.symbol)
            from .Position import Position
            from .Order import Order

            for p in positionCache:

                from .Constants import GDAX_FUNDS_ERROR
                while (response == GDAX_FUNDS_ERROR or response == None):
                    response = dict(
                        self.gdaxAuthClient.sell(product_id=self.symbol,
                                                 type='market',
                                                 funds=self.quantity))
                    if (response == GDAX_FUNDS_ERROR):
                        self.logger.addEvent(
                            'trading',
                            'INVALID_SELL_RESPONSE: GDAX_FUNDS_ERROR')

                pArgs = (p['entID'], p['direction'], p['ticker'],
                         p['quantity'], p['entryPrice'], p['entryTime'])
                completedPosition = Position(*pArgs)
                completedPosition.setExitID(response['id'])
                completedPositions.append(completedPosition)
                sellResponses.append(response)

                exitOrder = Order('EX', 'S', self.symbol, self.quantity)
                exitOrder.setErrorCode("NO_ERRORS")
                exitOrder.setOrderID(response['id'])
                exitOrders.append(exitOrder)
                response = None

            time.sleep(1)

            for posit, response in zip(completedPositions, sellResponses):

                exitedPos = "Exited Position:" + posit.exID
                self.logger.addEvent('trading', exitedPos)

                try:
                    orderStatus = dict(
                        self.gdaxAuthClient.get_order(posit.exID))
                    orderExitTime = orderStatus['done_at']
                    posit.setExitParams(float(response['executed_value']),
                                        orderExitTime)
                except BaseException as e:
                    self.logger.addEvent(
                        'trading',
                        ('GDAX_AUTHCLIENT_GETORDER_ERROR: ' + str(e)))

            self.pCacheRef.delete().run(self.connection)

        await asyncio.sleep(0)
        return (exitOrders, completedPositions)

    async def addToPositionCache(self, position):  #write

        if (position is not None):
            pDict = self.getObjectDict(position)
            self.pCacheRef.insert(pDict).run(self.connection)

        await asyncio.sleep(0)