Example #1
0
def buy_byprice(money, price, rate=1):
    num = money * rate / price
    hb.send_order(num,
                  symbol='btcusdt',
                  _type='buy-limit',
                  price=price,
                  source='api')
Example #2
0
def init_context():
    precision_data = houbi.get_symbol_precision(context['base'],
                                                context['quote'])
    context['price_precision'] = precision_data['price-precision']
    context['amount_precision'] = precision_data['amount-precision']
    context['dollars_per_share'] = (1.0 /
                                    (10**context['price_precision'])) * 100
    context['symbol'] = context['base'] + context['quote']

    # 获取账号的信息
    context['base_amount'] = houbi.get_symbol_balance(context['base'])
    context['quote_amount'] = houbi.get_symbol_balance(context['quote'])
Example #3
0
def handel_data():
    if context['sys1']:
        size = context['short_in_date']

    # 获取最新的市场数据
    market_data = houbi.get_kline(context['symbol'], context['period'],
                                  size + 1)['data']
    # 获取当前行情数据
    price = float(houbi.get_current_price(context['symbol']))
    # 计算ATR
    atr = cal_atr(market_data)

    # 2 判断加仓或止损
    if context['hold_flage'] is True and float(
            context['base_amount']) > 0:  # 先判断是否持仓
        temp = add_or_stop(price, float(context['break_price']), atr)
        if temp == 1:  # 判断加仓
            if int(context['add_time']) < int(
                    context['unit_limit']):  # 判断加仓次数是否超过上限
                print(f"产生加仓信号,加仓价格是:{price}")
                buy(atr, price)
                context['add_time'] += 1
                context['break_price'] = price
            else:
                print("加仓次数已经达到上限,不会加仓")
        elif temp == -1:  # 判断止损
            # 卖出止损
            print("产生止损信号")
            sell(price)
    else:
        # 根据当前价格判断入场还是出场
        in_out_flage = in_out(price, market_data, size)
        if in_out_flage == 1:  # 入场
            if context['hold_flage'] is False and float(
                    context['quote_amount']) > 0:
                # 有买入信号,执行买入
                print(f"产生入场信号, 突破价格是{price}")
                buy(atr, price)
                context['add_time'] = 1
                context['hold_flage'] = True
                context['break_price'] = price
            else:
                print("已经入场,不产生入场信号")
        elif in_out_flage == -1:  # 离场
            if context['hold_flage'] is True:
                if float(context['base_amount']) > 0:
                    print("产生离场信号")
                    sell(price)
            else:
                print("尚未入场或已经离场,不产生离场信号")
Example #4
0
def depth_main(num_str):
    q = huobi_py.get_depth(num_str.split(' ')[0], num_str.split(' ')[1])
    bids = [i[0] * i[1] for i in q['tick']['bids']]
    asks = [i[0] * i[1] for i in q['tick']['asks']]
    return (float(np.sum(bids) - np.sum(asks)),
            1.0 * (np.sum(bids) - np.sum(asks)) /
            np.sum(np.sum(bids) + np.sum(asks)))
Example #5
0
def Signal2(coin_symbol,para_min,para_up,para_low,show_len):
    resu_temp = hb.get_kline(coin_symbol, para_min,show_len)

    up_limit = para_up
    low_limit = para_low
    cur_kline_ts = resu_temp['data'][0]['id']
    date_seq = [time.strftime("%Y-%m-%d-%H-%M", time.localtime(int(x['id']))) for x in resu_temp['data']][::-1]

    amount_temp = [x['vol'] for x in resu_temp['data']]
    amount = np.array(amount_temp[::-1])

    vol_temp = [x['amount'] for x in resu_temp['data']]
    vol = np.array(vol_temp[::-1])

    # close_temp = [x['close'] for x in resu_temp['data']][1:]
    # close = np.array(close_temp[::-1])

    price_avg_long = float(amount.sum() / vol.sum())
    price_avg_short = float(amount[-1] / vol[-1])

    action_flag = 0
    delt = price_avg_short - price_avg_long
    if price_avg_short - price_avg_long > para_up:
        action_flag = -1
    elif price_avg_short - price_avg_long < para_low:
        action_flag = 1

    return action_flag,cur_kline_ts,up_limit,low_limit,delt
