Exemplo n.º 1
0
    async def start_market_making(
            self,  # type: HummingbotApplication
            strategy_name: str,
            restore: Optional[bool] = False):
        start_strategy: Callable = get_strategy_starter_file(strategy_name)
        if strategy_name in settings.STRATEGIES:
            start_strategy(self)
        else:
            raise NotImplementedError

        try:
            config_path: str = self.strategy_file_name
            self.start_time = time.time() * 1e3  # Time in milliseconds
            self.clock = Clock(ClockMode.REALTIME)
            if self.wallet is not None:
                self.clock.add_iterator(self.wallet)
            for market in self.markets.values():
                if market is not None:
                    self.clock.add_iterator(market)
                    self.markets_recorder.restore_market_states(
                        config_path, market)
                    if len(market.limit_orders) > 0:
                        if restore is False:
                            self._notify(
                                f"Cancelling dangling limit orders on {market.name}..."
                            )
                            await market.cancel_all(5.0)
                        else:
                            self._notify(
                                f"Restored {len(market.limit_orders)} limit orders on {market.name}..."
                            )
            if self.strategy:
                self.clock.add_iterator(self.strategy)
            if global_config_map["script_enabled"].value:
                script_file = global_config_map["script_file_path"].value
                folder = dirname(script_file)
                if folder == "":
                    script_file = join(settings.SCRIPTS_PATH, script_file)
                if self.strategy_name != "pure_market_making":
                    self._notify(
                        "Error: script feature is only available for pure_market_making strategy (for now)."
                    )
                else:
                    self._script_iterator = ScriptIterator(
                        script_file, list(self.markets.values()),
                        self.strategy, 0.1)
                    self.clock.add_iterator(self._script_iterator)
                    self._notify(f"Script ({script_file}) started.")
            # TODO: HAHA this is where everything starts
            self.strategy_task: asyncio.Task = safe_ensure_future(
                self._run_clock(), loop=self.ev_loop)
            self._notify(f"\n'{strategy_name}' strategy started.\n"
                         f"Run `status` command to query the progress.")
            self.logger().info("start command initiated.")

            if self._trading_required:
                self.kill_switch = KillSwitch(self)
                await self.wait_till_ready(self.kill_switch.start)
        except Exception as e:
            self.logger().error(str(e), exc_info=True)
 def setUp(self):
     self.weth_dai_data = DDEXOrderBookLoader("WETH-DAI", "WETH", "DAI")
     self.clock = Clock(ClockMode.BACKTEST, 1.0, self.start.timestamp(), self.end.timestamp())
     self.market = BacktestMarket()
     self.market.add_data(self.weth_dai_data)
     self.market.set_balance("WETH", 200.0)
     self.market.set_balance("DAI", 20000.0)
     self.clock.add_iterator(self.market)
Exemplo n.º 3
0
 def setUp(self):
     super().setUp()
     self.realtime_start_timestamp = time.time()
     self.realtime_end_timestamp = self.realtime_start_timestamp + 2.0  #
     self.clock_realtime = Clock(ClockMode.REALTIME, self.tick_size,
                                 self.realtime_start_timestamp,
                                 self.realtime_end_timestamp)
     self.clock_backtest = Clock(ClockMode.BACKTEST, self.tick_size,
                                 self.backtest_start_timestamp,
                                 self.backtest_end_timestamp)
Exemplo n.º 4
0
 def setUp(self):
     # self.weth_dai_data = DDEXOrderBookLoader("WETH-DAI", "WETH", "DAI")
     self.pair_data = BinanceOrderBookLoaderV2(self.market_name, "ETH", "USDT")
     # self.pair_data = HuobiOrderBookLoader(self.market_name, "", "")
     self.clock = Clock(ClockMode.BACKTEST, 1.0, self.start.timestamp(), self.end.timestamp())
     self.market = BacktestMarket()
     # self.market.add_data(self.weth_dai_data)
     self.market.add_data(self.pair_data)
     self.market.set_balance(self.quote, 200.0)
     self.market.set_balance(self.base, 20000.0)
     self.clock.add_iterator(self.market)
Exemplo n.º 5
0
def main():
    # Define the data cache path.
    hummingsim.set_data_path(os.path.join(os.environ["PWD"], "data"))

    # Define the parameters for the backtest.
    start = pd.Timestamp("2018-12-12", tz="UTC")
    end = pd.Timestamp("2019-01-12", tz="UTC")
    binance_trading_pair = ("ETHUSDT", "ETH", "USDT")
    ddex_trading_pair = ("WETH-DAI", "WETH", "DAI")

    binance_market = BacktestMarket()
    ddex_market = BacktestMarket()
    binance_market.config = MarketConfig(AssetType.BASE_CURRENCY, 0.001,
                                         AssetType.QUOTE_CURRENCY, 0.001, {})
    ddex_market.config = MarketConfig(AssetType.BASE_CURRENCY, 0.001,
                                      AssetType.QUOTE_CURRENCY, 0.001, {})
    binance_loader = BinanceOrderBookLoaderV2(*binance_trading_pair)
    ddex_loader = DDEXOrderBookLoader(*ddex_trading_pair)

    binance_market.add_data(binance_loader)
    ddex_market.add_data(ddex_loader)

    binance_market.set_quantization_param(
        QuantizationParams("ETHUSDT", 5, 3, 5, 3))
    ddex_market.set_quantization_param(
        QuantizationParams("WETH-DAI", 5, 3, 5, 3))

    market_pair = CrossExchangeMarketPair(
        *([ddex_market] + list(ddex_trading_pair) + [binance_market] +
          list(binance_trading_pair)))
    strategy = CrossExchangeMarketMakingStrategy(
        [market_pair],
        0.003,
        logging_options=CrossExchangeMarketMakingStrategy.
        OPTION_LOG_MAKER_ORDER_FILLED)

    clock = Clock(ClockMode.BACKTEST,
                  start_time=start.timestamp(),
                  end_time=end.timestamp())
    clock.add_iterator(binance_market)
    clock.add_iterator(ddex_market)
    clock.add_iterator(strategy)

    binance_market.set_balance("ETH", 10.0)
    binance_market.set_balance("USDT", 1000.0)
    ddex_market.set_balance("WETH", 10.0)
    ddex_market.set_balance("DAI", 1000.0)

    clock.backtest()
    binance_loader.close()
    ddex_loader.close()
