예제 #1
0
 def get_user(self, api_key):
     if api_key is None or api_key == "":
         raise HuobiApiException(HuobiApiException.KEY_MISSING,
                                 "[User] Key is empty or null")
     if api_key not in self.user_map:
         raise HuobiApiException(
             HuobiApiException.RUNTIME_ERROR,
             "[User] Cannot found user by key: " + api_key)
     return self.user_map[api_key]
예제 #2
0
def check_list(list_value, min_value, max_value, name):
    if list_value is None:
        return
    if len(list_value) > max_value:
        raise HuobiApiException(HuobiApiException.INPUT_ERROR,
                                "[Input] " + name + " is out of bound, the max size is " + str(max_value))
    if len(list_value) < min_value:
        raise HuobiApiException(HuobiApiException.INPUT_ERROR,
                                "[Input] " + name + " should contain " + str(min_value) + " item(s) at least")
예제 #3
0
def format_date(value, name):
    if value is None:
        return None
    if not isinstance(value, str):
        raise HuobiApiException(HuobiApiException.INPUT_ERROR, "[Input] " + name + " must be string")
    try:
        new_time = time.strptime(value, "%Y-%m-%d")
        return time.strftime("%Y-%m-%d", new_time)
    except:
        raise HuobiApiException(HuobiApiException.INPUT_ERROR, "[Input] " + name + " is not invalid date format")
예제 #4
0
 def update_kline(self):
     if not self.klines:
         raise HuobiApiException(HuobiApiException.INPUT_ERROR, "klines is not init")
     new_klines = self.req_client.get_contract_kline(symbol=self.symbol, period=self.interval, size=2)["data"]
     update_klines(self.klines, new_klines, self.size)
     interval_datas = interval_handler(self.klines)
     print(interval_datas[5][0], interval_datas[10][0], interval_datas[30][0])
예제 #5
0
    def __init__(self, req_client: HuobiDM, symbol='BCH_CW', interval=CandlestickInterval.MIN1, size=200, file_name=None):
        self.req_client = req_client
        self.symbol = symbol
        self.interval = interval
        self.size = size

        self.file_name = file_name if file_name else self.__class__.__name__
        self.json_data = load_json(self.file_name)

        self.strategy_pos = 0.0  # 给个默认的值
        self.boll_up = 0.0
        self.boll_dn = 0.0
        self.boll_mid = 0.0

        for key in self.variables:
            self.__setattr__(key, float(self.json_data.get(key, 0)))

        print(f"self.strategy_pos: {self.strategy_pos}")
        self.open_orders = []
        self.pos_dict = {}  # 默认的仓位信息.

        # 策略的参数.
        self.boll_window = 40  # 布林带的window
        self.boll_dev = 2.5  # 布林带的标准差倍数.
        self.trade_money = 1  # 10USDT.  每次交易的金额, 修改成自己下单的金额.
        self.min_volume = 0.001  # 最小的交易数量.
        self.trade_size = 0
        self.last_price = 0

        self.klines = req_client.get_contract_kline(symbol=symbol, period=interval, size=size)["data"]
        if not self.klines:
            raise HuobiApiException(HuobiApiException.INPUT_ERROR, "klines data init error")

        self.logger = logging.getLogger(__name__)
예제 #6
0
def check_range(value, min_value, max_value, name):
    if value is None:
        return
    if min_value > value or value > max_value:
        raise HuobiApiException(HuobiApiException.INPUT_ERROR,
                                "[Input] " + name + " is out of bound. " + str(value) + " is not in [" + str(
                                    min_value) + "," + str(max_value) + "]")
