websocket WIP 3

This commit is contained in:
2025-04-29 19:32:43 +03:00
parent 31966e5561
commit ffab00601a
4 changed files with 112 additions and 88 deletions

View File

@ -1,78 +1,19 @@
import json
import options
from random import randint
async def getLevels(amount, highPrice, lowPrice, roundDecimals):
# Returns array of prices from low to high for each level
levels = []
delta = (highPrice - lowPrice)/amount
levelPrice = lowPrice
for i in range(amount - 1):
levels.append(levelPrice)
levelPrice = round(levelPrice + delta, 2)
levels.append(highPrice)
return levels
async def parseParams(params):
paramsList = params.split()
paramsDict = {}
for i in range(len(options.paramsLines)):
paramsDict[options.paramsLines[i]] = paramsList[i]
return paramsDict
async def toDictPairParams(pair: str, params):
paramsList = params.split()
if len(paramsList) != len(options.paramsLines):
return -1
paramsDict = {pair: {}}
for i in range(len(options.paramsLines)):
paramsDict[pair][options.paramsLines[i]] = paramsList[i]
return paramsDict
async def checkPair(pair: str):
currentData = {}
try:
with open('data.json', 'r') as f:
currentData = json.load(f)
except json.decoder.JSONDecodeError as e:
print('WARNING: JSON file is empty! Ignore if your installation is fresh.')
if pair in currentData:
print(pair, ' exists in data file.')
return 1
else:
print(pair, ' not found in data file.')
return 0
async def deletePair(pair: str):
currentData = {}
try:
with open('data.json', 'r') as f:
currentData = json.load(f)
except json.decoder.JSONDecodeError as e:
print('WARNING: JSON file is empty! Ignore if your installation is fresh.')
if pair in currentData:
print(pair, ' exists in data file.')
del currentData[pair]
with open('data.json', 'w', encoding = 'utf-8') as f:
json.dump(currentData, f, ensure_ascii = False, indent = 4)
return 0
else:
print(pair, ' not found in data file.')
return -1
async def mainWrapper(pair: str, params):
newData = await toDictPairParams(pair, params)
if newData == -1:
return -1
currentData = {}
try:
with open('data.json', 'r') as f:
currentData = json.load(f)
except json.decoder.JSONDecodeError as e:
print('WARNING: JSON file is empty! Ignore if your installation is fresh.')
if pair in currentData:
print(pair, ' already exists.')
return -2
else:
with open('data.json', 'w', encoding = 'utf-8') as f:
currentData.update(newData)
json.dump(currentData, f, ensure_ascii = False, indent = 4)
print(pair, ' was added!')
return 0
def getArbus():
# Returnes n arbus (n is random 1 byte positive number)
return ("arbus"*randint(0, 255))

View File

@ -7,7 +7,7 @@ from pybit.unified_trading import WebSocket
import options
import credentials
import arbus
import jsonProcessing
async def getClient(apiKey, apiSecret, testnet):
@ -54,7 +54,7 @@ async def socketStrategy(pair: str, params):
# 'stopDelta',
# 'orderSize'
paramsDict = await arbus.parseParams(params)
paramsDict = await jsonProcessing.parseParams(params)
ws = WebSocket(
testnet = options.testnet,
@ -79,9 +79,9 @@ async def socketStrategy(pair: str, params):
)
i = 0
t = await arbus.checkPair(pair)
t = await jsonProcessing.checkPair(pair)
while t:
t = await arbus.checkPair(pair)
t = await jsonProcessing.checkPair(pair)
if t != 1:
# ws.exit()
# ws_private.exit()
@ -97,12 +97,12 @@ async def socketStrategy(pair: str, params):
async def strategy(client: HTTP, pair: str, params):
startTime = time.time()
print('Starting strategy with ', pair)
paramsDict = await arbus.parseParams(params)
paramsDict = await jsonProcessing.parseParams(params)
i = 0
t = await arbus.checkPair(pair)
t = await jsonProcessing.checkPair(pair)
while t:
t = await arbus.checkPair(pair)
t = await jsonProcessing.checkPair(pair)
if t != 1:
break

84
src/jsonProcessing.py Normal file
View File

