Exemplo n.º 1
0
 def test_decimal_io(self):
     key = DecimalTestVertex.get_property_by_name('test_val1')
     yield create_key(key, 'Float')
     dt1 = yield DecimalTestVertex.create(test_val1=_D((0, (5, 0, 0, 0), -3)))
     dt3 = yield DecimalTestVertex.create(test_val1=-1.001)
     try:
         dt2 = yield DecimalTestVertex.get(dt1._id)
         self.assertEqual(dt1.test_val1, dt2.test_val1)
         dt4 = yield DecimalTestVertex.get(dt3._id)
         self.assertEqual(dt4.test_val1, _D((1, (1, 0, 0, 1), -3)))
     finally:
         yield dt1.delete()
         yield dt3.delete()
 def to_python(self, value):
     val = super(Decimal, self).to_python(value)
     if val is not None:
         pos = 0
         if val < 0:
             pos = 1
         digs = [int(i) for i in str(val) if i.isdigit()]
         return _D((pos, digs, -3))
Exemplo n.º 3
0
    def test_decimal_io(self):
        print_("creating vertex")
        dt = yield DecimalTestVertex.create(test_val=_D('1.00'))
        print_("getting vertex from vertex: %s" % dt)
        dt2 = yield DecimalTestVertex.get(dt._id)
        print_("got vertex: %s\n" % dt2)
        self.assertEqual(dt2.test_val, dt.test_val)
        print_("deleting vertex")
        yield dt2.delete()

        dt = yield DecimalTestVertex.create(test_val=5)
        print_("\ncreated vertex: %s" % dt)
        dt2 = yield DecimalTestVertex.get(dt._id)
        print_("Got decimal vertex: %s" % dt2)
        self.assertEqual(dt2.test_val, _D('5'))
        print_("deleting vertex")
        yield dt2.delete()
Exemplo n.º 4
0
    def test_decimal_io(self):
        print_("creating vertex")
        dt = DecimalTestVertex.create(test_val=_D('1.00'))
        print_("getting vertex from vertex: %s" % dt)
        dt2 = DecimalTestVertex.get(dt._id)
        print_("got vertex: %s\n" % dt2)
        self.assertEqual(dt2.test_val, dt.test_val)
        print_("deleting vertex")
        dt2.delete()

        dt = DecimalTestVertex.create(test_val=5)
        print_("\ncreated vertex: %s" % dt)
        dt2 = DecimalTestVertex.get(dt._id)
        print_("Got decimal vertex: %s" % dt2)
        self.assertEqual(dt2.test_val, _D('5'))
        print_("deleting vertex")
        dt2.delete()
Exemplo n.º 5
0
 def add_or_change(self, side, price, size):
     # у bids обратная сортировка 10-9-8-7-...
     changed = False
     if side == 'bid':
         for item in self.bids:
             if item[0] == price:
                 item[1] = str(size)
                 changed = True
                 # print('изменил ' + str(self.ticker_name) + ' цена ' + str(price) + " кол-во " + str(size))
                 break
             elif item[0] < price:
                 self.bids.append([str(price), str(size)])
                 changed = True
                 self.bids.sort(reverse=True, key=lambda x: _D(x[0]))
                 # print('добавил ' + str(self.ticker_name) + ' цена ' + str(price) + " кол-во " + str(size))
                 break
         if not changed:
             self.bids.append([str(price), str(size)])
             self.bids.sort(reverse=True, key=lambda x: _D(x[0]))
             # print('добавил ' + str(self.ticker_name) + ' цена ' + str(price) + " кол-во " + str(size))
     # у asks прямая сортировка 7-8-9-10-...
     elif side == 'ask':
         for item in reversed(self.asks):
             if item[0] == price:
                 item[1] = str(size)
                 changed = True
                 # print('изменил ' + str(self.ticker_name) + ' цена ' + str(price) + " кол-во " + str(size))
                 break
             elif item[0] < price:
                 self.asks.append([str(price), str(size)])
                 changed = True
                 self.asks.sort(key=lambda x: _D(x[0]))
                 # print('добавил ' + str(self.ticker_name) + ' цена ' + str(price) + " кол-во " + str(size))
                 break
         if not changed:
             self.asks.append([str(price), str(size)])
             self.asks.sort(key=lambda x: _D(x[0]))
