Бот анализирует историю торгов за определенное количество дней и позволяет автоматически расставлять ордера длинных и коротких позиций на каждую из заданных пар по самой выгодной цене за рассматриваемый период с учетом заданного отклонения.

Это позволяет создать пул позиций, показывающий высокую торговую эффективность.

Заказано: ООО «Открытый институт». Используется в качестве учебного пособия для обучающихся экономического факультета.

Исходный код order.py

Python
from pybit.unified_trading import HTTP
import time
import telebot
import time
from aiogram.types import ReplyKeyboardRemove, \
    ReplyKeyboardMarkup, KeyboardButton, \
    InlineKeyboardMarkup, InlineKeyboardButton
import json
import requests
import json
import time
'''
days=10
min_max={}
slovar={}
time_now=int(str(time.time()).split('.')[0]+'000')
time_prev=time_now-(days*24*3600*1000)
print(time_prev)
for sym in ['MYROUSDT']:
    print(sym)
    
    slovar[sym]=[]
    session = HTTP(
        testnet=False,
        api_key="API_KEY",
        api_secret="API_SECRET",
    )
    prom=session.get_kline(
        category="linear",
        symbol=sym,
        interval='D',
        start=time_prev,
        end=time_now,
    )
    for re in prom['result']['list']:
        slovar[sym].append([float(i) for i in re])
    min_sym=1000000000
    max_sym=0
    for dat in slovar[sym]:
        print(dat)
        if(dat[2]>max_sym):
            max_sym=dat[2]
        if(dat[3]<min_sym):
            min_sym=dat[3]
        min_max[sym]=[min_sym,max_sym]
    print(min_max[sym])
input('sdccdsdc')
'''
'''
session = HTTP(
        testnet=False,
        api_key="API_KEY",
        api_secret="API_SECRET",
    )

print(session.place_order(
    category="linear",
    symbol="10000LADYSUSDT",
    side="Buy",
    orderType="Limit",
    qty="100",
    price="0.000495"
))
input('csdcsdcsd')
'''
'''
print(session.cancel_all_orders(
    category="linear",
    settleCoin="USDT",
))
input('sdcsdcssd')
input('scsdcs')
input('sdccscd')
print(session.get_open_orders(
    category="linear",
    symbol="TAOUSDT",
    openOnly=0,
    limit=50,
))
'''

def preobr(num):
    spis=[100,10,1,0.1,0.01,0.001]
    spis.reverse()
    ress=[]
    for i in spis:
        if('.' in str(i)):
            ress.append(str(num).split('.')[0]+'.'+str(num).split('.')[1][:len(str(i).split('.')[1])])
        else:
            ress.append(str(int(int(str(num).split('.')[0])/i)*i))
    return ress

#input('sdcsdcssd')


bot = telebot.TeleBot('API_KEY', threaded=False)

@bot.message_handler(commands=['start'])
def start_command(message):
    msg11=bot.send_message(message.chat.id, 'Чтобы разместить ордера введите команду /add')
    msg11=bot.send_message(message.chat.id, 'Чтобы закрыть все ордера введите команду /close')

@bot.message_handler(commands=['add'])
def start_command(message):
    msg11=bot.send_message(message.chat.id, 'Добавьте данные в формате:\n\nКоличество дней для анализа\nОтклонение в процентах\nПлечо\nЛонг/Шорт')            
    bot.register_next_step_handler(msg11, telephone)

@bot.message_handler(commands=['close'])
def start_command(message):
    session = HTTP(
        testnet=False,
        api_key="key",
        api_secret="API_SECRET",
    )
    aaaa=session.cancel_all_orders(
        category="linear",
        settleCoin="USDT",
    )
    bot.send_message(message.chat.id, 'Все ордера закрыты!')            



def telephone(message):
    try:
        add_para(message)
    except:
        print('ERROR!!!!')
        bot.send_message(message.chat.id, 'ОШИБКА')        


def add_para(message):
    all_coins=[]
    file=open('resss.txt', encoding='utf-8')
    for i in file:
        all_coins.append(i.strip())
    file.close()
    para=message.text.strip().split('\n')
    #all_coins=para[0].split(',')
    #all_coins=[i.strip().upper() for  i in all_coins]
    days=int(para[0])
    otklonenie=float(para[1])
    plecho=int(para[2])
    bot.send_message(message.chat.id, 'Ожидаемм...')
    if(para[3].lower()=='лонг' or para[3].lower()=='шорт'):
        min_max={}
        slovar={}
        time_now=int(str(time.time()).split('.')[0]+'000')
        time_prev=time_now-(days*24*3600*1000)
        for sym in all_coins[:]:
            print(sym)
            try:
                slovar[sym]=[]
                session = HTTP(
                    testnet=False,
                    api_key="API_KEY",
                    api_secret="API_SECRET",
                )
                prom=session.get_kline(
                    category="linear",
                    symbol=sym,
                    interval='D',
                    start=time_prev,
                    end=time_now,
                )
                for re in prom['result']['list']:
                    slovar[sym].append([float(i) for i in re])
                min_sym=1000000000
                max_sym=0
                for dat in slovar[sym]:
                    if(dat[2]>max_sym):
                        max_sym=dat[2]
                    if(dat[3]<min_sym):
                        min_sym=dat[3]
                    min_max[sym]=[min_sym,max_sym]
            except:
                bot.send_message(message.chat.id, 'Данные по данной паре не получены: '+sym)
                time.sleep(1)
        nadelite=[]
        for sym in min_max:
            print(sym,min_max[sym])
            if(min_max[sym][0]>1000):
                #del min_max[sym]
                nadelite.append(sym)
                #bot.send_message(message.chat.id, 'Цена больше 1000 : '+sym)
                time.sleep(1)
        for sym in nadelite:
            del min_max[sym]
        session = HTTP(
            testnet=False,
            api_key="API_KEY",
            api_secret="API_SECRET",
        )
        ballance_get=session.get_wallet_balance(
            accountType="UNIFIED"
        )
        print(ballance_get)
        res_balance=0
        for ccc in ballance_get['result']['list'][0]['coin']:
            if(ccc['coin']=='USDT'):
                res_balance=float(ccc['availableToWithdraw'])
        print(res_balance)
        usdt_for_all=res_balance/len(min_max)
        print(usdt_for_all)
        bot.send_message(message.chat.id, 'Среднее количество USDT на каждую пару: '+str(usdt_for_all))
        nadelite=[]
        for sym in min_max:
            min_otkl=min_max[sym][0]-((min_max[sym][0]*otklonenie)/100)
            max_otkl=min_max[sym][1]+((min_max[sym][1]*otklonenie)/100)
            min_max[sym].append(min_otkl)
            min_max[sym].append(max_otkl)
            min_max[sym].append(usdt_for_all/min_otkl)
            min_max[sym].append(usdt_for_all/max_otkl)
            print(sym,min_max[sym])
            if('e-' in str(min_max[sym][-2]) or 'e-' in str(min_max[sym][-1])):
                #del min_max[sym]
                nadelite.append(sym)
                #bot.send_message(message.chat.id, 'Слишком малое количество : '+sym)
        for sym in nadelite:
            del min_max[sym]   
        for sym in min_max:
            min_max[sym][2]=float(str(min_max[sym][2]).split('.')[0]+'.'+str(min_max[sym][2]).split('.')[1][:6])
            min_max[sym][3]=float(str(min_max[sym][3]).split('.')[0]+'.'+str(min_max[sym][3]).split('.')[1][:6])
            min_max[sym][4]=float(str(min_max[sym][4]).split('.')[0]+'.'+str(min_max[sym][4]).split('.')[1][:10])
            min_max[sym][5]=float(str(min_max[sym][5]).split('.')[0]+'.'+str(min_max[sym][5]).split('.')[1][:10])
            print(sym,min_max[sym])
        if(para[3].lower()=='шорт'):
            errors=[]
            nadelite=[]
            for sym in min_max:
                print('Plecho',sym)
                try:
                    pupupu=session.set_leverage(
                        category="linear",
                        symbol=sym,
                        buyLeverage=str(plecho),
                        sellLeverage=str(plecho),
                    )
                    print(pupupu)
                    time.sleep(0.2)
                except:
                    time.sleep(0.2)
                    print('ERROR!!!!')
                    #nadelite.append(sym)
                    #bot.send_message(message.chat.id, 'Ошибка при выставлении плеча: '+sym)
                
                time.sleep(1)
            for sym in nadelite:
                del min_max[sym]
            file=open('all_data.txt','w', encoding='utf-8')
            file.close()
            full=[]
            for sym in min_max:
                print('Order',sym)
                spisok_1=preobr(str(min_max[sym][5]))
                #spisok_1.reverse()
                print(str(min_max[sym][5]))
                print(spisok_1)
                
                
                for spp in spisok_1:
                    print('---',spp)
                    if(float(spp)>0):
                        try:
                            
                            pupuppp=session.place_order(
                                category="linear",
                                symbol=sym,
                                side="Sell",
                                orderType="Limit",
                                qty=spp,
                                price=str(min_max[sym][3])
                            )
                            print(pupuppp)
                            full.append(sym)
                            file=open('all_data.txt','a', encoding='utf-8')
                            file.write(sym+';'+spp+'\n')
                            file.close()
                            time.sleep(0.2)
                            break
                    
                        except:
                            #errors.append(sym)
                            time.sleep(0.4)
                            print('ERROR!!!!')
            '''
            for sym in min_max:
                print('Order',sym)
                try:
                    
                    pupuppp=session.place_order(
                        category="linear",
                        symbol=sym,
                        side="Sell",
                        orderType="Limit",
                        qty=str(min_max[sym][5]),
                        price=str(min_max[sym][3])
                    )
                    print(pupuppp)
                    
                    #time.sleep(1)
                except:
                    errors.append(sym)
                    print('ERROR!!!!')
            '''
            file=open('all_data.txt','a', encoding='utf-8')  
            file.write('----------------------\n')
            file.write('----------------------\n')
            file.write('----------------------\n')
            for sym in min_max:
                if(sym not in full):
                    file.write(sym+'-'+'\n')
            file.close()
            if(errors!=[]):
                bot.send_message(message.chat.id, 'Готово.')
                bot.send_message(message.chat.id, 'Созданых ордеров: '+str(len(full)))
                bot.send_document(message.chat.id,open('all_data.txt', 'rb'))
            else:
                bot.send_message(message.chat.id, 'Готово.')
                bot.send_message(message.chat.id, 'Созданых ордеров: '+str(len(full)))
                bot.send_document(message.chat.id,open('all_data.txt', 'rb'))
        if(para[3].lower()=='лонг'):
            errors=[]
            nadelite=[]
            
            for sym in min_max:
                print('Plecho',sym)
                try:
                    pupupu=session.set_leverage(
                        category="linear",
                        symbol=sym,
                        buyLeverage=str(plecho),
                        sellLeverage=str(plecho),
                    )
                    print(pupupu)
                    time.sleep(0.2)
                except:
                    print('ERROR!!!!')
                    time.sleep(0.2)
                                
            for sym in nadelite:
                del min_max[sym]
            file=open('all_data.txt','w', encoding='utf-8')
            file.close()
            full=[]
            for sym in min_max:
                print('Order',sym)
                spisok_1=preobr(str(min_max[sym][4]))
                #spisok_1.reverse()
                print(str(min_max[sym][4]))
                print(spisok_1)
                

                for spp in spisok_1:
                    print('---',spp)
                    if(float(spp)>0):
                        try:
                            
                            pupuppp=session.place_order(
                                category="linear",
                                symbol=sym,
                                side="Buy",
                                orderType="Limit",
                                qty=spp,
                                price=str(min_max[sym][2])
                            )
                            print(pupuppp)
                            full.append(sym)
                            file=open('all_data.txt','a', encoding='utf-8')
                            file.write(sym+';'+spp+'\n')
                            file.close()
                            time.sleep(0.4)
                            break
                    
                        except:
                            #errors.append(sym)
                            time.sleep(0.2)
                            print('ERROR!!!!')
            file=open('all_data.txt','a', encoding='utf-8')  
            file.write('----------------------\n')
            file.write('----------------------\n')
            file.write('----------------------\n')
            for sym in min_max:
                if(sym not in full):
                    file.write(sym+'-'+'\n')
            file.close()
                       
            if(errors!=[]):
                bot.send_message(message.chat.id, 'Готово.')
                bot.send_message(message.chat.id, 'Созданых ордеров: '+str(len(full)))
                bot.send_document(message.chat.id,open('all_data.txt', 'rb'))
                '''
                time.sleep(1)
                bot.send_message(message.chat.id, 'Ордера по данным парам не созданы: '+', '.join(errors))
                '''
            else:
                bot.send_message(message.chat.id, 'Готово.')
                bot.send_message(message.chat.id, 'Созданых ордеров: '+str(len(full)))
                bot.send_document(message.chat.id,open('all_data.txt', 'rb'))
                '''
                time.sleep(1)
                bot.send_message(message.chat.id, 'Ордера по всем парам созданы!!!')
                '''

            
    else:
        a=1/0

while(True):
    try:
        bot.polling()
    except:
        print('Error!!!!')

session = HTTP(
    testnet=False,
    api_key="API_KEY",
    api_secret="API_SECRET",
)

print(session.get_wallet_balance(
    accountType="UNIFIED"
))

input('sascsdcsd')

'''
print(session.place_order(
    category="linear",
    symbol="1000RATSUSDT",
    side="Buy",
    orderType="Limit",
    qty="10",
    price="0.2"
))

input('scsdcs')

'''

print(session.get_open_orders(
    category="linear",
    symbol="1000RATSUSDT",
    openOnly=0,
    limit=50,
))



input('sdcsdcssd')

print(session.get_positions(
    category="linear",
    symbol="1000RATSUSDT",
))

input('sdcsdcssd')


'''

print(session.cancel_all_orders(
    category="linear",
    settleCoin="USDT",
))
input('sdcsdcssd')
'''
))

input('sdcsdcssd')
Python