Пример #1
0
 def revoke_order(self, order_id, now_time_sec):
     try:
         self.timeLog('撤单成功,order_id: %s, result: %s, 时间: %s'
                            % (order_id, self.spotAPI.revoke_order(instrument_id, order_id),
                               timestamp2string(now_time_sec)))
         return True
     except Exception as e:
         traceback.print_exc()
         self.timeLog(
             "撤单失败: %s, order_id: %s, 时间: %s" % (repr(e), order_id, timestamp2string(now_time_sec)))
         return False
Пример #2
0
def buyin_more(okFuture,
               coin_name,
               time_type,
               buy_price,
               amount=None,
               lever_rate=20,
               taker=False):
    json_ret = json.loads(okFuture.future_userinfo_4fix())
    balance = float(json_ret["info"][coin_name]["balance"])
    if not amount:
        amount = math.floor(balance * lever_rate * buy_price / 10)

    while amount >= 1:
        if taker:
            ret = okFuture.future_trade(coin_name + "_usd", time_type, '',
                                        amount, 1, 1, lever_rate)
        else:
            ret = okFuture.future_trade(coin_name + "_usd", time_type,
                                        buy_price, amount, 1, 0, lever_rate)
        print(ret)
        if 'true' in ret:
            email_msg = "下单做多%s成功,最新价格: %.4f, 成交张数: %d, 时间: %s, 成交结果: %s" \
                        % (coin_name, buy_price, amount, timestamp2string(time.time()), ret)
            thread.start_new_thread(send_email, (email_msg, ))
            return json.loads(ret)["order_id"]
        amount = math.floor(amount * 0.95)

    return False
Пример #3
0
def sell_more_batch(coin_name, time_type, latest_price, lever_rate = 20):
    global processing
    processing = True
    jRet = json.loads(okFuture.future_position_4fix(coin_name+"_usd", time_type, "1"))
    print(jRet)
    flag = True
    ret = u'没有做多订单'
    while len(jRet["holding"]) > 0:
        cancel_uncompleted_order(coin_name, time_type)
        if flag:
            flag = False
            amount = jRet["holding"][0]["buy_available"]
            order_data = gen_orders_data(latest_price, amount, 3, 5)
            ret = okFuture.future_batchTrade(coin_name + "_usd", time_type, order_data, lever_rate)
        else:
            buy_available = jRet["holding"][0]["buy_available"]
            ret = okFuture.future_trade(coin_name + "_usd", time_type, '', buy_available, 3, 1, lever_rate)
        if 'true' in ret:
            time.sleep(2)
            jRet = json.loads(okFuture.future_position_4fix(coin_name + "_usd", time_type, "1"))

    sell_more_suc()
    email_msg = "做多%s批量卖出成交, 时间: %s, 成交结果: %s" \
                % (coin_name, timestamp2string(time.time()), ret)
    thread.start_new_thread(send_email, (email_msg,))
    processing = False
    return True
Пример #4
0
def ensure_sell_less(coin_name, time_type, lever_rate=20):
    sleep_time = 30
    while sleep_time > 0:
        time.sleep(sleep_time)
        jRet = json.loads(
            okFuture.future_position_4fix(coin_name + "_usd", time_type, "1"))
        if len(jRet["holding"]) > 0:
            cancel_uncompleted_order(coin_name, time_type)
            time.sleep(1)
            jRet = json.loads(
                okFuture.future_position_4fix(coin_name + "_usd", time_type,
                                              "1"))
            sell_available = jRet["holding"][0]["sell_available"]
            okFuture.future_trade(coin_name + "_usd", time_type, '',
                                  sell_available, 4, 1, lever_rate)

        else:
            break
    ts = time.time()
    now_time = timestamp2string(ts)
    info = u'做空卖出成功!!!卖出价格:' + str(latest_price) + u', 收益: ' + str(buy_price - latest_price) \
           + ', ' + now_time
    thread.start_new_thread(send_email, (info, ))
    with codecs.open(file_transaction, 'a+', 'utf-8') as f:
        f.writelines(info + '\n')
Пример #5
0
def sell_more_suc():
    global more
    ts = time.time()
    now_time = timestamp2string(ts)
    info = u'发出卖出信号!!!卖出价格:' + str(latest_price) + u', 收益: ' + str(latest_price - buy_price) \
           + ', ' + now_time
    with codecs.open(file_transaction, 'a+', 'utf-8') as f:
        f.writelines(info + '\n')
    more = 0
Пример #6
0
 def get_account_money(self, coin_name):
     ret = self.spotAPI.get_coin_account_info(coin_name)
     self.timeLog(str(ret))
     coin_balance = float(ret['balance'])
     price = float(self.spotAPI.get_specific_ticker(instrument_id)['last'])
     usdt_ret = self.spotAPI.get_coin_account_info("usdt")
     usdt_balance = float(usdt_ret['balance'])
     self.timeLog(str(usdt_ret))
     total_usdt = coin_balance * price + usdt_balance
     self.timeLog("当前时间: %s, 持有%s: %.4f,单价: %.4f, usdt: %.4f, 折合: %.4f USDT"
                  % (timestamp2string(time.time()), coin_name, coin_balance, price, usdt_balance, total_usdt))
Пример #7
0
 def delete_overdue_order(self, latest_deal_price):
     now_ts = int(time.time())
     self.timeLog('Start to delete pending orders..., %s' % timestamp2string(now_ts))
     orders_list = self.spotAPI.get_orders_list('open', instrument_id)
     self.timeLog('before delete, pending orders num: %d' % len(orders_list))
     for order in orders_list[0]:
         o_price = float(order['price'])
         o_time = string2timestamp(order['timestamp'])
         if o_time < now_ts - 60 or o_price < latest_deal_price * 0.995 or o_price or o_price > 1.005 * latest_deal_price:
             order_id = order['order_id']
             self.revoke_order(order_id, now_ts)
     self.timeLog('Finish delete pending orders')
Пример #8
0
def on_message(ws, message):
    global latest_price, deque_3s, deque_10s, deque_min, deque_3m, deque_15m, \
        ind_3s, ind_10s, ind_1min, ind_3m, ind_15m, write_lines, swap_latest_price

    ts = time.time()
    now_time = timestamp2string(ts)

    message = bytes.decode(inflate(message), 'utf-8')  # data decompress
    json_message = json.loads(message)
    for json_data in json_message['data']:
        ins_id = json_data['instrument_id']
        if ins_id == swap_instrument_id:
            swap_latest_price = float(json_data['last'])
            continue
        latest_price = float(json_data['price'])
        deal_entity = DealEntity(json_data['trade_id'], latest_price, round(float(json_data['size']), 3), ts,
                                 json_data['side'])

        handle_deque(deque_3s, deal_entity, ts, ind_3s)
        handle_deque(deque_10s, deal_entity, ts, ind_10s)
        handle_deque(deque_min, deal_entity, ts, ind_1min)
        handle_deque(deque_3m, deal_entity, ts, ind_3m)
        handle_deque(deque_15m, deal_entity, ts, ind_15m)

        avg_3s_price = ind_3s.cal_avg_price()
        avg_10s_price = ind_10s.cal_avg_price()
        avg_min_price = ind_1min.cal_avg_price()
        avg_3m_price = ind_3m.cal_avg_price()
        price_10s_change = cal_rate(avg_3s_price, avg_10s_price)
        price_1m_change = cal_rate(avg_3s_price, avg_min_price)
        price_3m_change = cal_rate(avg_3s_price, avg_3m_price)
        price_change_3m_ago = cal_rate(latest_price, deque_3m[0].price)

        price_info = deal_entity.type + u' now_price: %.4f, 3s_price: %.4f, 10s_price: %.4f, 1m_price: %.4f, ' \
                                        u'3min_price: %.4f' % (latest_price, avg_3s_price, avg_10s_price, avg_min_price,
                                                               avg_3m_price)
        vol_info = u'cur_vol: %.3f, 3s vol: %.3f, 10s vol: %.3f, 1min vol: %.3f, ask_vol: %.3f, bid_vol: %.3f, ' \
                   u'3s_ask_vol: %.3f, 3s_bid_vol: %.3f, 3min vol: %.3f, 3min_ask_vol: %.3f, 3min_bid_vol: %.3f' \
                   % (deal_entity.amount, ind_3s.vol, ind_10s.vol, ind_1min.vol, ind_1min.ask_vol, ind_1min.bid_vol,
                      ind_3s.ask_vol, ind_3s.bid_vol, ind_3m.vol, ind_3m.ask_vol, ind_3m.bid_vol)
        rate_info = u'10s_rate: %.2f%%, 1min_rate: %.2f%%, 3min_rate: %.2f%%' \
                    % (price_10s_change, price_1m_change, price_3m_change)
        print_message = price_info + u', ' + vol_info + u', ' + rate_info + u', ' + now_time + '\r\n'
        write_lines.append(print_message)
        if len(write_lines) >= 100:
            with codecs.open(file_deal, 'a+', 'UTF-8') as f:
                f.writelines(write_lines)
                write_lines = []
        print('less: %d, more: %d' % (less, more))
        print(price_info + '\r\n' + vol_info + '\r\n' + rate_info + u', ' + now_time)
Пример #9
0
def buyin_more_batch(okFuture,
                     coin_name,
                     time_type,
                     latest_price,
                     lever_rate=20,
                     amount=None):
    json_ret = json.loads(okFuture.future_userinfo_4fix())
    balance = float(json_ret["info"][coin_name]["balance"])
    if amount is None:
        amount = math.floor(balance * lever_rate * latest_price / 10 * 0.9)
    while amount >= 5:
        order_data = gen_orders_data(latest_price, amount, 1, 5)
        ret = okFuture.future_batchTrade(coin_name + "_usd", time_type,
                                         order_data, lever_rate)
        if 'true' in ret:
            email_msg = "批量下单做多%s成功,最新价格: %.4f, 成交张数: %d, 时间: %s, 成交结果: %s" \
                        % (coin_name, latest_price, amount, timestamp2string(time.time()), ret)
            thread.start_new_thread(send_email, (email_msg, ))
            return True
        amount *= 0.95
    return False
