예제 #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_less(futureAPI, coin_name, time_type, buy_price, amount=None, lever_rate=20, taker=True):
    ts = time.time()
    now_time = timestamp2string(ts)
    try:
        coin_account = futureAPI.get_coin_account(coin_name)
        balance = float(coin_account['equity'])
        if balance < 1:
            log_trade_v3("In future buyin_less function, available balance less than 1, balance: %.2f" % balance)
            return False
        if not amount:
            amount = math.floor(balance * lever_rate * (buy_price - 0.1) / 10 * 0.95)
            log_trade_v3('In buyin_less function, plan to buyin amount: %d' % amount)

        if amount >= 1:
            if taker:
                ret = futureAPI.take_order('', time_type, 2, buy_price, amount, 1, lever_rate)
            else:
                ret = futureAPI.take_order('', time_type, 2, buy_price, amount, 0, lever_rate)

            log_trade_v3('In future_buyin_less function: %s, time: %s' % (ret, now_time))

            if ret and ret['result']:
                email_msg = "下单做空%s成功,最新价格: %.4f, 成交张数: %d, 时间: %s, 成交结果: %s" \
                            % (coin_name, buy_price, amount, now_time, ret)
                thread.start_new_thread(send_email, (email_msg,))
                return ret["order_id"]
        else:
            return False
    except Exception as e:
        info = traceback.format_exc()
        log_trade_v3("In future buyinless func, info: %s" % info)
        return False
예제 #3
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')
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
예제 #5
0
def buyin_less_batch(futureAPI, coin_name, time_type, buy_price, lever_rate=20, amount=None):
    now_time = timestamp2string(time.time())
    try:
        if not amount:
            coin_account = futureAPI.get_coin_account(coin_name)
            balance = float(coin_account['total_avail_balance'])
            if balance < 1:
                log_trade_v3(
                    'In future buyin_less_batch function, %s balance less than 1, balance: %.2f' % (coin_name, balance))
                return False
            amount = math.floor(balance * lever_rate * buy_price / 10 * 0.95)
        while amount >= 5:
            order_data = gen_orders_data(buy_price, amount, 2, 5)
            ret = futureAPI.take_orders(time_type, order_data, lever_rate)
            if ret and ret['result']:
                email_msg = "批量下单做空%s成功,最新价格: %.4f, 成交张数: %d, 时间: %s, 成交结果: %s" \
                            % (coin_name, buy_price, amount, now_time, ret)
                thread.start_new_thread(send_email, (email_msg,))
                return True
            amount = math.floor(amount * 0.95)
        return False
    except Exception as e:
        log_trade_v3("In future buyin_less_batch func, error info: %s, time: %s" % (repr(e), now_time))
        log_trade_v3(traceback.format_exc())
        return False
예제 #6
0
def ensure_sell_less(futureAPI, coin_name, time_type, latest_price, buy_price, lever_rate=20):
    now_time = timestamp2string(time.time())
    try:
        sleep_time = 3
        while True:
            time.sleep(sleep_time)
            jRet = futureAPI.get_specific_position(time_type)

            if len(jRet["holding"]) > 0:
                cancel_uncompleted_order(futureAPI, coin_name, time_type)
                time.sleep(1)
                jRet = futureAPI.get_specific_position(time_type)
                short_available = int(jRet["holding"][0]["short_avail_qty"])
                if short_available == 0:
                    break
                futureAPI.take_order('', time_type, 4, latest_price, short_available, 1, lever_rate)
            else:
                break

        info = u'做空卖出成功!!!卖出价格:' + str(latest_price) + u', 收益: ' + str(buy_price - latest_price) \
               + ', ' + now_time
        thread.start_new_thread(send_email, (info,))
        file_transaction = coin_name + '_future_transaction.txt'
        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
            f.writelines(info + '\n')
    except Exception as e:
        log_trade_v3("In future ensure_sell_less function, error: %s\r\n traceback: %s\r\n time: %s"
                     % (repr(e), traceback.format_exc(), now_time))
        return False