Exemplo n.º 6
0
def calculate_price(amount=0, o_type=None, bids=None, asks=None):
    if amount == 0:
        return 0
    if o_type == 'buy' and bids is None:
        raise BidsAsksTypeException('Отсутствует стакан для покупки')
    if o_type == 'sell' and asks is None:
        raise BidsAsksTypeException('Отсутствует стакан для продажи')

    depth = _D(settings.DEPTH_COEFFICIENT) * _D(amount)

    if o_type == 'buy':
        bids = calculate_full_order_book(bids)
        sum_t = _D(0)
        for i in range(len(bids)):
            sum_t += _D(bids[i][2])
            if sum_t > depth:
                return _D(bids[i][0]) + _D('.00000001')
    elif o_type == 'sell':
        asks = calculate_full_order_book(asks)
        sum_t = _D(0)
        for i in range(len(asks)):
            sum_t += _D(asks[i][2])
            if sum_t > depth:
                return _D(asks[i][0]) - _D('.00000001')
Exemplo n.º 7
0
def get_btc_wallet_history():
    wallet, c = Wallets.objects.get_or_create(name='BTC')
    btc_uw = UserWallet.objects.filter(wallet=wallet)
    if len(btc_uw) > 0:
        for uw in btc_uw:
            btc_to_usd = CryptoConvert('usd', 'btc')
            data = requests.get('https://blockchain.info/ru/rawaddr/' +
                                uw.address)
            try:
                transactions = data.json()
                if transactions:
                    uw.balance = transactions['final_balance'] / 100000000
                    uw.total_usd = btc_to_usd.convert('usd', 'btc', uw.balance)
                    uw.total_btc = uw.balance
                    uw.save()
                    for item in transactions['txs']:
                        try:
                            transaction = Transaction.objects.get(
                                name=uw.wallet.name + str(uw.pk),
                                hash=item['hash'])
                        except Transaction.MultipleObjectsReturned:
                            pass
                        except Transaction.DoesNotExist:
                            transaction = Transaction()
                            transaction.name = uw.wallet.name + str(uw.pk)
                            transaction.t_type = 'wallet'
                            transaction.number = item['tx_index']
                            transaction.date = datetime.datetime.fromtimestamp(
                                item['time'])
                            transaction.currency = 'BTC'
                            t_from = ''
                            transaction.type = 'unknown'
                            for item_from in item['inputs']:
                                t_from += item_from['prev_out'][
                                    'addr'] + '<br/>'
                                if item_from['prev_out']['addr'] == uw.address:
                                    transaction.type = 'out'
                                    transaction.value = _D(
                                        item_from['prev_out']['value']) / _D(
                                            100000000)
                            t_to = ''
                            for item_to in item['out']:
                                t_to += item_to['addr'] + '<br/>'
                                if item_to['addr'] == uw.address:
                                    transaction.type = 'in'
                                    transaction.value = _D(
                                        item_to['value']) / _D(100000000)
                            transaction.t_to = t_to
                            transaction.t_from = t_from
                            transaction.usd_value = btc_to_usd.convert(
                                'usd', 'btc', _D(transaction.value))
                            transaction.hash = item['hash']
                            transaction.block_hash = '-'
                            transaction.save()
            except JSONDecodeError as json_er:
                print('Ошибка разбора ответа: {}'.format(json_er))
                continue

    else:
        print("Кошельки отсутствуют")
    return True