Пример #10
0
def on_message(ws, message):
    global spot_latest_price, swap_latest_price
    ts = time.time()
    now_time = timestamp2string(ts)

    message = bytes.decode(inflate(message), 'utf-8')  # data decompress
    json_message = json.loads(message)
    for json_data in json_message['data']:
        ins_id = json_data['instrument_id']
        if ins_id == instrument_id:
            spot_latest_price = float(json_data['last'])
        elif ins_id == swap_instrument_id:
            swap_latest_price = float(json_data['last'])
        write_info_into_file(
            'spot price = ' + str(spot_latest_price) + ', swap price = ' +
            str(swap_latest_price), file_deal)
        diff = round(swap_latest_price - spot_latest_price, 4)
        diff_rate = round(diff / (spot_latest_price + 0.001) * 100, 3)
        write_info_into_file(
            'diff = ' + str(diff) + ', rate = ' + str(diff_rate) + '%',
            file_deal)
Пример #11
0
def sell_more_batch(coin_name, time_type, latest_price, lever_rate=20):
    global processing, more2less
    processing = True
    jRet = json.loads(
        okFuture.future_position_4fix(coin_name + "_usd", time_type, "1"))
    print(jRet)
    flag = True
    ret = u'没有做多订单'
    while len(jRet["holding"]) > 0:
        cancel_uncompleted_order(coin_name, time_type)
        if flag:
            flag = False
            amount = jRet["holding"][0]["buy_available"]
            order_data = gen_orders_data(latest_price, amount, 3, 5)
            ret = okFuture.future_batchTrade(coin_name + "_usd", time_type,
                                             order_data, lever_rate)
        else:
            buy_available = jRet["holding"][0]["buy_available"]
            ret = okFuture.future_trade(coin_name + "_usd", time_type, '',
                                        buy_available, 3, 1, lever_rate)
        if 'true' in ret:
            time.sleep(2)
            jRet = json.loads(
                okFuture.future_position_4fix(coin_name + "_usd", time_type,
                                              "1"))

    sell_more_suc()
    if more2less == 1:
        if buyin_less(coin_name, time_type, latest_price):
            info = u'发出反手做空信号!!!买入价格:' + str(latest_price)
            with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                f.writelines(info + '\n')
        else:
            more2less = 0
    email_msg = "做多%s批量卖出成交, 时间: %s, 成交结果: %s" \
                % (coin_name, timestamp2string(time.time()), ret)
    thread.start_new_thread(send_email, (email_msg, ))
    processing = False
    return True
Пример #12
0
def sell_less(okFuture, coin_name, time_type, price=None, lever_rate=20):
    jRet = json.loads(
        okFuture.future_position_4fix(coin_name + "_usd", time_type, "1"))

    while len(jRet["holding"]) > 0:
        cancel_uncompleted_order(okFuture, coin_name, time_type)
        sell_available = jRet["holding"][0]["sell_available"]
        if price:
            ret = okFuture.future_trade(coin_name + "_usd", time_type, price,
                                        sell_available, 4, 0, lever_rate)
        else:
            ret = okFuture.future_trade(coin_name + "_usd", time_type, '',
                                        sell_available, 4, 1, lever_rate)
        if 'true' in ret:
            time.sleep(2)
            jRet = json.loads(
                okFuture.future_position_4fix(coin_name + "_usd", time_type,
                                              "1"))

    email_msg = "卖出做空%s成功, 时间: %s, 成交结果: %s" \
                % (coin_name, timestamp2string(time.time()), ret)
    thread.start_new_thread(send_email, (email_msg, ))
    return True
Пример #13
0
def log_trade_v3(log):
    format_log = timestamp2string(time.time()) + " " + log
    print(format_log)
    with codecs.open(trade_log_path, 'a+', 'utf-8') as f:
        f.writelines(format_log + '\r\n')
Пример #14
0
def on_message(ws, message):
    message = bytes.decode(inflate(message), 'utf-8')  # data decompress
    if 'pong' in message or 'addChannel' in message:
        return
    global latest_price, last_avg_price, buy_price, more, less, deque_3s, deque_10s, deque_min, buy_sell_ratio, \
        deque_5m, ind_3s, ind_10s, ind_1min, ind_5m, write_lines, last_minute_ts, last_second_ts, order_id_queue, now_time
    jmessage = json.loads(message)

    ts = time.time()
    now_time = timestamp2string(ts)

    for each_message in jmessage:
        for jdata in each_message['data']:
            latest_price = float(jdata[1])
            exe_second(ts)
            exe_minute(ts)

            deal_entity = DealEntity(jdata[0], float(jdata[1]),
                                     round(float(jdata[2]), 3), ts, jdata[4])

            handle_deque(deque_3s, deal_entity, ts, ind_3s)
            handle_deque(deque_10s, deal_entity, ts, ind_10s)
            handle_deque(deque_min, deal_entity, ts, ind_1min)
            handle_deque(deque_5m, deal_entity, ts, ind_5m)

            avg_3s_price = ind_3s.cal_avg_price()
            avg_10s_price = ind_10s.cal_avg_price()
            avg_min_price = ind_1min.cal_avg_price()
            avg_5m_price = ind_5m.cal_avg_price()
            price_10s_change = cal_rate(avg_3s_price, avg_10s_price)
            price_1m_change = cal_rate(avg_3s_price, avg_min_price)
            price_5m_change = cal_rate(avg_3s_price, avg_5m_price)

            # 单边上涨行情持有做多单,达到卖出条件
            if more == 1:
                if price_1m_change <= -0.2 or price_5m_change <= 0:
                    if sell_more_batch(coin.name, time_type, latest_price):
                        more = 0
                        thread.start_new_thread(ensure_sell_more, (
                            coin.name,
                            time_type,
                        ))
            # 单边下跌行情持有做空单,达到卖出条件
            elif less == 1:
                if price_1m_change >= 0.2 or price_5m_change >= 0:
                    if sell_less_batch(coin.name, time_type, latest_price):
                        less = 0
                        thread.start_new_thread(ensure_sell_less, (
                            coin.name,
                            time_type,
                        ))
            # 单边上涨行情
            if price_1m_change >= incr_1m_rate and price_5m_change >= incr_5m_rate:
                # 撤单开空、平多单
                cancel_uncompleted_order(coin.name, time_type, 2)
                cancel_uncompleted_order(coin.name, time_type, 3)
                # 撤单平空单
                cancel_uncompleted_order(coin.name, time_type, 4)
                # 空单全部卖出
                if sell_less_batch(coin.name, time_type, latest_price):
                    thread.start_new_thread(ensure_sell_less, (
                        coin.name,
                        time_type,
                    ))
                # 做多买入
                if buyin_more(coin.name, time_type, latest_price):
                    more = 1
                    thread.start_new_thread(
                        ensure_buyin_more,
                        (coin.name, time_type, latest_price))

            # 单边下跌行情
            elif price_1m_change < -incr_1m_rate and price_5m_change < -incr_5m_rate:
                # 撤单开多,平空单
                cancel_uncompleted_order(coin.name, time_type, 1)
                cancel_uncompleted_order(coin.name, time_type, 4)
                # 撤单平多单
                cancel_uncompleted_order(coin.name, time_type, 3)
                # 多单全部卖出
                if sell_more_batch(coin.name, time_type, latest_price):
                    thread.start_new_thread(ensure_sell_more, (
                        coin.name,
                        time_type,
                    ))
                # 做空买入
                if buyin_less(coin.name, time_type, latest_price):
                    less = 1
                    thread.start_new_thread(
                        ensure_buyin_less,
                        (coin.name, time_type, latest_price))

            if -0.05 < price_1m_change < 0.05 and -0.02 < price_10s_change < 0.02 and ind_1min.vol < 6000 and ind_10s.vol < 1000:
                more_order_id, less_order_id = buyin_moreandless(
                    coin.name, time_type, latest_price, 20, buy_sell_ratio)

                if more_order_id:
                    order_id_queue.append(more_order_id)
                    print('more order_id: %s' % more_order_id)

                if less_order_id:
                    order_id_queue.append(less_order_id)
                    print('less order_id: %s' % less_order_id)
Пример #15
0
 status = order_info['status']
 side = order_info['side']
 if status == 'filled':
     print("order %s 已完全成交" % str(old_order_id))
     del_list.append(old_order_id)
     if side == 'buy':
         more = 1
     elif side == 'sell':
         more = 0
 elif status == 'part_filled':
     if side == 'buy':
         more = 1
 elif status == 'cancelled':
     del_list.append(old_order_id)
 elif int(ts) - (string2timestamp(order_info['timestamp']) + 8 * 3600) >= 3:
     print('撤单重挂,ts:%s, 真实时间:%s' % (timestamp2string(ts), timestamp2string(time.time())))
     try:
         print('撤单结果: %s' % spotAPI.revoke_order(instrument_id, old_order_id))
     except Exception as e:
         print(repr(e))
         traceback.print_exc()
         del_list.append(old_order_id)
         continue
     ret = spotAPI.get_specific_ticker(instrument_id)
     print('当前行情: %s' % ret)
     if side == 'buy':
         buy_price = float(ret['best_ask'])
         try:
             order_id = buy_all_position(spotAPI, instrument_id, buy_price)
             if order_id:
                 order_id_queue.append(order_id)