예제 #7
0
 def update_kline(self):
     if not self.klines:
         raise HuobiApiException(HuobiApiException.INPUT_ERROR,
                                 "klines is not init")
     new_klines = self.req_client.get_contract_kline(symbol=self.symbol,
                                                     period=self.interval,
                                                     size=2)["data"]
     if new_klines[-1]["id"] == self.klines[-1]["id"]:
         self.klines[-1] = new_klines[-1]
     elif new_klines[-2]["id"] == self.klines[-1]["id"]:
         self.klines[-1] = new_klines[-2]
         self.klines.append(new_klines[-1])
         if len(self.klines) > self.size:
             self.klines.pop(0)
     else:
         raise HuobiApiException(HuobiApiException.INPUT_ERROR,
                                 "update klines error")
예제 #8
0
 def get_account_by_id(self, api_key, account_id):
     user = self.get_user(api_key)
     account = user.get_account_by_id(account_id)
     if account is None:
         raise HuobiApiException(
             HuobiApiException.RUNTIME_ERROR,
             "[User] Cannot find the account, key: " + api_key +
             ", account id: " + str(account_id))
     return account
예제 #9
0
파일: user.py 프로젝트: drupal6/coin-client
    def get_account_by_id(self, account_id):
        """
        Get account by account id.

        :param account_id: The specified account id.
        :return: The account.
        """
        for account in self.accounts:
            if account.id == account_id:
                return account
        raise HuobiApiException(HuobiApiException.INPUT_ERROR,
                                "[Input] No such account")
예제 #10
0
def check_response(json_wrapper):
    if json_wrapper.contain_key("status"):
        status = json_wrapper.get_string("status")
        if status == "error":
            err_code = json_wrapper.get_string("err-code")
            err_msg = json_wrapper.get_string("err-msg")
            raise HuobiApiException(HuobiApiException.EXEC_ERROR,
                                    "[Executing] " + err_code + ": " + err_msg)
        elif status != "ok":
            raise HuobiApiException(
                HuobiApiException.RUNTIME_ERROR,
                "[Invoking] Response is not expected: " + status)
    elif json_wrapper.contain_key("success"):
        success = json_wrapper.get_boolean("success")
        if success is False:
            err_code = etf_result_check(json_wrapper.get_int("code"))
            err_msg = json_wrapper.get_string("message")
            if err_code == "":
                raise HuobiApiException(HuobiApiException.EXEC_ERROR,
                                        "[Executing] " + err_msg)
            else:
                raise HuobiApiException(
                    HuobiApiException.EXEC_ERROR,
                    "[Executing] " + err_code + ": " + err_msg)
    elif json_wrapper.contain_key("code"):
        code = json_wrapper.get_int("code")
        if code != 200:
            raise HuobiApiException(HuobiApiException.EXEC_ERROR,
                                    "[Executing] " + str(code))
    else:
        raise HuobiApiException(
            HuobiApiException.RUNTIME_ERROR,
            "[Invoking] Status cannot be found in response.")
예제 #11
0
파일: user.py 프로젝트: drupal6/coin-client
    def get_account_by_type(self, account_type, subtype: 'str' = None):
        """
        Get account by account type.

        :param account_type: The specified account type.
        :param subtype: for margin trade
        :return: The account.
        """
        margin_account_type_list = [AccountType.MARGIN]
        if account_type in margin_account_type_list and subtype is None or len(
                subtype) == 0:
            raise HuobiApiException(
                HuobiApiException.INPUT_ERROR,
                "[Input] subtype for margin account error")
        for account in self.accounts:
            if account.account_type == account_type:
                if account_type in margin_account_type_list:
                    if account.subtype == subtype:
                        return account
                else:
                    return account
        raise HuobiApiException(HuobiApiException.INPUT_ERROR,
                                "[Input] No such account")
예제 #12
0
def update_klines(klins, new_klines, size):
    if len(new_klines) == 1:
        if new_klines[-1]["id"] == klins[-1]["id"]:
            klins = new_klines[-1]
        else:
            klins.append(new_klines[-1])
            if len(klins) > size:
                klins.pop(0)
    else:
        if new_klines[-1]["id"] == klins[-1]["id"]:
            klins = new_klines[-1]
        elif new_klines[-2]["id"] == klins[-1]["id"]:
            klins[-1] = new_klines[-2]
            klins.append(new_klines[-1])
            if len(klins) > size:
                klins.pop(0)
        else:
            raise HuobiApiException(HuobiApiException.INPUT_ERROR,
                                    "update klines error")
