コード例 #1
0
def delete_order(bot: Client, q: CallbackQuery):
    tg_id = q.from_user.id
    user = User.get(tg_id=tg_id)

    edit_message(bot, tg_id, user.temp['msg_ids'][1], '🕐 Deleting order')
    time.sleep(1)
    bot.delete_messages(tg_id, user.temp['msg_ids'])
コード例 #2
0
def rfrsh_main(bot: Client, q: CallbackQuery):
    tg_id = q.from_user.id
    msg_id = q.message.message_id
    user = User.get_or_none(tg_id=tg_id)

    edit_message(bot, user.tg_id, msg_id, '🕐 Refreshing data...')

    response = get_balance(user.api_key, user.secret)
    connected = response[0]

    # Авторизован на Bithumb, есть балансы
    if connected:
        edit_message(bot,
                     user.tg_id,
                     msg_id,
                     gen_main_msg(response),
                     reply_markup=refresh_main_btn())

    # Ошибка авторизации
    else:
        err_code = response[1]  # Код ошибки
        err_msg = response[2]  # Текст ошибки
        if err_code == '9000' or err_code == '9002':
            user.api_key = ''
            user.secret = ''
            edit_message(bot, user.tg_id, msg_id,
                         gen_err_msg(err_creds, input_msg=input_api_key_msg))
            db_save(user)
        else:
            edit_message(bot, user.tg_id, msg_id,
                         gen_err_msg(err + err_msg, input_msg="Try again"))

    return
コード例 #3
0
def cancel_order(bot: Client, q: CallbackQuery):
    tg_id = q.from_user.id
    user = User.get(tg_id=tg_id)
    msg_id = q.message.message_id
    order = Order.get(b_msg_id=msg_id)
    u_msg_id = order.u_msg_id

    bh = BithumbGlobalRestAPI(decr(user.api_key), decr(user.secret))

    bot.edit_message_text(tg_id, msg_id, '🕐 Cancelling order...')

    try:
        bh.cancel_order(order.pair, order.order_id)
        order.status = 'cancelled'
        user.orders_count -= 1
        db_save(order)
        db_save(user)
        print(f'Order {order.order_id} cancelled')

        bot.edit_message_text(tg_id, msg_id, '✅ Order cancelled...')
        time.sleep(2)
        bot.delete_messages(tg_id, [msg_id, u_msg_id])

    except Exception as e:
        if e.code == '20012':
            # Статус ордера изменился
            bh_response = bh.post('singleOrder', {
                'orderId': order.order_id,
                'symbol': order.pair
            })
            if bh_response['status'] == 'cancel':
                order.status = 'cancelled'
                db_save(order)
                print(f'Order {order.order_id} cancelled')

                bot.edit_message_text(
                    tg_id, msg_id,
                    '⚠️ Order was already cancelled on Exchange...')
                time.sleep(2)
                bot.delete_messages(tg_id, [msg_id, u_msg_id])
                return

        err_msg = e.msg
        edit_message(bot,
                     user.tg_id,
                     msg_id,
                     gen_err_msg(f'🔴 <b>Error</b>\n{err_msg}\n\nTry again'),
                     reply_markup=cancel_order_btn())
コード例 #4
0
ファイル: creds.py プロジェクト: dinodigital/bhrobot
def step_1(bot: Client, m: Message):
    """
    Обработчик присланного API ключа
    """
    user = User.get(tg_id=m.from_user.id)
    user.api_key = encr(m.text)
    db_save(user)

    # Удаляем сообщение с API ключем
    m.delete()

    # Уведомляем о получении ключа
    msg_id = user.msg_ids['b_main']
    edit_message(bot, user.tg_id, msg_id,
                 gen_creds_msg(user, input_msg=input_secret_msg))

    return
コード例 #5
0
def refresh_order(bot: Client, q: CallbackQuery):
    tg_id = q.from_user.id
    user = User.get(tg_id=tg_id)
    order_msg_id = q.message.message_id
    order = Order.get(b_msg_id=order_msg_id)
    bh = BithumbGlobalRestAPI(decr(user.api_key), decr(user.secret))

    edit_message(bot, tg_id, order_msg_id, '🕐 Refreshing data...')

    # Обновляем сообщение
    try:
        refresh_order_msg(order, bh, bot, user)
    except Exception as e:
        err_msg = e.msg
        edit_message(bot,
                     user.tg_id,
                     order_msg_id,
                     gen_err_msg(f'🔴 <b>Error</b>\n{err_msg}\n\nTry again'),
                     reply_markup=refresh_order_btn())
コード例 #6
0
ファイル: creds.py プロジェクト: dinodigital/bhrobot
def step_2(bot: Client, m: Message):
    """
    Обрабатывает Secret
    Запрашивает и выводит балансы
    """
    tg_id = m.from_user.id
    user = User.get(tg_id=m.from_user.id)

    # Сохраняем secret ключ в БД
    user.secret = encr(m.text)
    db_save(user)

    # Удаляем сообщения
    m.delete()

    # Уведомляем о получении ключа
    msg_id = user.msg_ids['b_main']
    edit_message(bot, tg_id, msg_id, gen_creds_msg(user, status='connecting'))

    response = get_balance(user.api_key, user.secret)
    connected = response[0]

    msg_id = user.msg_ids['b_main']
    if connected:
        edit_message(bot,
                     tg_id,
                     msg_id,
                     gen_main_msg(response),
                     reply_markup=refresh_main_btn())

    else:
        err_code = response[1]
        err_msg = response[2]
        if err_code == '9000' or err_code == '9002':
            user.api_key = ''
            user.secret = ''
            bot.edit_message_text(
                tg_id, msg_id,
                gen_err_msg(err_creds, input_msg=input_api_key_msg))
            db_save(user)

    return
