コード例 #1
0
async def docker_ipc_with_generator(method_name: str, *args,
                                    **kwargs) -> AsyncIterable[str]:
    from hummingbot.client.hummingbot_application import HummingbotApplication
    global _hummingbot_pipe

    if _hummingbot_pipe is None:
        raise RuntimeError(
            "Not in the main process, or hummingbot wasn't started via `fork_and_start()`."
        )
    try:
        _hummingbot_pipe.send((method_name, args, kwargs))
        while True:
            data = await _hummingbot_pipe.coro_recv()
            if data is None:
                break
            if isinstance(data, Exception):
                HummingbotApplication.main_application().notify(
                    "\nError: Unable to communicate with docker socket. "
                    "\nEnsure dockerd is running and /var/run/docker.sock exists, then restart Hummingbot."
                )
                raise data
            yield data
    except Exception as e:  # unable to communicate with docker socket
        HummingbotApplication.main_application().notify(
            "\nError: Unable to communicate with docker socket. "
            "\nEnsure dockerd is running and /var/run/docker.sock exists, then restart Hummingbot."
        )
        raise e
コード例 #2
0
 def notify_hb_app(self, msg: str):
     """
     Send a message to the hummingbot application
     """
     if self._hb_app_notification:
         from hummingbot.client.hummingbot_application import HummingbotApplication
         HummingbotApplication.main_application()._notify(msg)
コード例 #3
0
async def start_existing_gateway_container(
        client_config_map: "ClientConfigAdapter"):
    container_info: Optional[Dict[
        str, Any]] = await detect_existing_gateway_container(client_config_map)
    if container_info is not None and container_info["State"] != "running":
        from hummingbot.client.hummingbot_application import HummingbotApplication
        HummingbotApplication.main_application().logger().info(
            "Starting existing Gateway container...")
        await docker_ipc("start",
                         get_gateway_container_name(client_config_map))
コード例 #4
0
async def main_async(client_config_map: ClientConfigAdapter):
    await create_yml_files_legacy()

    # This init_logging() call is important, to skip over the missing config warnings.
    init_logging("hummingbot_logs.yml", client_config_map)

    AllConnectorSettings.initialize_paper_trade_settings(
        client_config_map.paper_trade.paper_trade_exchanges)

    hb = HummingbotApplication.main_application(client_config_map)

    # The listener needs to have a named variable for keeping reference, since the event listener system
    # uses weak references to remove unneeded listeners.
    start_listener: UIStartListener = UIStartListener(hb)
    hb.app.add_listener(HummingbotUIEvent.Start, start_listener)

    tasks: List[Coroutine] = [
        hb.run(),
        start_existing_gateway_container(client_config_map)
    ]
    if client_config_map.debug_console:
        if not hasattr(__builtins__, "help"):
            import _sitebuiltins
            __builtins__.help = _sitebuiltins._Helper()

        from hummingbot.core.management.console import start_management_console
        management_port: int = detect_available_port(8211)
        tasks.append(
            start_management_console(locals(),
                                     host="localhost",
                                     port=management_port))
    await safe_gather(*tasks)
コード例 #5
0
    def non_trading_connector_instance_with_default_configuration(
            self,
            trading_pairs: Optional[List[str]] = None) -> 'ConnectorBase':
        from hummingbot.client.config.config_helpers import ClientConfigAdapter
        from hummingbot.client.hummingbot_application import HummingbotApplication

        trading_pairs = trading_pairs or []
        connector_class = getattr(importlib.import_module(self.module_path()),
                                  self.class_name())
        kwargs = {}
        if isinstance(self.config_keys, Dict):
            kwargs = {
                key: (config.value or "")
                for key, config in self.config_keys.items()
            }  # legacy
        elif self.config_keys is not None:
            kwargs = {
                traverse_item.attr: traverse_item.value.get_secret_value()
                if isinstance(traverse_item.value, SecretStr) else
                traverse_item.value or ""
                for traverse_item in ClientConfigAdapter(
                    self.config_keys).traverse()
                if traverse_item.attr != "connector"
            }
        kwargs = self.conn_init_parameters(kwargs)
        kwargs = self.add_domain_parameter(kwargs)
        kwargs.update(trading_pairs=trading_pairs, trading_required=False)
        kwargs["client_config_map"] = HummingbotApplication.main_application(
        ).client_config_map
        connector = connector_class(**kwargs)

        return connector