Пример #16
0
                ret = spotAPI.get_specific_ticker(instrument_id)
                buy_price = float(ret['best_bid']) + 0.0001
                sell_price = float(ret['best_ask']) - 0.0001
                if more == 1 and check_trend(list(df['macd'])) == 'down':
                    order_id = sell_all_position(spotAPI, instrument_id,
                                                 sell_price)
                    if order_id:
                        order_id_queue.append(order_id)

                elif more == 0 and check_trend(list(df['macd'])) == 'up':
                    order_id = buy_all_position(spotAPI, instrument_id,
                                                buy_price)
                    if order_id:
                        order_id_queue.append(order_id)
                        less = 0

                last_macd = new_macd
                if first:
                    first = False
                    for i in range(0, len(diff)):
                        print(
                            "macd: %.6f, diff: %.6f, dea: %.6f, macd_time: %s"
                            % (2 * (diff[i] - dea[i]), diff[i], dea[i],
                               timestamp[i]))
                print(new_macd, diff[-1], dea[-1], timestamp[-1],
                      timestamp2string(ts))
        except Exception as e:
            print(repr(e))
            traceback.print_exc()
            continue
Пример #17
0
def on_message(ws, message):
    message = bytes.decode(inflate(message), 'utf-8')  # data decompress
    if 'pong' in message or 'addChannel' in message:
        return
    global latest_price, last_avg_price, less, deque_3s, deque_10s, deque_min, future_buy_price,\
        deque_3m, ind_3s, ind_10s, ind_1min, ind_3m, write_lines, lessless,\
        future_buy_time, spot_buy_time, spot_sell_price, spot_buy_price, lessmore, future_more_buy_price
    jmessage = json.loads(message)

    ts = time.time()
    now_time = timestamp2string(ts)
    # if int(ts) - last_3min_macd_ts > 60:
    #     last_3min_macd_ts = int(ts)
    #     df = get_spot_macd(spotAPI, instrument_id, 300)
    #     diff = list(df['diff'])
    #     dea = list(df['dea'])
    #     new_macd = 2 * (diff[-1] - dea[-1])
    #     with codecs.open(file_deal, 'a+', 'UTF-8') as f:
    #         f.writelines('update macd: %.6f\r\n' % new_macd)

    for each_message in jmessage:
        for jdata in each_message['data']:
            latest_price = float(jdata[1])
            deal_entity = DealEntity(jdata[0], float(jdata[1]),
                                     round(float(jdata[2]), 3), ts, jdata[4])

            handle_deque(deque_3s, deal_entity, ts, ind_1s)
            handle_deque(deque_10s, deal_entity, ts, ind_10s)
            handle_deque(deque_min, deal_entity, ts, ind_1min)
            handle_deque(deque_3m, deal_entity, ts, ind_3m)

            avg_3s_price = ind_1s.cal_avg_price()
            avg_10s_price = ind_10s.cal_avg_price()
            avg_min_price = ind_1min.cal_avg_price()
            avg_3m_price = ind_3m.cal_avg_price()
            price_10s_change = cal_rate(avg_3s_price, avg_10s_price)
            price_1m_change = cal_rate(avg_3s_price, avg_min_price)
            price_3m_change = cal_rate(avg_3s_price, avg_3m_price)
            price_change_3m_ago = cal_rate(latest_price, deque_3m[0])
            write_info("3min ago change: %.2f%%" % price_change_3m_ago)
            # 做空
            if less == 0 and price_change_3m_ago > -5 and check_do_future_less(
                    price_3m_change, price_1m_change,
                    price_10s_change) and price_change_3m_ago:
                lever_less_order_id = do_lever_less()
                if lever_less_order_id:
                    lever_less_time = int(ts)
                    time.sleep(1)
                    sell_order_info = leverAPI.get_order_info(
                        lever_less_order_id, instrument_id)
                    # 1:部分成交 2:完全成交
                    if sell_order_info['state'] == '1' or sell_order_info[
                            'state'] == '2':
                        less = 1
                        lever_sell_price = float(sell_order_info['price_avg'])
                        info = now_time + u' 杠杆卖出!!!卖出均价:' + str(
                            lever_sell_price)
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')
                    else:
                        leverAPI.revoke_order_exception(
                            instrument_id, lever_less_order_id)
            if less == 1:
                if price_1m_change > 0 and int(
                        ts
                ) - lever_less_time > 120 and ind_1min.bid_vol > ind_1min.ask_vol:
                    if stop_lever_less(latest_price):
                        less = 0

                if int(
                        ts
                ) - lever_less_time > 60 and latest_price > lever_sell_price:
                    if stop_lever_less(latest_price):
                        less = 0

            holding_status = 'spot_less: %d' % less
            price_info = deal_entity.type + u' now_price: %.4f, 3s_price: %.4f, 10s_price: %.4f, 1m_price: %.4f, ' \
                                            u'3min_price: %.4f' \
                         % (latest_price, avg_3s_price, avg_10s_price, avg_min_price, avg_3m_price)
            vol_info = u'cur_vol: %.3f, 3s vol: %.3f, 10s vol: %.3f, 1min vol: %.3f, ask_vol: %.3f, bid_vol: %.3f, ' \
                       u'3s_ask_vol: %.3f, 3s_bid_vol: %.3f, 3min vol: %.3f, 3min_ask_vol: %.3f, 3min_bid_vol: %.3f' \
                       % (deal_entity.amount, ind_1s.vol, ind_10s.vol, ind_1min.vol, ind_1min.ask_vol, ind_1min.bid_vol,
                          ind_1s.ask_vol, ind_1s.bid_vol, ind_3m.vol, ind_3m.ask_vol, ind_3m.bid_vol)
            rate_info = u'10s_rate: %.2f%%, 1min_rate: %.2f%%, 3min_rate: %.2f%%' \
                        % (price_10s_change, price_1m_change, price_3m_change)
            info = holding_status + u',' + price_info + u',' + vol_info + u',' + rate_info + u',' + now_time + '\r\n'
            write_lines.append(info)
            if len(write_lines) >= 100:
                with codecs.open(file_deal, 'a+', 'UTF-8') as f:
                    f.writelines(write_lines)
                    write_lines = []

            print(holding_status + '\r\n' + price_info + '\r\n' + vol_info +
                  '\r\n' + rate_info + u', ' + now_time)
Пример #18
0
def on_message(ws, message):
    global buy_price, sell_price, buy_queue, sell_queue, bid_price, ask_price, last_time_sec,latest_deal_price,last_time_account_sec
    message = bytes.decode(inflate(message), 'utf-8')  # data decompress
    if 'pong' in message or 'addChannel' in message:
        return
    jmessage = json.loads(message)
    each_message = jmessage[0]
    channel = each_message['channel']
    now_time_sec = float(time.time())
    if channel == 'ok_sub_spot_%s_usdt_depth_5' % coin_name:
        data = each_message['data']
        asks = data['asks'][::-1]
        bids = data['bids']
        ask_price = float(asks[0][0])
        bid_price = float(bids[0][0])
        ask_price_2 = float(asks[1][0])
        bid_price_2 = float(bids[1][0])
        mid_price = (ask_price + bid_price) / 2
        if now_time_sec > last_time_sec + 0.2:
            last_time_sec = now_time_sec
            print('撤单前sell_queue length: ', len(sell_queue))
            new_queue = []
            for order in sell_queue:
                is_revoke_suc = spot_maker.revoke_order(order.order_id, now_time_sec)
                if is_revoke_suc:
                    if latest_deal_price >= ask_price * 0.9999:
                        # 上涨行情, 追加买单
                        buy_price = mid_price
                        sell_price = max(buy_price * 1.001, ask_price_2)
                        buy_order_id = spot_maker.take_buy_order(2 * amount, buy_price)
                        if buy_order_id:
                            new_buy_order = Order(buy_order_id, buy_price, amount, 'buy', now_time_sec)
                            buy_queue.append(new_buy_order)
                            spot_maker.timeLog("挂买入单成功,时间:%s, 价格: %.4f, order_id: %s" % (
                                timestamp2string(now_time_sec), buy_price, buy_order_id))
                        continue
                    else:
                        sell_price = ask_price - 0.0001
                    if ask_price > bid_price * 1.0006:
                        sell_order_id = spot_maker.take_sell_order(amount, sell_price)
                        if sell_order_id:
                            new_sell_order = Order(sell_order_id, sell_price, amount, 'sell',
                                                   timestamp2string(now_time_sec))
                            new_queue.append(new_sell_order)
                            spot_maker.timeLog("挂卖出单成功,时间:%s, 价格: %.4f, order_id: %s" % (
                                timestamp2string(now_time_sec), sell_price, sell_order_id))

                else:
                    # 撤单失败,retry
                    spot_maker.timeLog('%s撤单失败,重试')
                    spot_maker.revoke_order(order.order_id, now_time_sec)

            sell_queue = copy.deepcopy(new_queue)
            new_queue = []
            print('撤单后sell_queue length: ', len(sell_queue))
            print('撤单前buy_queue length: ', len(buy_queue))
            for order in buy_queue:
                if spot_maker.revoke_order(order.order_id, now_time_sec):
                    if latest_deal_price <= bid_price * 1.0001:
                        # 下跌行情, 追加卖单
                        sell_price = mid_price
                        buy_price = min(sell_price * 0.999, bid_price_2)
                        sell_order_id = spot_maker.take_sell_order(amount, sell_price)
                        if sell_order_id:
                            new_sell_order = Order(sell_order_id, sell_price, 2 * amount, 'sell',
                                                   timestamp2string(now_time_sec))
                            sell_queue.append(new_sell_order)
                            spot_maker.timeLog("挂卖出单成功,时间:%s, 价格: %.4f, order_id: %s" % (
                                timestamp2string(now_time_sec), sell_price, sell_order_id))
                        continue
                    else:
                        buy_price = bid_price + 0.0001
                    if ask_price > bid_price * 1.0006:
                        buy_order_id = spot_maker.take_buy_order(amount, buy_price)
                        if buy_order_id:
                            new_buy_order = Order(buy_order_id, buy_price, amount, 'buy', now_time_sec)
                            new_queue.append(new_buy_order)
                            spot_maker.timeLog("挂买入单成功,时间:%s, 价格: %.4f, order_id: %s" % (
                                timestamp2string(now_time_sec), buy_price, buy_order_id))

            buy_queue = copy.deepcopy(new_queue)
            print('撤单后buy_queue length: ', len(buy_queue))

    elif channel == ('ok_sub_spot_%s_usdt_deals' % coin_name):


        jdata = each_message['data'][0]
        latest_deal_price = float(jdata[1])
        mid_price = (ask_price + bid_price) / 2
        deal_entity = DealEntity(jdata[0], float(jdata[1]), round(float(jdata[2]), 3), now_time_sec, jdata[4])
        handle_deque(deque_3s, deal_entity, now_time_sec, ind_3s)
        avg_3s_price = ind_3s.cal_avg_price()
        if now_time_sec > last_time_account_sec + 60:
            last_time_account_sec = now_time_sec
            spot_maker.get_account_money(coin_name)
            spot_maker.delete_overdue_order(latest_deal_price)
        price_3s_change = cal_rate(latest_deal_price, avg_3s_price)
        spot_maker.timeLog("最新成交价: %.4f, 中间价: %.4f, 买一价: %.4f, 卖一价: %.4f, 3秒平均价: %.4f, 波动: %.3f%%"
                           % (latest_deal_price, mid_price, bid_price, ask_price, avg_3s_price, price_3s_change))
        if price_3s_change > 0.03 or price_3s_change < -0.03:
            return
        elif latest_deal_price > bid_price * 1.0002 and ask_price > latest_deal_price * 1.0002 \
                and buy_price != bid_price + 0.0001 and sell_price != ask_price - 0.0001:
            buy_price = bid_price + 0.0001
            sell_price = ask_price - 0.0001
        elif ask_price > bid_price * 1.0006 and buy_price != bid_price + 0.0001 and sell_price != ask_price - 0.0001:
            if latest_deal_price < mid_price:
                buy_price = bid_price + 0.0001
                sell_price = buy_price * 1.0005
            else:
                sell_price = ask_price - 0.0001
                buy_price = ask_price * 0.9995
        else:
            # 不操作
            return
        try:
            buy_order_id = spot_buy(spotAPI, instrument_id, amount, buy_price)
        except Exception as e:
            buy_order_id = False
            traceback.print_exc()
        try:
            sell_order_id = spot_sell(spotAPI, instrument_id, amount, sell_price)
        except Exception as e:
            sell_order_id = False
            traceback.print_exc()
        if buy_order_id:
            buy_order = Order(buy_order_id, buy_price, amount, 'buy', timestamp2string(now_time_sec))
            buy_queue.append(buy_order)
            spot_maker.timeLog("挂买入单成功,时间:%s, 价格: %.4f, order_id: %s" % (
            timestamp2string(time.time()), buy_price, buy_order_id))
        if sell_order_id:
            sell_order = Order(sell_order_id, sell_price, amount, 'sell', timestamp2string(now_time_sec))
            sell_queue.append(sell_order)
            spot_maker.timeLog("挂卖出单成功,时间:%s, 价格: %.4f, order_id: %s" % (
            timestamp2string(time.time()), sell_price, sell_order_id))