def main():
    # Define the data cache path.
    hummingsim.set_data_path(os.path.join(os.environ["PWD"], "data"))

    # Define the parameters for the backtest.
    start = pd.Timestamp("2019-01-01", tz="UTC")
    end = pd.Timestamp("2019-01-02", tz="UTC")
    binance_trading_pair = ("ETHUSDT", "ETH", "USDT")
    # ddex_trading_pair = ("WETH-DAI", "WETH", "DAI")

    binance_market = BacktestMarket()
    ddex_market = BacktestMarket()
    binance_market.config = MarketConfig(AssetType.BASE_CURRENCY, 0.001,
                                         AssetType.QUOTE_CURRENCY, 0.001, {})
    ddex_market.config = MarketConfig(AssetType.BASE_CURRENCY, 0.001,
                                      AssetType.QUOTE_CURRENCY, 0.001, {})
    binance_loader = BinanceOrderBookLoaderV2(*binance_trading_pair)
    #ddex_loader = DDEXOrderBookLoader(*ddex_trading_pair)

    binance_market.add_data(binance_loader)
    #ddex_market.add_data(ddex_loader)

    binance_market.set_quantization_param(
        QuantizationParams("ETHUSDT", 5, 3, 5, 3))
    #ddex_market.set_quantization_param(QuantizationParams("WETH-DAI", 5, 3, 5, 3))

    market_pair = PureMarketPair(*([binance_market] +
                                   list(binance_trading_pair)))
    strategy = PureMarketMakingStrategy(
        [market_pair],
        order_size=50000,
        bid_place_threshold=0.003,
        ask_place_threshold=0.003,
        logging_options=PureMarketMakingStrategy.OPTION_LOG_ALL)

    clock = Clock(ClockMode.BACKTEST,
                  tick_size=60,
                  start_time=start.timestamp(),
                  end_time=end.timestamp())
    clock.add_iterator(binance_market)
    #clock.add_iterator(ddex_market)
    clock.add_iterator(strategy)

    binance_market.set_balance("ETH", 100000.0)
    binance_market.set_balance("USDT", 100000000.0)
    ddex_market.set_balance("WETH", 100000.0)
    ddex_market.set_balance("DAI", 1000.0)

    current = start.timestamp()
    step = 60

    while current <= end.timestamp():

        current += step
        clock.backtest_til(current)
        print("clock ticked")

    binance_loader.close()
Exemplo n.º 7
0
 def setUpClass(cls):
     cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()
     if API_MOCK_ENABLED:
         cls.web_app = HummingWebApp.get_instance()
         cls.web_app.add_host_to_mock(API_BASE_URL, ["/v1/common/timestamp", "/v1/common/symbols",
                                                     "/market/tickers", "/market/depth"])
         cls.web_app.start()
         cls.ev_loop.run_until_complete(cls.web_app.wait_til_started())
         cls._patcher = mock.patch("aiohttp.client.URL")
         cls._url_mock = cls._patcher.start()
         cls._url_mock.side_effect = cls.web_app.reroute_local
         mock_account_id = FixtureHuobi.GET_ACCOUNTS["data"][0]["id"]
         cls.web_app.update_response("get", API_BASE_URL, "/v1/account/accounts", FixtureHuobi.GET_ACCOUNTS)
         cls.web_app.update_response("get", API_BASE_URL, f"/v1/account/accounts/{mock_account_id}/balance",
                                     FixtureHuobi.GET_BALANCES)
         cls._t_nonce_patcher = unittest.mock.patch("hummingbot.market.huobi.huobi_market.get_tracking_nonce")
         cls._t_nonce_mock = cls._t_nonce_patcher.start()
     cls.clock: Clock = Clock(ClockMode.REALTIME)
     cls.market: HuobiMarket = HuobiMarket(
         API_KEY,
         API_SECRET,
         trading_pairs=["ethusdt"]
     )
     # Need 2nd instance of market to prevent events mixing up across tests
     cls.market_2: HuobiMarket = HuobiMarket(
         API_KEY,
         API_SECRET,
         trading_pairs=["ethusdt"]
     )
     cls.clock.add_iterator(cls.market)
     cls.clock.add_iterator(cls.market_2)
     cls.stack = contextlib.ExitStack()
     cls._clock = cls.stack.enter_context(cls.clock)
     cls.ev_loop.run_until_complete(cls.wait_til_ready())