コード例 #6
0
async def main():
    await create_yml_files()

    # This init_logging() call is important, to skip over the missing config warnings.
    init_logging("hummingbot_logs.yml")

    read_configs_from_yml()

    if __name__ == '__main__':
        hb = HummingbotApplication.main_application()
    with patch_stdout(log_field=hb.app.log_field):
        dev_mode = check_dev_mode()
        if dev_mode:
            hb.app.log(
                "Running from dev branches. Full remote logging will be enabled."
            )
        init_logging(
            "hummingbot_logs.yml",
            override_log_level=global_config_map.get("log_level").value,
            dev_mode=dev_mode)
        tasks: List[Coroutine] = [hb.run()]
        if global_config_map.get("debug_console").value:
            management_port: int = detect_available_port(8211)
            tasks.append(
                start_management_console(locals(),
                                         host="localhost",
                                         port=management_port))
        await asyncio.gather(*tasks)
コード例 #7
0
 async def set_up_class(cls):
     add_files_extension(settings.CONF_FILE_PATH, [".yml", ".json"],
                         ".temp")
     asyncio.ensure_future(hb_main())
     cls.hb = HummingbotApplication.main_application()
     await wait_til(lambda: 'Enter "config" to create a bot' in cls.hb.app.
                    output_field.document.text)
コード例 #8
0
def get_gateway_status():
    from hummingbot.client.hummingbot_application import HummingbotApplication
    hb = HummingbotApplication.main_application()
    gateway_status = "RUNNING" if hb._gateway_monitor.current_status is GatewayStatus.ONLINE else "STOPPED"
    gateway_conn_status = hb._gateway_monitor.current_connector_conn_status.name
    style = "class:log_field"
    return [(style, f"Gateway: {gateway_status}, {gateway_conn_status}")]
コード例 #9
0
ファイル: interface_utils.py プロジェクト: vyfirm/hummingbot
async def start_trade_monitor(trade_monitor):
    from hummingbot.client.hummingbot_application import HummingbotApplication
    hb = HummingbotApplication.main_application()
    trade_monitor.log("Trades: 0, Total P&L: 0.00, Return %: 0.00%")
    total_trades = 0
    return_pcts = []
    pnls = []
    quote_asset = ""

    while True:
        if hb.strategy_task is not None and not hb.strategy_task.done():
            if all(market.ready for market in hb.markets.values()):
                trades: List[TradeFill] = hb._get_trades_from_session(int(hb.init_time * 1e3),
                                                                      config_file_path=hb.strategy_file_name)
                if len(trades) > total_trades:
                    total_trades = len(trades)
                    market_info: Set[Tuple[str, str]] = set((t.market, t.symbol) for t in trades)
                    for market, symbol in market_info:
                        quote_asset = symbol.split("-")[1]  # Note that the qiote asset of the last pair is assumed to be the quote asset of P&L for simplicity
                        cur_trades = [t for t in trades if t.market == market and t.symbol == symbol]
                        cur_balances = await hb.get_current_balances(market)
                        cur_price = await get_last_price(market.replace("_PaperTrade", ""), symbol)
                        perf = calculate_performance_metrics(symbol, cur_trades, cur_balances, cur_price)
                        return_pcts.append(perf.return_pct)
                        pnls.append(perf.total_pnl)
                    avg_return = sum(return_pcts) / len(return_pcts) if len(return_pcts) > 0 else s_decimal_0
                    total_pnls = sum(pnls)  # Note that this sum doesn't handles cases with different multiple pairs for simplisity
                    trade_monitor.log(f"Trades: {total_trades}, Total P&L: {smart_round(total_pnls)} {quote_asset}, Return %: {avg_return:.2%}")
                    return_pcts.clear()
                    pnls.clear()
        await asyncio.sleep(2)  # sleeping for longer to manage resources