Example #6
0
def Acct_Info():
    resu = hb.get_balance(378)
    if resu['status'] == 'error':
        print('Acct_Info Errrrrr')
        return -1
    else:
        usdt_trade = []
        usdt_all = []
        btc_trade = []
        btc_all = []
        eos_trade = []
        eos_all = []
        resu_data = resu['data']['list']
        for i in range(len(resu_data)):
            if resu_data[i]['currency'] == 'usdt':
                usdt_all.append(float(resu_data[i]['balance']))
                if resu_data[i]['type'] == 'trade':
                    usdt_trade.append(float(resu_data[i]['balance']))
            elif resu_data[i]['currency'] == 'btc':
                btc_all.append(float(resu_data[i]['balance']))
                if resu_data[i]['type'] == 'trade':
                    btc_trade.append(float(resu_data[i]['balance']))
            elif resu_data[i]['currency'] == 'eos':
                eos_all.append(float(resu_data[i]['balance']))
                if resu_data[i]['type'] == 'trade':
                    eos_trade.append(float(resu_data[i]['balance']))
        ans_usdt = float(np.array(usdt_trade).sum())
        ans_usdt_all = float(np.array(usdt_all).sum())
        ans_btc = float(math.floor(np.array(btc_all).sum() * 1000) / 1000)
        ans_btc_trade = float(math.floor(np.array(btc_trade).sum() * 1000) / 1000)
        ans_eos = float(math.floor(np.array(eos_all).sum() * 100) / 100)
        ans_eos_trade = float(math.floor(np.array(eos_trade).sum() * 100) / 100)
        return ans_usdt, ans_usdt_all,ans_btc,ans_btc_trade, ans_eos,ans_eos_trade
Example #7
0
def Signal(coin_symbol,para_min,para_up,para_low):
    resu_temp = hb.get_kline(coin_symbol, para_min, 201)
    cur_kline_ts = resu_temp['data'][0]['id']

    #date_seq = [time.strftime("%Y-%m-%d-%H-%M", time.localtime(int(x['id']))) for x in resu_temp['data']][::-1]
    close_temp = [x['close'] for x in resu_temp['data']][1:]
    close = np.array(close_temp[::-1])

    macd_temp = ta.MACD(close, 12, 26, 9)
    up_limit = np.array([x for x in macd_temp[2] if str(x) != 'nan' and x > 0]).max() * para_up
    low_limit = np.array([x for x in macd_temp[2] if str(x) != 'nan' and x < 0]).min() * para_low

    up_mean = np.array([x for x in macd_temp[2] if str(x) != 'nan' and x > 0]).mean()
    low_mean = np.array([x for x in macd_temp[2] if str(x) != 'nan' and x < 0]).mean()
    #macd = macd_temp[2][-1]
    #print(macd*2)

    action_flag = 0

    # flag
    if (((macd_temp[2][-1] + macd_temp[2][-2] + macd_temp[2][-3]) * 2) < low_limit) and (
            macd_temp[2][-2] < macd_temp[2][-1]) and (macd_temp[2][-2] < macd_temp[2][-3]) and (
            macd_temp[2][-1] < 0) and (macd_temp[2][-3] < 0) and (
            macd_temp[2][-1] - macd_temp[2][-2] < abs(para_low * low_mean)):
        action_flag = 1
    elif (((macd_temp[2][-1] + macd_temp[2][-2] + macd_temp[2][-3]) * 2) > up_limit) and (
            macd_temp[2][-2] > macd_temp[2][-1]) and (macd_temp[2][-2] > macd_temp[2][-3]) and (
            macd_temp[2][-1] > 0) and (macd_temp[2][-3] > 0) and (
            macd_temp[2][-2] - macd_temp[2][-1] < abs(para_up * up_mean)):
        action_flag = -1
    return action_flag,cur_kline_ts,up_limit,low_limit
Example #8
0
 def get_curr_order(self, exCoin, tradetype):
     try:
         for i in range(3):
             try:
                 rq_ord_curr = HuobiServices.orders_list(
                     exCoin, 'submitted,partial-filled', None, '2018-07-01',
                     None, None, 'next', None)
             except Exception as ex:
                 print(Exception, ":", ex)
                 continue
             if rq_ord_curr.find('"status":"ok"') != -1:
                 break
             else:
                 print("order_curr,order_curr")
                 time.sleep(5)
         if rq_ord_curr.find(tradetype) != -1:
             orders = json.loads(rq_ord_curr)['data']
             for i in orders:
                 if str(i).find("'type': '" + tradetype + "'") != -1:
                     order_id = i['id']
                     creat_time = i['created-at']
                     set_price = i['price']
                     break
             return [str(order_id), str(creat_time), str(set_price)]
         else:
             return []
     except Exception as ex:
         print(Exception, ":", ex)
         return
