Пример #1
0
def collection():
    nav = 'collection'

    search = request.args.get('search', '')
    exchange = request.args.get('exchange', '')
    page = int(request.args.get('page', 1) or 1)

    limit = 25
    skip = limit * (page - 1)
    cond = {}
    if exchange:
        cond['exchange'] = exchange
    total = Collection.count(cond)
    pagination = Pagination(page, limit, total)

    collections = list(
        Collection.query(cond,
                         sort=[('offers_at', -1)],
                         skip=skip, limit=limit))
    for c in collections:
        lp = Quote.latest_price(c.exchange, c.symbol)
        if lp and c.offer_price:
            c.total_increase = lp / c.offer_price - 1
    return render_template('frontend/collection.html', **locals())
Пример #2
0
def collection_list():
    exchange = request.args.get('exchange', '')
    search = request.args.get('search', '')
    sort = request.args.get('sort', 'offers_at')
    order = request.args.get('order', 'desc')

    limit = int(request.args.get('limit', 25))
    offset = int(request.args.get('offset', 0))
    if sort in ['offers_at', 'exchange', 'name', 'symbol',
                'offer_price', 'offer_quantity']:
        dbsort = [(sort, 1 if order == 'asc' else -1)]
    else:
        dbsort = None

    cond = {}
    if exchange:
        cond['exchange'] = exchange
    if search:
        cond['$or'] = [
            {'exchange': {'$regex': search}},
            {'name': {'$regex': search}},
            {'symbol': {'$regex': search}},
        ]
    total = Collection.count(cond)
    qs = Collection.find(cond)
    if dbsort:
        qs = [Collection(c) for c in
              qs.sort(dbsort).skip(offset).limit(limit)]
    rows = [{
            'offers_at': c.offers_at,
            'exchange': c.exchange,
            'name': c.name,
            'symbol': c.symbol,
            'offer_price': c.offer_price,
            'offer_quantity': c.offer_quantity,
            'offer_cash_ratio': c.offer_cash_ratio,
            'offer_cash': c.offer_cash,
            'result_ratio_cash': c.result_ratio_cash,
            }
            for c in qs]

    for d in rows:
        d['total_increase'] = None
        lp = Quote.latest_price(d['exchange'], d['symbol'])
        if lp and d['offer_price']:
            d['total_increase'] = lp / d['offer_price'] - 1

    if not dbsort:
        rows = sorted(rows,
                      key=lambda x: x.get(sort) or 0,
                      reverse=order == 'desc')
        rows = rows[offset:offset + limit]

    for d in rows:
        d['offers_at'] = d['offers_at'].strftime(
            '%Y-%m-%d') if d['offers_at'] else None

        if d['offer_price']:
            d['offer_price'] = '{:.2f}'.format(d['offer_price'])

        if d['offer_cash_ratio']:
            d['offer_cash_ratio'] = '{:.0f}%'.format(
                d['offer_cash_ratio'] * 100)

        if d['offer_cash']:
            d['offer_cash'] = '{:.1f}'.format(d['offer_cash'])

        if d['result_ratio_cash']:
            d['result_ratio_cash'] = '{:.3f}%'.format(
                d['result_ratio_cash'] * 100)

        if d['total_increase']:
            d['total_increase'] = '{:.1f}%'.format(
                100 * (d['total_increase']))

    return jsonify(total=total, rows=rows)