Exemplo n.º 8
0
def pull_exchanges_balances(ue_pk=None):
    unnecessary_keys = ['free', 'total', 'used', 'info']
    if ue_pk is None:
        user_exchanges = UserExchange.objects.filter(is_active=True)
    else:
        user_exchanges = UserExchange.objects.filter(pk=ue_pk)
    if len(user_exchanges) > 0:
        for user_exchange in user_exchanges:
            exchange_object = class_for_name('ccxt',
                                             user_exchange.exchange.name)({
                                                 'apiKey':
                                                 user_exchange.apikey,
                                                 'secret':
                                                 user_exchange.apisecret
                                             })
            try:
                try:
                    balances = exchange_object.fetch_balance()
                except binascii.Error:
                    user_exchange.error = 'Incorrect apikey or secret'
                    user_exchange.is_correct = False
                    user_exchange.is_active = False
                    user_exchange.save()
                    continue
                if balances:
                    total_btc = _D(0)
                    for item in balances.items():
                        if item[0] not in unnecessary_keys:
                            try:
                                user_coin = UserBalance.objects.get(
                                    ue=user_exchange, coin=item[0].lower())
                                user_coin.total = (item[1]['total']
                                                   if item[1]['total']
                                                   is not None else 0)
                                user_coin.btc_value, user_coin.conversions = fetch_btc_value(
                                    user_exchange.exchange, item[0].lower(),
                                    item[1]['total'])
                                user_coin.used = (item[1]['used']
                                                  if item[1]['used']
                                                  is not None else 0)
                                user_coin.free = (item[1]['free']
                                                  if item[1]['free']
                                                  is not None else 0)
                                user_coin.save()
                                total_btc += _D(user_coin.btc_value)
                            except UserBalance.DoesNotExist:
                                new_user_coin = UserBalance()
                                new_user_coin.ue = user_exchange
                                new_user_coin.coin = item[0].lower()
                                new_user_coin.total = (
                                    item[1]['total']
                                    if not item[1]['total'] is None else 0)
                                new_user_coin.btc_value, new_user_coin.conversions = fetch_btc_value(
                                    user_exchange.exchange, item[0].lower(),
                                    item[1]['total'])
                                new_user_coin.used = (item[1]['used']
                                                      if item[1]['used']
                                                      is not None else 0)
                                new_user_coin.free = (item[1]['free']
                                                      if item[1]['free']
                                                      is not None else 0)
                                new_user_coin.save()
                                total_btc += _D(new_user_coin.btc_value)
                    user_exchange.total_btc = total_btc
                    user_exchange.total_usd = get_usd_value('btc', total_btc)
                    user_exchange.save()
            except ExchangeNotAvailable as e:
                # user_exchange.is_active = False
                # user_exchange.is_active_script = False
                user_exchange.error = e
                user_exchange.save()
            except RequestTimeout:
                continue
    return True