Example #9
0
 def get_filled_buy_order(self, exCoin, coin):
     try:
         buy_time = []
         buy_price = []
         for i in range(3):
             try:
                 rq_ord_filled = HuobiServices.orders_matchresults(
                     exCoin, None, '2018-07-01', None, None, 'next', None)
             except Exception as ex:
                 print(Exception, ":", ex)
                 continue
             if rq_ord_filled.find('"status":"ok"') != -1:
                 orders = json.loads(rq_ord_filled)['data']
                 break
             else:
                 print("order_fill,order_fill")
                 print(rq_ord_filled)
                 time.sleep(5)
         for i in orders:
             if str(i).find("'type': 'sell-limit'") != -1:
                 if orders.index(i) == 0 and float(self.account(coin)) > 1:
                     continue
                 else:
                     break
             elif str(i).find("'type': 'buy-limit'") != -1:
                 creat_time = i['created-at']
                 buy_time.append(str(creat_time))
                 set_price = i['price']
                 buy_price.append(str(set_price))
         return [list(reversed(buy_time)), list(reversed(buy_price))]
     except Exception as ex:
         print(Exception, ":", ex)
         return
Example #10
0
    def get_huobi_orderboook (self, currency ="btc"):
        huobiDepth = Huobi.get_depth(currency.lower() + "usdt", "step0")

        self.huobi = {}
        self.huobi.update(asks=huobiDepth['tick']['asks'][:self.amount])
        self.huobi.update(bids=huobiDepth['tick']['bids'][:self.amount])
        tick2 = time.time()
Example #11
0
    def get_huobi_depth(self,currency = ""):
        if currency == "":
            currency = self.currency

        huobiDepth = huobi.get_depth(currency.lower()+"usdt","step0")
        self.marketDepth['asks'] = huobiDepth['tick']['asks']
        self.marketDepth['bids'] = huobiDepth['tick']['bids']
Example #12
0
def Signal(coin_symbol,para_min,para_up,para_low,show_len):
    resu_temp = hb.get_kline(coin_symbol, para_min, 200+show_len)
    cur_kline_ts = resu_temp['data'][0]['id']
    date_seq = [time.strftime("%Y-%m-%d-%H-%M", time.localtime(int(x['id']))) for x in resu_temp['data']][::-1]

    amount_temp = [x['vol'] for x in resu_temp['data']]
    amount = np.array(amount_temp[::-1])

    vol_temp = [x['amount'] for x in resu_temp['data']]
    vol = np.array(vol_temp[::-1])

    close_temp = [x['close'] for x in resu_temp['data']]
    close = np.array(close_temp[::-1])

    price_avg_long0 = []
    price_avg_long = []
    price_avg_short = []
    price_close = []
    delt_list = []
    for i in range(201,len(amount)):
        price_avg_long.append(float(amount[i-200:i+1].mean()/vol[i-200:i+1].mean()))
        price_avg_long0.append(float(amount[:i + 1].mean() / vol[:i + 1].mean()))
        if vol[i] == 0:
            temp_short = price_avg_short[-1]
            price_avg_short.append(temp_short)
        else:
            price_avg_short.append(float(amount[i]/vol[i]))
        price_close.append(close[i])
        delt_list.append(float(amount[i-200:i+1].mean()/vol[i-200:i+1].mean()) / float(amount[i-1-200:i].mean()/vol[i-1-200:i].mean()))

    resu = []
    color = []
    macd_temp = ta.MACD(close, 12, 26, 9)
    # up_limit = np.array([x for x in macd_temp[2] if str(x) != 'nan' and x > 0]).max() * para_up
    # low_limit = np.array([x for x in macd_temp[2] if str(x) != 'nan' and x < 0]).min() * para_low
    # up_mean = np.array([x for x in macd_temp[2] if str(x) != 'nan' and x > 0]).mean()
    # low_mean = np.array([x for x in macd_temp[2] if str(x) != 'nan' and x < 0]).mean()
    macd_list = macd_temp[2][len(macd_temp[2])-len(price_close):len(macd_temp[2])]

    #macd_list = [x for x in macd_temp[2] if str(x) != 'nan']

    deal_list = []
    for j in range(len(macd_list)):
        macd = macd_list[j]
        action_flag = 0
        if j > 1:
            if macd_list[j-2] > macd_list[j-1] and macd_list[j] > macd_list[j-1] and macd_list[j] < 0 and macd_list[j-2] < 0 and (macd_list[j-2]+macd_list[j-1]+macd_list[j])<-0.1:
                action_flag = 1
            elif macd_list[j-2] < macd_list[j-1] and macd_list[j] < macd_list[j-1] and macd_list[j] > 0 and macd_list[j-2] > 0 and (macd_list[j-2]+macd_list[j-1]+macd_list[j])>0.1:
                action_flag = -1
        if action_flag != 0:
            deal_list.append(j)
        if macd >= 0:
            color.append('g')
        else:
            color.append('r')
        resu.append(macd)

    return price_avg_long0,price_avg_long,price_avg_short,price_close,delt_list,macd_list,color,deal_list
