Saving logs+data to dir. fixes
This commit is contained in:
@ -7,10 +7,10 @@ from random import randint
|
||||
startTime = None
|
||||
|
||||
def setStartTime():
|
||||
global startTime
|
||||
startTime = time.time()
|
||||
|
||||
def getPnL(pair):
|
||||
PnL = 0.0
|
||||
with open("tradingLog.log", "r") as f:
|
||||
lines = f.readlines()
|
||||
|
||||
|
||||
27
src/bybit.py
27
src/bybit.py
@ -14,6 +14,33 @@ from logger import generalLogger
|
||||
from logger import tradingLogger
|
||||
|
||||
|
||||
def getPrice(client, pair):
|
||||
ticker = client.get_tickers(
|
||||
category = "linear",
|
||||
symbol = pair
|
||||
)
|
||||
price = float(ticker.get('result').get('list')[0].get('ask1Price'))
|
||||
return price
|
||||
|
||||
def getStartBalance(client, pair):
|
||||
coin = pair[:-4]
|
||||
response = client.get_wallet_balance(
|
||||
accountType = "UNIFIED",
|
||||
coin = coin
|
||||
)
|
||||
balance = float(response['result']['list'][0]['totalAvailableBalance'])
|
||||
return balance
|
||||
|
||||
def getStartFilters(client, pair):
|
||||
instrumentInfo = client.get_instruments_info(
|
||||
symbol = pair,
|
||||
category = "linear"
|
||||
)
|
||||
infoContents = instrumentInfo.get('result').get('list')[0]
|
||||
minimumQty = float(infoContents.get('lotSizeFilter').get('minOrderQty'))
|
||||
return minimumQty
|
||||
|
||||
|
||||
class tradingData:
|
||||
def __init__(self, pair, levels, highBreak, lowBreak, takeDelta, stopDelta, orderSize):
|
||||
self.client = HTTP(
|
||||
|
||||
@ -8,12 +8,18 @@ from logger import generalLogger
|
||||
import options
|
||||
|
||||
|
||||
jsonPath = 'data/data.json'
|
||||
|
||||
|
||||
def startUp():
|
||||
filePath = 'data.json'
|
||||
filePath = jsonPath
|
||||
|
||||
if not(os.path.exists('data')):
|
||||
os.mkdir('data')
|
||||
|
||||
if os.path.exists(filePath):
|
||||
timestamp = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
|
||||
backupPath = (f'data_backup_{timestamp}.json')
|
||||
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
|
||||
backupPath = (f'data/data_backup_{timestamp}.json')
|
||||
shutil.copy(filePath, backupPath)
|
||||
generalLogger.info(f'JSON backup was created: {backupPath}')
|
||||
|
||||
@ -47,10 +53,10 @@ async def checkPair(pair: str):
|
||||
# Returnes 1 if pair exists and 0 if not
|
||||
currentData = {}
|
||||
try:
|
||||
with open('data.json', 'r') as f:
|
||||
with open(jsonPath, 'r') as f:
|
||||
currentData = json.load(f)
|
||||
except json.decoder.JSONDecodeError as e:
|
||||
generalLogger.info('WARNING: JSON file is empty! Ignore if your installation is fresh.')
|
||||
generalLogger.warning('JSON file is empty!')
|
||||
|
||||
if pair in currentData:
|
||||
return 1
|
||||
@ -61,14 +67,14 @@ async def deletePair(pair: str):
|
||||
# Returnes 0 if deleted successfully and -1 if not
|
||||
currentData = {}
|
||||
try:
|
||||
with open('data.json', 'r') as f:
|
||||
with open(jsonPath, 'r') as f:
|
||||
currentData = json.load(f)
|
||||
except json.decoder.JSONDecodeError as e:
|
||||
generalLogger.info('WARNING: JSON file is empty! Ignore if your installation is fresh.')
|
||||
generalLogger.warning('JSON file is empty!')
|
||||
|
||||
if pair in currentData:
|
||||
del currentData[pair]
|
||||
with open('data.json', 'w', encoding = 'utf-8') as f:
|
||||
with open(jsonPath, 'w', encoding = 'utf-8') as f:
|
||||
json.dump(currentData, f, ensure_ascii = False, indent = 4)
|
||||
generalLogger.info(f'Pair {pair} was deleted successfully!')
|
||||
return 0
|
||||
@ -85,16 +91,16 @@ async def savePairParams(pair: str, params):
|
||||
|
||||
currentData = {}
|
||||
try:
|
||||
with open('data.json', 'r') as f:
|
||||
with open(jsonPath, 'r') as f:
|
||||
currentData = json.load(f)
|
||||
except json.decoder.JSONDecodeError as e:
|
||||
generalLogger.info('WARNING: JSON file is empty! Ignore if your installation is fresh.')
|
||||
generalLogger.warning('JSON file is empty!')
|
||||
|
||||
if pair in currentData:
|
||||
generalLogger.info(f"Pair {pair} already exists.")
|
||||
return -2
|
||||
else:
|
||||
with open('data.json', 'w', encoding = 'utf-8') as f:
|
||||
with open(jsonPath, 'w', encoding = 'utf-8') as f:
|
||||
currentData.update(newData)
|
||||
json.dump(currentData, f, ensure_ascii = False, indent = 4)
|
||||
generalLogger.info(f"Pair {pair} was added!")
|
||||
@ -105,8 +111,8 @@ async def loadJson():
|
||||
# Returnes the contents of the JSON file as a dictionary
|
||||
data = {}
|
||||
try:
|
||||
with open('data.json', 'r') as f:
|
||||
with open(jsonPath, 'r') as f:
|
||||
data = json.load(f)
|
||||
except json.decoder.JSONDecodeError as e:
|
||||
generalLogger.info('WARNING: JSON file is empty! Ignore if your installation is fresh.')
|
||||
generalLogger.warning('JSON file is empty!')
|
||||
return data
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
import logging
|
||||
import sys
|
||||
import os
|
||||
|
||||
import options
|
||||
|
||||
|
||||
generalLogPath = "./generalLog.log"
|
||||
tradingLogPath = "./tradingLog.log"
|
||||
generalLogPath = "./data/generalLog.log"
|
||||
tradingLogPath = "./data/tradingLog.log"
|
||||
|
||||
|
||||
def setupLogger(name, level, logPath, formatter):
|
||||
@ -23,15 +24,18 @@ def setupLogger(name, level, logPath, formatter):
|
||||
return logger
|
||||
|
||||
|
||||
if not(os.path.exists('data')):
|
||||
os.mkdir('data')
|
||||
|
||||
# Основной лог
|
||||
generalFormatter = logging.Formatter('%(asctime)s - %(module)s - %(levelname)s - %(message)s')
|
||||
generalLogger = setupLogger('general', logging.INFO, generalLogPath, generalFormatter)
|
||||
|
||||
# Торговый лог (ордера)
|
||||
# Торговый лог (открытие, закрытие ордеров, запуск стратегии)
|
||||
tradingFormatter = logging.Formatter('%(asctime)s - %(message)s')
|
||||
tradingLogger = setupLogger('trade', logging.NOTSET, tradingLogPath, tradingFormatter)
|
||||
|
||||
# Максимально подробный общий лог, вызывает повторы в логировании. Его наличие настраивается
|
||||
# Максимально подробный дебаг лог, вызывает повторы в логировании. Его наличие настраивается
|
||||
if options.showExtraDebugLogs:
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
superGeneralLogger = logging.getLogger('superGeneral')
|
||||
|
||||
29
src/main.py
29
src/main.py
@ -115,6 +115,7 @@ async def capture_params(message: Message, state: FSMContext):
|
||||
|
||||
data = await state.get_data()
|
||||
t = await jsonProcessing.savePairParams(pair=data.get("pair"), params=data.get("params"))
|
||||
params = await jsonProcessing.parseParams(params=data.get("params"))
|
||||
if t == 0:
|
||||
client = await bybit.getClient(
|
||||
credentials.api_key,
|
||||
@ -124,15 +125,31 @@ async def capture_params(message: Message, state: FSMContext):
|
||||
)
|
||||
if client == -1:
|
||||
msgText = strings.authFailed
|
||||
generalLogger.info("Auth failed. Strategy not started")
|
||||
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:
|
||||
orderSize = float(params.get('orderSize'))
|
||||
minqty = bybit.getStartFilters(client, data.get("pair"))
|
||||
qtyDecimals = arbus.countDecimals(minqty)
|
||||
balance = bybit.getStartBalance(client, data.get("pair"))
|
||||
price = bybit.getPrice(client, data.get("pair"))
|
||||
|
||||
qty = arbus.floor(orderSize/price, qtyDecimals)
|
||||
if qty <= minqty:
|
||||
generalLogger.info("Qty < minqty. Strategy not started")
|
||||
msgText = strings.orderSizeLowerThanQty
|
||||
await jsonProcessing.deletePair(pair=data.get("pair"))
|
||||
msgText = (strings.strategyError)
|
||||
elif balance <= orderSize:
|
||||
generalLogger.info("Balance < order size. Strategy not started")
|
||||
msgText = strings.notEnoughBalance
|
||||
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:
|
||||
|
||||
@ -54,6 +54,10 @@ pairNotFound = "Стратегия на данную монетную пару
|
||||
|
||||
authFailed = (f"Аутентификация не удалась, пожалуйста сообщите администратору если увидете данное сообщение.")
|
||||
|
||||
orderSizeLowerThanQty = "Введённая сумма меньше минимального размера ордера на Bybit."
|
||||
|
||||
notEnoughBalance = "На балансе недостаточно средств для зпуска стратегии."
|
||||
|
||||
wrongFormat = "Параметры введены в неверном формате, пожалуйста начните заново."
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user