def remove_inactive_markets_from_buffer(marketsBuffer): newMarketsBuffer = [] for m in marketsBuffer: if m["isActive"]: newMarketsBuffer.append(m) log.event_log_append("Inactive markets removed from buffer. The current marketsBuffer is:\n", log.tab, newMarketsBuffer) return newMarketsBuffer
def _markets_buffer_format_check(self): if type(self.marketsBuffer) is not list: raise TypeError("marketsBuffer must be a list.") tc, mc = "tradedCurrency", "mainCurrency" sym, rta = "symbol", "tradablePortion" for m in self.marketsBuffer: if not 0 <= m[tc][rta] <= 1 \ or not 0 <= m[mc][rta] <= 1: err = "tradablePortion numbers must be int or float between 0 and 1" log.event_log_append("Session crashed.\n", log.tab, err) raise ValueError(err) log.event_log_append("markets_buffer_format_check OK.")
def __init__(self, clientName, run=True): self.clientName = clientName self.isrunning = run self.localTimestamp = time() self.localDateTime = datetime.fromtimestamp(self.localTimestamp) logMessage = f'\n\n{self.localDateTime}\nSession created with "{self.clientName}" credentials and run = {run}' log.event_log_append(logMessage) log.raw_log_append(logMessage) # RESTRICTIONS TO BE IMPLEMENTED... WHERE? # statuses = [] # [ID, runningOrClosed, crashingInfo, *args] self.market = MarketManager() self.wait = DEFAULT_WAIT if self.isrunning: self.sessionID = ID("session") logMessage = f'Session has started with session ID: {self.sessionID.partialID}.\n' log.event_log_append(logMessage) log.raw_log_append(logMessage) while self.isrunning: log.event_log_append('\nCurrent marketsBuffer = ', self.market.marketsBuffer) try: self.newStatus = Status(self.clientName, self.market.current()) self.wait = DEFAULT_WAIT except IDOverflowError or IndexError: self.statusIDReset = ID("status", getNew=False, reset=True) self.isrunning = False logMessage = f'\nSession terminated for statusID overflow.\n' log.event_log_append(logMessage) log.raw_log_append(logMessage) break """ except Exception as err: if self.wait < MAX_WAIT: self.wait *= WAIT_MULTIPLIER_0 logMessage = f'\nStatus crashed with error:\n {err.__repr__()}\n' log.event_log_append(logMessage) log.raw_log_append(logMessage) """ self.market.set_next_to_current() """ #if newStatus.getMarketData() is different from marketData, update sessionConfig.json try: self.lastMarket = newStatus.getMarketData() except: self.lastMarket = self.marketsBuffer[0] if len(self.marketsBuffer) > 1: self.marketsBuffer = self.marketsBuffer[1:] self.marketsBuffer.append(self.lastMarket) """ sleep(self.wait)
def _markets_buffer_amounts_splitting(self): tc, mc = "tradedCurrency", "mainCurrency" sym, rta = "symbol", "tradablePortion" tmpDict0 = {} for m in self.marketsBuffer: tmpDict0[m[tc][sym]] = 0 tmpDict0[m[mc][sym]] = 0 tmpDict1 = tmpDict0.copy() for m in self.marketsBuffer: if m[tc][rta] == 0: tmpDict0[m[tc][sym]] += 1 else: tmpDict1[m[tc][sym]] += m[tc][rta] if m[mc][rta] == 0: tmpDict0[m[mc][sym]] += 1 else: tmpDict1[m[mc][sym]] += m[mc][rta] for tm in tmpDict0: try: tmpDict1[tm] = int( (1 - tmpDict1[tm]) / tmpDict0[tm] * 1000) / 1000 except ZeroDivisionError: pass for tm in tmpDict1: if tmpDict1[tm] < 0: err = "The sum of the of all the tradablePortions related to a symbol of an active "\ "market must not be greater than 1." log.event_log_append('Session crashed.\n', log.tab, err) raise ValueError(err) #print(tmpDict1) #print(tmpDict1[marketsBuffer[0][tc][sym]]) for i in range(0, len(self.marketsBuffer)): if self.marketsBuffer[i][tc][rta] == 0: self.marketsBuffer[i][tc][rta] = tmpDict1[self.marketsBuffer[i] [tc][sym]] if self.marketsBuffer[i][mc][rta] == 0: self.marketsBuffer[i][mc][rta] = tmpDict1[self.marketsBuffer[i] [mc][sym]] #print(marketsBuffer) log.event_log_append( "After splitting the tradablePortion, marketBuffer is:\n", log.tab, self.marketsBuffer)
def __init__(self, client_name, market_data, run=True, allow_order_placing=True, password='', *args): self.clientName = client_name self.run = run self.allow_order_placing = allow_order_placing logMessage = f'\n\nStatus called with "{self.clientName}" credentials and run = {run}' log.event_log_append(logMessage) log.raw_log_append(logMessage) #self.rawLogHeader = ['status full ID', 'status partial ID'] if self.run: self.statusID = ID("status") self.market = market_data() """ self.marketData = market_data self.tradedCurrency = market_data["tradedCurrency"]["symbol"] self.mainCurrency = market_data["mainCurrency"]["symbol"] self.marketSymbol = self.tradedCurrency + self.mainCurrency self.marketSymbolDict = {'symbol': self.marketSymbol} """ self.localTimestamp = int(time()) self.localDateTime = datetime.fromtimestamp(self.localTimestamp) logMessage = f'{self.localDateTime}\tstatus started with status ID: {self.statusID.partialID}.\n{self.market.symbolString}\t{self.statusID.fullID}' log.event_log_append(logMessage) log.raw_log_append(logMessage) self.wait = DEFAULT_WAIT with open(paths.clientConfig, 'r') as f: client_data = json.load(f) client_data = client_data['clientNames'][self.clientName] if client_data["api_key"]["isEncrypted"]: api_key = customEncrypter.decrypt( client_data["api_key"]["value"], password) else: api_key = client_data["api_key"]["value"] if client_data["api_key"]["isEncrypted"]: api_secret = customEncrypter.decrypt( client_data["api_secret"]["value"], password) else: api_secret = client_data["api_secret"]["value"] self.client = Client(api_key, api_secret) logMessage = f'{self.localDateTime}\t-\t{self.localTimestamp}\t-\tapi keys successfully fetched.' log.event_log_append(logMessage) log.raw_log_append(logMessage) self.serverTime = int( int(self.getServerTime()["serverTime"]) / 1000) sleep(self.wait) logMessage = f'ServerTime:\t{self.serverTime}' log.event_log_append(logMessage) log.raw_log_append(logMessage) if self.market.needsRestart == True: self.openOrders = self.cancelAllOpenOrders() self.market.needsRestart = False log.event_log_append( "NEEDS_RESTART WAS TRUE BUT THE CODE ISN'T READY FOR THAT!!!!" ) # check the whole code and remember to update marketsBuffer.. it probably doesn't work now. # print log stuff # restore log config file return self.openOrders = [] self.get_open_orders(fromServer=True) sleep(self.wait) self.lastFilledOrder = self.getLastFilledOrder() sleep(self.wait) self.accountInfo = self.client.get_account() self.freeBalances = self.getFreeBalances() self.totalBalances = self.getTotalBalances() sleep(self.wait) self.market_info = self.client.get_symbol_info( self.market.symbolString) sleep(self.wait) logMessage = f'MarketData:\t{self.market.marketData}\nFree Balances:\t{self.freeBalances}\nTotalBalances:\t{self.totalBalances}' log.raw_log_append(logMessage) self.simplifiedStatus = self.getSimplifiedStatus() log.raw_log_append("Simplified Status:\n", self.getPrintableSimplifiedStatus()) botOneProcessor = BotOneAlgo(self.simplifiedStatus, self.market_info) self.tasksList = botOneProcessor.get_tasks() log.raw_log_append("New Orders:") print(f'TasksList: {self.tasksList}') for task in self.tasksList: if self.allow_order_placing: try: if task["taskType"] == "createOrder": self.client.create_order(**self.market.symbolD, type='limit', timeInForce='GTC', side=task["side"], quantity=task["quantity"], price=task["price"]) log.new_orders_log_csv_append( self.get_list_of_new_orders_log_csv_variables( task)) log.raw_log_append( f'\tprice:\t{task["price"]}\tquantity:\t{task["quantity"]}' ) except Exception as err: log.raw_log_append( f'Task not found or incorrectly formatted. Skipping this step...\n\t{err.__repr__()}' ) sleep(self.wait) log.raw_log_append(f'Total Balance in Main Currency:\t\t', self.getTotalEquivalentBalanceInMainCurrency()) sleep(self.wait)
def __init__(self, clientName, password='', run=True, **jsonConfigKeysToOverride): self.clientName = clientName self.password = password self.isrunning = run self.localTimestamp = time() self.localDateTime = datetime.fromtimestamp(self.localTimestamp) logMessage = f'\n\n{self.localDateTime}\nSession created with "{self.clientName}" credentials and run = {run}' log.event_log_append(logMessage) log.raw_log_append(logMessage) """ with open(paths.clientConfig, 'r') as f: jsonClientConfig = json.load(f) self.clientData = jsonClientConfig[client_name] """ with open(paths.sessionConfig, 'r') as f: jsonSessionConfig = json.load(f) for key in jsonConfigKeysToOverride: jsonSessionConfig[key] = jsonConfigKeysToOverride[key] self.marketsBuffer = jsonSessionConfig["sessionData"]["marketsBuffer"] markets_buffer_format_check(self.marketsBuffer) self.marketsBuffer = remove_inactive_markets_from_buffer(self.marketsBuffer) self.marketsBuffer = marketsBufferAmountsSplitting(self.marketsBuffer) # RESTRICTIONS TO BE IMPLEMENTE IN STATUS, NOT HERE!!!!!! # statuses = [] # [ID, runningOrClosed, crashingInfo, *args] wait = DEFAULT_WAIT if self.isrunning: self.sessionID = ID("session") logMessage = f'Session has started with session ID: {self.sessionID.partialID}.\n' log.event_log_append(logMessage) log.raw_log_append(logMessage) while self.isrunning: log.event_log_append('\nCurrent marketsBuffer = ', self.marketsBuffer) try: newStatus = Status(self.clientName, self.password, self.marketsBuffer[0]) wait = DEFAULT_WAIT except IDOverflowError: self.statusIDReset = ID("status", getNew=False, reset=True) self.isrunning = False logMessage = f'\nSession terminated for statusID overflow.\n' log.event_log_append(logMessage) log.raw_log_append(logMessage) break except Exception as err: if wait < MAX_WAIT: wait *= WAIT_MULTIPLIER_0 logMessage = f'\nStatus crashed with error:\n {err.__repr__()}\n' log.event_log_append(logMessage) log.raw_log_append(logMessage) log.error_log_append(err.__repr__(), self.sessionID.partialID, ID("status", getNew=False, reset=False).partialID) #if newStatus.getMarketData() is different from marketData, update sessionConfig.json try: self.lastMarket = newStatus.getMarketData() except: self.lastMarket = self.marketsBuffer[0] if len(self.marketsBuffer) > 1: self.marketsBuffer = self.marketsBuffer[1:] self.marketsBuffer.append(self.lastMarket) sleep(wait)
print( '\nPlease type your password if your data is encrypted, otherwise press Enter' ) password = input(">") if command == startStr: wait = WAIT_TIME #sleep(wait) print("\nBotOne-v0.1-alpha is running for the very first time.\n") sleep(wait) print("GOOD LUCK!\n") #sleep(wait) print("Ch'a Maronn t'accumpagn\n\n") #sleep(wait) #startStrstart log.event_log_append("An instance of ", "BotOne-v0.1-alpha ", "has been launched.") while command.lower() == startStr.lower(): newSession = Session("clientOne", password) print('\nBye!\n') sleep(BYE_TIME) ## keys0 API keys - remind to restrict the IPs after the bot is running #myApiKey = 'vdBlDHNvNdjDyGq2OVOpAasIaw9KCuX64Tkyd8UMPBAKZt9iy0CI4NJsSo0Cugpd' #mySecretKey = 'OQUD762C24JvzHzFqeWozndcWz4ykfkbQ6ViP8SAenpIRWejWN0zaXOX0y8iU4bc' #client = Client(myApiKey, mySecretKey) #session0 = client._init_session()