Example #13
0
    def get_huobi_ticker(self, currency = ""):
        if currency == "":
            currency = self.currency

        huobiTicker = huobi.get_ticker(currency.lower()+"usdt")['tick']
        huobiTicker['askPrice'] = huobiTicker['ask'][0]
        huobiTicker['bidPrice'] = huobiTicker['bid'][0]
        self.btcQuote['global']['ticker'] = huobiTicker
def get_symbols():
    # symbols = ['btcusdt', 'bchusdt', 'ethusdt', 'etcusdt', 'ltcusdt', 'eosusdt', 'adausdt', 'xrpusdt', 'omgusdt', 'iotausdt', 'steemusdt', 'dashusdt', 'zecusdt', 'hb10usdt']
    # symbols += ['bchbtc', 'ethbtc', 'ltcbtc', 'etcbtc', 'eosbtc', 'adabtc', 'xrpbtc', 'iotabtc', 'omgbtc', 'dashbtc', 'steembtc', 'zecbtc', 'xmrbtc']
    # symbols += ['eoseth', 'adaeth', 'omgeth', 'xmreth', 'steemeth', 'iotaeth']
    raw_data = hs.get_symbols()
    symbols = []
    for x in raw_data['data']:
        symbols.append(x['symbol'])
    return symbols
Example #15
0
def getlast5close():
    history_close = []
    datas = hb.get_kline('btcusdt', '1min', size=5)
    if datas is not None:
        if 'data' in datas:
            last5info = datas['data']
            for info in last5info:
                history_close.append(info['close'])
    return history_close
Example #16
0
def get_cur_price_by_kline():
    res = hb.get_kline('btcusdt', '5min')
    if res:
        res = res.get('data')
        cur_price = res[0].get('close')
        # print(res)
        #print('price:{}'.format(cur_price))
        return cur_price
    else:
        return None
Example #17
0
def get_last_order(coin_symbol,type):
    # 获取上一次市价买单的成交价(即成本价)
    last_order_temp = hb.orders_list(symbol=coin_symbol, states='filled', direct='next',types=type)
    last_order_dict = last_order_temp['data']
    last_price = 0.00
    for i in range(len(last_order_dict)):
        if str(last_order_dict[i]['type'])[:4] == str(type)[:4]:
            last_order_id = last_order_dict[i]['id']
            last_price = float(last_order_dict[i]['field-cash-amount']) / float(last_order_dict[i]['field-amount'])
            break
    return last_price
Example #18
0
def Acct_Info(curr_type):
    resu = hb.get_balance(xxxxxxxx)
    if resu['status'] == 'error':
        print('Acct_Info Errrrrr')
        return -1
    else:
        resu_data = resu['data']['list']
        for i in range(len(resu_data)):
            if resu_data[i]['currency'] == curr_type and resu_data[i]['type'] == 'trade':
                return float(resu_data[i]['balance'])
        return 0
