def test_fetchBinanceBalance(self): MarketEngine.instance()._binance.privateGetAccount = MagicMock() MarketEngine.instance()._binance.privateGetAccount.return_value = { "makerCommission": 15, "takerCommission": 15, "buyerCommission": 0, "sellerCommission": 0, "canTrade": True, "canWithdraw": True, "canDeposit": True, "updateTime": 123456789, "balances": [ { "asset": "ETH", "free": "0.8893", "locked": "0.00000000" }, { "asset": "XRP", "free": "987", "locked": "0.00000000" }, { "asset": "EOS", "free": "2034", "locked": "0.00000000" } ] } self.assertEqual(MarketEngine.instance().fetchBalance(Exchange.BINANCE), { Currency.ETH: ('0.8893', '0.8893'), Currency.XRP: ('987', '987'), Currency.EOS: ('2034', '2034'), })
def exploitArbitrage(self, orders): if len(orders) == 2: MarketEngine.instance().makeSafeTrades(orders) else: print( "Number of orders was larger than 2! That is currently not supported" ) print(orders)
def test_fetchKrakenBalance(self): MarketEngine.instance()._kraken.privatePostBalance = MagicMock() MarketEngine.instance()._kraken.privatePostBalance.return_value = { 'error': [], 'result': { 'XETH': '0.998374', 'XXRP': '3024', 'XEOS': '10984', } } self.assertEqual(MarketEngine.instance().fetchBalance(Exchange.KRAKEN), { Currency.ETH: ('0.998374', '0.998374'), Currency.XRP: ('3024', '3024'), Currency.EOS: ('10984', '10984'), })
class Simulator: """ Handles general information and configuration of the simulation. Links the bot with the market engine through callbacks. """ def __init__(self, initialEquity, startDate, endDate, bot): self.initialEquity = initialEquity self.startDate = startDate self.endDate = endDate self.bot = bot self.mainDataFolder = self._getMainDataFolder() self.resultsFilePath = self.mainDataFolder + f'{self.bot}.csv' self.market = MarketEngine() # link bot and market through callbacks self.bot.addOrderCallback = self.market.addOrder self.bot.cancelOrderCallback = self.market.cancelOrder self.bot.getOpenOrdersCallback = self.market.getOpenOrders self.bot.getEquityCallback = self.market.getEquity self.market.orderExecutedCallback = self.bot.orderExecutedCallback def startSimulation(self): # load results if already available, perform the simulation otherwise if util.fileExists(self.resultsFilePath): util.logger.info( f"Results for this simulation are already available: {self.resultsFilePath}" ) self.results = util.loadDataset(self.resultsFilePath) else: symbolDataFilePath = self.mainDataFolder + self.bot.symbol + '_prices.csv' symbolData = util.getSymbolData(symbolDataFilePath) util.logger.info("Simulation started") self.bot.createInitialGrid(startPrice=symbolData['Price'][0]) self.market.startSimulation(symbolData) self.results = self.market.getResults() self.results.to_csv(self.resultsFilePath) util.logger.info(f"Results saved in {self.mainDataFolder}") def _getMainDataFolder(self): """ The data folder of a simulation is defined by the start and end dates. It has the format: datasets/yyyy-MM-dd-hhh-mmm_yyyy-MM-dd-hhh-mmm/ """ startDateString = f"{self.startDate.year}-{self.startDate.month:02d}-{self.startDate.day:02d}-{self.startDate.hour:02d}h-{self.startDate.minute:02d}m" endDateString = f"{self.endDate.year}-{self.endDate.month:02d}-{self.endDate.day:02d}-{self.endDate.hour:02d}h-{self.endDate.minute:02d}m" return f'datasets/{startDateString}_{endDateString}/'
def __init__(self, initialEquity, startDate, endDate, bot): self.initialEquity = initialEquity self.startDate = startDate self.endDate = endDate self.bot = bot self.mainDataFolder = self._getMainDataFolder() self.resultsFilePath = self.mainDataFolder + f'{self.bot}.csv' self.market = MarketEngine() # link bot and market through callbacks self.bot.addOrderCallback = self.market.addOrder self.bot.cancelOrderCallback = self.market.cancelOrder self.bot.getOpenOrdersCallback = self.market.getOpenOrders self.bot.getEquityCallback = self.market.getEquity self.market.orderExecutedCallback = self.bot.orderExecutedCallback
def run(): exchanges, pairs = initializeEverything() searchForOpportunities = True while searchForOpportunities: try: marketData = {} for exchange in exchanges: marketData[exchange] = MarketEngine.instance().fetchTickers( exch=exchange, pairs=pairs) VirtualMarket.instance().updateMarket(marketData=marketData) ArbitrageEngine.instance().updateGraph() ArbitrageEngine.instance()._graph.print() arbitrage_path = ArbitrageEngine.instance().findArbitrage( graph=ArbitrageEngine.instance()._graph, src=Currency.USDT, ) if arbitrage_path: percentGrowth = ArbitrageEngine.instance().verifyArbitrage(path=arbitrage_path) if percentGrowth >= SafetyValues.MinimumOpportunity.value: orders = ArbitrageEngine.instance().pathToOrders( path=arbitrage_path, graph=ArbitrageEngine.instance()._graph) pprint(orders) safe_orders = MarketEngine.instance().createSafeTrades(orders) if safe_orders: print('\n{0}Safe Orders:{1}'.format('\033[92m', '\033[0m')) pprint(safe_orders) print('\n\n') for order in safe_orders: pprint(MarketEngine.instance().makeUnsafeTrade(order=order)) print("Executed Order: {}".format(order.toStringShort())) pprint(BookKeeper.instance()._balances) else: print("{0}No arbitrage opportunity found!{1}\n".format('\033[91m','\033[0m')) sleep(5) except Exception as e: pprint(e) break
def initializeEverything(): currencies = [ Currency.BTC, Currency.ETH, Currency.LTC, Currency.XRP, ] exchanges = [ Exchange.BINANCE, Exchange.KRAKEN ] MarketEngine.initialize(currencies, exchanges, None) pairs = MarketEngine.instance().supportedCurrencyPairs() ArbitrageEngine.initialize(currencies, exchanges, pairs) BookKeeper.initialize(currencies, exchanges) VirtualMarket.initialize(currencies, exchanges, pairs) try: marketData = {} for exchange in exchanges: marketData[exchange] = MarketEngine.instance().fetchTickers( exch=exchange, pairs=pairs) VirtualMarket.instance().updateMarket(marketData=marketData) print("Market Initialized!") for key,value in VirtualMarket.instance()._market.items(): pprint(value.print()) for exchange in exchanges: MarketEngine.instance().fetchBalance(exch=exchange) print("Book Keeper Initialized!") pprint(BookKeeper.instance()._balances) except Exception as e: print("Initialization failed!") pprint(e) return return (exchanges, pairs)
def test_supportedCurrencies(self): supported_currencies = MarketEngine.instance().supportedCurrencies() self.assertEqual(supported_currencies, [ Currency.USDT, Currency.EOS, Currency.XRP, ])