Пример #1
0
    def test_save_balances(self):
        self.target._create_all()

        dt = datetime.now()

        b1 = Balance()
        b1.bc_site = 'ts'
        b1.bc_acct = AccountType.CASH
        b1.bc_unit = UnitType.QTY
        b1.bc_time = dt + timedelta(minutes=1)
        b1.bc_amnt = Decimal('1.2')

        b2 = Balance()
        b2.bc_site = 'ts'
        b2.bc_acct = AccountType.CASH
        b2.bc_unit = UnitType.QTY
        b2.bc_time = dt + timedelta(minutes=2)
        b2.bc_amnt = Decimal('1.2')

        b3 = copy(b1)
        b3.bc_amnt = Decimal('3.4')

        b4 = copy(b2)
        b4.bc_amnt = Decimal('4.5')

        b5 = copy(b1)
        b5.bc_unit = None

        # All new records
        results = self.target.save_balances([b1, b2])
        self.assertEqual(len(results), 2)
        self.assertTrue(b1 in results)
        self.assertTrue(b2 in results)

        # Existing records
        results = self.target.save_balances([b3, None, b4])
        self.assertEqual(len(results), 2)
        self.assertTrue(b3 in results)
        self.assertTrue(b4 in results)

        # PK Failure
        with self.assertRaises(BaseException):
            self.target.save_balances([b5])

        # Read-only
        self.target._is_read_only = lambda: True
        results = self.target.save_balances([b1])
        self.assertEqual(len(results), 0)
Пример #2
0
    def _process_margin(self):

        try:

            now = self.__context.get_now()

            balances = self._query_private('/api/v1/user/margin?currency=all')

            values = []

            for balance in balances if balances is not None else []:

                if 'XBt' != balance.get('currency'):
                    continue

                value = Balance()
                value.bc_site = self._ID
                value.bc_acct = AccountType.MARGIN
                value.bc_unit = UnitType.BTC
                value.bc_time = now
                value.bc_amnt = balance.get('walletBalance') * self._SATOSHI

                values.append(value)

            self.__context.save_balances(values)

            for value in values:
                self.__logger.debug('Margin : %s', value)

        except Exception as e:

            self.__logger.warn('Margin Failure : %s - %s', type(e), e.args)
Пример #3
0
    def test_Balance(self):
        value = Balance()
        self.assertEqual("{'table': 't_balance', 'site': 'None', 'account': 'None', "
                         "'unit': 'None', 'time': 'None', 'amount': 'None'}", str(value))

        value.bc_site = 'foo'
        value.bc_acct = AccountType.CASH
        value.bc_unit = UnitType.JPY
        value.bc_time = datetime.fromtimestamp(1234567890.123456, tz=utc)
        value.bc_amnt = Decimal('1.2')
        self.assertEqual("{'table': 't_balance', 'site': 'foo', 'account': 'CASH', 'unit': 'JPY', "
                         "'time': '2009-02-13 23:31:30.123456 UTC', 'amount': '1.2'}", str(value))
Пример #4
0
    def _process_balance(self):

        try:

            token = self.__context.get_property(self._ID, 'token', None)

            if token is None:
                return

            now = self.__context.get_now()

            accounts = self.__context.requests_get(
                self.__endpoint + '/v1/accounts',
                headers={"Authorization": "Bearer " + token}
            )

            values = []

            for account in accounts.get('accounts', {}) if accounts is not None else []:

                details = self.__context.requests_get(
                    self.__endpoint + '/v1/accounts/%s' % account.get('accountId'),
                    headers={"Authorization": "Bearer " + token}
                )

                if details is None:
                    continue

                try:
                    unit = UnitType[details.get('accountCurrency')]
                except KeyError:
                    continue

                value = Balance()
                value.bc_site = self._ID
                value.bc_acct = AccountType.MARGIN
                value.bc_unit = unit
                value.bc_time = now
                value.bc_amnt = details.get('balance')

                values.append(value)

            self.__context.save_balances(values)

            for value in values:
                self.__logger.debug('Balance : %s', value)

        except Exception as e:

            self.__logger.warn('Balance Failure : %s - %s', type(e), e.args)
Пример #5
0
    def _process_balance(self, account):

        try:

            now = self.__context.get_now()

            response = self._query_private('/v1/account/accounts/' + account +
                                           '/balance')

            if response is None or response.get(
                    'status') != 'ok' or 'data' not in response:
                return

            amounts = {}

            for balance in response.get('data').get('list', []):

                ccy = balance.get('currency')

                try:
                    unit = UnitType[ccy.upper()]
                except KeyError:
                    continue

                amounts[unit] = amounts.get(unit, self._ZERO) + Decimal(
                    balance.get('balance', '0'))

            values = []

            for unit, amount in amounts.items():
                value = Balance()
                value.bc_site = self._ID
                value.bc_acct = AccountType.CASH
                value.bc_unit = unit
                value.bc_time = now
                value.bc_amnt = amount
                values.append(value)

            self.__context.save_balances(values)

            for value in values:
                self.__logger.debug('Balance : [%s] %s', account, value)

        except Exception as e:

            self.__logger.warn('Balance Failure : [%s] %s - %s', account,
                               type(e), e.args)
Пример #6
0
    def _process_balance(self):

        try:

            now = self.__context.get_now()

            balance = self._query_private('/api/v1/balance')

            if balance is None:
                return

            if not balance.get('result', True):
                raise Exception('Code : %s' % balance.get('code'))

            values = []

            for key, val in balance.items():

                if not key.endswith('_balance'):
                    continue

                ccy = key[: len(key) - len('_balance')]

                try:
                    unit = UnitType[ccy.upper()]
                except KeyError:
                    continue

                value = Balance()
                value.bc_site = self._ID
                value.bc_acct = AccountType.CASH
                value.bc_unit = unit
                value.bc_time = now
                value.bc_amnt = val + balance.get(ccy + '_lock', self._ZERO)

                values.append(value)

            self.__context.save_balances(values)

            for value in values:
                self.__logger.debug('Balance : %s', value)

        except Exception as e:

            self.__logger.warn('Balance Failure : %s - %s', type(e), e.args)
Пример #7
0
    def _process_balance(self):

        try:

            response = self._query_private('get_info2')

            if response is None:
                return

            if response.get('success', 1) != 1:
                raise Exception(str(response))

            returns = response.get('return', {})

            timestamp = self.__context.parse_iso_timestamp(
                returns.get('server_time'))

            values = []

            for currency, amount in returns.get('deposit', {}).items():

                try:
                    unit = UnitType[currency.upper()]
                except KeyError:
                    continue

                value = Balance()
                value.bc_site = self._ID
                value.bc_acct = AccountType.CASH
                value.bc_unit = unit
                value.bc_time = timestamp
                value.bc_amnt = amount

                values.append(value)

            self.__context.save_balances(values)

            for value in values:
                self.__logger.debug('Cash : %s', value)

        except Exception as e:

            self.__logger.warn('Cash Failure : %s - %s', type(e), e.args)
Пример #8
0
    def _process_balance(self):

        try:

            now = self.__context.get_now()

            response = self._query_private('/v1/user/assets')

            if response is None:
                return

            if response.get('success', 1) != 1:
                raise Exception(str(response))

            values = []

            for asset in response.get('data', {}).get('assets', {}):

                ccy = asset.get('asset')

                try:
                    unit = UnitType[ccy.upper()]
                except KeyError:
                    continue

                value = Balance()
                value.bc_site = self._ID
                value.bc_acct = AccountType.CASH
                value.bc_unit = unit
                value.bc_time = now
                value.bc_amnt = asset.get('onhand_amount')

                values.append(value)

            self.__context.save_balances(values)

            for value in values:
                self.__logger.debug('Balance : %s', value)

        except Exception as e:

            self.__logger.warn('Balance Failure : %s - %s', type(e), e.args)
Пример #9
0
    def _process_cash(self):

        try:

            now = self.__context.get_now()

            balances = self._query_private('/api/accounts/balance')

            if balances is None:
                return

            if not balances.get('success', True):
                raise Exception(str(balances))

            values = []

            for key, val in balances.items():

                try:
                    unit = UnitType[key.upper()]
                except KeyError:
                    continue

                value = Balance()
                value.bc_site = self._ID
                value.bc_acct = AccountType.CASH
                value.bc_unit = unit
                value.bc_time = now
                value.bc_amnt = Decimal(val) + Decimal(
                    balances.get(key + '_reserved'))

                values.append(value)

            self.__context.save_balances(values)

            for value in values:
                self.__logger.debug('Cash : %s', value)

        except Exception as e:

            self.__logger.warn('Cash Failure : %s - %s', type(e), e.args)
Пример #10
0
    def _process_balance(self, path, account_type):

        try:

            now = self.__context.get_now()

            balances = self._query_private(path)

            if balances is None:
                return

            values = []

            for balance in balances:

                ccy = balance.get('currency_code')

                try:
                    unit = UnitType[ccy]
                except KeyError:
                    continue

                value = Balance()
                value.bc_site = self._ID
                value.bc_acct = account_type
                value.bc_unit = unit
                value.bc_time = now
                value.bc_amnt = balance.get('amount')

                values.append(value)

            self.__context.save_balances(values)

            for value in values:
                self.__logger.debug('Balance : %s - %s', account_type.name, value)

        except Exception as e:

            self.__logger.warn('Balance Failure - %s : %s - %s', account_type, type(e), e.args)