Exemplo n.º 8
0
    def setUpClass(cls):
        cls.ev_loop = asyncio.get_event_loop()

        if API_MOCK_ENABLED:
            cls.web_app = MockWebServer.get_instance()
            cls.web_app.add_host_to_mock(API_HOST, ["/products", "/currencies"])
            cls.web_app.start()
            cls.ev_loop.run_until_complete(cls.web_app.wait_til_started())
            cls._patcher = mock.patch("aiohttp.client.URL")
            cls._url_mock = cls._patcher.start()
            cls._url_mock.side_effect = cls.web_app.reroute_local
            cls.web_app.update_response("get", API_HOST, "/fiat_accounts", FixtureLiquid.FIAT_ACCOUNTS)
            cls.web_app.update_response("get", API_HOST, "/crypto_accounts",
                                        FixtureLiquid.CRYPTO_ACCOUNTS)
            cls.web_app.update_response("get", API_HOST, "/orders", FixtureLiquid.ORDERS_GET)
            cls._t_nonce_patcher = unittest.mock.patch(
                "hummingbot.connector.exchange.liquid.liquid_exchange.get_tracking_nonce")
            cls._t_nonce_mock = cls._t_nonce_patcher.start()
        cls.clock: Clock = Clock(ClockMode.REALTIME)
        cls.market: LiquidExchange = LiquidExchange(
            API_KEY, API_SECRET,
            poll_interval=5,
            trading_pairs=['CEL-ETH'],
        )
        # cls.ev_loop.run_until_complete(cls.market._update_balances())
        print("Initializing Liquid market... this will take about a minute.")
        cls.clock.add_iterator(cls.market)
        cls.stack: contextlib.ExitStack = contextlib.ExitStack()
        cls._clock = cls.stack.enter_context(cls.clock)
        cls.ev_loop.run_until_complete(cls.wait_til_ready())
        print("Ready.")
 def setUpClass(cls) -> None:
     cls._db_path = realpath(join(__file__, "../fixtures/gateway_cancel_fixture.db"))
     cls._http_player = HttpPlayer(cls._db_path)
     cls._clock: Clock = Clock(ClockMode.REALTIME)
     cls._client_config_map = ClientConfigAdapter(ClientConfigMap())
     cls._connector: GatewayEVMAMM = GatewayEVMAMM(
         client_config_map=cls._client_config_map,
         connector_name="uniswap",
         chain="ethereum",
         network=NETWORK,
         wallet_address=WALLET_ADDRESS,
         trading_pairs=[TRADING_PAIR],
         trading_required=True
     )
     cls._clock.add_iterator(cls._connector)
     cls._patch_stack = ExitStack()
     cls._patch_stack.enter_context(cls._http_player.patch_aiohttp_client())
     cls._patch_stack.enter_context(
         patch(
             "hummingbot.core.gateway.gateway_http_client.GatewayHttpClient._http_client",
             return_value=ClientSession(),
         )
     )
     cls._patch_stack.enter_context(cls._clock)
     GatewayHttpClient.get_instance().base_url = "https://localhost:5000"
     ev_loop.run_until_complete(cls.wait_til_ready())
 def setUp(self):
     self.log_records = []
     self.start: pd.Timestamp = pd.Timestamp("2019-01-01", tz="UTC")
     self.end: pd.Timestamp = pd.Timestamp("2019-01-01 01:00:00", tz="UTC")
     self.start_timestamp: float = self.start.timestamp()
     self.end_timestamp: float = self.end.timestamp()
     self.connector_name: str = "mock_paper_exchange"
     self.trading_pair: str = "HBOT-USDT"
     self.base_asset, self.quote_asset = self.trading_pair.split("-")
     self.base_balance: int = 500
     self.quote_balance: int = 5000
     self.initial_mid_price: int = 100
     self.clock_tick_size = 1
     self.clock: Clock = Clock(ClockMode.BACKTEST, self.clock_tick_size,
                               self.start_timestamp, self.end_timestamp)
     self.connector: MockPaperExchange = MockPaperExchange(
         client_config_map=ClientConfigAdapter(ClientConfigMap()))
     self.connector.set_balanced_order_book(trading_pair=self.trading_pair,
                                            mid_price=100,
                                            min_price=50,
                                            max_price=150,
                                            price_step_size=1,
                                            volume_step_size=10)
     self.connector.set_balance(self.base_asset, self.base_balance)
     self.connector.set_balance(self.quote_asset, self.quote_balance)
     self.connector.set_quantization_param(
         QuantizationParams(self.trading_pair, 6, 6, 6, 6))
     self.clock.add_iterator(self.connector)
     ScriptStrategyBase.markets = {self.connector_name: {self.trading_pair}}
     self.strategy = ScriptStrategyBase(
         {self.connector_name: self.connector})
     self.strategy.logger().setLevel(1)
     self.strategy.logger().addHandler(self)
Exemplo n.º 11
0
    def test_update_order_status_skips_if_order_no_longer_tracked(
            self, mocked_api):
        order_id = "someId"
        exchange_id = "someExchangeId"

        url = KUCOIN_ROOT_API + CONSTANTS.ORDERS_PATH_URL
        regex_url = re.compile(f"^{url}")
        resp = self.get_order_response_mock(size=2, filled=2)
        mocked_api.get(
            regex_url,
            body=json.dumps(resp),
            callback=lambda *_, **__: self.exchange.stop_tracking_order(
                order_id),
        )

        clock = Clock(
            ClockMode.BACKTEST,
            start_time=self.exchange.UPDATE_ORDERS_INTERVAL,
            end_time=self.exchange.UPDATE_ORDERS_INTERVAL * 2,
        )
        TimeIterator.start(self.exchange, clock)
        self.exchange.in_flight_orders[
            order_id] = self.get_in_flight_order_mock(order_id, exchange_id)

        self.async_run_with_timeout(self.exchange._update_order_status())

        orders_filled_events = self.order_filled_logger.event_log
        order_completed_events = self.buy_order_completed_logger.event_log

        self.assertEqual(0, len(order_completed_events))
        self.assertEqual(0, len(orders_filled_events))