Пример #19
0
def on_message(ws, message):
    if 'pong' in message or 'addChannel' in message:
        return
    global more, less, buy_price, write_lines
    jmessage = json.loads(message)
    coin_name = jmessage[0]['channel'].split('_')[3]
    data = jmessage[0]['data']
    index = float(data['futureIndex'])
    timestamp = int(data['timestamp'])
    now_time = timestamp2string(timestamp)
    index_entity = IndexEntity(coin_name, index, timestamp)
    coin_info = "coin: %s, index: %.2f, time: %s" % (coin_name, index, now_time)

    if coin_name == 'btc':
        handle_deque(btc_deque_1s, index_entity, btc_ind_1s)
        handle_deque(btc_deque_1min, index_entity, btc_ind_1min)
        handle_deque(btc_deque_5min, index_entity, btc_ind_5min)
    elif coin_name == 'eth':
        handle_deque(eth_deque_1s, index_entity, eth_ind_1s)
        handle_deque(eth_deque_1min, index_entity, eth_ind_1min)
        handle_deque(eth_deque_5min, index_entity, eth_ind_5min)
    elif coin_name == 'ltc':
        handle_deque(ltc_deque_1s, index_entity, ltc_ind_1s)
        handle_deque(ltc_deque_1min, index_entity, ltc_ind_1min)
        handle_deque(ltc_deque_5min, index_entity, ltc_ind_5min)

    btc_avg_1s_price = btc_ind_1s.cal_avg_price()
    btc_avg_min_price = btc_ind_1min.cal_avg_price()
    btc_avg_5m_price = btc_ind_5min.cal_avg_price()

    eth_avg_1s_price = eth_ind_1s.cal_avg_price()
    eth_avg_min_price = eth_ind_1min.cal_avg_price()
    eth_avg_5m_price = eth_ind_5min.cal_avg_price()

    ltc_avg_1s_price = ltc_ind_1s.cal_avg_price()
    ltc_avg_min_price = ltc_ind_1min.cal_avg_price()
    ltc_avg_5m_price = ltc_ind_5min.cal_avg_price()

    btc_1m_change = cal_rate(btc_avg_1s_price, btc_avg_min_price)
    btc_5m_change = cal_rate(btc_avg_1s_price, btc_avg_5m_price)

    eth_1m_change = cal_rate(eth_avg_1s_price, eth_avg_min_price)
    eth_5m_change = cal_rate(eth_avg_1s_price, eth_avg_5m_price)

    ltc_1m_change = cal_rate(ltc_avg_1s_price, ltc_avg_min_price)
    ltc_5m_change = cal_rate(ltc_avg_1s_price, ltc_avg_5m_price)

    weighted_1min_rate = btc_1m_change * btc_weight + eth_1m_change * eth_weight + ltc_1m_change * ltc_weight
    weighted_5min_rate = btc_5m_change * btc_weight + eth_5m_change * eth_weight + ltc_5m_change * ltc_weight

    if more == 1 and not processing:
        if weighted_5min_rate <= 0:
            thread.start_new_thread(sell_more_batch, (coin.name, time_type, latest_price,))
    elif less == 1 and not processing:
        if weighted_5min_rate >= 0:
            thread.start_new_thread(sell_less_batch, (coin.name, time_type, latest_price,))

    elif weighted_1min_rate >= incr_1m_rate and weighted_5min_rate >= incr_5m_rate \
            and btc_5m_change >= incr_1m_rate and eth_5m_change >= incr_1m_rate and ltc_5m_change >= incr_1m_rate:
        if buyin_more(coin.name, time_type, latest_price):
            more = 1
            thread.start_new_thread(ensure_buyin_more, (coin.name, time_type, latest_price,))
            buy_price = latest_price
            info = u'发出做多信号!!!买入价格:' + str(buy_price) + u', ' + now_time
            with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                f.writelines(info + '\n')
    elif weighted_1min_rate <= -incr_1m_rate and weighted_5min_rate <= -incr_5m_rate \
            and btc_5m_change < -incr_1m_rate and eth_5m_change < -incr_1m_rate and ltc_5m_change < -incr_1m_rate:
        if buyin_less(coin.name, time_type, latest_price):
            less = 1
            thread.start_new_thread(ensure_buyin_less, (coin.name, time_type, latest_price,))
            buy_price = latest_price
            info = u'发出做空信号!!!买入价格:' + str(buy_price) + u', ' + now_time
            with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                f.writelines(info + '\n')

    btc_rate_info = u'btc      1min_rate: %.2f%%, 5min_rate: %.2f%%' % (btc_1m_change, btc_5m_change)

    eth_rate_info = u'eth      1min_rate: %.2f%%, 5min_rate: %.2f%%' % (eth_1m_change, eth_5m_change)

    ltc_rate_info = u'ltc      1min_rate: %.2f%%, 5min_rate: %.2f%%' % (ltc_1m_change, ltc_5m_change)

    weighted_rate_info = u'weighted 1min_rate: %.3f%%, 5min_rate: %.3f%%' % (weighted_1min_rate, weighted_5min_rate)

    print(coin_info)
    print(btc_rate_info)
    print(eth_rate_info)
    print(ltc_rate_info)
    print(weighted_rate_info)
    write_info = coin_info + '\n' + btc_rate_info + '\n' + eth_rate_info + '\n' + ltc_rate_info + '\n' \
                 + weighted_rate_info + '\r\n'
    write_lines.append(write_info)
    if len(write_lines) >= 10:
        with codecs.open(file_deal, 'a+', 'UTF-8') as f:
            f.writelines(write_lines)
            write_lines = []
Пример #20
0
        print(coin_name.upper())
        time_gap = sys.argv[2]
        time_type = coin_name.upper() + "-USD-190329"
        turtle = Turtle(coin_name, "ETC-USD-190329")
        prev_calc_time = 0
        while True:
            try:
                now_time = int(time.time())
                if now_time - prev_calc_time > 600:
                    prev_calc_time = now_time
                    turtle.calc_unit()
                ticker = futureAPI.get_specific_ticker(turtle.instrument_id)
                last = float(ticker['last'])
                recent_vol = turtle.get_recent_vol(2)
                print('最新: %.3f, 最高: %.3f, 最低: %.3f, 成交量: %d, 时间: %s' %
                      (last, highest, lowest, recent_vol,
                       timestamp2string(time.time())))
                vol_24h = int(int(ticker['volume_24h']) / 24 / 60)
                if recent_vol > 6 * vol_24h:
                    turtle.build_position(ticker)
                turtle.add_position(ticker)
                # turtle.process_pending_orders()
                time.sleep(1)
            except Exception as e:
                print(repr(e))
                traceback.print_exc()
                continue
    else:
        print('缺少参数')
        print('for example: python turtle.py `eos` `5min`')
Пример #21
0
def process_message(message):
    global latest_price, last_avg_price, less, deque_3s, deque_10s, deque_min, future_buy_price,\
        deque_3m, ind_3s, ind_10s, ind_1min, ind_3m, write_lines, last_3min_macd_ts, new_macd, lessless,\
        future_buy_time, spot_buy_time, spot_sell_price, spot_buy_price, lessmore, future_more_buy_price
    ts = time.time()
    now_time = timestamp2string(ts)
    for each_message in message['data']:
        latest_price = float(each_message['price'])
        trade_id = each_message['trade_id']
        size = each_message['size']
        side = each_message['side']
        deal_entity = DealEntity(trade_id, latest_price, size, ts, side)
        print('detail:' + deal_entity.detail())

        handle_deque(deque_3s, deal_entity, ts, ind_1s)
        handle_deque(deque_10s, deal_entity, ts, ind_10s)
        handle_deque(deque_min, deal_entity, ts, ind_1min)
        handle_deque(deque_3m, deal_entity, ts, ind_3m)

        avg_3s_price = ind_1s.cal_avg_price()
        avg_10s_price = ind_10s.cal_avg_price()
        avg_min_price = ind_1min.cal_avg_price()
        avg_3m_price = ind_3m.cal_avg_price()
        price_10s_change = cal_rate(avg_3s_price, avg_10s_price)
        price_1m_change = cal_rate(avg_3s_price, avg_min_price)
        price_3m_change = cal_rate(avg_3s_price, avg_3m_price)

        # 做空
        if less == 0 and check_do_future_less(price_3m_change, price_1m_change,
                                              price_10s_change):
            sell_id = sell_all_position(spotAPI, instrument_id,
                                        latest_price - 0.001)
            if sell_id:
                spot_buy_time = int(ts)
                time.sleep(1)
                sell_order_info = spotAPI.get_order_info(
                    sell_id, instrument_id)
                if sell_order_info['status'] == 'filled' or sell_order_info[
                        'status'] == 'part_filled':
                    less = 1
                    spot_sell_price = float(sell_order_info['price'])
                    info = now_time + u' 现货全部卖出!!!spot_sell_price:' + str(
                        spot_sell_price)
                    with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                        f.writelines(info + '\n')
                else:
                    spotAPI.revoke_order_exception(instrument_id, sell_id)
        if less == 1:
            if price_1m_change > 0 and new_macd > 0:
                usdt_account = spotAPI.get_coin_account_info("usdt")
                usdt_available = float(usdt_account['available'])
                amount = math.floor(usdt_available / latest_price)
                if amount > 0:
                    buy_id = spot_buy(spotAPI, instrument_id, amount,
                                      latest_price)
                    if buy_id:
                        time.sleep(3)
                        order_info = spotAPI.get_order_info(
                            buy_id, instrument_id)
                        if order_info['status'] == 'filled':
                            less = 0
                            spot_buy_price = order_info['price']
                            info = u'macd > 0, 买入现货止盈!!!买入价格:' + str(
                                spot_buy_price) + u', ' + now_time
                            with codecs.open(file_transaction, 'a+',
                                             'utf-8') as f:
                                f.writelines(info + '\n')
                        else:
                            attempts = 5
                            while attempts > 0:
                                attempts -= 1
                                spotAPI.revoke_order_exception(
                                    instrument_id, buy_id)
                                time.sleep(1)
                                order_info = spotAPI.get_order_info(
                                    buy_id, instrument_id)
                                if order_info['status'] == 'cancelled':
                                    break
                else:
                    less = 0

            if int(ts) - spot_buy_time > 60:
                if latest_price > spot_sell_price and price_1m_change >= 0 and price_10s_change >= 0 \
                        and (ind_1min.bid_vol > ind_1min.ask_vol or price_3m_change >= 0):
                    usdt_account = spotAPI.get_coin_account_info("usdt")
                    usdt_available = float(usdt_account['available'])
                    amount = math.floor(usdt_available / latest_price)
                    if amount > 0:
                        buy_id = spot_buy(spotAPI, instrument_id, amount,
                                          latest_price)
                        if buy_id:
                            time.sleep(3)
                            order_info = spotAPI.get_order_info(
                                buy_id, instrument_id)
                            if order_info['status'] == 'filled':
                                less = 0
                                spot_buy_price = order_info['price']
                                info = u'macd > 0, 买入现货止损!!!买入价格:' + str(
                                    spot_buy_price) + u', ' + now_time
                                with codecs.open(file_transaction, 'a+',
                                                 'utf-8') as f:
                                    f.writelines(info + '\n')
                            else:
                                attempts = 5
                                while attempts > 0:
                                    attempts -= 1
                                    spotAPI.revoke_order_exception(
                                        instrument_id, buy_id)
                                    time.sleep(1)
                                    order_info = spotAPI.get_order_info(
                                        buy_id, instrument_id)
                                    if order_info['status'] == 'cancelled':
                                        break
                    else:
                        less = 0

        holding_status = 'spot_less: %d' % less
        price_info = deal_entity.type + u' now_price: %.4f, 3s_price: %.4f, 10s_price: %.4f, 1m_price: %.4f, ' \
                                        u'3min_price: %.4f' \
                     % (latest_price, avg_3s_price, avg_10s_price, avg_min_price, avg_3m_price)
        vol_info = u'cur_vol: %.3f, 3s vol: %.3f, 10s vol: %.3f, 1min vol: %.3f, ask_vol: %.3f, bid_vol: %.3f, ' \
                   u'3s_ask_vol: %.3f, 3s_bid_vol: %.3f, 3min vol: %.3f, 3min_ask_vol: %.3f, 3min_bid_vol: %.3f' \
                   % (deal_entity.amount, ind_1s.vol, ind_10s.vol, ind_1min.vol, ind_1min.ask_vol, ind_1min.bid_vol,
                      ind_1s.ask_vol, ind_1s.bid_vol, ind_3m.vol, ind_3m.ask_vol, ind_3m.bid_vol)
        rate_info = u'10s_rate: %.2f%%, 1min_rate: %.2f%%, 3min_rate: %.2f%%, new_macd: %.6f' \
                    % (price_10s_change, price_1m_change, price_3m_change, new_macd)
        write_info = holding_status + u', ' + price_info + u', ' + vol_info + u', ' + rate_info + u', ' + now_time + '\r\n'
        write_lines.append(write_info)
        if len(write_lines) >= 100:
            with codecs.open(file_deal, 'a+', 'UTF-8') as f:
                f.writelines(write_lines)
                write_lines = []

        print(holding_status + '\r\n' + price_info + '\r\n' + vol_info +
              '\r\n' + rate_info + u', ' + now_time)
Пример #22
0
    def add_position(self, ticker):
        global positions, N
        try:
            # 加仓&止损
            if len(positions) > 0:
                last = float(ticker['last'])
                print('当前仓位: %d, 仓位信息:' % len(positions))
                for i in range(len(positions)):
                    cur = positions[i]
                    if cur.side == 'more':
                        profit = (last - cur.price) / cur.price * 100
                    else:
                        profit = (cur.price - last) / cur.price * 100
                    print(
                        '第%d个仓位: 委托价: %.3f, 数量: %.2f, 方向: %s, 止损价: %.3f, 买入时间: %s, 当前盈利: %.2f%%'
                        % (i + 1, cur.price, cur.amount, cur.side,
                           cur.stop_loss, cur.time, profit))
                prev_position = positions[-1]
                last_buy_price = prev_position.price
                side = prev_position.side
                amount = int(position_unit * 2 * last)
                last_stop_loss_price = prev_position.stop_loss

                if side == 'more':
                    if last - last_buy_price >= 0.5 * N:
                        ret = futureAPI.take_order('', self.instrument_id, 1,
                                                   last, amount, 1, 20)
                        if ret and ret['result']:
                            new_order_id = ret['order_id']
                            print('多仓加仓,order_id: %s' % new_order_id)
                            time.sleep(WAIT_DEAL)
                            info = futureAPI.get_order_info(
                                new_order_id, self.instrument_id)
                            print('订单信息: %s' % info)
                            status = info['status']
                            if status == '2':
                                deal_price = float(info['price_avg'])
                                filled_qty = int(info['filled_qty'])
                                coin_amount = float(filled_qty * 10 /
                                                    deal_price)
                                stop_loss = deal_price - 0.5 * N
                                position = Position(price=deal_price,
                                                    amount=coin_amount,
                                                    stop_loss=stop_loss,
                                                    time=timestamp2string(
                                                        time.time()),
                                                    side='more')
                                positions.append(position)
                            else:
                                futureAPI.revoke_order(self.instrument_id,
                                                       new_order_id)

                    elif last <= last_stop_loss_price or last <= lowest:
                        sell_more_batch(futureAPI, self.instrument_id, last)
                        thread.start_new_thread(ensure_sell_more, (
                            futureAPI,
                            self.coin_name,
                            self.instrument_id,
                            last,
                            last_buy_price,
                        ))
                        positions = []
                if side == 'less':
                    if last < last_buy_price - 0.5 * N:
                        ret = futureAPI.take_order('', self.instrument_id, 2,
                                                   last, amount, 1, 20)
                        if ret and ret['result']:
                            new_order_id = ret['order_id']
                            print('空仓加仓,order_id: %s' % new_order_id)
                            time.sleep(WAIT_DEAL)
                            info = futureAPI.get_order_info(
                                new_order_id, self.instrument_id)
                            print('订单信息: %s' % info)
                            status = info['status']
                            if status == '2':
                                deal_price = float(info['price_avg'])
                                filled_qty = int(info['filled_qty'])
                                coin_amount = float(filled_qty * 10 /
                                                    deal_price)
                                stop_loss = deal_price + 0.5 * N
                                position = Position(price=deal_price,
                                                    amount=coin_amount,
                                                    stop_loss=stop_loss,
                                                    time=timestamp2string(
                                                        time.time()),
                                                    side='less')
                                positions.append(position)
                            else:
                                futureAPI.revoke_order(self.instrument_id,
                                                       new_order_id)

                    elif last >= last_stop_loss_price or last >= highest:
                        sell_less_batch(futureAPI, self.instrument_id, last)
                        thread.start_new_thread(ensure_sell_less, (
                            futureAPI,
                            self.coin_name,
                            self.instrument_id,
                            last,
                            last_buy_price,
                        ))
                        positions = []
        except Exception as e:
            print('加仓出错:%s' % repr(e))
            traceback.print_exc()
Пример #23
0
                    else:
                        more = 0
                elif less == 1:
                    jRet = json.loads(
                        okFuture.future_position_4fix(coin.name + "_usd",
                                                      time_type, "1"))
                    if len(jRet["holding"]) > 0:
                        sell_available = jRet["holding"][0]["sell_available"]
                        if sell_available > 0:
                            print("确认持有做空单: ", jRet)
                        else:
                            less = 0
                    else:
                        less = 0
                else:
                    print('未持有单, %s' % timestamp2string(int(ts)))
                df = get_spot_macd(spotAPI, instrument_id, 300)
                # df = get_macd(okFuture, coin.name + "_usd", time_type, "5min", 300)
                diff = list(df['diff'])
                dea = list(df['dea'])
                timestamp = list(df['time'])
                new_macd = 2 * (diff[-1] - dea[-1])
                macd_5min = list(df['macd'])

                # df_15 = get_macd(okFuture, coin.name + "_usd", time_type, "15min", 300)
                # diff_15 = list(df_15['diff'])
                # dea_15 = list(df_15['dea'])
                # timestamp_15 = list(df_15['timestamp'])
                # macd_15min = list(df_15['macd'])
                # new_macd_15 = macd_15min[-1]
Пример #24
0
    def build_position(self, ticker):
        global positions, highest, lowest
        try:
            last = float(ticker['last'])
            amount = int(position_unit * 2 * last)
            # 建仓
            if len(positions) == 0 and last >= highest:
                ret = futureAPI.take_order('', self.instrument_id, 1, last,
                                           amount, 1, 20)
                if ret and ret['result']:
                    new_order_id = ret['order_id']
                    print('建多仓:挂单开多,order_id: %s' % new_order_id)
                    time.sleep(WAIT_DEAL)
                    info = futureAPI.get_order_info(new_order_id,
                                                    self.instrument_id)
                    print('建仓订单信息: %s' % info)
                    status = info['status']
                    if status == '2':
                        deal_price = float(info['price_avg'])
                        filled_qty = int(info['filled_qty'])
                        coin_amount = float(filled_qty * 10 / deal_price)
                        stop_loss = deal_price - 0.5 * N
                        position = Position(price=deal_price,
                                            amount=coin_amount,
                                            stop_loss=stop_loss,
                                            time=timestamp2string(time.time()),
                                            side='more')
                        positions.append(position)
                    else:
                        futureAPI.revoke_order(self.instrument_id,
                                               new_order_id)

            if len(positions) == 0 and last <= lowest:
                ret = futureAPI.take_order('', self.instrument_id, 2, last,
                                           amount, 1, 20)
                if ret and ret['result']:
                    new_order_id = ret['order_id']
                    print('建空仓:挂单开空,order_id: %s' % new_order_id)
                    time.sleep(WAIT_DEAL)
                    info = futureAPI.get_order_info(new_order_id,
                                                    self.instrument_id)
                    print('订单信息: %s' % info)
                    status = info['status']
                    if status == '2':
                        deal_price = float(info['price_avg'])
                        filled_qty = int(info['filled_qty'])
                        coin_amount = float(filled_qty * 10 / deal_price)
                        stop_loss = deal_price + 0.5 * N
                        position = Position(price=deal_price,
                                            amount=coin_amount,
                                            stop_loss=stop_loss,
                                            time=timestamp2string(time.time()),
                                            side='less')
                        positions.append(position)
                    else:
                        futureAPI.revoke_order(self.instrument_id,
                                               new_order_id)

            highest = max(highest, last)
            lowest = min(lowest, last)

        except Exception as e:
            print('建仓出错, %s' % repr(e))
            traceback.print_exc()
Пример #25
0
def write_info_into_file(info, file_name):
    print(info)
    with codecs.open(file_name, 'a+', 'utf-8') as f:
        f.writelines(timestamp2string(time.time()) + ' ' + info + '\n')
Пример #26
0
def on_message(ws, message):
    message = bytes.decode(inflate(message), 'utf-8')  # data decompress
    if 'pong' in message or 'addChannel' in message:
        return
    global latest_price, last_avg_price, buy_price, more, less, deque_3s, deque_10s, deque_min, \
        deque_5m, ind_3s, ind_10s, ind_1min, ind_5m, write_lines, last_5min_macd, last_5min_macd_ts
    jmessage = json.loads(message)

    ts = time.time()
    now_time = timestamp2string(ts)
    if int(ts) - int(last_5min_macd_ts) >= 300:
        last_5min_macd_ts = int(ts)
        print(last_5min_macd_ts)
        if more == 0 and less == 0:
            ret = json.loads(
                okFuture.future_position_4fix("etc_usd", "quarter", "1"))
            print(ret)
            if len(ret["holding"]) > 0:
                buy_available = ret["holding"][0]["buy_available"]
                sell_available = ret["holding"][0]["sell_available"]
                if buy_available > 0:
                    thread.start_new_thread(ensure_sell_more, (
                        coin.name,
                        time_type,
                    ))
                if sell_available > 0:
                    thread.start_new_thread(ensure_sell_less, (
                        coin.name,
                        time_type,
                    ))
            else:
                print("确认未持仓")

    for each_message in jmessage:
        for jdata in each_message['data']:
            latest_price = float(jdata[1])
            deal_entity = DealEntity(jdata[0], float(jdata[1]),
                                     round(float(jdata[2]), 3), ts, jdata[4])

            handle_deque(deque_3s, deal_entity, ts, ind_3s)
            handle_deque(deque_10s, deal_entity, ts, ind_10s)
            handle_deque(deque_min, deal_entity, ts, ind_1min)
            handle_deque(deque_5m, deal_entity, ts, ind_5m)

            avg_3s_price = ind_3s.cal_avg_price()
            avg_10s_price = ind_10s.cal_avg_price()
            avg_min_price = ind_1min.cal_avg_price()
            avg_5m_price = ind_5m.cal_avg_price()
            price_10s_change = cal_rate(avg_3s_price, avg_10s_price)
            price_1m_change = cal_rate(avg_3s_price, avg_min_price)
            price_5m_change = cal_rate(avg_3s_price, avg_5m_price)

            if more == 1:
                if price_10s_change < 0:
                    cancel_uncompleted_order(coin.name, time_type)
                    if sell_more_batch(coin.name, time_type, latest_price):
                        more = 0
                        thread.start_new_thread(ensure_sell_more, (
                            coin.name,
                            time_type,
                        ))

            elif less == 1:
                if price_10s_change > 0:
                    cancel_uncompleted_order(coin.name, time_type)
                    if sell_less_batch(coin.name, time_type, latest_price):
                        less = 0
                        thread.start_new_thread(ensure_sell_less, (
                            coin.name,
                            time_type,
                        ))

            elif check_vol():
                if price_10s_change > incr_10s_rate:
                    if ind_3s.bid_vol >= vol_3s_bal * ind_3s.ask_vol and ind_1min.bid_vol >= vol_1m_bal * ind_1min.ask_vol:
                        latest_order_id = buyin_more_price(
                            coin.name, time_type, latest_price)
                        if latest_order_id:
                            more = 1
                            thread.start_new_thread(pend_order, (
                                coin.name,
                                time_type,
                                latest_order_id,
                                'more',
                            ))
                            buy_price = latest_price
                            info = u'发出做多信号!!!买入价格:' + str(
                                buy_price) + u', ' + now_time
                            with codecs.open(file_transaction, 'a+',
                                             'utf-8') as f:
                                f.writelines(info + '\n')

                elif price_10s_change < -incr_10s_rate:
                    if ind_3s.ask_vol >= vol_3s_bal * ind_3s.bid_vol and ind_1min.ask_vol >= vol_1m_bal * ind_1min.bid_vol:
                        latest_order_id = buyin_less_price(
                            coin.name, time_type, latest_price)
                        if latest_order_id:
                            less = 1
                            thread.start_new_thread(pend_order, (
                                coin.name,
                                time_type,
                                latest_order_id,
                                'less',
                            ))
                            buy_price = latest_price
                            info = u'发出做空信号!!!买入价格:' + str(
                                buy_price) + u', ' + now_time
                            with codecs.open(file_transaction, 'a+',
                                             'utf-8') as f:
                                f.writelines(info + '\n')

            price_info = deal_entity.type + u' now_price: %.4f, 3s_price: %.4f, 10s_price: %.4f, 1m_price: %.4f, ' \
                                            u'5min_price: %.4f' \
                         % (latest_price, avg_3s_price, avg_10s_price, avg_min_price, avg_5m_price)
            vol_info = u'cur_vol: %.3f, 3s vol: %.3f, 10s vol: %.3f, 1min vol: %.3f, ask_vol: %.3f, bid_vol: %.3f, 3s_ask_vol: %.3f, 3s_bid_vol: %.3f' \
                       % (deal_entity.amount, ind_3s.vol, ind_10s.vol, ind_1min.vol, ind_1min.ask_vol, ind_1min.bid_vol,
                          ind_3s.ask_vol, ind_3s.bid_vol)
            rate_info = u'10s_rate: %.2f%%, 1min_rate: %.2f%%, 5min_rate: %.2f%%, 5min_macd: %.6f' \
                        % (price_10s_change, price_1m_change, price_5m_change, last_5min_macd)

            print(price_info + '\r\n' + vol_info + '\r\n' + rate_info + u', ' +
                  now_time)
                        more = 0

                elif less == 1 and new_macd >= 0:
                    order_id = sell_less_price(okFuture, coin.name, time_type, buy_price)
                    if order_id:
                        order_id_queue.append(order_id)
                        less = 0

                if more == 0 and last_macd < 0 < new_macd:
                    order_id = buyin_more_price(okFuture, coin.name, time_type, buy_price)
                    if order_id:
                        order_id_queue.append(order_id)
                        print("挂单开多, order_id: %s, 价格: %.3f" % (str(order_id), buy_price))
                        more = 1
                elif less == 0 and last_macd > 0 > new_macd:
                    order_id = buyin_less_price(okFuture, coin.name, time_type, sell_price)
                    if order_id:
                        order_id_queue.append(order_id)
                        print("挂单开空, order_id: %s, 价格: %.3f" % (str(order_id), sell_price))
                        less = 1
                last_macd = new_macd
                if first:
                    first = False
                    for i in range(0, len(diff)):
                        print("macd: %.6f, diff: %.6f, dea: %.6f, macd_time: %s" % (
                        2 * (diff[i] - dea[i]), diff[i], dea[i], timestamp2string(timestamp[i])))
                print(new_macd, diff[-1], dea[-1], timestamp2string(timestamp[-1]), timestamp2string(ts))
        except:
            continue