Пример #11
0
    def _process_assets(self):

        try:

            now = self.__context.get_now()

            response = self._query_private('/v1/account/assets')

            if response is None or response.get(
                    'status', None) != 0 or not isinstance(
                        response.get('data'), list):
                raise Exception(str(response))

            values = []

            for asset in response.get('data'):

                try:
                    unit = UnitType[asset.get('symbol', '').upper()]
                except KeyError:
                    continue

                value = Balance()
                value.bc_site = self._ID
                value.bc_acct = AccountType.CASH
                value.bc_unit = unit
                value.bc_time = now
                value.bc_amnt = asset.get('amount')

                values.append(value)

            self.__context.save_balances(values)

            for value in values:
                self.__logger.debug('Asset : %s', value)

        except Exception as e:

            self.__logger.warn('Assets Failure : %s - %s', type(e), e.args)
Пример #12
0
    def _process_cash(self):

        try:

            now = self.__context.get_now()

            balances = self._query_private('/accounts/balance')

            values = []

            for balance in balances if balances is not None else []:

                ccy = balance.get('currency')

                try:
                    unit = UnitType[ccy]
                except KeyError:
                    continue

                value = Balance()
                value.bc_site = self._ID
                value.bc_acct = AccountType.CASH
                value.bc_unit = unit
                value.bc_time = now
                value.bc_amnt = balance.get('balance')

                values.append(value)

            self.__context.save_balances(values)

            for value in values:
                self.__logger.debug('Balance : %s', value)

        except Exception as e:

            self.__logger.warn('Balance Failure : %s - %s', type(e), e.args)
Пример #13
0
    def _process_cash(self, token, *, retry=True):

        if token is None:
            return

        try:

            params = {
                self._TOKEN: token
            }

            headers = {
                'Content-Type': 'application/json'
            }

            path = self.__endpoint + '/bpj-api/rc_balance_list'

            now = self.__context.get_now()

            response = self.__context.requests_post(path, params=params, headers=headers, json={})

            if response is None:
                return

            if response.get('resultCode', self._FAILURE) != self._SUCCESS:
                raise Exception(response)

            values = []

            for balance in response.get('rcBalanceList', []):

                currency = balance.get('currencyCd')

                try:
                    unit = UnitType[currency.upper()]
                except KeyError:
                    continue

                value = Balance()
                value.bc_site = self._ID
                value.bc_acct = AccountType.CASH
                value.bc_unit = unit
                value.bc_time = now
                value.bc_amnt = balance.get('cashBalance')

                values.append(value)

            self.__context.save_balances(values)

            for value in values:
                self.__logger.debug('Cash : %s', value)

        except Exception as e:

            if retry:

                token = self._fetch_token(force=True)

                self._process_cash(token, retry=False)

            else:

                self.__logger.warn('Cash Failure : %s - %s', type(e), e.args)
Пример #14
0
    def _process_coin(self, token, *, retry=True):

        if token is None:
            return

        try:

            params = {
                self._TOKEN: token
            }

            headers = {
                'Content-Type': 'application/json'
            }

            path = self.__endpoint + '/bpj-api/vc_balance_list'

            json = {
                "calcCurrencyCd": self.__context.get_property(self._ID, 'calc', 'JPY'),
                "currencyCdList": self.__context.get_property(self._ID, 'coins', 'BTC').split(',')
            }

            now = self.__context.get_now()

            response = self.__context.requests_post(path, params=params, headers=headers, json=json)

            if response is None:
                return

            if response.get('resultCode', self._FAILURE) != self._SUCCESS:
                raise Exception(response)

            balances = []

            tickers = []

            for entry in response.get('vcBalanceList', []):

                currency1 = entry.get('currencyCd1')
                currency2 = entry.get('currencyCd2')

                try:
                    unit1 = UnitType[currency1.upper()]
                except KeyError:
                    continue

                try:
                    unit2 = UnitType[currency2.upper()]
                except KeyError:
                    continue

                balance = Balance()
                balance.bc_site = self._ID
                balance.bc_acct = AccountType.CASH
                balance.bc_unit = unit1
                balance.bc_time = now
                balance.bc_amnt = entry.get('nominal')
                balances.append(balance)

                ticker = Ticker()
                ticker.tk_site = self._ID
                ticker.tk_code = unit1.name + '_' + unit2.name
                ticker.tk_time = now
                ticker.tk_ltp = entry.get('valuationPrice')
                tickers.append(ticker)

            self.__context.save_balances(balances)

            for balance in balances:
                self.__logger.debug('Coin : %s', balance)

            self.__context.save_tickers(tickers)

            for ticker in tickers:
                self.__logger.debug('Tick : %s', ticker)

        except Exception as e:

            if retry:

                token = self._fetch_token(force=True)

                self._process_coin(token, retry=False)

            else:

                self.__logger.warn('Coin Failure : %s - %s', type(e), e.args)