コード例 #10
0
async def quick_start(args):
    config_file_name = args.config_file_name
    wallet = args.wallet
    password = args.config_password

    if args.auto_set_permissions is not None:
        autofix_permissions(args.auto_set_permissions)

    if password is not None and not Security.login(password):
        logging.getLogger().error("Invalid password.")
        return

    await Security.wait_til_decryption_done()
    await create_yml_files()
    init_logging("hummingbot_logs.yml")
    read_system_configs_from_yml()

    hb = HummingbotApplication.main_application()
    # Todo: validate strategy and config_file_name before assinging

    if config_file_name is not None:
        hb.strategy_file_name = config_file_name
        hb.strategy_name = update_strategy_config_map_from_file(
            os.path.join(CONF_FILE_PATH, config_file_name))

    # To ensure quickstart runs with the default value of False for kill_switch_enabled if not present
    if not global_config_map.get("kill_switch_enabled"):
        global_config_map.get("kill_switch_enabled").value = False

    if wallet and password:
        global_config_map.get("ethereum_wallet").value = wallet

    if hb.strategy_name and hb.strategy_file_name:
        if not all_configs_complete(hb.strategy_name):
            hb.status()

    with patch_stdout(log_field=hb.app.log_field):
        dev_mode = check_dev_mode()
        if dev_mode:
            hb.app.log(
                "Running from dev branches. Full remote logging will be enabled."
            )

        log_level = global_config_map.get("log_level").value
        init_logging("hummingbot_logs.yml",
                     override_log_level=log_level,
                     dev_mode=dev_mode)

        if hb.strategy_file_name is not None and hb.strategy_name is not None:
            await write_config_to_yml(hb.strategy_name, hb.strategy_file_name)
            hb.start(log_level)

        tasks: List[Coroutine] = [hb.run()]
        if global_config_map.get("debug_console").value:
            management_port: int = detect_available_port(8211)
            tasks.append(
                start_management_console(locals(),
                                         host="localhost",
                                         port=management_port))
        await safe_gather(*tasks)
コード例 #11
0
ファイル: hummingbot.py プロジェクト: vinhtran91/beaxy-bot
async def main():
    await create_yml_files()

    # This init_logging() call is important, to skip over the missing config warnings.
    init_logging("hummingbot_logs.yml")

    read_system_configs_from_yml()

    hb = HummingbotApplication.main_application()

    with patch_stdout(log_field=hb.app.log_field):
        dev_mode = check_dev_mode()
        if dev_mode:
            hb.app.log("Running from dev branches. Full remote logging will be enabled.")
        init_logging("hummingbot_logs.yml",
                     override_log_level=global_config_map.get("log_level").value,
                     dev_mode=dev_mode)
        tasks: List[Coroutine] = [hb.run()]
        if global_config_map.get("debug_console").value:
            if not hasattr(__builtins__, "help"):
                import _sitebuiltins
                __builtins__.help = _sitebuiltins._Helper()

            from hummingbot.core.management.console import start_management_console
            management_port: int = detect_available_port(8211)
            tasks.append(start_management_console(locals(), host="localhost", port=management_port))
        await safe_gather(*tasks)
コード例 #12
0
 def notify(self, msg: str):
     from . import INFO
     self.log(INFO, msg)
     if not HummingbotLogger.is_testing_mode():
         from hummingbot.client.hummingbot_application import HummingbotApplication
         hummingbot_app: HummingbotApplication = HummingbotApplication.main_application()
         hummingbot_app._notify(f"({pd.Timestamp.fromtimestamp(int(time.time()))}) {msg}")