Пример #3
0
def accounting(user):
    """ 对账号进行自动记账(如果用户已配置) """
    operated_at = datetime.utcnow() + timedelta(hours=8)

    def add_transaction(type_, exchange, symbol, price, quantity):
        t = Transaction({
            'user': user._id,
            'type_': type_,
            'operated_at': operated_at,
            'exchange': exchange,
            'symbol': symbol,
            'price': price,
            'quantity': quantity,
        })
        t.save()
        if not Position.do_op(t):
            t.remove()

    if user.auto_accounting:
        op = Position.user_position(user._id)
        p2pairs = {}
        for ta in TradeAccount.query({'user': user._id}):
            for p in ta.position or []:
                pair = (ta.exchange, p.symbol)
                if pair not in p2pairs:
                    p2pairs[pair] = p
                else:
                    pp = p2pairs[pair]
                    amount = p.average_price * p.quantity + \
                        pp.average_price * pp.quantity
                    p.quantity += pp.quantity
                    if p.quantity > 0:
                        p.average_price = amount / p.quantity
                    p2pairs[pair] = p
        p1pairs = {(p1['exchange'], p1['symbol']): p1 for p1 in op}
        # 检查更改项
        for p1 in op:
            pair = p1['exchange'], p1['symbol']
            if pair[0] in ['湖南文交所', '海西文交所', '上海邮币卡',
                           '上海文交所', '中俄邮币卡']:
                continue
            if pair in p2pairs:
                p2 = p2pairs[pair]
                quantity = p2.quantity - p1['quantity']
                if quantity != 0:
                    type_ = 'buy' if quantity > 0 else 'sell'
                    if type_ == 'buy':
                        price = (p2.average_price * p2.quantity -
                                 p1['avg_buy_price'] * p1['quantity']) / quantity
                    else:
                        price = p2.price
                    if price < 0.01:
                        price = Quote.latest_price(p1['exchange'], p1['symbol'])
                    price = int(price * 100) / 100.
                    add_transaction(
                        type_, pair[0], pair[1], price, abs(quantity))
            else:
                # 按现价计算已卖出
                if p1['quantity'] > 0:
                    price = Quote.latest_price(p1['exchange'], p1['symbol'])
                    price = int(price * 100) / 100.
                    add_transaction(
                        'sell', pair[0], pair[1], price, p1['quantity'])
        # 检查新增项
        for pair, p2 in p2pairs.items():
            if pair[0] in ['湖南文交所', '海西文交所', '上海邮币卡',
                           '上海文交所', '中俄邮币卡']:
                continue
            if pair not in p1pairs and p2.quantity > 0:
                price = int(p2.average_price * 100) / 100.
                add_transaction('buy', pair[0], pair[1], price, p2.quantity)
Пример #4
0
def accounting(user):
    """ 对账号进行自动记账(如果用户已配置) """
    operated_at = datetime.utcnow() + timedelta(hours=8)

    def add_transaction(type_, exchange, symbol, price, quantity):
        t = Transaction({
            'user': user._id,
            'type_': type_,
            'operated_at': operated_at,
            'exchange': exchange,
            'symbol': symbol,
            'price': price,
            'quantity': quantity,
        })
        t.save()
        if not Position.do_op(t):
            t.remove()

    if user.auto_accounting:
        op = Position.user_position(user._id)
        p2pairs = {}
        for ta in TradeAccount.query({'user': user._id}):
            for p in ta.position or []:
                pair = (ta.exchange, p.symbol)
                if pair not in p2pairs:
                    p2pairs[pair] = p
                else:
                    pp = p2pairs[pair]
                    amount = p.average_price * p.quantity + \
                        pp.average_price * pp.quantity
                    p.quantity += pp.quantity
                    if p.quantity > 0:
                        p.average_price = amount / p.quantity
                    p2pairs[pair] = p
        p1pairs = {(p1['exchange'], p1['symbol']): p1 for p1 in op}
        # 检查更改项
        for p1 in op:
            pair = p1['exchange'], p1['symbol']
            if pair[0] in ['湖南文交所', '海西文交所', '上海邮币卡', '上海文交所', '中俄邮币卡']:
                continue
            if pair in p2pairs:
                p2 = p2pairs[pair]
                quantity = p2.quantity - p1['quantity']
                if quantity != 0:
                    type_ = 'buy' if quantity > 0 else 'sell'
                    if type_ == 'buy':
                        price = (
                            p2.average_price * p2.quantity -
                            p1['avg_buy_price'] * p1['quantity']) / quantity
                    else:
                        price = p2.price
                    if price < 0.01:
                        price = Quote.latest_price(p1['exchange'],
                                                   p1['symbol'])
                    price = int(price * 100) / 100.
                    add_transaction(type_, pair[0], pair[1], price,
                                    abs(quantity))
            else:
                # 按现价计算已卖出
                if p1['quantity'] > 0:
                    price = Quote.latest_price(p1['exchange'], p1['symbol'])
                    price = int(price * 100) / 100.
                    add_transaction('sell', pair[0], pair[1], price,
                                    p1['quantity'])
        # 检查新增项
        for pair, p2 in p2pairs.items():
            if pair[0] in ['湖南文交所', '海西文交所', '上海邮币卡', '上海文交所', '中俄邮币卡']:
                continue
            if pair not in p1pairs and p2.quantity > 0:
                price = int(p2.average_price * 100) / 100.
                add_transaction('buy', pair[0], pair[1], price, p2.quantity)