Example #19
0
def get_portfolio(coin_list,para_min):

    #获取 k 线数据,检查时间戳,不一致的话返回[]
    init_ts = ''
    list_return = []
    for i in range(len(coin_list)):
        resu_temp = hb.get_kline(str(coin_list[i]) + 'usdt', para_min, 201)
        cur_kline_ts = resu_temp['data'][0]['id']
        if i == 0:
            init_ts = cur_kline_ts
        elif init_ts != cur_kline_ts:
            return []

        #date_seq = [time.strftime("%Y-%m-%d-%H-%M", time.localtime(int(x['id']))) for x in resu_temp['data']][::-1]
        close_temp = [x['close'] for x in resu_temp['data']][1:]
        close = np.array(close_temp[::-1])

        if len(close) != 200:
            return []

        ri = []
        ri = close/close[0]
        ri = ri - 1.0
        ri = ri * 100
        list_return.append(ri)
    #list_return.append(np.array([float(0.00)] * 200))


    # 求协方差矩阵
    cov = np.cov(np.array(list_return))
    # 求特征值和其对应的特征向量
    ans = np.linalg.eig(cov)
    # 排序,特征向量中负数置0,非负数归一
    ans_index = copy.copy(ans[0])
    ans_index.sort()
    resu = []
    for k in range(len(ans_index)):
        con_temp = []
        con_temp.append(ans_index[k])
        content_temp1 = ans[1][np.argwhere(ans[0] == ans_index[k])[0][0]]
        content_temp2 = []
        #content_sum = np.array([x for x in content_temp1 if x >= 0.00]).sum()
        content_sum = np.array([abs(x) for x in content_temp1]).sum()
        for m in range(len(content_temp1)):
            content_temp2.append(abs(content_temp1[m]) / content_sum)
            # if content_temp1[m] >= 0 and content_sum > 0:
            #     content_temp2.append(content_temp1[m]/content_sum)
            # else:
            #     content_temp2.append(0.00)

        con_temp.append(content_temp2)
        resu.append(con_temp)

    return resu
Example #20
0
def getcoin():
    if request.method == 'POST' and request.is_json:
        coin_name = request.get_json()['coin_name']
        period = request.get_json()['period']
        size1 = request.get_json()['size']
        size = int(size1)
        result = api.get_kline(coin_name, period, size)
        #print(coin_name,period,size)
        #print(result)
        json.dump(result)
        return result
Example #21
0
def get_cur_acount(itype):
    acct_id = hb.get_accounts()
    #print(acct_id)
    idLists = acct_id['data']
    masterid = idLists[0]['id']
    master_balance = hb.get_balance(masterid)
    balancelists = master_balance['data']['list']
    res = []
    for listnum in balancelists:
        if (itype == 'usdt'):
            if (listnum['currency'] == 'usdt'):
                return float(listnum['balance'])
        elif (itype == 'btc'):
            if (listnum['currency'] == 'btc'):
                return float(listnum['balance'])
        else:
            if (listnum['currency'] == 'usdt' and listnum['type'] == 'trade'):
                res.append(listnum['balance'])
            if (listnum['currency'] == 'btc' and listnum['type'] == 'trade'):
                res.append(listnum['balance'])
    return res
Example #22
0
def Signal(coin_symbol, para_min, para_up, para_low):
    resu_temp = hb.get_kline(coin_symbol, para_min, 200)
    cur_kline_ts = resu_temp['data'][0]['id']

    date_seq = [
        time.strftime("%Y-%m-%d-%H-%M", time.localtime(int(x['id'])))
        for x in resu_temp['data']
    ][::-1]
    close_temp = [x['close'] for x in resu_temp['data']][1:]
    close = np.array(close_temp[::-1])

    resu = []
    color = []
    macd_temp = ta.MACD(close, 12, 26, 9)
    up_limit = np.array([x for x in macd_temp[2] if str(x) != 'nan' and x > 0
                         ]).max() * para_up
    low_limit = np.array(
        [x
         for x in macd_temp[2] if str(x) != 'nan' and x < 0]).min() * para_low
    up_mean = np.array([x for x in macd_temp[2]
                        if str(x) != 'nan' and x > 0]).mean()
    low_mean = np.array([x for x in macd_temp[2]
                         if str(x) != 'nan' and x < 0]).mean()
    macd_list = [x for x in macd_temp[2] if str(x) != 'nan']
    for i in range(len(macd_list)):
        macd = macd_list[i]
        if macd >= 0:
            color.append('g')
        else:
            color.append('r')
        resu.append(macd)

    action_flag = 0

    # flag
    if (((macd_temp[2][-1] + macd_temp[2][-2] + macd_temp[2][-3]) *
         2) < low_limit) and (macd_temp[2][-2] < macd_temp[2][-1]) and (
             macd_temp[2][-2] < macd_temp[2][-3]
         ) and (macd_temp[2][-1] < 0) and (macd_temp[2][-3] < 0) and (
             macd_temp[2][-1] - macd_temp[2][-2] < abs(para_low * low_mean)):
        action_flag = 1
    elif (((macd_temp[2][-1] + macd_temp[2][-2] + macd_temp[2][-3]) * 2) >
          up_limit) and (macd_temp[2][-2] > macd_temp[2][-1]) and (
              macd_temp[2][-2] > macd_temp[2][-3]
          ) and (macd_temp[2][-1] > 0) and (macd_temp[2][-3] > 0) and (
              macd_temp[2][-2] - macd_temp[2][-1] < abs(para_up * up_mean)):
        action_flag = -1
    return action_flag, resu, color, up_limit, low_limit