コード例 #13
0
    async def get_connector_price(self, connector_name: str, chain: str,
                                  network: str, trading_pair: str,
                                  is_buy: bool,
                                  amount: Decimal) -> Optional[Decimal]:
        key: GatewayPriceShimKey = GatewayPriceShimKey(
            connector_name=connector_name,
            chain=chain,
            network=network,
            trading_pair=trading_pair)
        if key not in self._shim_entries:
            return None

        shim_entry: GatewayPriceShimEntry = self._shim_entries[key]
        exchange_market: Optional[
            ExchangeBase] = HummingbotApplication.main_application(
            ).markets.get(shim_entry.from_exchange)
        if exchange_market is None:
            self.logger().warning(
                f"Gateway price shim failure: "
                f"reference exchange market '{shim_entry.from_exchange}' not found. "
                f"Going to use on-chain prices instead.")
            return None

        exchange_price: Decimal = await exchange_market.get_quote_price(
            shim_entry.from_trading_pair, is_buy, amount)
        if key in self._delta_entries:
            delta_entry: GatewayPriceDeltaEntry = self._delta_entries[key]
            now: float = time.time()
            if now <= delta_entry.end_timestamp:
                exchange_price += delta_entry.delta
            else:
                del self._delta_entries[key]
        return exchange_price
コード例 #14
0
ファイル: main.py プロジェクト: bitpif/hum-botInterface
async def main():
    chdir_to_data_directory()

    await create_yml_files()

    # This init_logging() call is important, to skip over the missing config warnings.
    init_logging("hummingbot_logs.yml")
    hb = HummingbotApplication.main_application()
    setHummingInstance(hb)

    read_configs_from_yml()
    ExchangeRateConversion.get_instance().start()

    with patch_stdout(log_field=hb.app.log_field):
        dev_mode = check_dev_mode()
        if dev_mode:
            hb.app.log(
                "Running from dev branches. Full remote logging will be enabled."
            )
        init_logging(
            "hummingbot_logs.yml",
            override_log_level=global_config_map.get("log_level").value,
            dev_mode=dev_mode)
        tasks: List[Coroutine] = [hb.run(), sio.connect('ws://localhost:5000')]
        await safe_gather(*tasks)
コード例 #15
0
async def quick_start():
    try:
        args = CmdlineParser().parse_args()

        strategy = args.strategy
        config_file_name = args.config_file_name
        wallet = args.wallet
        password = args.config_password

        await create_yml_files()
        init_logging("hummingbot_logs.yml")
        read_configs_from_yml()
        ExchangeRateConversion.get_instance().start()
        await ExchangeRateConversion.get_instance().wait_till_ready()
        hb = HummingbotApplication.main_application()

        in_memory_config_map.get("password").value = password
        in_memory_config_map.get("strategy").value = strategy
        in_memory_config_map.get("strategy").validate(strategy)
        in_memory_config_map.get("strategy_file_path").value = config_file_name
        in_memory_config_map.get("strategy_file_path").validate(config_file_name)

        # To ensure quickstart runs with the default value of False for kill_switch_enabled if not present
        if not global_config_map.get("kill_switch_enabled"):
            global_config_map.get("kill_switch_enabled").value = False

        if wallet and password:
            global_config_map.get("wallet").value = wallet
            hb.acct = unlock_wallet(public_key=wallet, password=password)

        if not hb.config_complete:
            config_map = load_required_configs()
            empty_configs = [key for key, config in config_map.items() if config.value is None and config.required]
            empty_config_description: str = "\n- ".join([""] + empty_configs)
            raise ValueError(f"Missing empty configs: {empty_config_description}\n")

        with patch_stdout(log_field=hb.app.log_field):
            dev_mode = check_dev_mode()
            if dev_mode:
                hb.app.log("Running from dev branches. Full remote logging will be enabled.")

            log_level = global_config_map.get("log_level").value
            init_logging("hummingbot_logs.yml",
                         override_log_level=log_level,
                         dev_mode=dev_mode,
                         strategy_file_path=config_file_name)
            await write_config_to_yml()
            hb.start(log_level)

            tasks: List[Coroutine] = [hb.run()]
            if global_config_map.get("debug_console").value:
                management_port: int = detect_available_port(8211)
                tasks.append(start_management_console(locals(), host="localhost", port=management_port))
            await safe_gather(*tasks)

    except Exception as e:
        # In case of quick start failure, start the bot normally to allow further configuration
        logging.getLogger().warning(f"Bot config incomplete: {str(e)}. Starting normally...")
        await normal_start()