@ -0,0 +1,84 @@
import json
import options
async def parseParams(params):
# Returnes dictionary of params as paramsLines in options
paramsList = params.split()
paramsDict = {}
for i in range(len(options.paramsLines)):
paramsDict[options.paramsLines[i]] = paramsList[i]
return paramsDict
async def toDictPairParams(pair: str, params):
# Returnes dictionary as pair:internal(params)
paramsList = params.split()
if len(paramsList) != len(options.paramsLines):
return -1
paramsDict = {pair: {}}
for i in range(len(options.paramsLines)):
paramsDict[pair][options.paramsLines[i]] = paramsList[i]
return paramsDict
async def checkPair(pair: str):
# Returnes 1 if pair exists and 0 if not
currentData = {}
try:
with open('data.json', 'r') as f:
currentData = json.load(f)
except json.decoder.JSONDecodeError as e:
print('WARNING: JSON file is empty! Ignore if your installation is fresh.')
if pair in currentData:
# print(pair, ' exists in data file.')
return 1
else:
# print(pair, ' not found in data file.')
return 0
async def deletePair(pair: str):
# Returnes 0 if deleted successfully and -1 if not
currentData = {}
try:
with open('data.json', 'r') as f:
currentData = json.load(f)
except json.decoder.JSONDecodeError as e:
print('WARNING: JSON file is empty! Ignore if your installation is fresh.')
if pair in currentData:
# print(pair, ' exists in data file.')
del currentData[pair]
with open('data.json', 'w', encoding = 'utf-8') as f:
json.dump(currentData, f, ensure_ascii = False, indent = 4)
return 0
else:
# print(pair, ' not found in data file.')
return -1
async def savePairParams(pair: str, params):
# Saves or updates data in JSON
# Fix no file or empty file
newData = await toDictPairParams(pair, params)
if newData == -1:
return -1
currentData = {}
try:
with open('data.json', 'r') as f:
currentData = json.load(f)
except json.decoder.JSONDecodeError as e:
print('WARNING: JSON file is empty! Ignore if your installation is fresh.')
if pair in currentData:
print(pair, ' already exists.')
return -2
else:
with open('data.json', 'w', encoding = 'utf-8') as f:
currentData.update(newData)
json.dump(currentData, f, ensure_ascii = False, indent = 4)
print(pair, ' was added!')
return 0

View File

@ -13,7 +13,7 @@ from aiogram.fsm.state import State, StatesGroup
from aiogram.fsm.storage.memory import MemoryStorage
import bybit
import arbus
import jsonProcessing
import credentials
import strings
@ -82,7 +82,7 @@ async def capture_start_pair(message: Message, state: FSMContext):
data = await state.get_data()
t = 0
if await arbus.checkPair(data.get("pair")) == 1:
if await jsonProcessing.checkPair(data.get("pair")) == 1:
msg_text = (f'Стратегия на паре <b>{data.get("pair")}</b> уже запущена.\nПожалуйста остановите стратегию либо введите другую пару.')
t = 1
else:
@ -101,14 +101,13 @@ async def capture_params(message: Message, state: FSMContext):
await state.update_data(params=message.text)
data = await state.get_data()
t = await arbus.mainWrapper(pair=data.get("pair"), params=data.get("params"))
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)
if client == -1:
msg_text = (f'Аутентификация не удалась, сообщите администратору если увидете данное сообщение.')
else:
asyncio.create_task(bybit.socketStrategy(data.get("pair"), data.get("params")))
# asyncio.create_task(bybit.strategy(client, data.get("pair"), data.get("params")))
msg_text = (f'Вы запустили стратегию на паре <b>{data.get("pair")}</b> с данными параметрами:\n<b>{data.get("params")}</b>\n')
elif t == -1:
msg_text = (f'Параметры введены в неверном формате, пожалуйста начните заново.')
@ -132,8 +131,8 @@ async def capture_stop_pair(message: Message, state: FSMContext):
await state.update_data(pair=message.text)
data = await state.get_data()
if await arbus.checkPair(data.get("pair")) == 1:
t = await arbus.deletePair(data.get("pair"))
if await jsonProcessing.checkPair(data.get("pair")) == 1:
t = await jsonProcessing.deletePair(data.get("pair"))
if t == 0:
print('Deleted pair succesfuly')
else: