Files
TradingBot-with-BybitAPI/src/main.py
EugeneBee 808f7112f7
All checks were successful
Build and Push Docker Image / build-and-push (release) Successful in 1m13s
Added status and PnL
2025-05-19 15:45:30 +03:00

185 lines
6.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import time
from datetime import datetime
import asyncio
from aiogram import Bot, Dispatcher
from aiogram.filters import Command
from aiogram.types import Message
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.types import BotCommand, BotCommandScopeDefault
from aiogram.fsm.context import FSMContext
from aiogram import Router, F
from aiogram.fsm.state import State, StatesGroup
from aiogram.fsm.storage.memory import MemoryStorage
from logger import generalLogger
from logger import tradingLogger
import bybit
import arbus
import jsonProcessing
import credentials
import whitelist
import strings
import options
async def set_commands():
commands = [BotCommand(command='start', description='Старт'),
BotCommand(command='help', description='Инструкция'),
BotCommand(command='info', description='Статус'),
BotCommand(command='strategy', description='Запустить стратегию'),
BotCommand(command='stop', description='Остановить стратегию')
]
await bot.set_my_commands(commands, BotCommandScopeDefault())
class startForm(StatesGroup):
pair = State()
params = State()
class stopForm(StatesGroup):
pair = State()
dp = Dispatcher(storage=MemoryStorage())
bot = Bot(
token=credentials.bot_token,
default=DefaultBotProperties(parse_mode=ParseMode.HTML),
)
strategy_router = Router()
stop_router = Router()
@dp.message(Command("start"))
async def commandStart(message: Message) -> None:
await message.answer(strings.startCommand)
@dp.message(Command("help"), F.chat.id.in_(whitelist.chatIDs))
async def commandHelp(message: Message) -> None:
await message.answer(strings.helpCommand)
@dp.message(Command("status"), F.chat.id.in_(whitelist.chatIDs))
async def commandStatus(message: Message) -> None:
currentTime = time.time()
timeDiff = round(currentTime - arbus.startTime) # Время работы в секундах
timeDiffH = round(timeDiff/60/60, 3) # Время работы в часах
await message.answer(strings.status + str(timeDiff) + ' секунд' \
+ ' (' + str(timeDiffH) + ' часов)')
@dp.message(Command("info"), F.chat.id.in_(whitelist.chatIDs))
async def commandInfo(message: Message) -> None:
data = await jsonProcessing.loadJson()
msgText = ''
if data == {}:
msgText = strings.noData
else:
msgText = strings.foundData
for i in data:
pnl = arbus.getPnL(str(i))
msgText += (f"<b>{str(i)}</b>: P&L - {pnl}%\n")
await message.answer(msgText)
@strategy_router.message(Command("strategy"), F.chat.id.in_(whitelist.chatIDs))
async def commandStrategy(message: Message, state: FSMContext):
await message.answer(strings.strategyCommand + '\n' + strings.askPair)
await state.set_state(startForm.pair)
@strategy_router.message(F.text, startForm.pair)
async def capture_start_pair(message: Message, state: FSMContext):
await state.update_data(pair=message.text)
data = await state.get_data()
t = 0
if await jsonProcessing.checkPair(data.get("pair")) == 1:
msgText = strings.strategyAlreadyRunning
t = 1
else:
msgText = strings.askParams
await message.answer(msgText)
if t == 1:
await state.clear()
else:
await state.set_state(startForm.params)
@strategy_router.message(F.text, startForm.params)
async def capture_params(message: Message, state: FSMContext):
await state.update_data(params=message.text)
data = await state.get_data()
t = await jsonProcessing.savePairParams(pair=data.get("pair"), params=data.get("params"))
if t == 0:
client = await bybit.getClient(
credentials.api_key,
credentials.api_secret,
options.testnet,
options.demoTrading
)
if client == -1:
msgText = strings.authFailed
await jsonProcessing.deletePair(pair=data.get("pair"))
else:
try:
asyncio.create_task(bybit.strategy(data.get("pair"), data.get("params")))
msgText = (f'Вы запустили стратегию на паре <b>{data.get("pair")}</b> \
с данными параметрами:\n<b>{data.get("params")}</b>\n')
except:
await jsonProcessing.deletePair(pair=data.get("pair"))
msgText = (strings.strategyError)
elif t == -1:
msgText = strings.wrongFormat
elif t == -2:
msgText = (f"Стратегия на паре <b>{data.get("pair")}</b> уже запущена.")
else:
msgText = strings.unexpectedError
await message.answer(msgText)
await state.clear()
@stop_router.message(Command("stop"), F.chat.id.in_(whitelist.chatIDs))
async def commandStop(message: Message, state: FSMContext):
await message.answer(strings.stopCommand + '\n' + strings.askPair)
await state.set_state(stopForm.pair)
@stop_router.message(F.text, stopForm.pair)
async def capture_stop_pair(message: Message, state: FSMContext):
await state.update_data(pair=message.text)
data = await state.get_data()
t = await jsonProcessing.deletePair(data.get("pair"))
if t == 0:
msgText = strings.stopStrategy
else:
msgText = strings.pairNotFound
await message.answer(msgText)
await state.clear()
async def start_bot():
await set_commands()
async def main() -> None:
dp.include_router(strategy_router)
dp.include_router(stop_router)
dp.startup.register(start_bot)
await dp.start_polling(bot)
# Main
if __name__ == "__main__":
arbus.setStartTime()
jsonProcessing.startUp()
currentTime = datetime.now().strftime("%H:%M:%S")
generalLogger.info(f"Started bot!")
tradingLogger.info(f"Started bot!")
asyncio.run(main())