fix app/telegram/handlers/handlers.py, fix app/telegram/functions/functions.py || change two buttons "Начать торговлю" || fix text registration message, fix text profile || delete app/services/Bybit/config.py || delete comments

This commit is contained in:
Kirill Strelnikov
2025-07-21 16:55:30 +07:00
parent fb0c14aba1
commit 242be34a97
9 changed files with 34 additions and 145 deletions

View File

@@ -1,9 +0,0 @@
API_KEY=''
API_SECRET=''
SYMBOL=''
'''
API_KEY = 'o5854uk3qBD4lySnjv'
SECRET_KEY = 'aMFPbs0AKyOSLTgXyrqCfREDi7byjnsOd0Kj'
SYMBOL = "SHIB1000USDT"
'''

View File

@@ -71,7 +71,7 @@ async def contract_long(tg_id, message, margin_mode):
setMarginMode=margin_mode # margin_type setMarginMode=margin_mode # margin_type
) )
martingale_factor = float(data_main_stgs['martingale_factor']) # Исправлено: было maximal_quantity martingale_factor = float(data_main_stgs['martingale_factor'])
max_martingale_steps = int(data_main_stgs['maximal_quantity']) max_martingale_steps = int(data_main_stgs['maximal_quantity'])
starting_quantity = float(data_main_stgs['starting_quantity']) starting_quantity = float(data_main_stgs['starting_quantity'])
max_risk_percent = float(data_risk_management_stgs['max_risk_deal']) max_risk_percent = float(data_risk_management_stgs['max_risk_deal'])
@@ -172,23 +172,7 @@ async def contract_long(tg_id, message, margin_mode):
orderLinkId=f"deal_{SYMBOL}_{time.time()}" orderLinkId=f"deal_{SYMBOL}_{time.time()}"
) )
await info_access_open_deal(message, SYMBOL, data_main_stgs['trading_mode'], margin_mode, data_main_stgs['size_leverage'], next_quantity) await info_access_open_deal(message, SYMBOL, data_main_stgs['trading_mode'], margin_mode, data_main_stgs['size_leverage'], next_quantity)
print(f'''
=====================
===================
===================
===================
=================
{r}
===============
===============
=============
===============
==============
''')
except exceptions.InvalidRequestError as e: except exceptions.InvalidRequestError as e:
await message.answer('Недостаточно баланса') await message.answer('Недостаточно баланса')
@@ -225,7 +209,7 @@ async def contract_short(tg_id, message, margin_mode):
setMarginMode=margin_mode # margin_type setMarginMode=margin_mode # margin_type
) )
martingale_factor = float(data_main_stgs['martingale_factor']) # Исправлено: было maximal_quantity martingale_factor = float(data_main_stgs['martingale_factor'])
max_martingale_steps = int(data_main_stgs['maximal_quantity']) max_martingale_steps = int(data_main_stgs['maximal_quantity'])
starting_quantity = float(data_main_stgs['starting_quantity']) starting_quantity = float(data_main_stgs['starting_quantity'])
max_risk_percent = float(data_risk_management_stgs['max_risk_deal']) max_risk_percent = float(data_risk_management_stgs['max_risk_deal'])
@@ -251,47 +235,17 @@ async def contract_short(tg_id, message, margin_mode):
realised_pnl = float(position['unrealisedPnl']) realised_pnl = float(position['unrealisedPnl'])
if realised_pnl > 0: if realised_pnl > 0: # Прибыльная сделка
print(f'''
=====================
=====Сделка=========
===уСПЕШНЕАЯ================
===================
=================
{realised_pnl}
===============
===============
=============
===============
==============
''')
starting_quantity = next_quantity starting_quantity = next_quantity
current_martingale_step = 0 current_martingale_step = 0
elif not realised_pnl: elif not realised_pnl:
next_quantity = starting_quantity next_quantity = starting_quantity
current_martingale_step += 1 current_martingale_step += 1
else: else: # Убыточная сделка
current_martingale_step += 1 current_martingale_step += 1
next_quantity = last_quantity * martingale_factor next_quantity = last_quantity * martingale_factor
starting_quantity = next_quantity starting_quantity = next_quantity
print(f'''
======СДЕЛКА===============
=====УБЫТОЧНАЯ==============
===================
===================
=================
{realised_pnl}
===============
===============
=============
===============
==============
''')
except Exception as e: except Exception as e:
print("Не получены позиции") print("Не получены позиции")
next_quantity = starting_quantity next_quantity = starting_quantity
@@ -324,23 +278,7 @@ async def contract_short(tg_id, message, margin_mode):
orderLinkId=f"deal_{SYMBOL}_{time.time()}" orderLinkId=f"deal_{SYMBOL}_{time.time()}"
) )
await info_access_open_deal(message, SYMBOL, data_main_stgs['trading_mode'], margin_mode, data_main_stgs['size_leverage'], next_quantity) await info_access_open_deal(message, SYMBOL, data_main_stgs['trading_mode'], margin_mode, data_main_stgs['size_leverage'], next_quantity)
print(f'''
=====================
===================
===================
===================
=================
{r}
===============
===============
=============
===============
==============
''')
except exceptions.InvalidRequestError as e: except exceptions.InvalidRequestError as e:
await message.answer('Недостаточно баланса') await message.answer('Недостаточно баланса')