예제 #13
0
def create_signature_v2(api_key, secret_key, method, url, builder):
    if api_key is None or secret_key is None or api_key == "" or secret_key == "":
        raise HuobiApiException(HuobiApiException.KEY_MISSING,  "API key and secret key are required")

    timestamp = utc_now()
    builder.put_url("accessKey", api_key)
    builder.put_url("signatureVersion", "2.1")
    builder.put_url("signatureMethod", "HmacSHA256")
    builder.put_url("timestamp", timestamp)

    host = urllib.parse.urlparse(url).hostname
    path = urllib.parse.urlparse(url).path

    # 对参数进行排序:
    keys = sorted(builder.param_map.keys())
    # 加入&
    qs0 = '&'.join(['%s=%s' % (key, parse.quote(builder.param_map[key], safe='')) for key in keys])
    # 请求方法,域名,路径,参数 后加入`\n`
    payload0 = '%s\n%s\n%s\n%s' % (method, host, path, qs0)
    dig = hmac.new(secret_key.encode('utf-8'), msg=payload0.encode('utf-8'), digestmod=hashlib.sha256).digest()
    # 进行base64编码
    s = base64.b64encode(dig).decode()
    builder.put_url("signature", s)
    builder.put_url("authType", "api")

    params = {
        "accessKey": api_key,
        "signatureVersion": "2.1",
        "signatureMethod": "HmacSHA256",
        "timestamp": timestamp,
        "signature":s,
        "authType":"api"
    }

    builder.put_url("action", "req")
    builder.put_url("ch", "auth")
    builder.put_url("params", params)

    """
예제 #14
0
def check_symbol(symbol):
    if not isinstance(symbol, str):
        raise HuobiApiException(HuobiApiException.INPUT_ERROR, "[Input] symbol must be string")
    if re.match(reg_ex, symbol):
        raise HuobiApiException(HuobiApiException.INPUT_ERROR, "[Input] " + symbol + "  is invalid symbol")
예제 #15
0
def greater_or_equal(value, base, name):
    if value is not None and value < base:
        raise HuobiApiException(HuobiApiException.INPUT_ERROR,
                                "[Input] " + name + " should be greater than " + base)
예제 #16
0
 def __check_mandatory_field(self, name):
     if name not in self.json_object:
         raise HuobiApiException(
             HuobiApiException.RUNTIME_ERROR,
             "[Json] Get json item field: " + name + " does not exist")
예제 #17
0
def check_should_none(value, name):
    if value is not None:
        raise HuobiApiException(HuobiApiException.INPUT_ERROR, "[Input] " + name + " should be null")
예제 #18
0
def check_currency(currency):
    if not isinstance(currency, str):
        raise HuobiApiException(HuobiApiException.INPUT_ERROR, "[Input] currency must be string")
    if re.match(reg_ex, currency) is not None:
        raise HuobiApiException(HuobiApiException.INPUT_ERROR, "[Input] " + currency + "  is invalid currency")
예제 #19
0
def check_symbol_list(symbols):
    if not isinstance(symbols, list):
        raise HuobiApiException(HuobiApiException.INPUT_ERROR, "[Input] symbols in subscription is not a list")
    for symbol in symbols:
        check_symbol(symbol)
예제 #20
0
 def on_error(self, error_message):
     if self.request.error_handler is not None:
         exception = HuobiApiException(HuobiApiException.SUBSCRIPTION_ERROR,
                                       error_message)
         self.request.error_handler(exception)
     self.logger.error("[Sub][" + str(self.id) + "] " + str(error_message))