Exemplo n.º 12
0
    def test_update_order_status_notifies_on_order_filled(self, mocked_api):
        url = KUCOIN_ROOT_API + CONSTANTS.ORDERS_PATH_URL
        regex_url = re.compile(f"^{url}")
        resp = self.get_order_response_mock(size=2, filled=2)
        mocked_api.get(regex_url, body=json.dumps(resp))

        clock = Clock(
            ClockMode.BACKTEST,
            start_time=self.exchange.UPDATE_ORDERS_INTERVAL,
            end_time=self.exchange.UPDATE_ORDERS_INTERVAL * 2,
        )
        TimeIterator.start(self.exchange, clock)
        order_id = "someId"
        exchange_id = "someExchangeId"
        self.exchange.in_flight_orders[
            order_id] = self.get_in_flight_order_mock(order_id, exchange_id)
        order = self.exchange.in_flight_orders[order_id]

        self.async_run_with_timeout(self.exchange._update_order_status())

        orders_filled_events = self.order_filled_logger.event_log
        order_completed_events = self.buy_order_completed_logger.event_log

        self.assertTrue(order.is_done)
        self.assertEqual(1, len(order_completed_events))
        self.assertEqual(1, len(orders_filled_events))
        self.assertEqual(order_id, order_completed_events[0].order_id)
        self.assertEqual(order_id, orders_filled_events[0].order_id)
    def setUp(self):
        self.clock_tick_size = 1
        self.clock: Clock = Clock(ClockMode.BACKTEST, self.clock_tick_size,
                                  self.start_timestamp, self.end_timestamp)
        self.market: BacktestMarket = BacktestMarket()
        self.book_data: MockOrderBookLoader = MockOrderBookLoader(
            self.trading_pair, self.base_asset, self.quote_asset)
        self.mid_price = 100
        self.bid_spread = 0.01
        self.ask_spread = 0.01
        self.order_refresh_time = 30
        self.book_data.set_balanced_order_book(mid_price=self.mid_price,
                                               min_price=1,
                                               max_price=200,
                                               price_step_size=1,
                                               volume_step_size=10)
        self.market.add_data(self.book_data)
        self.market.set_balance("HBOT", 500)
        self.market.set_balance("ETH", 5000)
        self.market.set_quantization_param(
            QuantizationParams(self.trading_pair, 6, 6, 6, 6))
        self.market_info = MarketTradingPairTuple(self.market,
                                                  self.trading_pair,
                                                  self.base_asset,
                                                  self.quote_asset)
        self.clock.add_iterator(self.market)
        self.order_fill_logger: EventLogger = EventLogger()
        self.cancel_order_logger: EventLogger = EventLogger()
        self.market.add_listener(MarketEvent.OrderFilled,
                                 self.order_fill_logger)
        self.market.add_listener(MarketEvent.OrderCancelled,
                                 self.cancel_order_logger)

        self.ext_market: BacktestMarket = BacktestMarket()
        self.ext_data: MockOrderBookLoader = MockOrderBookLoader(
            self.trading_pair, self.base_asset, self.quote_asset)
        self.ext_market_info: MarketTradingPairTuple = MarketTradingPairTuple(
            self.ext_market, self.trading_pair, self.base_asset,
            self.quote_asset)
        self.ext_data.set_balanced_order_book(mid_price=100,
                                              min_price=1,
                                              max_price=400,
                                              price_step_size=1,
                                              volume_step_size=100)
        self.ext_market.add_data(self.ext_data)
        self.order_book_asset_del = OrderBookAssetPriceDelegate(
            self.ext_market, self.trading_pair)

        self.one_level_strategy = PureMarketMakingStrategy()
        self.one_level_strategy.init_params(
            self.market_info,
            bid_spread=Decimal("0.01"),
            ask_spread=Decimal("0.01"),
            order_amount=Decimal("1"),
            order_refresh_time=3.0,
            filled_order_delay=3.0,
            order_refresh_tolerance_pct=-1,
            minimum_spread=-1,
            asset_price_delegate=self.order_book_asset_del,
            take_if_crossed=True)
 def setUpClass(cls):
     cls.clock: Clock = Clock(ClockMode.REALTIME)
     cls.market: CoinbaseProMarket = CoinbaseProMarket(
         ethereum_rpc_url=conf.test_web3_provider_list[0],
         coinbase_pro_api_key=conf.coinbase_pro_api_key,
         coinbase_pro_secret_key=conf.coinbase_pro_secret_key,
         coinbase_pro_passphrase=conf.coinbase_pro_passphrase,
         symbols=["ETH-USDC", "ETH-USD"])
     cls.wallet: Web3Wallet = Web3Wallet(
         private_key=conf.web3_private_key_coinbase_pro,
         backend_urls=conf.test_web3_provider_list,
         erc20_token_addresses=[
             conf.mn_weth_token_address, conf.mn_zerox_token_address
         ],
         chain=EthereumChain.MAIN_NET)
     print(
         "Initializing Coinbase Pro market... this will take about a minute."
     )
     cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()
     cls.clock.add_iterator(cls.market)
     cls.clock.add_iterator(cls.wallet)
     stack = contextlib.ExitStack()
     cls._clock = stack.enter_context(cls.clock)
     cls.ev_loop.run_until_complete(cls.wait_til_ready())
     print("Ready.")
Exemplo n.º 15
0
    def setUp(self):

        super().setUp()
        self.log_records = []

        self.clock: Clock = Clock(ClockMode.BACKTEST, self.clock_tick_size,
                                  self.start_timestamp, self.end_timestamp)
        self.market: BacktestMarket = BacktestMarket()
        self.maker_data: MockOrderBookLoader = MockOrderBookLoader(
            *self.maker_trading_pairs)
        self.mid_price = 100
        self.order_delay_time = 15
        self.cancel_order_wait_time = 45
        self.maker_data.set_balanced_order_book(mid_price=self.mid_price,
                                                min_price=1,
                                                max_price=200,
                                                price_step_size=1,
                                                volume_step_size=10)
        self.market.add_data(self.maker_data)
        self.market.set_balance("COINALPHA", 500)
        self.market.set_balance("WETH", 50000)
        self.market.set_balance("QETH", 500)
        self.market.set_quantization_param(
            QuantizationParams(self.maker_trading_pairs[0], 6, 6, 6, 6))

        self.market_info: MarketTradingPairTuple = MarketTradingPairTuple(
            *([self.market] + self.maker_trading_pairs))

        # Define strategies to test
        self.limit_buy_strategy: TwapTradeStrategy = TwapTradeStrategy(
            [self.market_info],
            order_price=Decimal("99"),
            cancel_order_wait_time=self.cancel_order_wait_time,
            is_buy=True,
            order_delay_time=self.order_delay_time,
            target_asset_amount=Decimal("2.0"),
            order_step_size=Decimal("1.0"))
        self.limit_sell_strategy: TwapTradeStrategy = TwapTradeStrategy(
            [self.market_info],
            order_price=Decimal("101"),
            cancel_order_wait_time=self.cancel_order_wait_time,
            is_buy=False,
            order_delay_time=self.order_delay_time,
            target_asset_amount=Decimal("5.0"),
            order_step_size=Decimal("1.67"))

        self.clock.add_iterator(self.market)
        self.maker_order_fill_logger: EventLogger = EventLogger()
        self.cancel_order_logger: EventLogger = EventLogger()
        self.buy_order_completed_logger: EventLogger = EventLogger()
        self.sell_order_completed_logger: EventLogger = EventLogger()

        self.market.add_listener(MarketEvent.BuyOrderCompleted,
                                 self.buy_order_completed_logger)
        self.market.add_listener(MarketEvent.SellOrderCompleted,
                                 self.sell_order_completed_logger)
        self.market.add_listener(MarketEvent.OrderFilled,
                                 self.maker_order_fill_logger)
        self.market.add_listener(MarketEvent.OrderCancelled,
                                 self.cancel_order_logger)
