Beispiel #1
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
Beispiel #2
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
Beispiel #3
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
Beispiel #4
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())
Beispiel #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())
Beispiel #6
0
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
Beispiel #7
0
def full_order(bot: Client, m: Message):
    user = User.get(tg_id=m.from_user.id)

    # Не авторизован
    if not user.api_key or not user.secret:
        return

    # Удаляем старые сообщения юзера и бота, если юзер присал новое
    if user.temp:
        bot.delete_messages(user.tg_id, user.temp['msg_ids'])

    # Лимит активных ордеров
    if user.orders_count >= MAX_ACTIVE_ORDERS:
        r = send_message(
            bot, user.tg_id,
            f'⚠️ <b>Orders limit exceed</b>\nYou can have only {MAX_ACTIVE_ORDERS} active order in alpha version of ths bot.\n\n<i>PM @gorbunov if you need more active orders.</i>'
        )
        user.temp['msg_ids'] = [m.message_id, r.message_id]
        user.temp['text'] = m.text
        db_save(user)
        return

    # Обработчик ошибок пользователя
    params = parse_full_order_data(m.text)
    if type(params) is tuple:
        err_msg = params[1]
        r = send_message(bot, user.tg_id,
                         gen_err_msg(f'🔴 <b>Error</b>\n{err_msg}'))
        user.temp['msg_ids'] = [m.message_id, r.message_id]
        db_save(user)
        return

    # Генерация сообщения с ордером
    msg = buy_full_order_msg(params)
    markup = full_order_create_btns()
    r = send_message(bot, user.tg_id, msg, reply_markup=markup)

    # Сохраняем id временных сообщений в базу
    user.temp['msg_ids'] = [m.message_id, r.message_id]
    user.temp['text'] = m.text
    db_save(user)