コード例 #16
0
ファイル: test_layout.py プロジェクト: srirambandi/hummingbot
    def test_get_strategy_file(self):
        hb = HummingbotApplication.main_application()
        hb._strategy_file_name = "some_strategy.yml"
        res = get_strategy_file()
        style, text = res[0]

        self.assertEqual("class:log-field", style)
        self.assertEqual(f"Strategy File: {hb._strategy_file_name}", text)
コード例 #17
0
ファイル: test_layout.py プロジェクト: srirambandi/hummingbot
    def test_get_active_strategy(self):
        hb = HummingbotApplication.main_application()
        hb.strategy_name = "SomeStrategy"
        res = get_active_strategy()
        style, text = res[0]

        self.assertEqual("class:log-field", style)
        self.assertEqual(f"Strategy: {hb.strategy_name}", text)
コード例 #18
0
async def quick_start():
    try:
        args = CmdlineParser().parse_args()

        strategy = args.strategy
        config_file_name = args.config_file_name
        wallet = args.wallet
        wallet_password = args.wallet_password

        await create_yml_files()
        init_logging("hummingbot_logs.yml")
        read_configs_from_yml()
        hb = HummingbotApplication.main_application()

        in_memory_config_map.get("strategy").value = strategy
        in_memory_config_map.get("strategy").validate(strategy)
        in_memory_config_map.get("strategy_file_path").value = config_file_name
        in_memory_config_map.get("strategy_file_path").validate(
            config_file_name)

        if wallet and wallet_password:
            global_config_map.get("wallet").value = wallet
            hb.acct = unlock_wallet(public_key=wallet,
                                    password=wallet_password)

        if not hb.config_complete:
            empty_configs = hb._get_empty_configs()
            empty_config_description: str = "\n- ".join([""] + empty_configs)
            raise ValueError(
                f"Missing empty configs: {empty_config_description}\n")

        with patch_stdout(log_field=hb.app.log_field):
            dev_mode = check_dev_mode()
            if dev_mode:
                hb.app.log(
                    "Running from dev branches. Full remote logging will be enabled."
                )

            log_level = global_config_map.get("log_level").value
            init_logging("hummingbot_logs.yml",
                         override_log_level=log_level,
                         dev_mode=dev_mode)
            hb.start(log_level)

            tasks: List[Coroutine] = [hb.run()]
            if global_config_map.get("debug_console").value:
                management_port: int = detect_available_port(8211)
                tasks.append(
                    start_management_console(locals(),
                                             host="localhost",
                                             port=management_port))
            await asyncio.gather(*tasks)

    except Exception as e:
        # In case of quick start failure, start the bot normally to allow further configuration
        logging.getLogger().warning(
            f"Bot config incomplete: {str(e)}. Starting normally...")
        await normal_start()
コード例 #19
0
 def __init__(self, client_config_map: Optional["ClientConfigAdapter"] = None):
     if client_config_map is None:
         from hummingbot.client.hummingbot_application import HummingbotApplication
         client_config_map = HummingbotApplication.main_application().client_config_map
     api_host = client_config_map.gateway.gateway_api_host
     api_port = client_config_map.gateway.gateway_api_port
     if GatewayHttpClient.__instance is None:
         self._base_url = f"https://{api_host}:{api_port}"
     self._client_confi_map = client_config_map
     GatewayHttpClient.__instance = self
