Example #1
0
    def _initialize_markets(self, market_names: List[Tuple[str, List[str]]]):
        ethereum_rpc_url = global_config_map.get("ethereum_rpc_url").value

        # aggregate trading_pairs if there are duplicate markets
        market_trading_pairs_map = {}
        for market_name, trading_pairs in market_names:
            if market_name not in market_trading_pairs_map:
                market_trading_pairs_map[market_name] = []
            for hb_trading_pair in trading_pairs:
                market_trading_pairs_map[market_name].append(hb_trading_pair)

        for connector_name, trading_pairs in market_trading_pairs_map.items():
            if global_config_map.get("paper_trade_enabled").value:
                try:
                    connector = create_paper_trade_market(
                        market_name, trading_pairs)
                except Exception:
                    raise
                paper_trade_account_balance = global_config_map.get(
                    "paper_trade_account_balance").value
                for asset, balance in paper_trade_account_balance.items():
                    connector.set_balance(asset, balance)

            elif connector_name in CEXES or connector_name in DERIVATIVES:
                keys = dict((key, value.value) for key, value in dict(
                    filter(lambda item: connector_name in item[0],
                           global_config_map.items())).items())
                connector_class = get_connector_class(connector_name)
                connector = connector_class(
                    **keys,
                    trading_pairs=trading_pairs,
                    trading_required=self._trading_required)

            elif connector_name in DEXES:
                assert self.wallet is not None
                keys = dict((key, value.value) for key, value in dict(
                    filter(lambda item: connector_name in item[0],
                           global_config_map.items())).items())
                connector_class = get_connector_class(connector_name)
                connector = connector_class(
                    **keys,
                    wallet=self.wallet,
                    ethereum_rpc_url=ethereum_rpc_url,
                    trading_pairs=trading_pairs,
                    trading_required=self._trading_required)
                # TO-DO for DEXes: rename all extra argument to match key in global_config_map

            else:
                raise ValueError(
                    f"Connector name {connector_name} is invalid.")

            self.markets[connector_name] = connector

        self.markets_recorder = MarketsRecorder(
            self.trade_fill_db,
            list(self.markets.values()),
            self.strategy_file_name,
            self.strategy_name,
        )
        self.markets_recorder.start()
    async def _cancel_outstanding_orders(self) -> bool:
        success = True
        try:
            on_chain_cancel_on_exit = global_config_map.get("on_chain_cancel_on_exit").value
            bamboo_relay_use_coordinator = global_config_map.get("bamboo_relay_use_coordinator").value
            kill_timeout: float = self.KILL_TIMEOUT
            self._notify("Cancelling outstanding orders...")

            for market_name, market in self.markets.items():
                if market_name == "idex":
                    self._notify(f"IDEX cancellations may take up to {int(self.IDEX_KILL_TIMEOUT)} seconds...")
                    kill_timeout = self.IDEX_KILL_TIMEOUT
                # By default, the bot does not cancel orders on exit on Radar Relay or Bamboo Relay,
                # since all open orders will expire in a short window
                if not on_chain_cancel_on_exit and (market_name == "radar_relay" or (market_name == "bamboo_relay" and not bamboo_relay_use_coordinator)):
                    continue
                cancellation_results = await market.cancel_all(kill_timeout)
                uncancelled = list(filter(lambda cr: cr.success is False, cancellation_results))
                if len(uncancelled) > 0:
                    success = False
                    uncancelled_order_ids = list(map(lambda cr: cr.order_id, uncancelled))
                    self._notify("\nFailed to cancel the following orders on %s:\n%s" % (
                        market_name,
                        '\n'.join(uncancelled_order_ids)
                    ))
        except Exception:
            self.logger().error(f"Error canceling outstanding orders.", exc_info=True)
            success = False

        if success:
            self._notify("All outstanding orders cancelled.")
        return success
Example #3
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")

    await read_system_configs_from_yml()

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

    hb = HummingbotApplication.main_application()

    # 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:
        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)
