def allenabledmarkets(): priceSources = {} sources = haasomeClient.marketDataApi.get_enabled_price_sources().result for source in sources: print(source.capitalize()) print(str(source).capitalize()) print(source) print(EnumPriceSource(EnumPriceSource(str(source)))) priceSources[str( source)] = haasomeClient.marketDataApi.get_price_markets( (EnumPriceSource(source))).result print(priceSources) print(priceSources) return (priceSources)
def save_all_markets_history_to_db(self): ''' Downloads all the market history for every enabled market ''' total_markets = len(self.markets) for market in self.markets.iterrows(): print(f'YO {market[1]["obj"]}') market_history = self.get_last_ticks( EnumPriceSource(market[1]["obj"].priceSource).name, market[1]["obj"].primaryCurrency, market[1]["obj"].secondaryCurrency) # print(market_history.content.decode('utf-8')) data_dict = market_history.json().get('Data') index = [] # print(data_dict) # df = pd.DataFrame(market_history.json().get('Data')) for d in data_dict: index.append(pd.to_datetime(d['T'], unit='s')) # dti = pd.DatetimeIndex(index) df = pd.DataFrame(data_dict, index=index) # df.T = pd.to_datetime(df['T'], unit='s') total_markets -= 1 self.save_market_history_to_db(market[1]["obj"], df) print(df) print(f'There are {total_markets} left to download')
def bot_config(self, bot): botdict = { "pricesource": EnumPriceSource(bot.priceMarket.priceSource).name, "primarycoin": bot.priceMarket.primaryCurrency, "secondarycoin": bot.priceMarket.secondaryCurrency, "interval": int(bot.interval), "signalconsensus": bool(bot.useTwoSignals), "resetmiddle": bool(bot.bBands["ResetMid"]), "allowmidsells": bool(bot.bBands["AllowMidSell"]), "matype": bot.bBands["MaType"], "fcc": bool(bot.bBands["RequireFcc"]), "rsil": str(bot.rsi["RsiLength"]), "rsib": str(bot.rsi["RsiOversold"]), "rsis": str(bot.rsi["RsiOverbought"]), "bbl": str(bot.bBands["Length"]), "devup": str(bot.bBands["Devup"]), "devdn": str(bot.bBands["Devdn"]), "macdfast": str(bot.macd["MacdFast"]), "macdslow": str(bot.macd["MacdSlow"]), "macdsign": str(bot.macd["MacdSign"]), "roi": int(bot.roi), "trades": int(len(bot.completedOrders)), 'orderbook': [{x: y for x, y in self.trades_to_df(bot).items()}] } return df
def get_price_markets(self, pricesource: EnumPriceSource): """ Returns markets for specified price source :param pricesource: :class:`~haasomeapi.enums.EnumPriceSource`: Price Source (Exchange) :returns: :class:`~haasomeapi.dataobjects.util.HaasomeClientResponse` :returns: In .result List[:class:`~haasomeapi.dataobjects.marketdata.Market`] of markets """ response = super()._execute_request("/GetPriceMarkets", { "priceSourceName": EnumPriceSource(pricesource).name.capitalize() }) markets = [] for market in response["Result"]: markets.append(super()._from_json(market, Market)) try: return HaasomeClientResponse( EnumErrorCode(int(response["ErrorCode"])), response["ErrorMessage"], markets) except: return HaasomeClientResponse( EnumErrorCode(int(response["ErrorCode"])), response["ErrorMessage"], {})
def get_order_book(self, pricesource: EnumPriceSource, primarycoin: str, secondarycoin: str, contractname: str): """ Returns the current order book for specified market :param pricesource: :class:`~haasomeapi.enums.EnumPriceSource`: Price Source (Exchange) to get ticker from :param primarycoin: str: Primary currency Ex. If BNB/BTC then set this to BNB :param secondarycoin: str: Secondary currency Ex. If BNB/BTC then set this to BTC :param contractname: str: Contract Name (Optional) :returns: :class:`~haasomeapi.dataobjects.util.HaasomeClientResponse` :returns: In .result :class:`~haasomeapi.dataobjects.marketdata.Orderbook`: Orderbook object """ response = super()._execute_request( "/GetOrderbook", { "priceSourceName": EnumPriceSource(pricesource).name.capitalize(), "primaryCoin": primarycoin, "secondaryCoin": secondarycoin, "contractName": contractname }) try: return HaasomeClientResponse( EnumErrorCode(int(response["ErrorCode"])), response["ErrorMessage"], super()._from_json(response["Result"], Orderbook)) except: return HaasomeClientResponse( EnumErrorCode(int(response["ErrorCode"])), response["ErrorMessage"], {})
def get_market_history(priceMarket, ticks): saved = 0 interval = 1 nohistory = 0 count = 0 historystat = haasomeClient.marketDataApi.get_history_from_market( priceMarket, interval, ticks) if historystat.errorCode.value == 100: print(historystat.errorCode.name, historystat.errorMessage, priceMarket.primaryCurrency, priceMarket.secondaryCurrency) print(len(historystat.result)) if len(historystat.result) > 0: marketdata = historystat.result filename = str(EnumPriceSource( priceMarket.priceSource).name) + '_' + str( priceMarket.primaryCurrency) + '_' + str( priceMarket.secondaryCurrency) + '_' + str( len(marketdata)) + '_' + str(interval) + '.csv' currentfile = Path(str(filename)) currentfile.touch() print(filename, 'has been saved!') with open(filename, 'w', newline='') as csvfile: fieldnames = [ 'timeStamp', 'unixTimeStamp', 'open', 'highValue', 'lowValue', 'close', 'volume', 'currentBuyValue', 'currentSellValue' ] csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames) csvwriter.writeheader() for tick in marketdata: csvwriter.writerow({ 'timeStamp': str(tick.timeStamp), 'unixTimeStamp': str(tick.unixTimeStamp), 'open': float(tick.open), 'highValue': float(tick.highValue), 'lowValue': float(tick.lowValue), 'close': float(tick.close), 'volume': float(tick.volume), 'currentBuyValue': str(tick.currentBuyValue), 'currentSellValue': float(tick.currentSellValue) }) saved += 1 print(saved, 'ticks has been saved') else: print(historystat.errorCode) historystat = haasomeClient.marketDataApi.get_history_from_market( priceMarket, interval, ticks) time.wait()
def get_market_Data(frozen): market_object = jsonpickle.decode(frozen) market_data = MarketData().get_ticks( EnumPriceSource(market_object.priceSource).name, market_object.primaryCurrency, market_object.secondaryCurrency, 1, 'LASTTICKS') frozen = market_data.to_json() return frozen
def main(): all_markets = MarketData().get_all_markets() # print(all_markets.pricesource.unique()) # print(len(all_markets.pricesource.unique())) # print(all_markets.primarycurrency.unique()) # print(len(all_markets.primarycurrency.unique())) all_markets[['pricesource', 'primarycurrency', 'secondarycurrency']].to_csv('all_markets_pairs.csv') all_markets[['primarycurrency', 'secondarycurrency']].to_csv('all_pairs.csv') all_markets.pricesource.to_csv('all_exchanges.csv') print(EnumPriceSource(all_markets.obj[0].priceSource)) # all_markets.to_csv('all_markets.csv') print(all_markets.obj[0].priceSource)
def get_all_markets(self): markets = [( EnumPriceSource(i.priceSource).name, i.primaryCurrency, i.secondaryCurrency, i, ) for i in self.c().marketDataApi.get_all_price_markets().result] df = pd.DataFrame(markets, columns=([ "pricesource", "primarycurrency", "secondarycurrency", "obj" ])) return df
def get_history(self, pricesource: EnumPriceSource, primarycoin: str, secondarycoin: str, contractname: str, interval: int, depth: int): """ Get price history from price servers :param pricesource: :class:`~haasomeapi.enums.EnumPriceSource`: Price Source (Exchange) to get ticker from :param primarycoin: str: Primary currency Ex. If BNB/BTC then set this to BNB :param secondarycoin: str: Secondary currency Ex. If BNB/BTC then set this to BTC :param contractname: str: Contract Name (Optional) :param interval: int: The candle interval value Ex. 1,2,3,5,15,30,etc (In minutes) :param depth: int: The depth or how many candles to get :returns: :class:`~haasomeapi.dataobjects.util.HaasomeClientResponse` :returns: In .result List[:class:`~haasomeapi.dataobjects.marketdata.PriceTick`]: List of Price Tick objects """ response = super()._execute_request( "/GetHistory", { "priceSourceName": EnumPriceSource(pricesource).name.capitalize(), "primaryCoin": primarycoin, "secondaryCoin": secondarycoin, "contractName": contractname, "interval": str(interval), "depth": str(depth) }) priceticks = [] try: for pricetick in response["Result"]: priceTickModel = super()._from_json(pricetick, PriceTick) priceTickModel.timeStamp = parser.parse( priceTickModel.timeStamp) priceticks.append(priceTickModel) return HaasomeClientResponse( EnumErrorCode(int(response["ErrorCode"])), response["ErrorMessage"], priceticks) except: return HaasomeClientResponse( EnumErrorCode(int(response["ErrorCode"])), response["ErrorMessage"], {})
def get_enabled_accounts(self): accounts = [[ i[1].name, EnumPriceSource(i[1].connectedPriceSource), i[1].isSimulatedAccount, i[1].guid, i[1].platformType, ] for i in self.connect.accountDataApi.get_all_account_details(). result.items()] df = pd.DataFrame( accounts, columns=[ "name", "connectedPriceSource", "simulated", "guid", "platformType", ], ) return accounts
def price_source_num_to_str(pricesourcenum: int): return EnumPriceSource(pricesourcenum).name
def backtest_all_markets_with_bot(haasip: str, haasport: int, haassecret: str, accountguid: str, botguid: str, timeframeinminutes: int, contractname: str, iscustombot: bool): logging.info("Started the backtest of all markets") HaasManager.init_haas_manager(haasip, haasport, haassecret) backtestTasks = {} backtestResults = {} count = 0 markets = HaasManager.get_all_markets_for_guid(accountguid) accountInfo = HaasManager.get_account_info_for_id(accountguid) baseBotInfo = None if iscustombot: baseBotInfo = HaasManager.get_custom_bot_by_id(botguid) else: baseBotInfo = HaasManager.get_trade_bot_by_id(botguid) logging.info(baseBotInfo) logging.info(baseBotInfo.name) for market in markets: task = None if iscustombot: task = backtest_custom_bot_on_market(haasip, haasport, haassecret, accountguid, botguid, timeframeinminutes, market.primaryCurrency, market.secondaryCurrency, contractname) else: task = backtest_trade_bot_on_market(haasip, haasport, haassecret, accountguid, botguid, timeframeinminutes, market.primaryCurrency, market.secondaryCurrency, contractname) backtestTasks[count] = task count = count + 1 lastUpdateCount = 0 while len(backtestResults) != len(backtestTasks): for k, v in backtestTasks.items(): result = v.get() if result != None: if k in backtestResults: pass else: backtestResults[k] = result BasicAnalysisManager.create_basic_analysis_results_model( accountguid, EnumPriceSource(accountInfo.connectedPriceSource).name, botguid, baseBotInfo.name, result.priceMarket.primaryCurrency, result.priceMarket.secondaryCurrency, result.roi, iscustombot) if len(backtestResults) > lastUpdateCount: BasicAnalysisManager.update_amount_retrieved(len(backtestResults)) lastUpdateCount = len(backtestResults) time.sleep(1) BasicAnalysisManager.mark_completed() logging.info("Completed the backtest of all markets task")