Пример #28
0
def on_message(ws, message):
    message = bytes.decode(inflate(message), 'utf-8')  # data decompress
    if 'pong' in message or 'addChannel' in message:
        return
    global latest_price, last_avg_price, buy_price, more, less, deque_3s, deque_10s, deque_min, \
        deque_5m, ind_3s, ind_10s, ind_1min, ind_5m, write_lines, last_5min_macd, last_5min_macd_ts, moreless
    jmessage = json.loads(message)

    ts = time.time()
    now_time = timestamp2string(ts)
    if int(ts) - int(last_5min_macd_ts) >= 60:
        last_5min_macd_ts = int(ts)
        print(ts, last_5min_macd_ts)
        if more == 0 and less == 0 and moreless == 0:
            ret = futureAPI.get_specific_position(time_type)
            print(ret)
            if len(ret["holding"]) > 0:
                buy_available = int(ret["holding"][0]["long_avail_qty"])
                sell_available = int(ret["holding"][0]["short_avail_qty"])
                if buy_available > 0:
                    thread.start_new_thread(ensure_sell_more, (
                        futureAPI,
                        coin.name,
                        time_type,
                        latest_price,
                        buy_price,
                    ))
                if sell_available > 0:
                    thread.start_new_thread(ensure_sell_less, (
                        futureAPI,
                        coin.name,
                        time_type,
                        latest_price,
                        buy_price,
                    ))
            else:
                print("确认未持仓")

    for each_message in jmessage:
        for jdata in each_message['data']:
            latest_price = float(jdata[1])
            deal_entity = DealEntity(jdata[0], float(jdata[1]),
                                     round(float(jdata[2]), 3), ts, jdata[4])

            handle_deque(deque_3s, deal_entity, ts, ind_3s)
            handle_deque(deque_10s, deal_entity, ts, ind_10s)
            handle_deque(deque_min, deal_entity, ts, ind_1min)
            handle_deque(deque_5m, deal_entity, ts, ind_5m)

            # price_5m_ago = cal_price_ago(deque_5m)
            # print("price_5m_ago: %.4f" % price_5m_ago)
            avg_3s_price = ind_3s.cal_avg_price()
            avg_10s_price = ind_10s.cal_avg_price()
            avg_min_price = ind_1min.cal_avg_price()
            avg_5m_price = ind_5m.cal_avg_price()
            price_10s_change = cal_rate(avg_3s_price, avg_10s_price)
            price_1m_change = cal_rate(avg_3s_price, avg_min_price)
            price_5m_change = cal_rate(avg_3s_price, avg_5m_price)
            # price_5m_ago_change = cal_rate(latest_price, price_5m_ago)

            if more == 1:
                # 盈利中,放宽卖出条件,盈利最大化
                if latest_price > buy_price:
                    if price_1m_change <= -0.1 and price_5m_change <= 0:
                        if sell_more_batch(futureAPI, time_type, latest_price):
                            more = 0
                            thread.start_new_thread(ensure_sell_more, (
                                futureAPI,
                                coin.name,
                                time_type,
                                latest_price,
                                buy_price,
                            ))
                else:
                    if price_1m_change <= -0.2 or price_5m_change <= 0:
                        if sell_more_batch(futureAPI, time_type, latest_price):
                            more = 0
                            thread.start_new_thread(ensure_sell_more, (
                                futureAPI,
                                coin.name,
                                time_type,
                                latest_price,
                                buy_price,
                            ))

            elif less == 1:
                # 盈利中,放宽卖出条件,盈利最大化
                if latest_price < buy_price:
                    if price_1m_change >= 0.1 and price_5m_change >= 0:
                        if sell_less_batch(futureAPI, time_type, latest_price):
                            less = 0
                            thread.start_new_thread(ensure_sell_less, (
                                futureAPI,
                                coin.name,
                                time_type,
                                latest_price,
                                buy_price,
                            ))
                else:
                    if price_1m_change >= 0.2 or price_5m_change >= 0:
                        if sell_less_batch(futureAPI, time_type, latest_price):
                            less = 0
                            thread.start_new_thread(ensure_sell_less, (
                                futureAPI,
                                coin.name,
                                time_type,
                                latest_price,
                                buy_price,
                            ))

            if price_1m_change >= 0.2 and price_5m_change >= 0.3:
                btc_change = coin_recent_change_rate("btc")
                eth_change = coin_recent_change_rate("eth")
                print('btc_change: %.2f%%, eth change: %.2f%%' %
                      (btc_change, eth_change))
                write_lines.append(
                    'btc_change: %.2f%%, eth change: %.2f%% \r\n' %
                    (btc_change, eth_change))

                if btc_change >= 0.5 and eth_change >= 0.5:
                    if buyin_more(futureAPI, coin.name, time_type,
                                  latest_price + 0.01):
                        more = 1
                        thread.start_new_thread(ensure_buyin_more, (
                            futureAPI,
                            coin.name,
                            time_type,
                            latest_price,
                        ))
                        buy_price = latest_price
                        info = u'发出做多信号!!!买入价格:' + str(
                            buy_price) + u', ' + now_time
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')

            elif price_1m_change <= -0.2 and price_5m_change <= -0.3:
                btc_change = coin_recent_change_rate("btc")
                eth_change = coin_recent_change_rate("eth")
                print('btc_change: %.2f%%, eth change: %.2f%%' %
                      (btc_change, eth_change))
                write_lines.append(
                    'btc_change: %.2f%%, eth change: %.2f%% \r\n' %
                    (btc_change, eth_change))
                if btc_change <= -0.6 and eth_change <= -0.6:
                    if buyin_less(futureAPI, coin.name, time_type,
                                  latest_price - 0.01):
                        less = 1
                        thread.start_new_thread(ensure_buyin_less, (
                            futureAPI,
                            coin.name,
                            time_type,
                            latest_price,
                        ))
                        buy_price = latest_price
                        info = u'发出做空信号!!!买入价格:' + str(
                            buy_price) + u', ' + now_time
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')

            last_avg_price = latest_price

            price_info = deal_entity.type + u' now_price: %.4f, 3s_price: %.4f, 10s_price: %.4f, 1m_price: %.4f, ' \
                                            u'5min_price: %.4f' \
                         % (latest_price, avg_3s_price, avg_10s_price, avg_min_price, avg_5m_price)
            vol_info = u'cur_vol: %.3f, 3s vol: %.3f, 10s vol: %.3f, 1min vol: %.3f, ask_vol: %.3f, bid_vol: %.3f, 3s_ask_vol: %.3f, 3s_bid_vol: %.3f' \
                       % (deal_entity.amount, ind_3s.vol, ind_10s.vol, ind_1min.vol, ind_1min.ask_vol, ind_1min.bid_vol,
                          ind_3s.ask_vol, ind_3s.bid_vol)
            rate_info = u'10s_rate: %.2f%%, 1min_rate: %.2f%%, 5min_rate: %.2f%%' \
                        % (price_10s_change, price_1m_change, price_5m_change)
            write_info = price_info + u', ' + vol_info + u', ' + rate_info + u', ' + now_time + '\r\n'
            write_lines.append(write_info)
            if len(write_lines) >= 100:
                with codecs.open(file_deal, 'a+', 'UTF-8') as f:
                    f.writelines(write_lines)
                    write_lines = []

            print(price_info + '\r\n' + vol_info + '\r\n' + rate_info + u', ' +
                  now_time)
Пример #29
0
def spot_buy(spotAPI, instrument_id, amount, price):
    try:
        if amount > 0:
            amount = float(math.floor(amount * 100) / 100)
            ret = spotAPI.take_order('limit', 'buy', instrument_id, amount, margin_trading=1, client_oid='', price=price, funds='', )
            if ret and ret['result']:
                return ret["order_id"]
        return False
    except Exception as e:
        log_trade_v3("In spot_buy func, error: %s, time: %s" % (traceback.format_exc(), timestamp2string(time.time())))
        return "spot_buy_exception"