Exemplo n.º 9
0
def fetch_btc_value(exchange, coin, amount=None, convertations=None):
    if amount is None:
        amount = 0
    if _D(amount) == _D(0):
        return 0, 'Null balance'
    if convertations is None:
        convertations = [
            coin + ' (' + str(_D(str(amount)).quantize(_D('.00000001'))) + ')'
        ]
    if coin.lower() == 'btc':
        return amount, '->'.join(convertations)
    try:
        coin = ExchangeCoin.objects.get(symbol=coin.lower(), exchange=exchange)
        # print('Нашел валюту: {}'.format(coin.symbol.upper()))
        try:
            # print('1Ищу пару BTC_{}'.format(coin.symbol.upper()))
            pair = Pair.objects.get(main_coin=ExchangeCoin.objects.get(
                symbol='btc', exchange=exchange),
                                    second_coin=coin)
            # print('1Нашел пару {}_{}'.format(pair.main_coin.symbol, pair.second_coin.symbol))
            ticker = ExchangeTicker.objects.filter(
                pair_id=pair.pk, exchange_id=exchange.pk).latest('id')
            # print('1Нашел тикер {} {}'.format(ticker, ticker.last))
            new_amount = _D(amount).quantize(_D('.00000001')) * _D(
                ticker.last).quantize(_D('.00000001'))
            convertations.append(
                'btc (' + str(_D(str(new_amount)).quantize(_D('.00000001'))) +
                ')')
            return new_amount, '->'.join(convertations)
        except Pair.DoesNotExist:
            try:
                # print('2Ищу пару {}_BTC'.format(coin.symbol.upper()))
                pair = Pair.objects.get(second_coin=ExchangeCoin.objects.get(
                    symbol='btc', exchange=exchange),
                                        main_coin=coin)
                # print('2Нашел пару {}_{}'.format(pair.main_coin.symbol, pair.second_coin.symbol))
                ticker = ExchangeTicker.objects.filter(
                    pair_id=pair.pk, exchange_id=exchange.pk).latest('id')
                # print('2Нашел тикер {} {}'.format(ticker, ticker.last))
                new_amount = _D(amount).quantize(_D('.00000001')) / _D(
                    ticker.last).quantize(_D('.00000001'))
                convertations.append(
                    'btc (' +
                    str(_D(str(new_amount)).quantize(_D('.00000001'))) + ')')
                return new_amount, '->'.join(convertations)
            except Pair.DoesNotExist:
                try:
                    # print('3Ищу пару где вторая валюта {}'.format(coin.symbol.upper()))
                    pair = Pair.objects.get(second_coin=coin)
                    # print('3Нашел пару {}_{}'.format(pair.main_coin.symbol, pair.second_coin.symbol))
                    ticker = ExchangeTicker.objects.filter(
                        pair_id=pair.pk, exchange_id=exchange.pk).latest('id')
                    # print('3Нашел тикер {} {}'.format(ticker, ticker.last))
                    in_first_coin = _D(ticker.last) * _D(amount)
                    convertations.append(
                        pair.main_coin.symbol + ' (' +
                        str(_D(str(in_first_coin)).quantize(_D('.00000001'))) +
                        ')')
                    fetch_btc_value(exchange, pair.main_coin.symbol,
                                    in_first_coin, convertations)
                except Pair.DoesNotExist:
                    # print('3Пара на найдена')
                    return 0, 'Not found'
                except ExchangeTicker.DoesNotExist:
                    # print("3Тикер не найден")
                    return 0, 'Not found'
            except ExchangeTicker.DoesNotExist:
                # print("2Тикер не найден")
                return 0, 'Not found'
        except ExchangeTicker.DoesNotExist:
            # print("1Тикер не найден")
            return 0, 'Not found'
    except ExchangeCoin.DoesNotExist:
        # print('Валюта не найдена')
        return 0, 'Not found'
Exemplo n.º 10
0
 def to_python(self, value):
     val = super(Decimal, self).to_python(value)
     if val is not None:
         return _D(val)
Exemplo n.º 11
0
class DecimalPropertyTestCase(GraphPropertyBaseClassTestCase):
    klass = Decimal
    good_cases = (1.101, 1.11, 0.001, _D((0, (1, 0, 0, 0), -3)),
                  _D((0, (1, 0, 0, ), -2)))
    bad_cases = (0, 1.2345, 'val', ['val'], {'val': 1}, '', '1.234',
                 _D((0, (1, 0, 0, 0, 1), -4)))
Exemplo n.º 12
0
class DecimalPropertyTestCase(GraphPropertyBaseClassTestCase):
    klass = Decimal
    good_cases = (1.1, 0.0, _D(1.1), None)
    bad_cases = (0, 'val', ['val'], {'val': 1})
Exemplo n.º 13
0
 def to_python(self, value):
     val = super(Decimal, self).to_python(value)
     if val is not None:
         return _D(val)