예제 #7
0
def ensure_sell_more(futureAPI, coin_name, time_type, latest_price, buy_price, lever_rate=20):
    try:
        sleep_time = 10
        while sleep_time > 0:
            time.sleep(sleep_time)
            jRet = futureAPI.get_specific_position(time_type)

            if len(jRet["holding"]) > 0:
                cancel_uncompleted_order(futureAPI, coin_name, time_type)
                time.sleep(1)
                jRet = futureAPI.get_specific_position(time_type)
                buy_available = int(jRet["holding"][0]["long_avail_qty"])
                futureAPI.take_order('', time_type, 3, latest_price, buy_available, 1, lever_rate)
            else:
                break
        ts = time.time()
        now_time = timestamp2string(ts)
        info = u'做多卖出成功!!!卖出价格:' + str(latest_price) + u', 收益: ' + str(latest_price - buy_price) \
               + ', ' + now_time
        thread.start_new_thread(send_email, (info,))
        file_transaction = coin_name + '_future_transaction.txt'
        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
            f.writelines(info + '\n')
    except Exception as e:
        log_trade_v3(repr(e))
        return False
예제 #8
0
def ensure_buyin_less(futureAPI, coin_name, time_type, buy_price, order_id, lever_rate=20):
    now_time = timestamp2string(time.time())
    try:
        retry = 3
        while retry > 0:
            time.sleep(2)
            retry -= 1
            if order_id:
                futureAPI.revoke_order(time_type, order_id)
            else:
                cancel_uncompleted_order(futureAPI, coin_name, time_type, 2)
            time.sleep(1)
            coin_account = futureAPI.get_coin_account(coin_name)
            balance = float(coin_account['total_avail_balance'])
            # 撤销所有未完成挂单后,若balance<1则认为已全仓买入
            if balance < 1:
                return
            amount = math.floor(balance * lever_rate * buy_price / 10 * 0.95)
            if not buyin_less_batch(futureAPI, coin_name, time_type, buy_price, 20, amount):
                break
        time.sleep(5)
        cancel_uncompleted_order(futureAPI, coin_name, time_type, 2)
    except Exception as e:
        log_trade_v3("In ensure_buyin_less function, error: %s, time: %s" % (traceback.format_exc(), now_time))
        return
예제 #9
0
 def print_detail(self):
     print(timestamp2string(self.timestamp))
     for i in range(0, 20):
         print('sell' + str(20 - i) + '\t' + self.asks[i][0] + ':\t' +
               self.asks[i][1])
     for i in range(0, 20):
         print('buy ' + str(i + 1) + '\t' + self.bids[i][0] + ':\t' +
               self.bids[i][1])
예제 #10
0
def buyin_less_turn(futureAPI, coin_name, time_type, buy_price, amount=None, lever_rate=20, taker=True):
    try:
        coin_account = futureAPI.get_coin_account(coin_name)
        balance = float(coin_account['equity'])
        if not amount:
            amount = math.floor(balance * lever_rate * (buy_price - 0.1) / 10 * 0.95)

        turn = int(amount / batch_size)
        ts = time.time()
        now_time = timestamp2string(ts)

        if turn == 0 and amount >= 1:
            if taker:
                ret = futureAPI.take_order('', time_type, 2, buy_price, amount, 1, lever_rate)
            else:
                ret = futureAPI.take_order('', time_type, 2, buy_price, amount, 0, lever_rate)

            log_trade_v3('In future_buyin_less funciton: %s, time: %s' % (ret, now_time))

            if ret and ret['result']:
                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 ret["order_id"]
        else:
            amount -= turn * batch_size
            while turn > 0:
                futureAPI.take_order('', time_type, 2, '', batch_size, 1, lever_rate)
                time.sleep(0.3)
                turn -= 1
            while amount >= 1:
                ret = futureAPI.take_order('', time_type, 2, buy_price, amount, 1, lever_rate)
                log_trade_v3(ret)

                if ret and ret['result']:
                    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 ret["order_id"]
                amount = math.floor(amount * 0.95)
                time.sleep(1)
        return True
    except Exception as e:
        log_trade_v3(repr(e))
        return False