Пример #30
0
def on_message(ws, message):
    message = bytes.decode(inflate(message), 'utf-8')  # data decompress
    if 'pong' in message or 'addChannel' in message:
        return
    global latest_price, last_avg_price, less, deque_3s, deque_10s, deque_min, future_buy_price,\
        deque_3m, ind_3s, ind_10s, ind_1min, ind_3m, write_lines, last_3min_macd_ts, new_macd, lessless,\
        future_buy_time, spot_buy_time, spot_sell_price, spot_buy_price, lessmore, future_more_buy_price
    jmessage = json.loads(message)

    ts = time.time()
    now_time = timestamp2string(ts)
    if int(ts) - last_3min_macd_ts > 60:
        last_3min_macd_ts = int(ts)
        df = get_spot_macd(spotAPI, instrument_id, 300)
        diff = list(df['diff'])
        dea = list(df['dea'])
        new_macd = 2 * (diff[-1] - dea[-1])
        with codecs.open(file_deal, 'a+', 'UTF-8') as f:
            f.writelines('update macd: %.6f\r\n' % new_macd)

    for each_message in jmessage:
        for jdata in each_message['data']:
            latest_price = float(jdata[1])
            deal_entity = DealEntity(jdata[0], float(jdata[1]), round(float(jdata[2]), 3), ts, jdata[4])

            handle_deque(deque_3s, deal_entity, ts, ind_1s)
            handle_deque(deque_10s, deal_entity, ts, ind_10s)
            handle_deque(deque_min, deal_entity, ts, ind_1min)
            handle_deque(deque_3m, deal_entity, ts, ind_3m)

            avg_3s_price = ind_1s.cal_avg_price()
            avg_10s_price = ind_10s.cal_avg_price()
            avg_min_price = ind_1min.cal_avg_price()
            avg_3m_price = ind_3m.cal_avg_price()
            price_10s_change = cal_rate(avg_3s_price, avg_10s_price)
            price_1m_change = cal_rate(avg_3s_price, avg_min_price)
            price_3m_change = cal_rate(avg_3s_price, avg_3m_price)

            # 做空
            if lessless == 0 and check_do_future_less(price_3m_change, price_1m_change, price_10s_change):
                latest_future_price = get_latest_future_price(futureAPI, future_instrument_id)
                if not latest_future_price:
                    latest_future_price = latest_price
                future_buyin_less_order_id = buyin_less(
                    futureAPI, coin.name, future_instrument_id, latest_future_price, amount=None, lever_rate=20, taker=True)
                if future_buyin_less_order_id:
                    lessless = 1
                    future_buy_time = int(ts)
                    thread.start_new_thread(ensure_buyin_less,
                                            (futureAPI, coin.name, future_instrument_id, latest_future_price, future_buyin_less_order_id,))
                    future_buy_price = latest_price - 0.01

                    info = now_time + u' 发出做空信号!!future_buy_price: ' + str(future_buy_price)
                    with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                        f.writelines(info + '\n')
            if less == 0 and check_do_future_less(price_3m_change, price_1m_change, price_10s_change):
                sell_id = sell_all_position(spotAPI, instrument_id, latest_price - 0.001)
                if sell_id:
                    spot_buy_time = int(ts)
                    time.sleep(1)
                    sell_order_info = spotAPI.get_order_info(sell_id, instrument_id)
                    if sell_order_info['status'] == 'filled' or sell_order_info['status'] == 'part_filled':
                        less = 1
                        spot_sell_price = float(sell_order_info['price'])
                        info = now_time + u' 现货全部卖出!!!spot_sell_price:' + str(spot_sell_price)
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')
                    else:
                        spotAPI.revoke_order_exception(instrument_id, sell_id)

            if lessless == 1:
                if price_1m_change > 0 and new_macd > 0:
                    if sell_less(futureAPI, future_instrument_id):
                        lessless = 0
                        thread.start_new_thread(ensure_sell_less, (futureAPI, coin.name, future_instrument_id,latest_price, future_buy_price))
                        info = u'做空止盈,盈利%.3f, time: %s' % (future_buy_price - latest_price, now_time)
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')
                        time.sleep(5)

                        # do more
                        retry = 10
                        while retry > 0:
                            retry -= 1
                            latest_future_price = get_latest_future_price(futureAPI, future_instrument_id)
                            if not latest_future_price:
                                latest_future_price = latest_price
                            future_buyin_more_order_id = buyin_more(
                                futureAPI, coin.name, future_instrument_id, latest_future_price, amount=None,
                                lever_rate=20, taker=True)
                            if future_buyin_more_order_id:
                                lessmore = 1
                                thread.start_new_thread(ensure_buyin_more,
                                                        (futureAPI, coin.name, future_instrument_id, latest_future_price, future_buyin_more_order_id,))
                                future_more_buy_price = latest_price
                                info = u'%s 反手做多,现货价格: %.3f' % (now_time, latest_price)
                                with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                                    f.writelines(info + '\n')
                                break
                            time.sleep(0.5)

                elif int(ts) - future_buy_time >= 60 and price_10s_change > 0.01:
                    if sell_less(futureAPI, future_instrument_id):
                        lessless = 0
                        thread.start_new_thread(ensure_sell_less, (
                            futureAPI, coin.name, future_instrument_id, latest_price, future_buy_price))
                        info = u'做空止损,亏损%.2f, time: %s' % ((latest_price - spot_buy_price), now_time)
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')
                elif latest_price > future_buy_price * 1.01:
                    if sell_less(futureAPI, future_instrument_id):
                        lessless = 0
                        thread.start_new_thread(ensure_sell_less, (
                            futureAPI, coin.name, future_instrument_id, latest_price, future_buy_price))
                        info = u'做空止损,亏损%.2f, time: %s' % ((latest_price - spot_sell_price), now_time)
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')
            if less == 1:
                if price_1m_change > 0 and new_macd > 0:
                    usdt_account = spotAPI.get_coin_account_info("usdt")
                    usdt_available = float(usdt_account['available'])
                    amount = math.floor(usdt_available / latest_price)
                    if amount > 0:
                        buy_id = spot_buy(spotAPI, instrument_id, amount, latest_price)
                        if buy_id:
                            time.sleep(3)
                            order_info = spotAPI.get_order_info(buy_id, instrument_id)
                            if order_info['status'] == 'filled':
                                less = 0
                                spot_buy_price = order_info['price']
                                info = u'macd > 0, 买入现货止盈!!!买入价格:' + str(spot_buy_price) + u', ' + now_time
                                with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                                    f.writelines(info + '\n')
                            else:
                                attempts = 5
                                while attempts > 0:
                                    attempts -= 1
                                    spotAPI.revoke_order_exception(instrument_id, buy_id)
                                    time.sleep(1)
                                    order_info = spotAPI.get_order_info(buy_id, instrument_id)
                                    if order_info['status'] == 'cancelled':
                                        break
                    else:
                        less = 0

                if int(ts) - spot_buy_time > 60:
                    if latest_price > spot_sell_price and price_1m_change >= 0 and price_10s_change >= 0 \
                            and (ind_1min.bid_vol > ind_1min.ask_vol or price_3m_change >= 0):
                        usdt_account = spotAPI.get_coin_account_info("usdt")
                        usdt_available = float(usdt_account['available'])
                        amount = math.floor(usdt_available / latest_price)
                        if amount > 0:
                            buy_id = spot_buy(spotAPI, instrument_id, amount, latest_price)
                            if buy_id:
                                time.sleep(3)
                                order_info = spotAPI.get_order_info(buy_id, instrument_id)
                                if order_info['status'] == 'filled':
                                    less = 0
                                    spot_buy_price = order_info['price']
                                    info = u'macd > 0, 买入现货止盈!!!买入价格:' + str(spot_buy_price) + u', ' + now_time
                                    with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                                        f.writelines(info + '\n')
                                else:
                                    attempts = 5
                                    while attempts > 0:
                                        attempts -= 1
                                        spotAPI.revoke_order_exception(instrument_id, buy_id)
                                        time.sleep(1)
                                        order_info = spotAPI.get_order_info(buy_id, instrument_id)
                                        if order_info['status'] == 'cancelled':
                                            break
                        else:
                            less = 0

            if lessmore == 1:
                if new_macd < 0 or latest_price < future_more_buy_price * 0.995:
                    if sell_more(futureAPI, future_instrument_id):
                        lessmore = 0
                        thread.start_new_thread(ensure_sell_more, (futureAPI, coin.name, future_instrument_id, latest_price, future_more_buy_price))
                        info = u'做多止盈,盈利%.3f, time: %s' % (future_more_buy_price - latest_price, now_time)
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')

            holding_status = 'future_less: %d, spot_less: %d, future_more: %d' % (lessless, less, lessmore)
            price_info = deal_entity.type + u' now_price: %.4f, 3s_price: %.4f, 10s_price: %.4f, 1m_price: %.4f, ' \
                                            u'3min_price: %.4f' \
                         % (latest_price, avg_3s_price, avg_10s_price, avg_min_price, avg_3m_price)
            vol_info = u'cur_vol: %.3f, 3s vol: %.3f, 10s vol: %.3f, 1min vol: %.3f, ask_vol: %.3f, bid_vol: %.3f, ' \
                       u'3s_ask_vol: %.3f, 3s_bid_vol: %.3f, 3min vol: %.3f, 3min_ask_vol: %.3f, 3min_bid_vol: %.3f' \
                       % (deal_entity.amount, ind_1s.vol, ind_10s.vol, ind_1min.vol, ind_1min.ask_vol, ind_1min.bid_vol,
                          ind_1s.ask_vol, ind_1s.bid_vol, ind_3m.vol, ind_3m.ask_vol, ind_3m.bid_vol)
            rate_info = u'10s_rate: %.2f%%, 1min_rate: %.2f%%, 3min_rate: %.2f%%, new_macd: %.6f' \
                        % (price_10s_change, price_1m_change, price_3m_change, new_macd)
            write_info = holding_status + u', ' + price_info + u', ' + vol_info + u', ' + rate_info + u', ' + now_time + '\r\n'
            write_lines.append(write_info)
            if len(write_lines) >= 100:
                with codecs.open(file_deal, 'a+', 'UTF-8') as f:
                    f.writelines(write_lines)
                    write_lines = []

            print(holding_status + '\r\n' + price_info + '\r\n' + vol_info + '\r\n' + rate_info + u', ' + now_time)