Example #23
0
 def cancel_order(self, exCoin, tradetype):
     try:
         for i in range(3):
             try:
                 rq_ord_cancel = HuobiServices.cancel_order(
                     self.get_curr_order(exCoin, tradetype)[0])
             except Exception as ex:
                 print(Exception, ":", ex)
                 continue
             if rq_ord_cancel.find('"status":"ok"') != -1:
                 break
             else:
                 print("cancel_order,cancel_order")
                 time.sleep(5)
     except Exception as ex:
         print(Exception, ":", ex)
         return
Example #24
0
 def account(self, coin):
     try:
         for i in range(3):
             try:
                 rq_acc = HuobiServices.get_balance('443597')
             except:
                 continue
             if rq_acc.find('"status":"ok"') != -1:
                 l = re.search(
                     '"currency":"' + coin +
                     '","type":"trade","balance":"(.+?)"', rq_acc).group(1)
                 break
             else:
                 print("accout,accout")
                 time.sleep(5)
         return l
     except Exception as ex:
         print(Exception, ":", ex)
         return
Example #25
0
 def trade(self, coin, exCoin, tradeType, tradePrice):
     try:
         for i in range(3):
             try:
                 rq_tra = HuobiServices.send_order(
                     self.get_coin_amount(coin, exCoin), 'spot-app', exCoin,
                     tradeType, tradePrice)
             except Exception as ex:
                 print(Exception, ":", ex)
                 continue
             if rq_tra.find('"status":"ok"') != -1:
                 print(rq_tra)
                 break
             else:
                 print("trade,trade 11")
                 time.sleep(5)
     except Exception as ex:
         print(Exception, ":", ex)
         return
Example #26
0
def get_avg_order(coin_symbol,cur_price):
    # 获取上一次市价买单的成交价(即成本价)
    resu_orders_temp = hb.orders_matchresults(symbol=coin_symbol, direct='next')
    resu_orders_dict = resu_orders_temp['data']
    his_amount = []
    his_vol = []
    last_buy_ts = 0
    for i in range(len(resu_orders_dict)):
        if str(resu_orders_dict[i]['type'])[:4] == 'sell':
            break
        elif str(resu_orders_dict[i]['type'])[:3] == 'buy':
            his_amount.append(float(resu_orders_dict[i]['price'])*float(resu_orders_dict[i]['filled-amount']))
            his_vol.append(float(resu_orders_dict[i]['filled-amount']))
            last_buy_ts = max(last_buy_ts,int(resu_orders_dict[i]['created-at']))
    if len(his_amount) == 0:
        return 0.00,0
    else:
        ans = float((np.array(his_amount).mean())/(np.array(his_vol).mean()))
        return ans,math.floor(last_buy_ts/1000)