예제 #11
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
예제 #12
0
def buyin_more(futureAPI, coin_name, time_type, buy_price=None, amount=None, lever_rate=20):
    try:
        if not amount:
            result = futureAPI.get_coin_account(coin_name)
            balance = float(result['equity'])
            amount = math.floor(balance * lever_rate * buy_price / 10)

        turn = int(amount / batch_size)

        if turn == 0 and amount >= 1:
            if buy_price:
                ret = futureAPI.take_order('', time_type, 1, buy_price, amount, 0, lever_rate)
            else:
                ret = futureAPI.take_order('', time_type, 1, buy_price, amount, 1, lever_rate)
            log_trade_v3(ret)

            if ret and ret['result']:
                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 ret["order_id"]
        else:
            amount -= turn * batch_size
            while turn > 0:
                futureAPI.take_order('', time_type, 1, buy_price, batch_size, 1, lever_rate)
                time.sleep(0.3)
                turn -= 1
            while amount >= 1:
                ret = futureAPI.take_order('', time_type, 1, buy_price, amount, 1, lever_rate)
                log_trade_v3(ret)

                if ret and ret['result']:
                    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 ret["order_id"]
                amount = math.floor(amount * 0.95)
                time.sleep(1)
        return True
    except Exception as e:
        info = traceback.format_exc()
        log_trade_v3("In future buyinmore func, info: %s" % info)
        return False
예제 #13
0
def gm_character_info(cmd, ts, args, sign):
    res_err = {'result': 1, 'character_info': {}}

    if len(args) != 1:
        res_err['result'] = GM_INVALID_ARGS
        defer.returnValue(res_err)

    _cid = int(args['character_id'])

    _dict_data = {}
    user = g_UserMgr.getUserByCid(_cid)
    if user:
        _dict_data = copy.deepcopy(user.info)
        if user.temp_lost:
            _dict_data['online'] = 0
        else:
            _dict_data['online'] = 1
    else:
        try:
            errorno = yield gs_call("gs_gm_login", (_cid, True))
            if errorno:
                res_err['result'] = GM_INVALID_CID
                defer.returnValue(res_err)

            _dict_data = yield gs_call('gs_gm_get_character_info', [_cid])
            _dict_data['online'] = 0
        except Exception as e:
            log.exception()
            res_err['result'] = GM_INVALID_ERROR
            defer.returnValue(res_err)

    _dict_data['register_time'] = timestamp2string(_dict_data['register_time'])
    _dict_data['last_login_time'] = timestamp2string(
        _dict_data['last_login_time'])

    _dict_data['forbidden_seconds'] = yield check_character_status(
        _cid, TYPE_FORBIDDEN)
    _dict_data['mute_seconds'] = yield check_character_status(_cid, TYPE_MUTE)

    res_err['character_info'] = _dict_data
    defer.returnValue(res_err)