コード例 #20
0
 async def set_up_class(cls):
     add_files_extension(settings.CONF_FILE_PATH, [".yml", ".json"],
                         ".temp")
     asyncio.ensure_future(hb_main())
     cls.hb = HummingbotApplication.main_application()
     await wait_til(
         lambda: ExchangeRateConversion.get_instance()._ready_notifier.
         is_set(), 20)
     await wait_til(lambda: 'Enter "config" to create a bot' in cls.hb.app.
                    output_field.document.text)
コード例 #21
0
async def quick_start(args: argparse.Namespace,
                      secrets_manager: BaseSecretsManager):
    config_file_name = args.config_file_name
    client_config = load_client_config_map_from_file()

    if args.auto_set_permissions is not None:
        autofix_permissions(args.auto_set_permissions)

    if not Security.login(secrets_manager):
        logging.getLogger().error("Invalid password.")
        return

    await Security.wait_til_decryption_done()
    await create_yml_files_legacy()
    init_logging("hummingbot_logs.yml", client_config)
    await read_system_configs_from_yml()

    AllConnectorSettings.initialize_paper_trade_settings(
        client_config.paper_trade.paper_trade_exchanges)

    hb = HummingbotApplication.main_application()
    # Todo: validate strategy and config_file_name before assinging

    strategy_config = None
    if config_file_name is not None:
        hb.strategy_file_name = config_file_name
        strategy_config = await load_strategy_config_map_from_file(
            STRATEGIES_CONF_DIR_PATH / config_file_name)
        hb.strategy_name = (strategy_config.strategy if isinstance(
            strategy_config, BaseStrategyConfigMap) else
                            strategy_config.get("strategy").value)
        hb.strategy_config_map = strategy_config

    if strategy_config is not None:
        if not all_configs_complete(strategy_config, hb.client_config_map):
            hb.status()

    # The listener needs to have a named variable for keeping reference, since the event listener system
    # uses weak references to remove unneeded listeners.
    start_listener: UIStartListener = UIStartListener(hb)
    hb.app.add_listener(HummingbotUIEvent.Start, start_listener)

    tasks: List[Coroutine] = [
        hb.run(), start_existing_gateway_container(client_config)
    ]
    if client_config.debug_console:
        management_port: int = detect_available_port(8211)
        tasks.append(
            start_management_console(locals(),
                                     host="localhost",
                                     port=management_port))

    await safe_gather(*tasks)
コード例 #22
0
async def quick_start(args):
    config_file_name = args.config_file_name
    wallet = args.wallet
    password = args.config_password

    if args.auto_set_permissions is not None:
        autofix_permissions(args.auto_set_permissions)

    if password is not None and not Security.login(password):
        logging.getLogger().error("Invalid password.")
        return

    await Security.wait_til_decryption_done()
    await create_yml_files()
    init_logging("hummingbot_logs.yml")
    await read_system_configs_from_yml()

    AllConnectorSettings.initialize_paper_trade_settings(
        global_config_map.get("paper_trade_exchanges").value)

    hb = HummingbotApplication.main_application()
    # Todo: validate strategy and config_file_name before assinging

    if config_file_name is not None:
        hb.strategy_file_name = config_file_name
        hb.strategy_name = await update_strategy_config_map_from_file(
            os.path.join(CONF_FILE_PATH, config_file_name))

    # To ensure quickstart runs with the default value of False for kill_switch_enabled if not present
    if not global_config_map.get("kill_switch_enabled"):
        global_config_map.get("kill_switch_enabled").value = False

    if wallet and password:
        global_config_map.get("ethereum_wallet").value = wallet

    if hb.strategy_name and hb.strategy_file_name:
        if not all_configs_complete(hb.strategy_name):
            hb.status()

    # The listener needs to have a named variable for keeping reference, since the event listener system
    # uses weak references to remove unneeded listeners.
    start_listener: UIStartListener = UIStartListener(hb)
    hb.app.add_listener(HummingbotUIEvent.Start, start_listener)

    tasks: List[Coroutine] = [hb.run()]
    if global_config_map.get("debug_console").value:
        management_port: int = detect_available_port(8211)
        tasks.append(
            start_management_console(locals(),
                                     host="localhost",
                                     port=management_port))

    await safe_gather(*tasks)
