Beispiel #1
0
def run():
    while 1:
        # 整点运行
        current = time.time()
        time.sleep(interval - current % interval)
        combination_list = Combination.all()
        try:
            for combination in combination_list:
                if combination.status != Status.Active:  # 不活跃的组合不再运行
                    continue
                # 获取account,避免频繁调用api
                fetch_combination_account(combination=combination,
                                          status=Status.Active)
                time.sleep(1)
        except Exception as e:
            try:
                ExceptionInfoModel(host=ip,
                                   source='FETCH_ACCOUNT_DATA',
                                   message=e.message,
                                   log_time=datetime.utcnow()).add()
            except:
                pass
            print("{}|Exception|{}".format(
                datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f'), e.message))
            print("Traceback|{}".format(traceback.format_exc()))
            time.sleep(5)
Beispiel #2
0
 def __init__(self, rds, id=None, combination=None):
     """
     用id或者组合来初始化,优先id
     :param id:
     :param combination:
     """
     if id is not None:
         self.combination = Combination.fetch_by_id(id)
     else:
         self.combination = Combination.fetch_by_combination(combination)
     self.first_market = self.combination.first_market
     self.second_market = self.combination.second_market
     self.rds = rds
     self.first_market_trade_api = None
     self.second_market_trade_api = None
     self.first_market_account = dict()
     self.second_market_account = dict()
     self.trader = None
     self.current_data_version = dict()
     self.account_fetch_time = time.time()
     self.initialize()
Beispiel #3
0
def get_task_object(rds, combination):
    combination_obj = Combination.fetch_by_combination(combination)
    if combination_obj.first_market == Market.HUOBI and combination_obj.second_market == Market.BINANCE:
        task_obj = HuobiBinanceCombinationTask(rds=rds,
                                               combination=combination)
    elif combination_obj.first_market == Market.OKEX and combination_obj.second_market == Market.BINANCE:
        task_obj = OKExBinanceCombinationTask(rds=rds, combination=combination)
    elif combination_obj.first_market == Market.HUOBI and combination_obj.second_market == Market.OKEX:
        task_obj = HuobiOKExCombinationTask(rds=rds, combination=combination)
    else:
        raise ValueError('Unsupported combination {}'.format(combination))
    return task_obj
Beispiel #4
0
def end_combination(name):
    """
    结束组合
    :param name:
    :return:
    """
    session = get_dbsession()
    try:
        combination_obj = Combination.fetch_by_combination(name)
        fetch_combination_account(combination_obj, Status.End)
        _db = session.query(CombinationModel).filter_by(
            combination=name).one_or_none()
        _db.status = Status.End
        session.commit()
    except:
        session.rollback()
        raise
    print("{}|EndCombination|{}".format(
        datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f'), name))
Beispiel #5
0
def run(combination):
    """
    coin对,都是小币在前,大币在后
    :param combination: 组合名称的list
    :return:
    """
    rds = Redis()
    combination_obj = Combination.fetch_by_combination(combination)
    if combination_obj.status != Status.Active:
        print('{}|CombinationNotActive|'.format(
            datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')))
        return
    if combination_obj.first_market == Market.HUOBI and combination_obj.second_market == Market.BINANCE:
        task_obj = HuobiBinanceCombinationTask(rds=rds,
                                               combination=combination)
    elif combination_obj.first_market == Market.OKEX and combination_obj.second_market == Market.BINANCE:
        task_obj = OKExBinanceCombinationTask(rds=rds, combination=combination)
    elif combination_obj.first_market == Market.HUOBI and combination_obj.second_market == Market.OKEX:
        task_obj = HuobiOKExCombinationTask(rds=rds, combination=combination)
    else:
        raise ValueError('Unsupported combination {}'.format(combination))
    # 获取一下account
    task_obj.get_account()
    # 检查Account
    if not task_obj.first_market_account.get(task_obj.combination.small_coin):
        raise NotEnoughCoinError('Not enough {} in {}'.format(
            task_obj.combination.small_coin, task_obj.first_market))
    if not task_obj.first_market_account.get(task_obj.combination.big_coin):
        raise NotEnoughCoinError('Not enough {} in {}'.format(
            task_obj.combination.big_coin, task_obj.first_market))
    if not task_obj.second_market_account.get(task_obj.combination.small_coin):
        raise NotEnoughCoinError('Not enough {} in {}'.format(
            task_obj.combination.small_coin, task_obj.second_market))
    if not task_obj.second_market_account.get(task_obj.combination.big_coin):
        raise NotEnoughCoinError('Not enough {} in {}'.format(
            task_obj.combination.big_coin, task_obj.second_market))

    while 1:
        try:
            task_obj.run()
            # 现在遇到异常先使用退出的方法
            if task_obj.trader.trade_exception is True:
                print('{}|MeetTradeException|'.format(
                    datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')))
                # 睡10s
                # 重新生成API
                time.sleep(10)
                task_obj.initialize()
                task_obj.get_account()
                task_obj.trader.trade_exception = False
        except Exception as e:
            print("{}|Exception|{}".format(
                datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f'), e.message))
            print("Traceback|{}".format(traceback.format_exc()))
            try:
                ExceptionInfoModel(host=ip,
                                   source='FETCH_TRADE_DATA',
                                   message=e.message,
                                   log_time=datetime.utcnow()).add()
            except:
                pass
            # 睡10s
            time.sleep(10)
            # 重新生成API
            task_obj.initialize()
            task_obj.get_account()
            task_obj.trader.trade_exception = False
Beispiel #6
0
def report_profit():
    """
    汇报收益
    :return:
    """
    active_combination_list = Combination.all_active()
    user_profit = defaultdict(list)
    today_str = datetime.utcnow().strftime('%Y-%m-%d')
    # today_str = '2018-03-31'
    session = get_dbsession()
    res = session.execute(
        'SELECT combination, init_big, init_small, init_bnb, init_huobi, yes_big, '
        'yes_small, yes_bnb, yes_huobi, now_big, now_small, now_bnb, now_huobi, '
        'daily_profit_rate, total_profit_rate, daily_profit, total_profit from '
        'combination_profit where substr(log_time, 1, 10)="{}"'.format(
            today_str))
    data_res = dict()
    for item in res:
        data_res[item[0]] = item
    for combination_obj in active_combination_list:
        if data_res.get(combination_obj.combination) is None:
            continue
        combination, init_big, init_small, init_bnb, init_huobi, yes_big, yes_small, yes_bnb, \
            yes_huobi, now_big, now_small, now_bnb, now_huobi, daily_profit_rate, total_profit_rate, \
            daily_profit, total_profit = data_res[combination_obj.combination]
        init_point_list = list()
        yes_point_list = list()
        now_point_list = list()
        if combination_obj.first_market == Market.HUOBI or combination_obj.second_market == Market.HUOBI:
            init_point_list.append(u'<p>火币点卡: {}</p>'.format(init_huobi))
            yes_point_list.append(u'<p>火币点卡: {}</p>'.format(yes_huobi))
            now_point_list.append(u'<p>火币点卡: {}</p>'.format(now_huobi))
        if combination_obj.first_market == Market.BINANCE or combination_obj.second_market == Market.BINANCE:
            init_point_list.append(u'<p>bnb: {}</p>'.format(init_bnb))
            yes_point_list.append(u'<p>bnb: {}</p>'.format(yes_bnb))
            now_point_list.append(u'<p>bnb: {}</p>'.format(now_bnb))
        message = u"""
        <tr>
        <td>{id}</td>
        <td><p>{first_market}: {second_market}</p><p>{small_coin}: {big_coin}</p></td>
        <td><p>当日:{daily_profit_rate}%</p><p>总体:{total_profit_rate}%</p></td>
        <td><p>当日:{daily_profit}</p><p>总体:{total_profit}</p></td>
        <td><p>{big_coin}:{now_big}</p><p>{small_coin}:{now_small}</p>{now_point}</td>
        <td><p>{big_coin}:{yes_big}</p><p>{small_coin}:{yes_small}</p>{yes_point}</td>
        <td><p>{big_coin}:{init_big}</p><p>{small_coin}:{init_small}</p>{init_point}</td>
        </tr>
        """.format(id=combination_obj.id,
                   small_coin=combination_obj.small_coin,
                   big_coin=combination_obj.big_coin,
                   init_big=init_big,
                   init_small=init_small,
                   yes_big=yes_big,
                   yes_small=yes_small,
                   now_big=now_big,
                   now_small=now_small,
                   daily_profit=daily_profit,
                   total_profit=total_profit,
                   daily_profit_rate='%.3f' % (daily_profit_rate * 100),
                   total_profit_rate='%.3f' % (total_profit_rate * 100),
                   init_point=u''.join(init_point_list),
                   yes_point=u''.join(yes_point_list),
                   now_point=u''.join(now_point_list),
                   first_market=combination_obj.first_market,
                   second_market=combination_obj.second_market)
        user_profit[combination_obj.user].append(message)

    for user, message_list in user_profit.items():
        if not message_list:
            continue
        user_db = UserModel.get(user)
        if user_db is None or user_db.email is None:
            continue
        user_html = u"""
            <table border="1" cellspacing="0">
            {header}
            {message}
            </table>
        """.format(header=profit_table_header, message='\n'.join(message_list))
        send_email(
            [user_db.email, '*****@*****.**', '*****@*****.**'],
            header='收益报表',
            text=None,
            html=user_html)