View File

@@ -16,23 +16,7 @@ async def get_balance(tg_id, message):
try: try:
balance = client.get_wallet_balance(accountType='UNIFIED', coin='USDT')['result']['list'][0]['coin'][0]['walletBalance'] balance = client.get_wallet_balance(accountType='UNIFIED', coin='USDT')['result']['list'][0]['coin'][0]['walletBalance']
print(f'''
=====================
=====BALANCE=========
======USDT=============
===================
=================
{balance}
===============
===============
=============
===============
==============
''')
return balance return balance
except Exception as e: except Exception as e:
await message.answer('Баланс не был получен') await message.answer('Баланс не был получен, подключите платформу')
return 0 return 0

View File

@@ -18,20 +18,4 @@ async def get_min_qty(tg_id, message):
price = await price_s.get_price(tg_id, message) price = await price_s.get_price(tg_id, message)
min_qty = int(5 / price * 1.1) min_qty = int(5 / price * 1.1)
print(f'''
=====================
=====MIN=========
=====QTY==============
===================
=================
{min_qty}
===============
===============
=============
===============
==============
''')
return min_qty return min_qty

View File

@@ -94,10 +94,8 @@ async def make_deal_bybit (callback: CallbackQuery):
else: else:
match trade_mode: match trade_mode:
case 'Long': case 'Long':
print('====================================LONG=========================================')
await Futures.contract_long(callback.from_user.id, callback.message, margin_mode) await Futures.contract_long(callback.from_user.id, callback.message, margin_mode)
case 'Short': case 'Short':
print('====================================SHORT=========================================')
await Futures.contract_short(callback.from_user.id, callback.message, margin_mode) await Futures.contract_short(callback.from_user.id, callback.message, margin_mode)
case 'Switch': case 'Switch':
await callback.message.edit_text('Режим Switch пока недоступен') await callback.message.edit_text('Режим Switch пока недоступен')

View File

@@ -18,22 +18,6 @@ async def get_price(tg_id, message):
try: try:
price = float(client.get_tickers(category='linear', symbol=SYMBOL).get('result').get('list')[0].get('ask1Price')) price = float(client.get_tickers(category='linear', symbol=SYMBOL).get('result').get('list')[0].get('ask1Price'))
print(f'''
=====================
=====PRICE=========
===================
===================
=================
{price}
===============
===============
=============
===============
==============
''')
return price return price
except exceptions.InvalidRequestError as e: except exceptions.InvalidRequestError as e:
await message.answer('Неверно указана торговая пара') await message.answer('Неверно указана торговая пара')

View File

@@ -1,12 +1,12 @@
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
start_markup = InlineKeyboardMarkup(inline_keyboard=[ start_markup = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text="Торговать", callback_data="callback_profile")] [InlineKeyboardButton(text="🔥 Начать торговлю", callback_data="clb_start_chatbot_message")]
]) ])
settings_markup = InlineKeyboardMarkup(inline_keyboard=[ settings_markup = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text="Настройки", callback_data='clb_settings_message')], [InlineKeyboardButton(text="Настройки", callback_data='clb_settings_message')],
[InlineKeyboardButton(text="Начать торговлю", callback_data='clb_start_trading')] [InlineKeyboardButton(text="Запуск", callback_data='clb_start_trading')]
]) ])
back_btn_profile = [InlineKeyboardButton(text="Назад", callback_data='callback_profile')] back_btn_profile = [InlineKeyboardButton(text="Назад", callback_data='callback_profile')]

View File