Example #4
0
    def _initialize_markets(self, market_names: List[Tuple[str, List[str]]]):
        # aggregate trading_pairs if there are duplicate markets

        for market_name, trading_pairs in market_names:
            if market_name not in self.market_trading_pairs_map:
                self.market_trading_pairs_map[market_name] = []
            for hb_trading_pair in trading_pairs:
                self.market_trading_pairs_map[market_name].append(
                    hb_trading_pair)

        for connector_name, trading_pairs in self.market_trading_pairs_map.items(
        ):
            conn_setting = CONNECTOR_SETTINGS[connector_name]
            if global_config_map.get(
                    "paper_trade_enabled"
            ).value and conn_setting.type == ConnectorType.Exchange:
                try:
                    connector = create_paper_trade_market(
                        connector_name, trading_pairs)
                except Exception:
                    raise
                paper_trade_account_balance = global_config_map.get(
                    "paper_trade_account_balance").value
                for asset, balance in paper_trade_account_balance.items():
                    connector.set_balance(asset, balance)
            else:
                Security.update_config_map(global_config_map)
                keys = {
                    key: config.value
                    for key, config in global_config_map.items()
                    if key in conn_setting.config_keys
                }
                init_params = conn_setting.conn_init_parameters(keys)
                init_params.update(trading_pairs=trading_pairs,
                                   trading_required=self._trading_required)
                if conn_setting.use_ethereum_wallet:
                    ethereum_rpc_url = global_config_map.get(
                        "ethereum_rpc_url").value
                    # Todo: Hard coded this execption for now until we figure out how to handle all ethereum connectors.
                    if connector_name in [
                            "balancer", "uniswap", "perpetual_finance"
                    ]:
                        private_key = get_eth_wallet_private_key()
                        init_params.update(wallet_private_key=private_key,
                                           ethereum_rpc_url=ethereum_rpc_url)
                    else:
                        assert self.wallet is not None
                        init_params.update(wallet=self.wallet,
                                           ethereum_rpc_url=ethereum_rpc_url)
                connector_class = get_connector_class(connector_name)
                connector = connector_class(**init_params)
            self.markets[connector_name] = connector

        self.markets_recorder = MarketsRecorder(
            self.trade_fill_db,
            list(self.markets.values()),
            self.strategy_file_name,
            self.strategy_name,
        )
        self.markets_recorder.start()
    def test_format_df_for_printout_table_format_from_global_config(self):
        df = pd.DataFrame(data={
            "first": [1, 2],
            "second": ["12345", "67890"],
        })

        global_config_map.get("tables_format").value = "psql"
        df_str = format_df_for_printout(df)
        target_str = ("+---------+----------+"
                      "\n|   first |   second |"
                      "\n|---------+----------|"
                      "\n|       1 |    12345 |"
                      "\n|       2 |    67890 |"
                      "\n+---------+----------+")

        self.assertEqual(target_str, df_str)

        global_config_map.get("tables_format").value = "simple"
        df_str = format_df_for_printout(df)
        target_str = ("  first    second"
                      "\n-------  --------"
                      "\n      1     12345"
                      "\n      2     67890")

        self.assertEqual(target_str, df_str)
Example #6
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)
Example #7
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_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)
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)
Example #9
0
 def ethereum_balance():
     ethereum_wallet = global_config_map.get("ethereum_wallet").value
     ethereum_rpc_url = global_config_map.get("ethereum_rpc_url").value
     web3 = Web3(Web3.HTTPProvider(ethereum_rpc_url))
     balance = web3.eth.getBalance(ethereum_wallet)
     balance = web3.fromWei(balance, "ether")
     return balance
Example #10
0
    def _initialize_wallet(self, token_trading_pairs: List[str]):
        # Todo: This function should be removed as it's currently not used by current working connectors

        if not using_wallet():
            return
        # Commented this out for now since get_erc20_token_addresses uses blocking call

        # if not self.token_list:
        #     self.token_list = get_erc20_token_addresses()

        ethereum_wallet = global_config_map.get("ethereum_wallet").value
        private_key = Security._private_keys[ethereum_wallet]
        ethereum_rpc_url = global_config_map.get("ethereum_rpc_url").value
        erc20_token_addresses = {
            t: l[0]
            for t, l in self.token_list.items() if t in token_trading_pairs
        }

        chain_name: str = global_config_map.get("ethereum_chain_name").value
        self.wallet: Web3Wallet = Web3Wallet(
            private_key=private_key,
            backend_urls=[ethereum_rpc_url],
            erc20_token_addresses=erc20_token_addresses,
            chain=getattr(EthereumChain, chain_name),
        )
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()
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()
    def __init__(self,
                 hummingbot_application: "HummingbotApplication"):  # noqa F821
        self._hummingbot_application = hummingbot_application

        self._kill_switch_enabled: bool = global_config_map.get("kill_switch_enabled").value
        self._kill_switch_rate: Decimal = Decimal(global_config_map.get("kill_switch_rate").value or "0.0")

        self._started = False
        self._update_interval = 10.0
        self._check_profitability_task: Optional[asyncio.Task] = None
        self._profitability: Optional[Decimal] = None