コード例 #23
0
async def docker_ipc(method_name: str, *args, **kwargs) -> Any:
    from hummingbot.client.hummingbot_application import HummingbotApplication
    global _hummingbot_pipe

    if _hummingbot_pipe is None:
        raise RuntimeError(
            "Not in the main process, or hummingbot wasn't started via `fork_and_start()`."
        )
    try:
        _hummingbot_pipe.send((method_name, args, kwargs))
        data = await _hummingbot_pipe.coro_recv()
        if isinstance(data, Exception):
            raise data
        return data

    except Exception as e:  # unable to communicate with docker socket
        HummingbotApplication.main_application().notify(
            "Notice: Hummingbot is unable to communicate with Docker. If you need gateway for DeFi,"
            "\nmake sure Docker is on, then restart Hummingbot. Otherwise, ignore this message."
        )
        raise e
コード例 #24
0
async def stop_gateway():
    from hummingbot.client.hummingbot_application import HummingbotApplication
    try:
        response = await docker_ipc(
            "containers",
            all=True,
            filters={"name": get_gateway_container_name()})
        if len(response) == 0:
            raise ValueError(
                f"Gateway container {get_gateway_container_name()} not found.")

        container_info = response[0]
        if container_info["State"] != "running":
            HummingbotApplication.main_application().notify(
                f"Gateway container {container_info['Id']} not running.")
            return

        await docker_ipc(
            "stop",
            container=container_info["Id"],
        )
        HummingbotApplication.main_application().notify(
            f"Gateway container {container_info['Id']} successfully stopped.")
    except Exception as e:
        HummingbotApplication.main_application().notify(
            f"Error occurred stopping Gateway container. {e}")
コード例 #25
0
async def start_trade_monitor(trade_monitor):
    from hummingbot.client.hummingbot_application import HummingbotApplication
    hb = HummingbotApplication.main_application()
    trade_monitor.log("Trades: 0, Total P&L: 0.00, Return %: 0.00%")
    return_pcts = []
    pnls = []

    while True:
        try:
            if hb.strategy_task is not None and not hb.strategy_task.done():
                if all(market.ready for market in hb.markets.values()):
                    with hb.trade_fill_db.get_new_session() as session:
                        trades: List[TradeFill] = hb._get_trades_from_session(
                            int(hb.init_time * 1e3),
                            session=session,
                            config_file_path=hb.strategy_file_name)
                        if len(trades) > 0:
                            market_info: Set[Tuple[str, str]] = set(
                                (t.market, t.symbol) for t in trades)
                            for market, symbol in market_info:
                                cur_trades = [
                                    t for t in trades if t.market == market
                                    and t.symbol == symbol
                                ]
                                cur_balances = await hb.get_current_balances(
                                    market)
                                perf = await PerformanceMetrics.create(
                                    symbol, cur_trades, cur_balances)
                                return_pcts.append(perf.return_pct)
                                pnls.append(perf.total_pnl)
                            avg_return = sum(return_pcts) / len(
                                return_pcts) if len(
                                    return_pcts) > 0 else s_decimal_0
                            quote_assets = set(
                                t.symbol.split("-")[1] for t in trades)
                            if len(quote_assets) == 1:
                                total_pnls = f"{PerformanceMetrics.smart_round(sum(pnls))} {list(quote_assets)[0]}"
                            else:
                                total_pnls = "N/A"
                            trade_monitor.log(
                                f"Trades: {len(trades)}, Total P&L: {total_pnls}, "
                                f"Return %: {avg_return:.2%}")
                            return_pcts.clear()
                            pnls.clear()
            await _sleep(2)  # sleeping for longer to manage resources
        except asyncio.CancelledError:
            raise
        except Exception:
            hb.logger().exception("start_trade_monitor failed.")