@@ -2,35 +2,36 @@
import app.telegram.Keyboards.reply_keyboards as reply_markup import app.telegram.Keyboards.reply_keyboards as reply_markup
async def start_message(message): async def start_message(message):
await message.answer(f""" Привет <b>{message.from_user.username}</b>! 👋 username = ''
if message.from_user.first_name == None:
username = message.from_user.last_name
elif message.from_user.last_name == None:
username = message.from_user.first_name
else:
username = f'{message.from_user.first_name} {message.from_user.last_name}'
await message.answer(f""" Привет <b>{username}</b>! 👋
Добро пожаловать в бот по трейдингу на Bibyt — вашего надежного помощника для анализа рынка и принятия взвешенных решений. Здесь вы получите: Добро пожаловать в чат-робот по трейдингу на Bybit — вашего надежного помощника для анализа рынка и принятия взвешенных решений.
Здесь вы получите:
<b> <b>
📊 Анализ текущих трендов 📊 Анализ текущих трендов
📈 Инструменты для прогнозирования и оценки рисков 📈 Инструменты для прогнозирования и оценки рисков
⚡️ Сигналы и рекомендации по сделкам ⚡️ Сигналы и рекомендации по сделкам
🔔 Уведомления о важных изменениях и новостях 🔔 Уведомления о важных изменениях и новостях
</b> </b>
Просто отправляйте интересующий вас инструмент или команду, и бот быстро предоставит актуальную информацию и аналитику.
Начнем торговать умно и эффективно вместе! 🚀
""", parse_mode='html', reply_markup=inline_markup.start_markup) """, parse_mode='html', reply_markup=inline_markup.start_markup)
async def profile_message(username, message): async def profile_message(username, message):
await message.answer(f""" <b>{username}</b> await message.answer(f""" <b>@{username}</b>
Баланс Баланс
⭐️ 0 ⭐️ 0
О себе
🚀 Профессиональный трейдер на платформе Bibyt с авторской стратегией и аналитикой в реальном времени.
📊 Постоянно улучшаю навыки и адаптируюсь к рыночным изменениям, чтобы максимально увеличить прибыль.
🔥 Всегда в поиске новых возможностей для роста и стабильного успеха!
""", parse_mode='html', reply_markup=inline_markup.settings_markup) """, parse_mode='html', reply_markup=inline_markup.settings_markup)
async def check_profile_message(message): async def check_profile_message(message):
await message.answer(f'Добро пожаловать {message.from_user.username}!', reply_markup=reply_markup.base_buttons_markup) await message.answer(f'Добро пожаловать {message.from_user.first_name} {message.from_user.last_name}!', reply_markup=reply_markup.base_buttons_markup)
async def settings_message(message): async def settings_message(message):
await message.edit_text("Выберите что настроить", reply_markup=inline_markup.special_settings_markup) await message.edit_text("Выберите что настроить", reply_markup=inline_markup.special_settings_markup)

View File

@@ -37,7 +37,7 @@ async def settings_msg(message: Message):
if user: if user:
await func.settings_message(message) await func.settings_message(message)
@router.callback_query(F.data == "callback_profile") @router.callback_query(F.data == "clb_start_chatbot_message")
async def clb_func_reg (callback: CallbackQuery): async def clb_func_reg (callback: CallbackQuery):
user = await rq.check_user(callback.from_user.id) user = await rq.check_user(callback.from_user.id)
@@ -53,11 +53,20 @@ async def clb_func_reg (callback: CallbackQuery):
await func_condition_settings.reg_new_user_default_condition_settings(callback.from_user.id, callback.message) await func_condition_settings.reg_new_user_default_condition_settings(callback.from_user.id, callback.message)
await func_additional_settings.reg_new_user_default_additional_settings(callback.from_user.id, callback.message) await func_additional_settings.reg_new_user_default_additional_settings(callback.from_user.id, callback.message)
await callback.message.answer(f'Регистрация прошла успешно, здравствуйте {callback.from_user.username}!', reply_markup=reply_markup.base_buttons_markup) await callback.message.answer(f'Регистрация прошла успешно, перейдите в профиль нажав на кнопку!', reply_markup=reply_markup.base_buttons_markup)
await func.profile_message(callback.from_user.username, callback.message) await func.profile_message(callback.from_user.username, callback.message)
await callback.answer() await callback.answer()
@router.callback_query(F.data == "callback_profile")
async def clb_profile_message (callback: CallbackQuery):
user = await rq.check_user(callback.from_user.id)
if user:
await func.profile_message(callback.from_user.username, callback.message)
await callback.answer()
# Настройки торговли # Настройки торговли
@router.callback_query(F.data == "clb_settings_message") @router.callback_query(F.data == "clb_settings_message")