Exemplo n.º 16
0
    def setUpClass(cls):
        global MAINNET_RPC_URL
        cls.ev_loop = asyncio.get_event_loop()

        if API_MOCK_ENABLED:
            cls.web_app = HummingWebApp.get_instance()
            cls.web_app.add_host_to_mock(API_HOST, ["/products", "/currencies"])
            cls.web_app.start()
            cls.ev_loop.run_until_complete(cls.web_app.wait_til_started())
            cls._patcher = mock.patch("aiohttp.client.URL")
            cls._url_mock = cls._patcher.start()
            cls._url_mock.side_effect = cls.web_app.reroute_local
            cls.web_app.update_response("get", API_HOST, "/fiat_accounts", FixtureLiquid.FIAT_ACCOUNTS)
            cls.web_app.update_response("get", API_HOST, "/crypto_accounts",
                                        FixtureLiquid.CRYPTO_ACCOUNTS)
            cls.web_app.update_response("get", API_HOST, "/orders", FixtureLiquid.ORDERS_GET)
            cls._t_nonce_patcher = unittest.mock.patch("hummingbot.market.liquid.liquid_market.get_tracking_nonce")
            cls._t_nonce_mock = cls._t_nonce_patcher.start()
        cls.clock: Clock = Clock(ClockMode.REALTIME)
        cls.market: LiquidMarket = LiquidMarket(
            API_KEY, API_SECRET,
            order_book_tracker_data_source_type=OrderBookTrackerDataSourceType.EXCHANGE_API,
            user_stream_tracker_data_source_type=UserStreamTrackerDataSourceType.EXCHANGE_API,
            trading_pairs=['CEL-ETH']
        )
        # cls.ev_loop.run_until_complete(cls.market._update_balances())
        print("Initializing Liquid market... this will take about a minute.")
        cls.clock.add_iterator(cls.market)
        cls.stack: contextlib.ExitStack = contextlib.ExitStack()
        cls._clock = cls.stack.enter_context(cls.clock)
        cls.ev_loop.run_until_complete(cls.wait_til_ready())
        print("Ready.")
 def setUpClass(cls) -> None:
     super().setUpClass()
     cls._db_path = realpath(
         join(__file__, "../fixtures/gateway_evm_amm_lp_fixture.db"))
     cls._http_player = HttpPlayer(cls._db_path)
     cls._clock: Clock = Clock(ClockMode.REALTIME)
     cls._client_config_map = ClientConfigAdapter(ClientConfigMap())
     cls._connector: GatewayEVMAMMLP = GatewayEVMAMMLP(
         client_config_map=cls._client_config_map,
         connector_name="uniswapLP",
         chain="ethereum",
         network="kovan",
         wallet_address="0xefb7be8631d154d4c0ad8676fec0897b2894fe8f",
         trading_pairs=["COIN1-COIN3"],
         trading_required=True)
     cls._clock.add_iterator(cls._connector)
     cls._patch_stack = ExitStack()
     cls._patch_stack.enter_context(cls._http_player.patch_aiohttp_client())
     cls._patch_stack.enter_context(
         patch(
             "hummingbot.core.gateway.gateway_http_client.GatewayHttpClient._http_client",
             return_value=ClientSession()))
     cls._patch_stack.enter_context(cls._clock)
     GatewayHttpClient.get_instance(client_config_map=cls._client_config_map
                                    ).base_url = "https://localhost:5000"
     ev_loop.run_until_complete(cls.wait_til_ready())
Exemplo n.º 18
0
 def setUp(self):
     self.clock_tick_size = 1
     self.clock: Clock = Clock(ClockMode.BACKTEST, self.clock_tick_size,
                               self.start_timestamp, self.end_timestamp)
     self.market: MockPaperExchange = MockPaperExchange()
     self.mid_price = 100
     self.bid_spread = 0.01
     self.ask_spread = 0.01
     self.order_refresh_time = 30
     self.market.set_balanced_order_book(trading_pair=self.trading_pair,
                                         mid_price=self.mid_price,
                                         min_price=1,
                                         max_price=200,
                                         price_step_size=1,
                                         volume_step_size=10)
     self.market.set_balance("HBOT", 500)
     self.market.set_balance("ETH", 5000)
     self.market.set_quantization_param(
         QuantizationParams(self.trading_pair, 6, 6, 6, 6))
     self.market_info = MarketTradingPairTuple(self.market,
                                               self.trading_pair,
                                               self.base_asset,
                                               self.quote_asset)
     self.clock.add_iterator(self.market)
     self.maker_order_fill_logger: EventLogger = EventLogger()
     self.cancel_order_logger: EventLogger = EventLogger()
     self.market.add_listener(MarketEvent.OrderFilled,
                              self.maker_order_fill_logger)
     self.market.add_listener(MarketEvent.OrderCancelled,
                              self.cancel_order_logger)
Exemplo n.º 19
0
    def setUpClass(cls):
        global MAINNET_RPC_URL

        cls.clock: Clock = Clock(ClockMode.REALTIME)
        connector = BinanceExchange(binance_api_key="",
                                    binance_api_secret="",
                                    trading_pairs=["ETH-USDT", "BTC-USDT"],
                                    trading_required=False)
        cls.market: PaperTradeExchange = PaperTradeExchange(
            order_book_tracker=OrderBookTracker(
                data_source=BinanceAPIOrderBookDataSource(
                    trading_pairs=["ETH-USDT", "BTC-USDT"],
                    connector=connector,
                    api_factory=connector._api_factory),
                trading_pairs=["ETH-USDT", "BTC-USDT"]),
            target_market=BinanceExchange,
            exchange_name="binance",
        )
        print(
            "Initializing PaperTrade execute orders market... this will take about a minute."
        )
        cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()
        cls.clock.add_iterator(cls.market)
        cls.stack: contextlib.ExitStack = contextlib.ExitStack()
        cls._clock = cls.stack.enter_context(cls.clock)
        cls.ev_loop.run_until_complete(cls.wait_til_ready())
        print("Ready.")
Exemplo n.º 20
0
 def setUpClass(cls) -> None:
     super().setUpClass()
     GatewayHttpClient.__instance = None
     cls._db_path = realpath(
         join(__file__, "../fixtures/gateway_evm_amm_fixture.db"))
     cls._http_player = HttpPlayer(cls._db_path)
     cls._clock: Clock = Clock(ClockMode.REALTIME)
     cls._client_config_map = ClientConfigAdapter(ClientConfigMap())
     cls._connector: GatewayEVMAMM = GatewayEVMAMM(
         client_config_map=cls._client_config_map,
         connector_name="uniswap",
         chain="ethereum",
         network="ropsten",
         wallet_address="0x5821715133bB451bDE2d5BC6a4cE3430a4fdAF92",
         trading_pairs=["DAI-WETH"],
         trading_required=True)
     cls._clock.add_iterator(cls._connector)
     cls._patch_stack = ExitStack()
     cls._patch_stack.enter_context(cls._http_player.patch_aiohttp_client())
     cls._patch_stack.enter_context(
         patch(
             "hummingbot.core.gateway.gateway_http_client.GatewayHttpClient._http_client",
             return_value=ClientSession()))
     cls._patch_stack.enter_context(cls._clock)
     GatewayHttpClient.get_instance(client_config_map=cls._client_config_map
                                    ).base_url = "https://localhost:5000"
     ev_loop.run_until_complete(cls.wait_til_ready())
    def setUp(self):
        self.clock: Clock = Clock(ClockMode.REALTIME)
        self.stack: contextlib.ExitStack = contextlib.ExitStack()
        self.lp: MockAMMLP = MockAMMLP("onion")
        self.lp.set_balance(BASE_ASSET, 500)
        self.lp.set_balance(QUOTE_ASSET, 500)
        self.market_info = MarketTradingPairTuple(self.lp, TRADING_PAIR, BASE_ASSET, QUOTE_ASSET)

        # Set some default price.
        self.lp.set_price(TRADING_PAIR, 1)

        self.strategy = UniswapV3LpStrategy(
            self.market_info,
            "LOW",
            Decimal("0.2"),
            Decimal("1"),
            Decimal("10"),
        )
        self.clock.add_iterator(self.lp)
        self.clock.add_iterator(self.strategy)

        self.stack.enter_context(self.clock)
        self.stack.enter_context(patch(
            "hummingbot.client.config.trade_fee_schema_loader.TradeFeeSchemaLoader.configured_schema_for_exchange",
            return_value=TradeFeeSchema()
        ))
        self.clock_task: asyncio.Task = safe_ensure_future(self.clock.run())
    def setUpClass(cls):
        cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()
        cls.coinbase_pro_auth = CoinbaseProAuth(conf.coinbase_pro_api_key,
                                                conf.coinbase_pro_secret_key,
                                                conf.coinbase_pro_passphrase)
        cls.trading_pairs = ["ETH-USDC"]
        cls.user_stream_tracker: CoinbaseProUserStreamTracker = CoinbaseProUserStreamTracker(
            coinbase_pro_auth=cls.coinbase_pro_auth,
            trading_pairs=cls.trading_pairs)
        cls.user_stream_tracker_task: asyncio.Task = safe_ensure_future(
            cls.user_stream_tracker.start())

        cls.clock: Clock = Clock(ClockMode.REALTIME)
        cls.market: CoinbaseProMarket = CoinbaseProMarket(
            conf.coinbase_pro_api_key,
            conf.coinbase_pro_secret_key,
            conf.coinbase_pro_passphrase,
            trading_pairs=cls.trading_pairs)
        print(
            "Initializing Coinbase Pro market... this will take about a minute."
        )
        cls.clock.add_iterator(cls.market)
        cls.stack = contextlib.ExitStack()
        cls._clock = cls.stack.enter_context(cls.clock)
        cls.ev_loop.run_until_complete(cls.wait_til_ready())
        print("Ready.")
Exemplo n.º 23
0
 def setUpClass(cls):
     if conf.test_bamboo_relay_chain_id == 3:
         chain = EthereumChain.ROPSTEN
     elif conf.test_bamboo_relay_chain_id == 4:
         chain = EthereumChain.RINKEBY
     elif conf.test_bamboo_relay_chain_id == 42:
         chain = EthereumChain.KOVAN
     else:
         chain = EthereumChain.MAIN_NET
     cls.chain = chain
     cls.base_token_symbol = conf.test_bamboo_relay_base_token_symbol
     cls.quote_token_symbol = conf.test_bamboo_relay_quote_token_symbol
     cls.clock: Clock = Clock(ClockMode.REALTIME)
     cls.wallet = Web3Wallet(private_key=conf.web3_private_key_bamboo,
                             backend_urls=conf.test_web3_provider_list,
                             erc20_token_addresses=[conf.test_bamboo_relay_base_token_address, 
                                                    conf.test_bamboo_relay_quote_token_address],
                             chain=chain)
     cls.market: BambooRelayMarket = BambooRelayMarket(
         wallet=cls.wallet,
         ethereum_rpc_url=conf.test_web3_provider_list[0],
         order_book_tracker_data_source_type=OrderBookTrackerDataSourceType.EXCHANGE_API,
         symbols=[conf.test_bamboo_relay_base_token_symbol + "-" + conf.test_bamboo_relay_quote_token_symbol],
         use_coordinator=True,
         pre_emptive_soft_cancels=True
     )
     print("Initializing Bamboo Relay market... ")
     cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()
     cls.clock.add_iterator(cls.wallet)
     cls.clock.add_iterator(cls.market)
     stack = contextlib.ExitStack()
     cls._clock = stack.enter_context(cls.clock)
     cls.ev_loop.run_until_complete(cls.wait_til_ready())
     print("Ready.")
Exemplo n.º 24
0
    def setUp(self):
        self.clock_tick_size = 1
        self.clock: Clock = Clock(ClockMode.BACKTEST, self.clock_tick_size, self.start_timestamp, self.end_timestamp)
        self.market: BacktestMarket = BacktestMarket()
        self.maker_data: MockOrderBookLoader = MockOrderBookLoader(*self.maker_trading_pairs)
        self.mid_price = 100
        self.maker_data.set_balanced_order_book(mid_price=self.mid_price, min_price=1,
                                                max_price=200, price_step_size=1, volume_step_size=10)
        self.market.add_data(self.maker_data)
        self.market.set_balance("COINALPHA", 500)
        self.market.set_balance("WETH", 5000)
        self.market.set_balance("QETH", 500)
        self.market.set_quantization_param(
            QuantizationParams(
                self.maker_trading_pairs[0], 6, 6, 6, 6
            )
        )
        self.market_info: MarketTradingPairTuple = MarketTradingPairTuple(
            self.market, self.maker_trading_pairs[0],
            self.maker_trading_pairs[1], self.maker_trading_pairs[2]
        )

        self.strategy: PureMarketMakingStrategy = PureMarketMakingStrategy(
            self.market_info,
            bid_spread=Decimal(.05),
            ask_spread=Decimal(.05),
            order_amount=Decimal(1),
            order_refresh_time=30,
            minimum_spread=0,
        )
Exemplo n.º 25
0
    def setUp(self) -> None:
        self.loop = asyncio.get_event_loop()
        self.clock_tick_size = 1
        self.clock: Clock = Clock(ClockMode.BACKTEST, self.clock_tick_size,
                                  self.start_timestamp, self.end_timestamp)

        self.mid_price = 100
        self.bid_spread = 0.01
        self.ask_spread = 0.01
        self.order_refresh_time = 1

        trading_pairs = list(
            map(lambda quote_asset: "ETH-" + quote_asset, ["USDT", "BTC"]))
        market, market_infos = self.create_market(trading_pairs,
                                                  self.mid_price, {
                                                      "USDT": 5000,
                                                      "ETH": 500,
                                                      "BTC": 100
                                                  })
        self.market = market
        self.market_infos = market_infos

        self.default_strategy = UniswapV3LpStrategy(
            self.market_infos[trading_pairs[0]], "MEDIUM", True,
            Decimal('144'), Decimal('2'), Decimal('0.01'), Decimal('0.01'),
            Decimal('1'), Decimal('1'), Decimal('0.05'))
    def setUp(self) -> None:
        self.clock_tick_size = 1
        self.clock: Clock = Clock(ClockMode.BACKTEST, self.clock_tick_size, self.start_timestamp, self.end_timestamp)

        self.mid_price = 100
        self.bid_spread = 0.01
        self.ask_spread = 0.01
        self.order_refresh_time = 1

        trading_pairs = list(map(lambda quote_asset: "ETH-" + quote_asset, ["USDT", "BTC"]))
        market, market_infos = self.create_market(trading_pairs, self.mid_price, {"USDT": 5000, "ETH": 500, "BTC": 100})
        self.market = market
        self.market_infos = market_infos

        self.clock.add_iterator(self.market)
        self.order_fill_logger: EventLogger = EventLogger()
        self.cancel_order_logger: EventLogger = EventLogger()
        self.market.add_listener(MarketEvent.OrderFilled, self.order_fill_logger)
        self.market.add_listener(MarketEvent.OrderCancelled, self.cancel_order_logger)

        self.default_strategy = LiquidityMiningStrategy()
        self.default_strategy.init_params(
            exchange=self.market,
            market_infos=self.market_infos,
            token="ETH",
            order_amount=Decimal(2),
            spread=Decimal(0.0005),
            inventory_skew_enabled=False,
            target_base_pct=Decimal(0.5),
            order_refresh_time=5,
            order_refresh_tolerance_pct=Decimal(0.1),  # tolerance of 10 % change
            max_order_age=3,
        )
Exemplo n.º 27
0
    def setUp(self):
        self.maxDiff = None
        self.clock: Clock = Clock(ClockMode.BACKTEST, 1.0,
                                  self.start_timestamp, self.end_timestamp)
        self.market: MockPaperExchange = MockPaperExchange()

        self.market.set_balanced_order_book(self.trading_pair, 10, 5, 15, 0.1,
                                            1)

        self.market.set_balance(self.base_asset, 500)
        self.market.set_balance(self.quote_asset, 500)
        self.market.set_quantization_param(
            QuantizationParams(self.trading_pair, 5, 5, 5, 5))
        self.market_info = MarketTradingPairTuple(self.market,
                                                  self.trading_pair,
                                                  self.base_asset,
                                                  self.quote_asset)
        self.logging_options: int = CeloArbStrategy.OPTION_LOG_ALL
        self.strategy = CeloArbStrategy()
        self.strategy.init_params(self.market_info,
                                  min_profitability=Decimal("0.01"),
                                  order_amount=Decimal("1"),
                                  celo_slippage_buffer=Decimal("0.001"),
                                  logging_options=self.logging_options,
                                  hb_app_notification=False,
                                  mock_celo_cli_mode=True)
        self.clock.add_iterator(self.market)
        self.clock.add_iterator(self.strategy)
        self.market_order_fill_logger: EventLogger = EventLogger()
        self.market.add_listener(MarketEvent.OrderFilled,
                                 self.market_order_fill_logger)
        CeloCLI.unlock_account(TEST_ADDRESS, TEST_PASSWORD)