예제 #14
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))
예제 #15
0
def gm_character_info(cmd, ts, args, sign):
    res_err = {'result': 1, 'character_info': {}}

    if len(args) != 1:
        res_err['result'] = GM_INVALID_ARGS
        defer.returnValue( res_err )

    _cid = int(args['character_id'])

    _dict_data = {}
    user = g_UserMgr.getUserByCid( _cid )
    if user:
        _dict_data = copy.deepcopy(user.info)
        if user.temp_lost:
            _dict_data['online'] = 0
        else:
            _dict_data['online'] = 1
    else:
        try:
            errorno = yield gs_call("gs_gm_login", (_cid, True))
            if errorno:
                res_err['result'] = GM_INVALID_CID
                defer.returnValue( res_err )

            _dict_data = yield gs_call('gs_gm_get_character_info', [_cid])
            _dict_data['online'] = 0
        except Exception as e:
            log.exception()
            res_err['result'] = GM_INVALID_ERROR
            defer.returnValue( res_err )

    _dict_data['register_time'] = timestamp2string( _dict_data['register_time'] )
    _dict_data['last_login_time'] = timestamp2string( _dict_data['last_login_time'] )

    _dict_data['forbidden_seconds'] = yield check_character_status(_cid, TYPE_FORBIDDEN)
    _dict_data['mute_seconds'] = yield check_character_status(_cid, TYPE_MUTE)

    res_err['character_info'] = _dict_data
    defer.returnValue( res_err )
예제 #16
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')
예제 #17
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
예제 #18
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
예제 #19
0
def buyin_less(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, 2, 1, lever_rate)
        else:
            ret = okFuture.future_trade(coin_name + "_usd", time_type, buy_price, amount, 2, 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
예제 #20
0
def sell_less(futureAPI, time_type, lever_rate=20):
    now_time = timestamp2string(time.time())
    try:
        position = futureAPI.get_specific_position(time_type)
        log_trade_v3('In sell_less func, %s position: %s' % (time_type, position))
        while len(position["holding"]) > 0:
            amount = int(position["holding"][0]["short_avail_qty"])
            if amount == 0:
                return True
            ret = futureAPI.take_order('', time_type, 4, '', amount, 1, lever_rate)
            log_trade_v3('In future sell_less func, sell less result: %s, time: %s' % (ret, now_time))
            if ret and ret['result']:
                break
            else:
                return False
        return True
    except Exception as e:
        info = traceback.format_exc()
        log_trade_v3("In future sell_less func, error: %s\r\n traceback: %s\r\n time: %s" % (repr(e), info, now_time))
        return False
예제 #21
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"
예제 #22
0
def buyin_more_batch(futureAPI, coin_name, time_type, latest_price, lever_rate=20, amount=None):
    now_time = timestamp2string(time.time())
    try:
        result = futureAPI.get_coin_account(coin_name)
        balance = float(result['equity'])
        if not amount:
            amount = math.floor(balance * lever_rate * latest_price / 10)
        while amount >= 5:
            order_data = gen_orders_data(latest_price, amount, 1, 5)
            ret = futureAPI.take_orders(time_type, order_data, lever_rate)
            if ret and ret['result']:
                email_msg = "批量下单做多%s成功,最新价格: %.4f, 成交张数: %d, 时间: %s, 成交结果: %s" \
                            % (coin_name, latest_price, amount, now_time, ret)
                thread.start_new_thread(send_email, (email_msg,))
                return True
            amount = math.floor(amount * 0.95)
        return False
    except Exception as e:
        log_trade_v3("In future buyin_more_batch function, error: %s, time: %s" % (repr(e), now_time))
        log_trade_v3(traceback.format_exc())
        return False
예제 #23
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(5)
            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
예제 #24
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)
예제 #25
0
                print('当前行情: %s' % ret)

                if more == 1 and (new_macd < 0 or
                                  (check_trend(list(df['macd'])) == 'down'
                                   and new_macd < buy_thread)):
                    sell_price = float(ret['best_ask']) - 0.0005
                    order_id = sell_all_position(spotAPI, instrument_id,
                                                 sell_price)
                    if order_id:
                        order_id_queue.append(order_id)

                elif more == 0 and last_macd <= buy_thread < new_macd:
                    buy_price = float(ret['best_bid']) + 0.0005
                    order_id = buy_all_position(spotAPI, instrument_id,
                                                buy_price)
                    if order_id:
                        order_id_queue.append(order_id)

                last_macd = new_macd
                for i in range(len(diff) - 10, len(diff)):
                    print(
                        "macd: %.6f, diff: %.6f, dea: %.6f, macd_time: %s\r\n"
                        % (2 *
                           (diff[i] - dea[i]), diff[i], dea[i], timestamp[i]))
                print("finish calculating macd... %s" % timestamp2string(ts))

        except Exception as e:
            print(repr(e))
            traceback.print_exc()
            continue