Example #14
0
    def __init__(self, hummingbot_application: "HummingbotApplication"):
        self._hummingbot_application = hummingbot_application

        self._kill_switch_enabled = global_config_map.get(
            "kill_switch_enabled").value
        self._kill_switch_rate = global_config_map.get(
            "kill_switch_rate").value

        self._started = False
        self._update_interval = 10.0
        self._check_profitability_task: Optional[asyncio.Task] = None
        self._profitability: Optional[float] = None
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)
Example #16
0
 def validate_ethereum_wallet() -> Optional[str]:
     if global_config_map.get("ethereum_wallet").value is None:
         return "Ethereum wallet is required."
     if global_config_map.get("ethereum_rpc_url").value is None:
         return "ethereum_rpc_url is required."
     if global_config_map.get("ethereum_wallet").value not in Security.private_keys():
         return "Ethereum private key file does not exist or corrupts."
     try:
         UserBalances.ethereum_balance()
     except Exception as e:
         return str(e)
     return None
    def _initialize_wallet(self, token_trading_pairs: List[str]):
        ethereum_rpc_url = global_config_map.get("ethereum_rpc_url").value
        erc20_token_addresses = get_erc20_token_addresses(token_trading_pairs)

        if self.acct is not None:
            chain_name: str = global_config_map.get("ethereum_chain_name").value
            self.wallet: Web3Wallet = Web3Wallet(
                private_key=self.acct.privateKey,
                backend_urls=[ethereum_rpc_url],
                erc20_token_addresses=erc20_token_addresses,
                chain=getattr(EthereumChain, chain_name),
            )
Example #18
0
    def __init__(self, token: str, chat_id: str, hb: "HummingbotApplication") -> None:
        super().__init__()
        self._token = token or global_config_map.get("telegram_token").value
        self._chat_id = chat_id or global_config_map.get("telegram_chat_id").value
        self._updater = Updater(token=token, workers=0)
        self._hb = hb
        self._ev_loop = asyncio.get_event_loop()
        self._async_call_scheduler = AsyncCallScheduler.shared_instance()

        # Register command handler and start telegram message polling
        handles = [MessageHandler(Filters.text, self.handler)]
        for handle in handles:
            self._updater.dispatcher.add_handler(handle)
Example #19
0
 async def _create_or_import_wallet(self,  # type: HummingbotApplication
                                    ):
     """
     Special handler function that asks the user to either create a new wallet,
     or import one by entering the private key.
     """
     choice = await self.app.prompt(prompt=global_config_map.get("wallet").prompt)
     if choice == "import":
         private_key = await self.app.prompt(prompt="Your wallet private key >>> ", is_password=True)
         password = in_memory_config_map["password"].value
         try:
             self.acct = import_and_save_wallet(password, private_key)
             self._notify("Wallet %s imported into hummingbot" % (self.acct.address,))
         except Exception as e:
             self._notify(f"Failed to import wallet key: {e}")
             result = await self._create_or_import_wallet()
             return result
     elif choice == "create":
         password = in_memory_config_map["password"].value
         self.acct = create_and_save_wallet(password)
         self._notify("New wallet %s created" % (self.acct.address,))
     else:
         self._notify('Invalid choice. Please enter "create" or "import".')
         result = await self._create_or_import_wallet()
         return result
     return self.acct.address
Example #20
0
def get_eth_wallet_private_key() -> Optional[str]:
    ethereum_wallet = global_config_map.get("ethereum_wallet").value
    if ethereum_wallet is None or ethereum_wallet == "":
        return None
    private_key = Security._private_keys[ethereum_wallet]
    account = Account.privateKeyToAccount(private_key)
    return account.privateKey.hex()
Example #21
0
def get_erc20_token_addresses() -> Dict[str, List]:
    token_list_url = global_config_map.get("ethereum_token_list_url").value
    address_file_path = TOKEN_ADDRESSES_FILE_PATH
    token_list = {}

    resp = requests.get(token_list_url, timeout=1)
    decoded_resp = resp.json()

    for token in decoded_resp["tokens"]:
        token_list[token["symbol"]] = [token["address"], token["decimals"]]

    try:
        with open(address_file_path) as f:
            overrides: Dict[str, str] = json.load(f)
            for token, address in overrides.items():
                override_token = token_list.get(token, [address, 18])
                token_list[token] = [address, override_token[1]]
    except FileNotFoundError:
        # create override file for first run w docker
        with open(address_file_path, "w+") as f:
            f.write(json.dumps({}))
    except Exception as e:
        logging.getLogger().error(e, exc_info=True)

    return token_list