Exemplo n.º 14
0
    def run(self, *args, **kwargs):
        task = pull_exchanges_balances.delay()
        while not AsyncResult(task.task_id).ready():
            time.sleep(1)
            pass
        try:
            user_orders = UserOrder.objects.filter(date_cancel=None)
            orders_to_close = user_orders.filter(
                Q(date_created__lte=timezone.now() -
                  timezone.timedelta(minutes=settings.ORDER_TTL))
                | Q(to_close=True))
            print('Ордера пользователей {}'.format(user_orders))
            print('Ордера к закрытию {}'.format(orders_to_close))
            for uo in user_orders:
                exchange_object = class_for_name('ccxt', uo.ue.exchange.name)({
                    'apiKey':
                    uo.ue.apikey,
                    'secret':
                    uo.ue.apisecret
                })
                try:
                    order_status = exchange_object.fetch_order_status(
                        str(uo.order_number))
                except Exception as er:
                    continue
                if order_status == 'open':
                    if uo in orders_to_close:
                        print(
                            'Ордер № {} пора закрыть, его время пришло'.format(
                                uo.order_number))
                        try:
                            print('Пытаюсь отменить ордер № {}'.format(
                                uo.order_number))
                            canc = exchange_object.cancel_order(
                                str(uo.order_number))
                            if canc['success'] == 1:
                                uo.date_cancel = timezone.now()
                                uo.cancel_desc = 'TTL'
                                uo.save()
                        except Exception as er:
                            print('При отмене ордера № {} возникла ошибка: {}'.
                                  format(uo.order_number, er))
                            continue
                    else:
                        try:
                            current_balance_main_coin = UserBalance.objects.get(
                                ue=uo.ue,
                                coin=uo.pair.main_coin.symbol.lower())
                            uo.interim_main_coin = current_balance_main_coin.total
                            uo.save()
                        except UserBalance.DoesNotExist:
                            pass
                elif order_status == 'closed':
                    print('Ордер № {} закрыт'.format(uo.order_number))
                    uo.date_cancel = timezone.now()
                    try:
                        current_balance_main_coin = UserBalance.objects.get(
                            ue=uo.ue, coin=uo.pair.main_coin.symbol.lower())
                        uo.main_coin_after_total = current_balance_main_coin.total
                        uo.main_coin_after_free = current_balance_main_coin.free
                        uo.main_coin_after_used = current_balance_main_coin.used
                    except UserBalance.DoesNotExist:
                        uo.main_coin_after_total = '-1'
                        uo.main_coin_after_used = '-1'
                        uo.main_coin_after_free = '-1'
                    try:
                        current_balance_second_coin = UserBalance.objects.get(
                            ue=uo.ue, coin=uo.pair.second_coin.symbol.lower())
                        uo.second_coin_after_total = current_balance_second_coin.total
                        uo.second_coin_after_used = current_balance_second_coin.used
                        uo.second_coin_after_free = current_balance_second_coin.free
                    except UserBalance.DoesNotExist:
                        uo.second_coin_after_total = '-1'
                        uo.second_coin_after_used = '-1'
                        uo.second_coin_after_free = '-1'
                    if uo.order_type == 'buy':
                        fact_total = _D(uo.interim_main_coin) - _D(
                            current_balance_main_coin.total)
                        uo.fact_total = fact_total
                        if fact_total != 0:
                            fact_fee = 100 * _D(
                                uo.total) / _D(fact_total) - 100
                            uo.fact_fee = fact_fee
                            if fact_fee > 0.2:
                                uo.is_ok = False
                    elif uo.order_type == 'sell':
                        fact_total = _D(current_balance_main_coin.total) - _D(
                            uo.interim_main_coin)
                        uo.fact_total = fact_total
                        if fact_total != 0:
                            fact_fee = 100 * _D(
                                uo.total) / _D(fact_total) - 100
                            uo.fact_fee = fact_fee
                            if fact_fee > 0.2:
                                uo.is_ok = False
                    uo.cancel_desc = 'Worked'
                    uo.save()
        except Exception as e:
            print('При проверке ордера возникла ошибка: {}'.format(e))
            pass
        try:
            to_trade = ToTrade.objects.filter(
                date_updated__gte=timezone.now() -
                timezone.timedelta(minutes=5)).earliest('date_created')

            already_in_orders = UserOrder.objects.filter(
                ue=to_trade.user_pair.user_exchange,
                pair=to_trade.user_pair.pair,
                date_cancel=None)
            if len(already_in_orders) > 0:
                to_trade.delete()
            else:
                print('Пытаюсь выставить ордер')
                exchange_name = to_trade.user_pair.user_exchange.exchange.name
                exchange_object = class_for_name('ccxt', exchange_name)({
                    'apiKey':
                    to_trade.user_pair.user_exchange.apikey,
                    'secret':
                    to_trade.user_pair.user_exchange.apisecret
                })
                user_balance_main_coin = UserBalance.objects.get(
                    ue=to_trade.user_pair.user_exchange,
                    coin=to_trade.user_pair.pair.main_coin.symbol)
                user_balance_second_coin = UserBalance.objects.get(
                    ue=to_trade.user_pair.user_exchange,
                    coin=to_trade.user_pair.pair.second_coin.symbol)
                order = None
                try:
                    if to_trade.type == 'buy':
                        order = exchange_object.create_limit_buy_order(
                            to_trade.user_pair.pair.second_coin.symbol.upper()
                            + '/' +
                            to_trade.user_pair.pair.main_coin.symbol.upper(),
                            to_trade.amount, to_trade.price, {'postOnly': 1})
                        print('Ответ от биржи (покупка): {}'.format(order))
                    elif to_trade.type == 'sell':
                        order = exchange_object.create_limit_sell_order(
                            to_trade.user_pair.pair.second_coin.symbol.upper()
                            + '/' +
                            to_trade.user_pair.pair.main_coin.symbol.upper(),
                            to_trade.amount, to_trade.price, {'postOnly': 1})
                        print('Ответ от биржи (продажа): {}'.format(order))
                    if order is not None:
                        pull_exchanges_balances.delay(
                            to_trade.user_pair.user_exchange.pk)
                        user_order = UserOrder()
                        user_order.ue = to_trade.user_pair.user_exchange
                        user_order.pair = to_trade.user_pair.pair
                        user_order.order_type = to_trade.type
                        user_order.order_number = order['id']
                        user_order.interim_main_coin = user_balance_main_coin.total
                        user_order.main_coin_before_total = user_balance_main_coin.total
                        user_order.main_coin_before_free = user_balance_main_coin.free
                        user_order.main_coin_before_used = user_balance_main_coin.used
                        user_order.second_coin_before_total = user_balance_second_coin.total
                        user_order.second_coin_before_free = user_balance_second_coin.free
                        user_order.second_coin_before_used = user_balance_second_coin.used
                        user_order.price = to_trade.price
                        user_order.amount = to_trade.amount
                        user_order.total = to_trade.price * to_trade.amount
                        user_order.fee = _D('0.0015')
                        user_order.save()
                    else:
                        pass
                except ExchangeError:
                    pass
            to_trade.delete()
        except ToTrade.DoesNotExist:
            pass
        except UserBalance.DoesNotExist:
            pass
        SetOrderTask.apply_async(queue='set_orders', countdown=10)
        return True
Exemplo n.º 15
0
def calculate_full_order_book(book):
    for item in book:
        item.append(str(_D(item[0]) * _D(item[1])))
    return book
Exemplo n.º 16
0
class DecimalValidatorTestCase(FloatValidatorTestCase):
    klass = DecimalValidator()
    good_cases = (1.1, _D(1.1))
class DecimalValidatorTestCase(FloatValidatorTestCase):
    klass = DecimalValidator()
    good_cases = (1.1, _D((0, (1, 0, 0, 0), -3)))
Exemplo n.º 18
0
def calculate_order_for_user(user_pair_pk, params, type):
    try:
        user_pair = UserPair.objects.get(pk=user_pair_pk)
        if type == 'buy':
            print("Расчитываю покупку")
            bids = params['bids']
            ticker_list = jsonpickle.decode(params['ticker'])
            try:
                user_main_coin = UserMainCoinPriority.objects.get(
                    main_coin__coin=user_pair.pair.main_coin,
                    user_exchange=user_pair.user_exchange)
                main_coin_active = user_main_coin.is_active
            except UserMainCoinPriority.DoesNotExist:
                main_coin_active = True
            if main_coin_active:
                user_balance_second_coin = UserBalance.objects.get(
                    ue=user_pair.user_exchange,
                    coin=user_pair.pair.second_coin.symbol.lower())
                user_balance_second_coin_in_btc = user_balance_second_coin.btc_value
                user_second_coin_percent = user_balance_second_coin_in_btc / (
                    user_pair.user_exchange.total_btc / 100)
                user_coin_share = UserCoinShare.objects.get(
                    user_exchange=user_pair.user_exchange,
                    coin=user_pair.pair.second_coin)
                user_need_second_coin_in_percent = user_coin_share.share
                user_nehvataen_in_percent_of_btc = user_need_second_coin_in_percent - user_second_coin_percent
                if user_nehvataen_in_percent_of_btc < 0.5:
                    return True
                # расчитываем приоритеты
                sum_priority_second_coin = UserPair.objects.filter(
                    user_exchange=user_pair.user_exchange,
                    pair__second_coin=user_pair.pair.second_coin).aggregate(
                        Sum('rank'))['rank__sum']
                user_need_to_buy_on_prior_in_percent_of_btc = _D(
                    user_nehvataen_in_percent_of_btc) * (
                        _D(user_pair.rank) / _D(sum_priority_second_coin))

                user_need_to_buy_on_prior_in_btc = (user_pair.user_exchange.total_btc / 100) * \
                                                   user_need_to_buy_on_prior_in_percent_of_btc
                print('Надо взять в BTC: {}'.format(
                    user_need_to_buy_on_prior_in_btc))

                # сколько нужно взять в первой валюте
                if user_pair.pair.main_coin.symbol.upper() == 'BTC':
                    user_need_to_buy_on_prior_in_first_coin = user_need_to_buy_on_prior_in_btc
                else:
                    ticker = ticker_list.get_ticker_by_name(
                        'BTC_' + user_pair.pair.main_coin.symbol.upper())
                    if ticker is not None:
                        user_need_to_buy_on_prior_in_first_coin = _D(
                            user_need_to_buy_on_prior_in_btc) / _D(ticker.last)
                    else:
                        ticker = ticker_list.get_ticker_by_name(
                            user_pair.pair.main_coin.symbol.upper() + '_BTC')
                        if ticker is not None:
                            user_need_to_buy_on_prior_in_first_coin = _D(
                                user_need_to_buy_on_prior_in_btc) * _D(
                                    ticker.last)
                        else:
                            print('ИДИТЕ НАЗУЙ С МОНЕТОЙ: ' +
                                  str(user_pair.pair.main_coin))
                            return True
                print('Нужно взять в {}: {}'.format(
                    user_pair.pair.main_coin.symbol.upper(),
                    user_need_to_buy_on_prior_in_first_coin))

                # надо потратить первой валюты user_need_to_buy_on_prior_in_first_coin
                try:
                    user_balance_main_coin = UserBalance.objects.get(
                        ue=user_pair.user_exchange,
                        coin=user_pair.pair.main_coin.symbol.lower())
                    if user_balance_main_coin.free == 0 or user_balance_main_coin.free < 0.0001:
                        print('{} доступно {}'.format(
                            user_pair.pair.main_coin.symbol.upper(),
                            user_balance_main_coin.free))
                        return True
                    if user_balance_main_coin.free < user_need_to_buy_on_prior_in_first_coin:
                        user_need_to_buy_on_prior_in_first_coin = user_balance_main_coin.free
                except UserBalance.DoesNotExist:
                    print('Не нашел такой валюты у пользователя')
                    return True
                price = calculate_price(
                    user_need_to_buy_on_prior_in_first_coin,
                    o_type='buy',
                    bids=bids)
                total = user_need_to_buy_on_prior_in_first_coin / price
                if user_need_to_buy_on_prior_in_first_coin < 0.0001:
                    return True
                print('Хочу потратить {} {} чтобы купить {} {}'.format(
                    user_need_to_buy_on_prior_in_first_coin,
                    user_pair.pair.main_coin.symbol.upper(), total,
                    user_pair.pair.second_coin.symbol.upper()))
                print('Считал по {}'.format(price))

                calculations = Сalculations()
                calculations.user_pair = user_pair
                calculations.type = type
                calculations.depth_coef = settings.DEPTH_COEFFICIENT
                calculations.price = price
                calculations.amount = total
                calculations.bids = json.dumps(bids)
                calculations.asks = None
                calculations.save()

                try:
                    to_trade = ToTrade.objects.get(user_pair=user_pair,
                                                   type='buy')
                    to_trade.price = price
                    to_trade.amount = total
                    to_trade.total = user_need_to_buy_on_prior_in_first_coin
                    to_trade.total_f = user_need_to_buy_on_prior_in_first_coin - (
                        user_need_to_buy_on_prior_in_first_coin * _D('.0015'))
                    to_trade.save()
                except ToTrade.DoesNotExist:
                    new_order = ToTrade()
                    new_order.user_pair = user_pair
                    new_order.type = 'buy'
                    new_order.price = price
                    new_order.amount = total
                    new_order.total = user_need_to_buy_on_prior_in_first_coin
                    new_order.total_f = user_need_to_buy_on_prior_in_first_coin - (
                        user_need_to_buy_on_prior_in_first_coin * _D('.0015'))
                    new_order.fee = _D('.0015')
                    new_order.cause = 'Change rate'
                    new_order.save()
        elif type == 'sell':
            print('Расчитываю продажу')
            asks = params['asks']
            user_have_second_coin = UserBalance.objects.get(
                ue=user_pair.user_exchange,
                coin=user_pair.pair.second_coin.symbol.lower())
            print('первой валюты {}'.format(user_have_second_coin.free))
            if user_have_second_coin.free > 0.001:
                price = calculate_price(amount=user_have_second_coin.free,
                                        o_type='sell',
                                        asks=asks)
                total = user_have_second_coin.free * _D(price)
                total_fee = total - (total * _D('.0015'))
                print('Второй валюты: {} * найденная цена: {} = итого: {}'.
                      format(user_have_second_coin.free, price, total))
                need_to_sell = False
                try:
                    last_buy_order = UserOrder.objects.filter(
                        ue=user_pair.user_exchange,
                        pair=user_pair.pair,
                        order_type='buy').latest('date_created')
                    print('последний ордер на покупку № {}, итого: {}'.format(
                        last_buy_order.pk, last_buy_order.total))
                    if last_buy_order.total < total_fee:
                        need_to_sell = True
                    else:
                        print(
                            'не буду продавать, купил {} продам на {}'.format(
                                last_buy_order.total, total_fee))
                except UserOrder.DoesNotExist:
                    need_to_sell = True
                if need_to_sell:
                    print('Нашел цену: ' + str(price))
                    print('Хочу потратить {} {} чтобы купить {} {}'.format(
                        user_have_second_coin.free,
                        user_pair.pair.second_coin.symbol.upper(), total,
                        user_pair.pair.main_coin.symbol.upper()))

                    calculations = Сalculations()
                    calculations.user_pair = user_pair
                    calculations.type = type
                    calculations.depth_coef = settings.DEPTH_COEFFICIENT
                    calculations.price = price
                    calculations.amount = user_have_second_coin.free
                    calculations.asks = json.dumps(asks)
                    calculations.bids = None
                    calculations.save()

                    try:
                        to_trade = ToTrade.objects.get(user_pair=user_pair,
                                                       type='sell')
                        to_trade.price = price
                        to_trade.amount = user_have_second_coin.free
                        to_trade.total = total
                        to_trade.total_f = total - (total * _D('.0015'))
                        to_trade.save()
                    except ToTrade.DoesNotExist:
                        new_order = ToTrade()
                        new_order.user_pair = user_pair
                        new_order.type = 'sell'
                        new_order.price = price
                        new_order.amount = user_have_second_coin.free
                        new_order.total = total
                        new_order.total_f = total - (total * _D('.0015'))
                        new_order.fee = _D('.0015')
                        new_order.cause = 'Change rate'
                        new_order.save()
                else:
                    print('Невыгодный ордер, отмена')
    except UserPair.DoesNotExist:
        pass
    return True