Exemplo n.º 28
0
    def setUpClass(cls):
        cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()
        if MOCK_API_ENABLED:
            cls.web_app = MockWebServer.get_instance()
            cls.web_app.add_host_to_mock(API_BASE_URL, [])
            cls.web_app.start()
            cls.ev_loop.run_until_complete(cls.web_app.wait_til_started())
            cls._patcher = mock.patch("aiohttp.client.URL")
            cls._url_mock = cls._patcher.start()
            cls._url_mock.side_effect = cls.web_app.reroute_local
            # mock_account_id = FixtureOKEx.GET_ACCOUNTS["data"][0]["id"]

            # warning: second parameter starts with /
            cls.web_app.update_response(
                "get", API_BASE_URL,
                cls.strip_host_from_okex_url(OKEX_INSTRUMENTS_URL),
                FixtureOKEx.OKEX_INSTRUMENTS_URL)
            cls.web_app.update_response(
                "get", API_BASE_URL,
                cls.strip_host_from_okex_url(OKEX_PRICE_URL).format(
                    trading_pair='ETH-USDT'), FixtureOKEx.INSTRUMENT_TICKER)
            cls.web_app.update_response(
                "get", API_BASE_URL,
                cls.strip_host_from_okex_url(OKEX_DEPTH_URL).format(
                    trading_pair='ETH-USDT'), FixtureOKEx.OKEX_ORDER_BOOK)
            cls.web_app.update_response(
                "get", API_BASE_URL,
                cls.strip_host_from_okex_url(OKEX_TICKERS_URL),
                FixtureOKEx.OKEX_TICKERS)
            cls.web_app.update_response("get", API_BASE_URL,
                                        '/' + OKEX_BALANCE_URL,
                                        FixtureOKEx.OKEX_BALANCE_URL)
            cls.web_app.update_response("get", API_BASE_URL,
                                        '/' + OKEX_SERVER_TIME,
                                        FixtureOKEx.TIMESTAMP)

            # cls.web_app.update_response("POST", API_BASE_URL, '/' + OKEX_PLACE_ORDER, FixtureOKEx.ORDER_PLACE)
            # cls.web_app.update_response("get", OKEX_BASE_URL, f"/v1/account/accounts/{mock_account_id}/balance",
            #                             FixtureOKEx.GET_BALANCES)

            cls._t_nonce_patcher = unittest.mock.patch(
                "hummingbot.connector.exchange.okex.okex_exchange.get_tracking_nonce"
            )
            cls._t_nonce_mock = cls._t_nonce_patcher.start()
        cls.clock: Clock = Clock(ClockMode.REALTIME)
        cls.market: OkexExchange = OkexExchange(API_KEY,
                                                API_SECRET,
                                                API_PASSPHRASE,
                                                trading_pairs=["ETH-USDT"])
        # Need 2nd instance of market to prevent events mixing up across tests
        cls.market_2: OkexExchange = OkexExchange(API_KEY,
                                                  API_SECRET,
                                                  API_PASSPHRASE,
                                                  trading_pairs=["ETH-USDT"])
        cls.clock.add_iterator(cls.market)
        cls.clock.add_iterator(cls.market_2)
        cls.stack = contextlib.ExitStack()
        cls._clock = cls.stack.enter_context(cls.clock)
        cls.ev_loop.run_until_complete(cls.wait_til_ready())
Exemplo n.º 29
0
    def setUpClass(cls):
        global MAINNET_RPC_URL

        cls.ev_loop = asyncio.get_event_loop()

        if API_MOCK_ENABLED:
            cls.web_app = HummingWebApp.get_instance()
            cls.web_app.add_host_to_mock(BASE_API_URL, [])
            cls.web_app.start()
            cls.ev_loop.run_until_complete(cls.web_app.wait_til_started())
            cls._patcher = mock.patch("aiohttp.client.URL")
            cls._url_mock = cls._patcher.start()
            cls._url_mock.side_effect = cls.web_app.reroute_local
            cls.web_app.update_response("get", BASE_API_URL,
                                        "/v2/public/get-ticker",
                                        fixture.TICKERS)
            cls.web_app.update_response("get", BASE_API_URL,
                                        "/v2/public/get-instruments",
                                        fixture.INSTRUMENTS)
            cls.web_app.update_response("get", BASE_API_URL,
                                        "/v2/public/get-book",
                                        fixture.GET_BOOK)
            cls.web_app.update_response("post", BASE_API_URL,
                                        "/v2/private/get-account-summary",
                                        fixture.BALANCES)
            cls.web_app.update_response("post", BASE_API_URL,
                                        "/v2/private/cancel-order",
                                        fixture.CANCEL)

            HummingWsServerFactory.start_new_server(WSS_PRIVATE_URL)
            HummingWsServerFactory.start_new_server(WSS_PUBLIC_URL)
            cls._ws_patcher = unittest.mock.patch("websockets.connect",
                                                  autospec=True)
            cls._ws_mock = cls._ws_patcher.start()
            cls._ws_mock.side_effect = HummingWsServerFactory.reroute_ws_connect

        cls.clock: Clock = Clock(ClockMode.REALTIME)
        cls.connector: CryptoComExchange = CryptoComExchange(
            crypto_com_api_key=API_KEY,
            crypto_com_api_secret=API_SECRET,
            trading_pairs=[cls.trading_pair],
            trading_required=True)
        print(
            "Initializing CryptoCom market... this will take about a minute.")
        cls.clock.add_iterator(cls.connector)
        cls.stack: contextlib.ExitStack = contextlib.ExitStack()
        cls._clock = cls.stack.enter_context(cls.clock)
        if API_MOCK_ENABLED:
            HummingWsServerFactory.send_json_threadsafe(WSS_PRIVATE_URL,
                                                        fixture.WS_INITIATED,
                                                        delay=0.5)
            HummingWsServerFactory.send_json_threadsafe(WSS_PRIVATE_URL,
                                                        fixture.WS_SUBSCRIBE,
                                                        delay=0.51)
            HummingWsServerFactory.send_json_threadsafe(WSS_PRIVATE_URL,
                                                        fixture.WS_HEARTBEAT,
                                                        delay=0.52)
        cls.ev_loop.run_until_complete(cls.wait_til_ready())
        print("Ready.")
 def setUpClass(cls):
     cls.ev_loop = asyncio.get_event_loop()
     cls.clock: Clock = Clock(ClockMode.BACKTEST, cls.tick_size, cls.start_timestamp, cls.end_timestamp)
     cls.market: MockPaperExchange = MockPaperExchange()
     cls.strategy: GetOrderBookStrategy = GetOrderBookStrategy(
         exchange=cls.market,
         trading_pair=cls.trading_pair,
     )