Example #22
0
    def history(
            self,  # type: HummingbotApplication
            days: float = 0,
            verbose: bool = False,
            precision: Optional[int] = None):
        if threading.current_thread() != threading.main_thread():
            self.ev_loop.call_soon_threadsafe(self.history)
            return

        if self.strategy_file_name is None:
            self._notify(
                "\n  Please first import a strategy config file of which to show historical performance."
            )
            return
        if global_config_map.get("paper_trade_enabled").value:
            self._notify(
                "\n  Paper Trading ON: All orders are simulated, and no real orders are placed."
            )
        start_time = get_timestamp(days) if days > 0 else self.init_time
        trades: List[TradeFill] = self._get_trades_from_session(
            int(start_time * 1e3), config_file_path=self.strategy_file_name)
        if not trades:
            self._notify("\n  No past trades to report.")
            return
        if verbose:
            self.list_trades(start_time)
        if self.strategy_name != "celo_arb":
            safe_ensure_future(
                self.history_report(start_time, trades, precision))
    def _initialize_wallet(self, token_trading_pairs: List[str]):
        if not using_wallet():
            return

        ethereum_wallet = global_config_map.get("ethereum_wallet").value
        private_key = Security._private_keys[ethereum_wallet]
        ethereum_rpc_url = global_config_map.get("ethereum_rpc_url").value
        erc20_token_addresses = get_erc20_token_addresses(token_trading_pairs)

        chain_name: str = global_config_map.get("ethereum_chain_name").value
        self.wallet: Web3Wallet = Web3Wallet(
            private_key=private_key,
            backend_urls=[ethereum_rpc_url],
            erc20_token_addresses=erc20_token_addresses,
            chain=getattr(EthereumChain, chain_name),
        )
Example #24
0
    async def start_check(self,  # type: HummingbotApplication
                          log_level: Optional[str] = None):

        if self.strategy_task is not None and not self.strategy_task.done():
            self._notify('The bot is already running - please run "stop" first')
            return

        is_valid = await self.status_check_all(notify_success=False)
        if not is_valid:
            return

        init_logging("hummingbot_logs.yml",
                     override_log_level=log_level.upper() if log_level else None,
                     strategy_file_path=self.strategy_file_name)

        # If macOS, disable App Nap.
        if platform.system() == "Darwin":
            import appnope
            appnope.nope()

        self._initialize_notifiers()

        self._notify(f"\nStatus check complete. Starting '{self.strategy_name}' strategy...")
        if global_config_map.get("paper_trade_enabled").value:
            self._notify("\nPaper Trading ON: All orders are simulated, and no real orders are placed.")
        await self.start_market_making(self.strategy_name)
Example #25
0
    def _handle_command(self, raw_command: str):
        # unset to_stop_config flag it triggered before loading any command
        if self.app.to_stop_config:
            self.app.to_stop_config = False

        raw_command = raw_command.lower().strip()
        command_split = raw_command.split()
        try:
            if self.placeholder_mode:
                pass
            else:
                shortcuts = global_config_map.get("command_shortcuts").value
                shortcut = None
                # see if we match against shortcut command
                if shortcuts is not None:
                    for s in shortcuts:
                        if command_split[0] == s['command']:
                            shortcut = s
                            break

                # perform shortcut expansion
                if shortcut is not None:
                    # check number of arguments
                    num_shortcut_args = len(shortcut['arguments'])
                    if len(command_split) == num_shortcut_args + 1:
                        # notify each expansion if there's more than 1
                        verbose = True if len(
                            shortcut['output']) > 1 else False
                        # do argument replace and re-enter this function with the expanded command
                        for output_cmd in shortcut['output']:
                            final_cmd = output_cmd
                            for i in range(1, num_shortcut_args + 1):
                                final_cmd = final_cmd.replace(
                                    f'${i}', command_split[i])
                            if verbose is True:
                                self._notify(f'  >>> {final_cmd}')
                            self._handle_command(final_cmd)
                    else:
                        self._notify(
                            'Invalid number of arguments for shortcut')
                # regular command
                else:
                    args = self.parser.parse_args(args=command_split)
                    kwargs = vars(args)
                    if not hasattr(args, "func"):
                        return
                    f = args.func
                    del kwargs["func"]
                    f(**kwargs)
        except InvalidCommandError as e:
            self._notify("Invalid command: %s" % (str(e), ))
        except ArgumentParserError as e:
            if not self.be_silly(raw_command):
                self._notify(str(e))
        except NotImplementedError:
            self._notify(
                "Command not yet implemented. This feature is currently under development."
            )
        except Exception as e:
            self.logger().error(e, exc_info=True)