예제 #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, less, deque_3s, deque_10s, deque_min,\
        deque_3m, ind_1s, ind_10s, ind_1min, ind_3m, write_lines, last_3min_macd_ts, new_macd, lessless,\
        future_buy_time, buyin_price_spot, moremore, freeze_time
    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 int(
                    ts) - freeze_time > 180 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)
                    buyin_price_spot = latest_price
                    thread.start_new_thread(ensure_buyin_less, (
                        futureAPI,
                        coin.name,
                        future_instrument_id,
                        latest_future_price,
                        future_buyin_less_order_id,
                    ))

                    info = now_time + u' 发出做空信号!!future_buy_price: ' + str(
                        latest_future_price)
                    with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                        f.writelines(info + '\n')

            if moremore == 0 and int(
                    ts) - freeze_time > 180 and check_do_future_more(
                        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_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:
                    moremore = 1
                    future_buy_time = int(ts)
                    buyin_price_spot = latest_price
                    thread.start_new_thread(ensure_buyin_more, (
                        futureAPI,
                        coin.name,
                        future_instrument_id,
                        latest_future_price,
                        future_buyin_more_order_id,
                    ))
                    info = now_time + u' 发出做多信号!!future_buy_price: ' + str(
                        latest_future_price)
                    with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                        f.writelines(info + '\n')
            if moremore == 1:
                if int(ts) - future_buy_time >= 60 and price_10s_change < -0.03:
                    if sell_more(futureAPI, future_instrument_id):
                        moremore = 0
                        thread.start_new_thread(
                            ensure_sell_more,
                            (futureAPI, coin.name, future_instrument_id,
                             latest_price, buyin_price_spot))
                        info = u'做多止盈,盈利%.3f, time: %s' % (
                            latest_price - buyin_price_spot, now_time)
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')
                        freeze_time = int(ts)
                elif latest_price < buyin_price_spot * 0.99:
                    if sell_more(futureAPI, future_instrument_id):
                        moremore = 0
                        thread.start_new_thread(
                            ensure_sell_more,
                            (futureAPI, coin.name, future_instrument_id,
                             latest_price, buyin_price_spot))
                        info = u'做多止损,亏损%.3f, time: %s' % (
                            buyin_price_spot - latest_price, now_time)
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')
                        freeze_time = int(ts)
            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, buyin_price_spot))
                        freeze_time = int(ts)
                        info = u'做空止盈,盈利%.3f, time: %s' % (
                            buyin_price_spot - latest_price, now_time)
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')

                elif int(ts
                         ) - future_buy_time >= 60 and price_10s_change > 0.03:
                    if sell_less(futureAPI, future_instrument_id):
                        lessless = 0
                        thread.start_new_thread(
                            ensure_sell_less,
                            (futureAPI, coin.name, future_instrument_id,
                             latest_price, buyin_price_spot))
                        freeze_time = int(ts)
                        info = u'做空止盈,盈利%.2f, time: %s' % (
                            (latest_price - buyin_price_spot), now_time)
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')
                elif latest_price > buyin_price_spot * 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, buyin_price_spot))
                        freeze_time = int(ts)
                        info = u'做空止损,亏损%.2f, time: %s' % (
                            (latest_price - buyin_price_spot), now_time)
                        with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                            f.writelines(info + '\n')

            holding_status = 'future_less: %d, future_more: %d' % (lessless,
                                                                   moremore)
            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)
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)
예제 #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, less, deque_3s, deque_10s, deque_min, future_buy_price,\
        deque_3m, ind_1s, 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
    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 ind_3m.vol > 500000 and ind_3m.ask_vol > 1.3 * ind_3m.bid_vol \
                    and ind_1min.vol > 300000 and ind_1min.ask_vol > 1.5 * ind_1min.bid_vol and -1.2 < price_1m_change \
                    and price_3m_change < price_1m_change < -0.4 and price_10s_change <= -0.05 and new_macd < 0:
                future_buyin_less_order_id = buyin_less(futureAPI,
                                                        coin.name,
                                                        future_instrument_id,
                                                        latest_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_price,
                        future_buyin_less_order_id,
                    ))
                    future_buy_price = latest_price - 0.01

                    info = u'发出做空信号!!买入时间: ' + now_time
                    with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                        f.writelines(info + '\n')
            if less == 0 and ind_3m.vol > 500000 and ind_3m.ask_vol > 1.3 * ind_3m.bid_vol \
                    and ind_1min.vol > 300000 and ind_1min.ask_vol > 1.5 * ind_1min.bid_vol and -1.2 < price_1m_change \
                    and price_3m_change < price_1m_change < -0.4 and price_10s_change <= -0.05 and new_macd < 0:
                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 = u'现货全部卖出!!!平均成交价格:' + spot_sell_price + u', ' + now_time
                        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')
                elif int(ts) - future_buy_time >= 60:
                    if latest_price > spot_sell_price and price_3m_change >= 0 and price_1m_change >= 0 and price_10s_change >= 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'做空止损,亏损%.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 > spot_sell_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_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
                                    apot_buy_price = order_info['price']
                                    info = u'macd > 0, 买入现货止盈!!!买入价格:' + str(
                                        apot_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 = 'future_less: %d, spot_less: %d' % (lessless,
                                                                 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)
예제 #29
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]
예제 #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, buy_price, more, less, deque_3s, deque_10s, deque_min, count, \
        deque_5m, ind_3s, ind_10s, ind_1min, ind_5m, write_lines, last_5min_macd, last_5min_macd_ts, prev_5m_price, prev_15m_price, \
        prev_5min_price_less_15min, prev_5min_price_more_15min
    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)
        last_5min_macd, tmp_ts = get_macd("etc_usd", time_type, "1min")
        print(last_5min_macd, 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)
            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_5m_price = ind_5m.cal_avg_price()
            avg_15m_price = ind_15m.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 avg_5m_price < prev_5m_price:
                    count += 1
                    if count > 3:
                        if sell_more(coin.name, time_type, latest_price):
                            more = 0
                            thread.start_new_thread(ensure_sell_more, (
                                coin.name,
                                time_type,
                            ))

            elif less == 1:
                if avg_5m_price > prev_5m_price:
                    count += 1
                    if count > 3:
                        if sell_less(coin.name, time_type, latest_price):
                            less = 0
                            thread.start_new_thread(ensure_sell_less, (
                                coin.name,
                                time_type,
                            ))

            elif prev_5m_price <= prev_15m_price and avg_5m_price > avg_15m_price:
                if buyin_more_price(coin.name, time_type,
                                    latest_price - 0.002):
                    more = 1
                    count = 0
                    buy_price = latest_price - 0.002
                    info = u'发出做多信号!!!买入价格:' + str(
                        buy_price) + u', ' + now_time
                    with codecs.open(file_transaction, 'a+', 'utf-8') as f:
                        f.writelines(info + '\n')

            elif prev_5m_price >= prev_15m_price and avg_5m_price < avg_15m_price:
                if buyin_less_price(coin.name, time_type,
                                    latest_price + 0.002):
                    less = 1
                    count = 0
                    buy_price = latest_price + 0.002
                    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, 15min_price: %.4f' \
                        % (price_10s_change, price_1m_change, price_5m_change, last_5min_macd, avg_15m_price)

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

            prev_5m_price = avg_5m_price
            prev_15m_price = avg_15m_price
예제 #31
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