コード例 #7
0
def publish_order(bot: Client, q: CallbackQuery):
    tg_id = q.from_user.id
    user = User.get(tg_id=tg_id)
    order_msg_id = user.temp['msg_ids'][1]  # 0 - user, 1 - bot
    text = user.temp['text']
    params = parse_full_order_data(text)

    # Уведомляем о публикации ордера на БХ
    bot.edit_message_text(tg_id, order_msg_id, '🕐 Publishing order...')

    # Размещаем ордер
    bh = BithumbGlobalRestAPI(decr(user.api_key), decr(user.secret))

    try:
        order_id = bh_publish_order(bh, params)
        if type(order_id) is tuple:
            err_msg = order_id[1]
            err_code = order_id[2]
            if err_code == '9011':
                return edit_message(
                    bot, user.tg_id, order_msg_id,
                    gen_err_msg(
                        f'🔴 <b>Error</b>\n{err_msg}\n\nPlease, allow "<b>Open Trading</b>" access in <a href="https://www.bithumb.pro/en-us/account/user/api-key/list">API Management</a> settings, wait 1 minute and create new order'
                    ))
            return edit_message(
                bot, user.tg_id, order_msg_id,
                gen_err_msg(
                    f'🔴 <b>Error</b>\n{err_msg}\n\nPlease, create new order'))

    except Exception as e:
        err_msg = e.msg
        edit_message(bot,
                     user.tg_id,
                     order_msg_id,
                     gen_err_msg(f'🔴 <b>Error</b>\n{err_msg}\n\nTry again'),
                     reply_markup=full_order_create_btns())
        return

    # Создаем ордер в БД
    order = create_order(order_id, text, params, user, status='active')
    print(f'Order #{order.id} created. Order_id: {order_id}')

    # Обновляем сообщение
    try:
        refresh_order_msg(order, bh, bot, user)
        user.temp = {}
        user.orders_count += 1
        db_save(user)
    except Exception as e:
        err_msg = e.msg
        edit_message(bot,
                     user.tg_id,
                     order_msg_id,
                     gen_err_msg(f'🔴 <b>Error</b>\n{err_msg}\n\nTry again'),
                     reply_markup=refresh_order_btn())

    return
コード例 #8
0
def new_main_msg(user: User, bot: Client):
    main_msg_id = user.msg_ids['b_main']

    # Обновляем главное сообщение
    bot.delete_messages(user.tg_id, main_msg_id)
    r = send_message(bot, user.tg_id, connecting_msg)

    user.msg_ids['b_main'] = msg_id = r.message_id
    db_save(user)

    response = get_balance(user.api_key, user.secret)
    connected = response[0]

    # Авторизован на Bithumb, есть балансы
    if connected:
        edit_message(bot,
                     user.tg_id,
                     msg_id,
                     gen_main_msg(response),
                     reply_markup=refresh_main_btn())

    # Ошибка авторизации
    else:
        err_code = response[1]  # Код ошибки
        err_msg = response[2]  # Текст ошибки
        if err_code == '9000' or err_code == '9002':
            user.api_key = ''
            user.secret = ''
            edit_message(bot, user.tg_id, msg_id,
                         gen_err_msg(err_creds, input_msg=input_api_key_msg))
            db_save(user)
        else:
            edit_message(bot, user.tg_id, msg_id,
                         gen_err_msg(err + err_msg, input_msg="Try again"))

    return
コード例 #9
0
ファイル: order_checker.py プロジェクト: dinodigital/bhrobot
def check_orders():
    orders = Order.select().where(Order.status == 'active')

    if len(orders) == 0:
        return

    r = multi_request(orders)

    success = []
    cancel = []
    for i, order in enumerate(orders, 0):
        bh_status = r[i]['status']

        if bh_status == 'success':
            success.append(order)
        elif bh_status == 'cancel':
            cancel.append(order)

    if not success and not cancel:
        return

    bot = Client('Listener', no_updates=True)
    bot.start()

    if success:
        for order in success:
            # Уведомление о выполнении ордера
            msg = '<b>Order completed</b>'
            bot.send_message(order.tg_id,
                             msg,
                             reply_to_message_id=order.b_msg_id,
                             reply_markup=hide_message_btn())

            # Меняем сообщение с одрером
            order_msg = completed_order_msg(order)
            edit_message(bot,
                         order.tg_id,
                         order.b_msg_id,
                         order_msg,
                         reply_markup=hide_message_btn(order.u_msg_id))

            user = User.get(tg_id=order.tg_id)
            user.orders_count -= 1
            order.status = 'success'
            db_save(order)
            db_save(user)

    if cancel:
        for order in cancel:
            # Меняем сообщение с одрером
            order_msg = cancelled_order_msg(order.text)
            edit_message(bot,
                         order.tg_id,
                         order.b_msg_id,
                         order_msg,
                         reply_markup=hide_message_btn(order.u_msg_id))

            user = User.get(tg_id=order.tg_id)
            user.orders_count -= 1
            order.status = 'cancel'
            db_save(order)
            db_save(user)

    bot.stop()
コード例 #10
0
ファイル: orders.py プロジェクト: dinodigital/bhrobot
def refresh_order_msg(order, bh, bot, user):
    current_price = bh.get_current_price(order.pair, order.side)
    msg = active_order_msg(order.text, current_price)
    markup = full_order_active_btns()
    edit_message(bot, user.tg_id, order.b_msg_id, msg, reply_markup=markup)