Example #26
0
 async def eth_n_erc20_balances() -> Dict[str, Decimal]:
     ethereum_rpc_url = global_config_map.get("ethereum_rpc_url").value
     connector = BalancerConnector(ethereum_required_trading_pairs(),
                                   get_eth_wallet_private_key(),
                                   ethereum_rpc_url, True)
     await connector._update_balances()
     return connector.get_all_balances()
Example #27
0
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)
Example #28
0
    async def _create_or_import_wallet(self):
        choice = await self.app.prompt(
            prompt=global_config_map.get("wallet").prompt)
        if choice == "import":
            private_key = await self.app.prompt(
                prompt="Your wallet private key >>> ", is_password=True)
            password = await self.app.prompt(
                prompt="A password to protect your wallet key >>> ",
                is_password=True)

            try:
                self.acct = import_and_save_wallet(password, private_key)
                self.app.log("Wallet %s imported into hummingbot" %
                             (self.acct.address, ))
            except Exception as e:
                self.app.log(f"Failed to import wallet key: {e}")
                result = await self._create_or_import_wallet()
                return result
        elif choice == "create":
            password = await self.app.prompt(
                prompt="A password to protect your wallet key >>> ",
                is_password=True)
            self.acct = create_and_save_wallet(password)
            self.app.log("New wallet %s created" % (self.acct.address, ))
        else:
            self.app.log('Invalid choice. Please enter "create" or "import".')
            result = await self._create_or_import_wallet()
            return result
        return self.acct.address
Example #29
0
 async def import_config_file(
         self,  # type: HummingbotApplication
         file_name):
     self.app.clear_input()
     self.placeholder_mode = True
     self.app.hide_input = True
     required_exchanges.clear()
     if file_name is None:
         file_name = await self.prompt_a_file_name()
     if self.app.to_stop_config:
         self.app.to_stop_config = False
         return
     strategy_path = os.path.join(CONF_FILE_PATH, file_name)
     strategy = await update_strategy_config_map_from_file(strategy_path)
     self.strategy_file_name = file_name
     self.strategy_name = strategy
     self.notify(
         f"Configuration from {self.strategy_file_name} file is imported.")
     self.placeholder_mode = False
     self.app.hide_input = False
     self.app.change_prompt(prompt=">>> ")
     try:
         all_status_go = await self.status_check_all()
     except asyncio.TimeoutError:
         self.strategy_file_name = None
         self.strategy_name = None
         raise
     if all_status_go:
         self.notify("\nEnter \"start\" to start market making.")
         autofill_import = global_config_map.get("autofill_import").value
         if autofill_import is not None:
             self.app.set_text(autofill_import)
Example #30
0
    async def start_check(
            self,  # type: HummingbotApplication
            log_level: Optional[str] = None,
            restore: Optional[bool] = False):
        if self.strategy_task is not None and not self.strategy_task.done():
            self._notify(
                'The bot is already running - please run "stop" first')
            return

        if settings.required_rate_oracle:
            if not (await self.confirm_oracle_conversion_rate()):
                self._notify("The strategy failed to start.")
                return
            else:
                RateOracle.get_instance().start()
        is_valid = await self.status_check_all(notify_success=False)
        if not is_valid:
            self._notify("Status checks failed. Start aborted.")
            return
        if self._last_started_strategy_file != self.strategy_file_name:
            init_logging(
                "hummingbot_logs.yml",
                override_log_level=log_level.upper() if log_level else None,
                strategy_file_path=self.strategy_file_name)
            self._last_started_strategy_file = self.strategy_file_name

        # If macOS, disable App Nap.
        if platform.system() == "Darwin":
            import appnope
            appnope.nope()

        self._initialize_notifiers()

        self._notify(
            f"\nStatus check complete. Starting '{self.strategy_name}' strategy..."
        )
        if global_config_map.get("paper_trade_enabled").value:
            self._notify(
                "\nPaper Trading ON: All orders are simulated, and no real orders are placed."
            )

        for exchange in settings.required_exchanges:
            connector = str(exchange)
            status = get_connector_status(connector)

            # Display custom warning message for specific connectors
            warning_msg = warning_messages.get(connector, None)
            if warning_msg is not None:
                self._notify(f"\nConnector status: {status}\n"
                             f"{warning_msg}")

            # Display warning message if the exchange connector has outstanding issues or not working
            elif status != "GREEN":
                self._notify(
                    f"\nConnector status: {status}. This connector has one or more issues.\n"
                    "Refer to our Github page for more info: https://github.com/coinalpha/hummingbot"
                )

        await self.start_market_making(self.strategy_name, restore)