コード例 #26
0
    def network(self, log_msg: str, app_warning_msg: Optional[str] = None, *args, **kwargs):
        from hummingbot.client.hummingbot_application import HummingbotApplication
        from . import NETWORK

        self.log(NETWORK, log_msg, *args, **kwargs)
        if app_warning_msg is not None and not HummingbotLogger.is_testing_mode():
            app_warning: ApplicationWarning = ApplicationWarning(
                time.time(),
                self.name,
                self.findCaller(),
                app_warning_msg
            )
            self.warning(app_warning.warning_msg)
            hummingbot_app: HummingbotApplication = HummingbotApplication.main_application()
            hummingbot_app.add_application_warning(app_warning)
コード例 #27
0
    async def show_order_book(self):
        from hummingbot.client.hummingbot_application import HummingbotApplication
        main_app = HummingbotApplication.main_application()

        if self._trading_pair not in self._exchange.order_books:
            self.logger().error(f"Invalid market {self._trading_pair} on {self._exchange.name} connector.")
            raise ValueError(f"Invalid market {self._trading_pair} on {self._exchange.name} connector.")

        await main_app.stop_live_update()
        main_app.app.live_updates = True
        while main_app.app.live_updates:
            await main_app.cls_display_delay(self.get_order_book() + "\n\n Press escape key to stop update.", 0.5)

        # NOTE: Currently there is no way for users to re-trigger the live orderbook display with this strategy.
        self.notify_hb_app("Stopped live orderbook display update. To show live orderbook again, re-run the strategy by running the `stop` and `start` command.")
コード例 #28
0
async def main():
    await create_yml_files()
    init_logging("hummingbot_logs.yml")
    read_configs_from_yml()
    hb = HummingbotApplication.main_application()
    hb.acct = unlock_wallet(public_key=WALLET_PUBLIC_KEY, password=WALLET_PASSWORD)

    with patch_stdout(log_field=hb.app.log_field):
        init_logging("hummingbot_logs.yml", override_log_level=global_config_map.get("log_level").value)
        logging.getLogger().info("____DEV_MODE__start_directly__")

        in_memory_config_map.get("strategy").value = STRATEGY
        in_memory_config_map.get("strategy").validate(STRATEGY)
        in_memory_config_map.get("strategy_file_path").value = STRATEGY_PATH
        in_memory_config_map.get("strategy_file_path").validate(STRATEGY_PATH)
        global_config_map.get("wallet").value = WALLET_PUBLIC_KEY

        tasks: List[Coroutine] = [hb.run()]
        await asyncio.gather(*tasks)
コード例 #29
0
async def handle_command(command):
    hb = HummingbotApplication.main_application()
    try:
        await hb._handle_command(command)
    except:
        pass

    if command == "status":
        try:
            with open('data/status.txt', 'r') as f:
                return (f.read())
        except:
            return ("Not started.")

    if command == "exit":
        try:
            with open('data/status.txt', 'w') as outfile:
                outfile.write("Stopped.")
        except:
            print("")

    return "OK"
コード例 #30
0
async def start_gateway(client_config_map: "ClientConfigAdapter"):
    from hummingbot.client.hummingbot_application import HummingbotApplication
    try:
        response = await docker_ipc(
            "containers",
            all=True,
            filters={"name": get_gateway_container_name(client_config_map)})
        if len(response) == 0:
            raise ValueError(
                f"Gateway container {get_gateway_container_name(client_config_map)} not found. "
            )

        container_info = response[0]
        if container_info["State"] == "running":
            HummingbotApplication.main_application().notify(
                f"Gateway container {container_info['Id']} already running.")
            return

        await docker_ipc("start", container=container_info["Id"])
        HummingbotApplication.main_application().notify(
            f"Gateway container {container_info['Id']} has started.")
    except Exception as e:
        HummingbotApplication.main_application().notify(
            f"Error occurred starting Gateway container. {e}")