Example #27
0
def Signal2(coin_symbol, para_min, para_up, para_low, show_len):
    resu_temp = hb.get_kline(coin_symbol, para_min, show_len)

    cur_kline_ts = resu_temp['data'][0]['id']
    date_seq = [time.strftime("%Y-%m-%d-%H-%M", time.localtime(int(x['id']))) for x in resu_temp['data']][::-1]

    amount_temp = [x['vol'] for x in resu_temp['data']]
    amount = np.array(amount_temp[::-1])

    vol_temp = [x['amount'] for x in resu_temp['data']]
    vol = np.array(vol_temp[::-1])

    close_temp = [x['close'] for x in resu_temp['data']][1:]
    close = np.array(close_temp[::-1])

    std = close.std()
    up_limit = para_up*std
    low_limit = para_low*std
    macd_temp = ta.MACD(close, 12, 26, 9)
    action_flag1 = 0
    if (macd_temp[2][-2] < macd_temp[2][-1]) and (macd_temp[2][-2] < macd_temp[2][-3]) and (macd_temp[2][-1] < 0) and (macd_temp[2][-3] < 0) and (macd_temp[2][-3]+macd_temp[2][-2]+macd_temp[2][-1]) < -0.079:
        action_flag1 = 1
    elif (macd_temp[2][-2] > macd_temp[2][-1]) and (macd_temp[2][-2] > macd_temp[2][-3]) and (macd_temp[2][-1] > 0) and (macd_temp[2][-3] > 0) and (macd_temp[2][-3]+macd_temp[2][-2]+macd_temp[2][-1]) > 0.079:
        action_flag1 = -1

    price_avg_long = float(amount.sum() / vol.sum())
    price_avg_short = float(amount[-1] / vol[-1])

    action_flag2 = 0
    delt = price_avg_short - price_avg_long
    if price_avg_short - price_avg_long > para_up*std:
        action_flag2 = -1
    elif price_avg_short - price_avg_long < para_low*std:
        action_flag2 = 1

    action_flag = 0
    if action_flag1 == action_flag2 == 1 :
        action_flag = 1
    elif action_flag1 == action_flag2 == -1 :
        action_flag = -1
    return action_flag, cur_kline_ts, up_limit, low_limit, delt,std
Example #28
0
 def get_jingdu(self, coin, precision_type):
     try:
         for i in range(3):
             try:
                 rq_jingdu = HuobiServices.get_symbols()
             except:
                 continue
             if rq_jingdu.find('"status":"ok"') != -1:
                 jingdu = json.loads(rq_jingdu)['data']
                 break
             else:
                 print("jingdu,jingdu,jingdu")
                 time.sleep(5)
         for i in jingdu:
             if i['base-currency'] == coin and i['quote-currency'] == 'usdt':
                 amount = i[precision_type]
                 return int(amount)
                 break
     except Exception as ex:
         print(Exception, ":", ex)
         return
Example #29
0
 def get_data(self, exCoin, period, size):
     try:
         List_data = []
         for i in range(3):
             try:
                 rq_data = HuobiServices.get_kline(exCoin, period, size)
             except:
                 continue
             if rq_data.find('"status":"ok"') != -1:
                 market = json.loads(rq_data)['data']
                 break
             else:
                 print("data,data,data")
                 print(rq_data)
                 time.sleep(5)
         for i in market:
             List_data.append(float(i['close']))
         return list(reversed(List_data))
     except Exception as ex:
         print(Exception, ":", ex)
         return
Example #30
0
def produce_model(timeInterval,column):
	
	np.random.seed(42)
	global data
	data = hb.get_kline('btcusdt', timeInterval, size=2000)
	data['data'].reverse()
	hist = pd.DataFrame(data['data'])
	hist = hist.set_index('id')
	hist.index = pd.to_datetime(hist.index, unit='s')
	hist_t = hist[:-1]
	target_col = column


	# data params
	window_len = 7
	zero_base = True

	# model params
	lstm_neurons = 20
	epochs = 50
	batch_size = 4
	loss = 'mae'
	dropout = 0.25
	optimizer = 'adam'
	#df, target_col, window_len=10, zero_base=True, test_size=0.2
	X_train, y_train = prepare_data(hist_t, target_col, window_len=window_len, zero_base=zero_base)
	global model_close
	global model_high
	global model_low
	if column == 'close':
		model_close = build_lstm_model(X_train, output_size=1, neurons=lstm_neurons, dropout=dropout, loss=loss,optimizer=optimizer)
		history = model_close.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=1, shuffle=True)
	elif column == 'high':
		model_high = build_lstm_model(X_train, output_size=1, neurons=lstm_neurons, dropout=dropout, loss=loss,optimizer=optimizer)
		history = model_high.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=1, shuffle=True)
	else:
		model_low = build_lstm_model(X_train, output_size=1, neurons=lstm_neurons, dropout=dropout, loss=loss,optimizer=optimizer)
		history = model_low.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=1, shuffle=True)