コード例 #1
0
ファイル: account.py プロジェクト: zbgapi/zbg-api-v1-sdk
    def __init__(self, **kwargs):
        super().__init__()

        self.currency = Utils.safe_string(kwargs, 'currency')
        self.balance = Utils.safe_float(kwargs, 'balance')
        self.available = Utils.safe_float(kwargs, 'available')
        self.freeze = Utils.safe_float(kwargs, 'freeze')
コード例 #2
0
ファイル: market.py プロジェクト: zbgapi/zbg-api-v1-sdk
 def json_parse(json_array):
     trade = Trade()
     trade.price = Utils.safe_float(json_array, 5)
     trade.amount = Utils.safe_float(json_array, 6)
     trade.side = 'buy' if Utils.safe_string(json_array,
                                             4) == 'bid' else 'sell'
     trade.timestamp = Utils.safe_integer(json_array, 2)
     return trade
コード例 #3
0
ファイル: common.py プロジェクト: zbgapi/zbg-api-v1-sdk
    def __init__(self, **kwargs):
        self.id = ""
        self.name = ""
        self.draw_flag = ""
        self.once_draw_limit = 0
        self.daily_draw_limit = 0

        super().__init__(**kwargs)
        self.draw_fee = Utils.safe_float(kwargs, "draw-fee")
        self.min_draw_limit = Utils.safe_float(kwargs, "min-draw-limit")
コード例 #4
0
    def load_markets(self, reload=False) -> SymbolList:
        if reload or not self.markets:
            self.markets = self.get_markets()
            self.markets_by_id = Utils.index_by(self.markets, "id")
            self.markets_by_name = Utils.index_by(self.markets, "symbol")

            self.currencies = self.get_currencies()
            self.currencies_by_id = Utils.index_by(self.currencies, "id")
            self.currencies_by_name = Utils.index_by(self.currencies, "name")

        return self.markets
コード例 #5
0
    def json_parse(data):
        obj = OrderChangeEvent()
        if isinstance(data[0], list):
            data = data[0]
            obj.timestamp = Utils.safe_integer(data, 3)
            obj.data = [OrderChange.json_parse(item) for item in data[4]]
            obj.data_size = len(obj.data)
        else:
            obj.timestamp = Utils.safe_integer(data, 3)
            obj.data = [OrderChange.json_parse(data[4:])]
            obj.data_size = 1

        return obj
コード例 #6
0
    def __init__(self, **kwargs):
        self.trade_id = ''
        self.order_id = ''
        self.match_id = ''
        self.symbol = ''
        self.side = ''
        self.role = ''
        self.created_at = 0

        super().__init__(**kwargs)

        self.price = Utils.safe_float(kwargs, 'price')
        self.filled_amount = Utils.safe_float(kwargs, 'filled-amount', 0)
        self.filled_fees = Utils.safe_float(kwargs, 'filled-fees', 0)
コード例 #7
0
    def __init__(self, **kwargs):
        self.order_id = ''
        self.symbol = ''
        self.side = ''
        self.state = ''
        self.created_at = 0

        super().__init__(**kwargs)

        self.price = Utils.safe_float(kwargs, 'price')
        self.amount = Utils.safe_float(kwargs, 'amount')
        self.available_amount = Utils.safe_float(kwargs, 'available-amount')
        self.filled_amount = Utils.safe_float(kwargs, 'filled-amount', 0)
        self.filled_cash_amount = Utils.safe_float(kwargs,
                                                   'filled-cash-amount', 0)
コード例 #8
0
    def sign(self, method='GET', params=None, headers=None):
        if self.__api_key == '' or self.__secret_key == '':
            raise AuthenticationError('Api key and secret key must not be empty.')

        timestamp = str(Utils.milliseconds())
        if self.use_server_time:
            timestamp = str(self.get_server_time())

        param = ''
        if method == 'GET' and params:
            for k in sorted(params):
                param += k + str(params[k])
        elif method == 'POST' and params:
            param = json.dumps(params, separators=(',', ':'))

        sig_str = self.__api_key + timestamp + param + self.__secret_key
        signature = hashlib.md5(sig_str.encode('utf-8')).hexdigest()

        new_headers = {
            'Apiid': self.__api_key,
            'Timestamp': timestamp,
            'Clienttype': "5",
            'Sign': signature
        }
        if headers:
            self.extend(new_headers, headers)

        if hasattr(self, "_ApiClient__passphrase"):
            new_headers['Passphrase'] = hashlib.md5((timestamp + self.__passphrase).encode('utf-8')).hexdigest()

        return new_headers
コード例 #9
0
ファイル: market.py プロジェクト: zbgapi/zbg-api-v1-sdk
    def json_parse(json_object):
        data_obj = PriceDepth()
        data_obj.timestamp = Utils.safe_integer(json_object, 'timestamp')
        data_obj.asks = [DepthEntry.json_parse(e) for e in json_object['asks']]
        data_obj.bids = [DepthEntry.json_parse(e) for e in json_object['bids']]

        return data_obj
コード例 #10
0
ファイル: market.py プロジェクト: zbgapi/zbg-api-v1-sdk
 def json_parse(json_array):
     data_obj = Ticker()
     data_obj.symbol_id = json_array[0]
     data_obj.close = Utils.safe_float(json_array, 1)
     data_obj.low = Utils.safe_float(json_array, 3)
     data_obj.high = Utils.safe_float(json_array, 2)
     data_obj.amount = Utils.safe_float(json_array, 9)
     data_obj.rate = Utils.safe_float(json_array, 5)
     data_obj.volume = Utils.safe_float(json_array, 4)
     data_obj.ask = Utils.safe_float(json_array, 8)
     data_obj.bid = Utils.safe_float(json_array, 7)
     return data_obj
コード例 #11
0
 def json_parse(data):
     obj = PriceDepthEvent()
     if isinstance(data[0], list):
         data = data[0]
         obj.timestamp = Utils.safe_integer(data, 3)
         obj.data = {
             'asks': [DepthEntry.json_parse(e) for e in data[4]['asks']],
             'bids': [DepthEntry.json_parse(e) for e in data[5]['bids']]
         }
     else:
         obj.data_type = 'E'
         obj.timestamp = Utils.safe_integer(data, 2)
         obj.data = {
             'side': 'buy'
             if 'bid' == Utils.safe_string(data, 4).lower() else 'sell',
             'price': Utils.safe_float(data, 5),
             'amount': Utils.safe_float(data, 6),
         }
     return obj
コード例 #12
0
    def on_open(self, ws):
        self.logger.info("[Sub][" + str(self.id) + "] Connected to server")
        self.ws = ws
        self.last_receive_time = Utils.milliseconds()
        self.state = ConnectionState.CONNECTED
        if self.request.subscription_handler is not None:
            self.request.subscription_handler(self)

        self.__watch_dog.on_connection_created(self)
        return
コード例 #13
0
ファイル: market.py プロジェクト: zbgapi/zbg-api-v1-sdk
 def json_parse(json_array):
     data_obj = CandleStick()
     data_obj.id = json_array[3]
     data_obj.open = Utils.safe_float(json_array, 4)
     data_obj.close = Utils.safe_float(json_array, 7)
     data_obj.low = Utils.safe_float(json_array, 6)
     data_obj.high = Utils.safe_float(json_array, 5)
     data_obj.amount = Utils.safe_float(json_array, 13)
     data_obj.rate = Utils.safe_float(json_array, 9)
     data_obj.volume = Utils.safe_float(json_array, 8)
     return data_obj
コード例 #14
0
ファイル: account.py プロジェクト: zbgapi/zbg-api-v1-sdk
    def __init__(self, **kwargs):
        self.withdraw_id = ''
        self.currency = ''
        self.address = ''
        self.tx_hash = ''
        self.state = ''
        self.fee = ''
        self.created_at = 0
        self.audited_at = 0

        super().__init__(**kwargs)

        self.amount = Utils.safe_float(kwargs, 'amount')
コード例 #15
0
ファイル: common.py プロジェクト: zbgapi/zbg-api-v1-sdk
    def __init__(self, **kwargs):
        self.id = ""
        self.base_currency = ""
        self.quote_currency = ""
        self.price_precision = 0
        self.amount_precision = 0
        self.symbol_partition = ""
        self.symbol = ""
        self.state = ""

        # self.max_order_amt = ""

        super().__init__(**kwargs)
        self.min_order_amt = Utils.safe_float(kwargs, "min-order-amt")
コード例 #16
0
ファイル: account.py プロジェクト: zbgapi/zbg-api-v1-sdk
    def __init__(self, **kwargs):
        self.deposit_id = ''
        self.currency = ''
        self.address = ''
        self.tx_hash = ''
        self.confirm_times = 0
        self.state = ''
        self.type = ''
        self.created_at = 0
        self.confirmed_at = 0

        super().__init__(**kwargs)

        self.amount = Utils.safe_float(kwargs, 'amount')
コード例 #17
0
    def on_message(self, message):
        self.last_receive_time = Utils.milliseconds()

        if isinstance(message, str):
            # print("RX string : ", message)
            json_wrapper = json.loads(message)
        elif isinstance(message, bytes):
            # print("RX bytes: " + gzip.decompress(message).decode("utf-8"))
            json_wrapper = json.load(gzip.decompress(message).decode("utf-8"))
        else:
            self.logger.error("[Sub][" + str(self.id) + "] RX unknown type : ",
                              type(message))
            return

        if 'code' in json_wrapper:
            print(json_wrapper)
            if '5021' == json_wrapper['code'] and 'PING' == json_wrapper[
                    'action']:
                return
            self.on_error(json_wrapper)
            return

        res = None
        try:
            if self.request.json_parser is not None:
                res = self.request.json_parser(json_wrapper)
        except Exception as e:
            self.logger.error(
                "[Sub][" + str(self.id) +
                "] Failed to parse server's response", e)
            self.on_error("Failed to parse server's response: " + str(e))

        try:
            if self.request.update_callback is not None:
                self.request.update_callback(res)
        except Exception as e:
            self.logger.error(
                "[Sub][" + str(self.id) +
                "] Failed to call the callback method", e)
            self.on_error(
                "Process error: " + str(e) +
                " You should capture the exception in your error handler")
コード例 #18
0
def watch_dog_job(*args):
    watch_dog_instance = args[0]
    for connection in watch_dog_instance.connection_list:
        if connection.state == ConnectionState.CONNECTED:
            if watch_dog_instance.is_auto_connect:
                ts = Utils.milliseconds() - connection.last_receive_time
                if ts > watch_dog_instance.receive_limit_ms:
                    watch_dog_instance.logger.warning(
                        "[Sub][" + str(connection.id) +
                        "] No response from server")
                    connection.re_connect_in_delay(
                        watch_dog_instance.connection_delay_failure)
        elif connection.in_delay_connection():
            watch_dog_instance.logger.warning("[Sub] call re_connect")
            connection.re_connect()
            pass
        elif connection.state == ConnectionState.CLOSED_ON_ERROR:
            if watch_dog_instance.is_auto_connect:
                connection.re_connect_in_delay(
                    watch_dog_instance.connection_delay_failure)
                pass
コード例 #19
0
    def json_parse(item):
        order = OrderChange()
        order.order_id = item[0]
        order.side = 'buy' if Utils.safe_integer(item, 1) == 1 else 'sell'
        # status :  0:craeted 1:canceled 2: filled 3:partial-filled
        status = Utils.safe_integer(item, 2)
        if status == 0:
            order.status = 'created'
        elif status == 1:
            order.status = 'canceled'
        elif status == 2:
            order.status = 'filled'
        elif status == 3:
            order.status = 'partial-filled'

        order.price = Utils.safe_float(item, 3)
        order.amount = Utils.safe_float(item, 4)
        order.filled_amount = Utils.safe_float(item, 5, 0.0)
        order.filled_cash_amount = Utils.safe_float(item, 6, 0.0)
        order.avg_amount = Utils.safe_float(item, 7, 0.0)
        order.timestamp = Utils.safe_integer(item, 8)

        return order
コード例 #20
0
    def request(self, path, api='public', method="GET", params={}, headers=None):
        if self.enable_rate_limit:
            self.throttle()

        self.last_rest_request_Timestamp = Utils.milliseconds()

        if api == 'private':
            headers = self.sign(method, params, headers)

        # 设置路径参数
        path = path.format(**params)
        api = self.urls['market_api'] if path.find('api/data/v1') >= 0 else self.urls['api']
        url = api + path

        response = None
        try:
            if self.verbose:
                print('method:', method, ', url :', url, ", request:", params)

            if method == "GET":
                response = requests.get(url, params=params, headers=headers)
            else:
                response = requests.post(url, data=json.dumps(params, separators=(',', ':')), headers=headers)

            if self.verbose:
                print('method:', method, ', url:', url, ", response:", response.text)

            self.handle_fail(response, method, url)

            return response.json()['datas']
        except Timeout as e:
            self.raise_error(RequestTimeout, method, url, e)
        except ValueError as e:
            self.raise_error(BadResponse, method, url, e, response.text)
        except KeyError as e:
            self.raise_error(BadResponse, method, url, e, response.text)
コード例 #21
0
 def test_index_by(self):
     symbols = self.client.load_markets()
     symbols_by_id = Utils.index_by(symbols, "id")
     self.assertTrue('336' in symbols_by_id)
コード例 #22
0
ファイル: account.py プロジェクト: zbgapi/zbg-api-v1-sdk
    def __init__(self, **kwargs):
        super().__init__()

        self.is_memo = kwargs['isMemo'] if 'isMemo' in kwargs else False
        self.address = Utils.safe_string(kwargs, 'address')
        self.memo = Utils.safe_string(kwargs, 'memo')
コード例 #23
0
 def throttle(self):
     now = float(Utils.milliseconds())
     elapsed = now - self.last_rest_request_Timestamp
     if elapsed < self.rate_limit:
         delay = self.rate_limit - elapsed
         time.sleep(delay / 1000.0)