Ejemplo n.º 1
0
    def test_login(self):
        password = "******"
        secrets_manager = ETHKeyFileSecretManger(password)
        store_password_verification(secrets_manager)

        Security.login(secrets_manager)
        config_map = self.store_binance_config()
        self.async_run_with_timeout(Security.wait_til_decryption_done(), timeout=2)

        self.assertTrue(Security.is_decryption_done())
        self.assertTrue(Security.any_secure_configs())
        self.assertTrue(Security.connector_config_file_exists(self.connector))

        api_keys = Security.api_keys(self.connector)
        expected_keys = api_keys_from_connector_config_map(config_map)

        self.assertEqual(expected_keys, api_keys)
 async def _test_existing_password(self):
     # check the 2 encrypted files exist
     self.assertTrue(
         os.path.exists(f"{temp_folder}encrypted_test_key_1.json"))
     self.assertTrue(
         os.path.exists(f"{temp_folder}encrypted_test_key_2.json"))
     self.assertTrue(Security.any_encryped_files())
     self.assertFalse(Security.new_password_required())
     # login fails with incorrect password
     result = Security.login("b")
     self.assertFalse(result)
     # login passes with correct password
     result = Security.login("a")
     self.assertTrue(result)
     # right after logging in, the decryption shouldn't finished yet
     self.assertFalse(Security.is_decryption_done())
     await Security.wait_til_decryption_done()
     self.assertEqual(len(Security.all_decrypted_values()), 2)
     config_value = Security.decrypted_value("test_key_1")
     self.assertEqual("test_value_1", config_value)
     Security.update_secure_config("test_key_1", "new_value")
     self.assertEqual("new_value", Security.decrypted_value("test_key_1"))
Ejemplo n.º 3
0
    async def status_check_all(self,  # type: HummingbotApplication
                               notify_success=True) -> bool:

        if self.strategy is not None:
            return self.strategy_status()

        # Preliminary checks.
        self._notify("\nPreliminary checks:")
        if self.strategy_name is None or self.strategy_file_name is None:
            self._notify('  - Strategy check: Please import or create a strategy.')
            return False

        if not Security.is_decryption_done():
            self._notify('  - Security check: Encrypted files are being processed. Please wait and try again later.')
            return False

        invalid_conns = await self.validate_required_connections()
        if invalid_conns:
            self._notify('  - Exchange check: Invalid connections:')
            for ex, err_msg in invalid_conns.items():
                self._notify(f"    {ex}: {err_msg}")
        elif notify_success:
            self._notify('  - Exchange check: All connections confirmed.')

        missing_configs = self.missing_configurations()
        if missing_configs:
            self._notify("  - Strategy check: Incomplete strategy configuration. The following values are missing.")
            for config in missing_configs:
                self._notify(f"    {config.key}")
        elif notify_success:
            self._notify('  - Strategy check: All required parameters confirmed.')
        if invalid_conns or missing_configs:
            return False

        if self.wallet is not None:
            # Only check node url when a wallet has been initialized
            eth_node_valid = check_web3(global_config_map.get("ethereum_rpc_url").value)
            if not eth_node_valid:
                self._notify('  - Node check: Bad ethereum rpc url. '
                             'Please re-configure by entering "config ethereum_rpc_url"')
                return False
            elif notify_success:
                self._notify("  - Node check: Ethereum node running and current.")

            if self.wallet.network_status is NetworkStatus.CONNECTED:
                if self._trading_required:
                    has_minimum_eth = self.wallet.get_balance("ETH") > 0.01
                    if not has_minimum_eth:
                        self._notify("  - ETH wallet check: Not enough ETH in wallet. "
                                     "A small amount of Ether is required for sending transactions on "
                                     "Decentralized Exchanges")
                        return False
                    elif notify_success:
                        self._notify("  - ETH wallet check: Minimum ETH requirement satisfied")
            else:
                self._notify("  - ETH wallet check: ETH wallet is not connected.")

        loading_markets: List[MarketBase] = []
        for market in self.markets.values():
            if not market.ready:
                loading_markets.append(market)

        if len(loading_markets) > 0:
            self._notify(f"  - Exchange connectors check:  Waiting for exchange connectors " +
                         ",".join([m.name.capitalize() for m in loading_markets]) + f" to get ready for trading. \n"
                         f"                    Please keep the bot running and try to start again in a few minutes. \n")

            for market in loading_markets:
                market_status_df = pd.DataFrame(data=market.status_dict.items(), columns=["description", "status"])
                self._notify(
                    f"  - {market.display_name.capitalize()} connector status:\n" +
                    "\n".join(["     " + line for line in market_status_df.to_string(index=False,).split("\n")]) +
                    "\n"
                )
            return False

        elif not all([market.network_status is NetworkStatus.CONNECTED for market in self.markets.values()]):
            offline_markets: List[str] = [
                market_name
                for market_name, market
                in self.markets.items()
                if market.network_status is not NetworkStatus.CONNECTED
            ]
            for offline_market in offline_markets:
                self._notify(f"  - Exchange connector check: {offline_market} is currently offline.")
            return False
        self.application_warning()
        self._notify(f"  - All checks: Confirmed.")
        return True
Ejemplo n.º 4
0
    async def status_check_all(self,  # type: HummingbotApplication
                               notify_success=True,
                               live=False) -> bool:

        if self.strategy is not None:
            if live:
                await self.stop_live_update()
                self.app.live_updates = True
                while self.app.live_updates and self.strategy:
                    script_status = '\n Status from script would not appear here. ' \
                                    'Simply run the status command without "--live" to see script status.'
                    await self.cls_display_delay(
                        await self.strategy_status(live=True) + script_status + "\n\n Press escape key to stop update.", 1
                    )
                self._notify("Stopped live status display update.")
            else:
                self._notify(await self.strategy_status())
            return True

        # Preliminary checks.
        self._notify("\nPreliminary checks:")
        if self.strategy_name is None or self.strategy_file_name is None:
            self._notify('  - Strategy check: Please import or create a strategy.')
            return False

        if not Security.is_decryption_done():
            self._notify('  - Security check: Encrypted files are being processed. Please wait and try again later.')
            return False

        invalid_conns = await self.validate_required_connections()
        if invalid_conns:
            self._notify('  - Exchange check: Invalid connections:')
            for ex, err_msg in invalid_conns.items():
                self._notify(f"    {ex}: {err_msg}")
        elif notify_success:
            self._notify('  - Exchange check: All connections confirmed.')

        missing_configs = self.missing_configurations()
        if missing_configs:
            self._notify("  - Strategy check: Incomplete strategy configuration. The following values are missing.")
            for config in missing_configs:
                self._notify(f"    {config.key}")
        elif notify_success:
            self._notify('  - Strategy check: All required parameters confirmed.')
        if invalid_conns or missing_configs:
            return False

        if self.wallet is not None:
            # Only check node url when a wallet has been initialized
            eth_node_valid = check_web3(global_config_map.get("ethereum_rpc_url").value)
            if not eth_node_valid:
                self._notify('  - Node check: Bad ethereum rpc url. '
                             'Please re-configure by entering "config ethereum_rpc_url"')
                return False
            elif notify_success:
                self._notify("  - Node check: Ethereum node running and current.")

            if self.wallet.network_status is NetworkStatus.CONNECTED:
                if self._trading_required:
                    has_minimum_eth = self.wallet.get_balance("ETH") > 0.01
                    if not has_minimum_eth:
                        self._notify("  - ETH wallet check: Not enough ETH in wallet. "
                                     "A small amount of Ether is required for sending transactions on "
                                     "Decentralized Exchanges")
                        return False
                    elif notify_success:
                        self._notify("  - ETH wallet check: Minimum ETH requirement satisfied")
            else:
                self._notify("  - ETH wallet check: ETH wallet is not connected.")

        loading_markets: List[ConnectorBase] = []
        for market in self.markets.values():
            if not market.ready:
                loading_markets.append(market)

        if len(loading_markets) > 0:
            self._notify("  - Connectors check:  Waiting for connectors " +
                         ",".join([m.name.capitalize() for m in loading_markets]) + " to get ready for trading. \n"
                         "                    Please keep the bot running and try to start again in a few minutes. \n")

            for market in loading_markets:
                market_status_df = pd.DataFrame(data=market.status_dict.items(), columns=["description", "status"])
                self._notify(
                    f"  - {market.display_name.capitalize()} connector status:\n" +
                    "\n".join(["     " + line for line in market_status_df.to_string(index=False,).split("\n")]) +
                    "\n"
                )
            return False

        elif not all([market.network_status is NetworkStatus.CONNECTED for market in self.markets.values()]):
            offline_markets: List[str] = [
                market_name
                for market_name, market
                in self.markets.items()
                if market.network_status is not NetworkStatus.CONNECTED
            ]
            for offline_market in offline_markets:
                self._notify(f"  - Connector check: {offline_market} is currently offline.")
            return False

        # Paper trade mode is currently not available for connectors other than exchanges.
        # Todo: This check is hard coded at the moment, when we get a clearer direction on how we should handle this,
        # this section will need updating.
        if global_config_map.get("paper_trade_enabled").value:
            if "balancer" in required_exchanges and \
                    str(global_config_map.get("ethereum_chain_name").value).lower() != "kovan":
                self._notify("Error: Paper trade mode is not available on balancer at the moment.")
                return False
            if "binance_perpetual" in required_exchanges:
                self._notify("Error: Paper trade mode is not available on binance_perpetual at the moment.")
                return False

        self.application_warning()
        self._notify("  - All checks: Confirmed.")
        return True
Ejemplo n.º 5
0
    async def status_check_all(
            self,  # type: HummingbotApplication
            notify_success=True,
            live=False) -> bool:

        if self.strategy is not None:
            if live:
                await self.stop_live_update()
                self.app.live_updates = True
                while self.app.live_updates and self.strategy:
                    script_status = '\n Status from script would not appear here. ' \
                                    'Simply run the status command without "--live" to see script status.'
                    await self.cls_display_delay(
                        await self.strategy_status(live=True) + script_status +
                        "\n\n Press escape key to stop update.", 1)
                self.app.live_updates = False
                self._notify("Stopped live status display update.")
            else:
                self._notify(await self.strategy_status())
            return True

        # Preliminary checks.
        self._notify("\nPreliminary checks:")
        if self.strategy_name is None or self.strategy_file_name is None:
            self._notify(
                '  - Strategy check: Please import or create a strategy.')
            return False

        if not Security.is_decryption_done():
            self._notify(
                '  - Security check: Encrypted files are being processed. Please wait and try again later.'
            )
            return False

        network_timeout = float(
            global_config_map["other_commands_timeout"].value)
        try:
            invalid_conns = await asyncio.wait_for(
                self.validate_required_connections(), network_timeout)
        except asyncio.TimeoutError:
            self._notify(
                "\nA network error prevented the connection check to complete. See logs for more details."
            )
            raise
        if invalid_conns:
            self._notify('  - Exchange check: Invalid connections:')
            for ex, err_msg in invalid_conns.items():
                self._notify(f"    {ex}: {err_msg}")
        elif notify_success:
            self._notify('  - Exchange check: All connections confirmed.')

        missing_configs = self.missing_configurations()
        if missing_configs:
            self._notify(
                "  - Strategy check: Incomplete strategy configuration. The following values are missing."
            )
            for config in missing_configs:
                self._notify(f"    {config.key}")
        elif notify_success:
            self._notify(
                '  - Strategy check: All required parameters confirmed.')
        if invalid_conns or missing_configs:
            return False

        loading_markets: List[ConnectorBase] = []
        for market in self.markets.values():
            if not market.ready:
                loading_markets.append(market)

        if len(loading_markets) > 0:
            self._notify(
                "  - Connectors check:  Waiting for connectors " +
                ",".join([m.name.capitalize() for m in loading_markets]) +
                " to get ready for trading. \n"
                "                    Please keep the bot running and try to start again in a few minutes. \n"
            )

            for market in loading_markets:
                market_status_df = pd.DataFrame(
                    data=market.status_dict.items(),
                    columns=["description", "status"])
                self._notify(
                    f"  - {market.display_name.capitalize()} connector status:\n"
                    + "\n".join([
                        "     " + line for line in market_status_df.to_string(
                            index=False, ).split("\n")
                    ]) + "\n")
            return False

        elif not all([
                market.network_status is NetworkStatus.CONNECTED
                for market in self.markets.values()
        ]):
            offline_markets: List[str] = [
                market_name for market_name, market in self.markets.items()
                if market.network_status is not NetworkStatus.CONNECTED
            ]
            for offline_market in offline_markets:
                self._notify(
                    f"  - Connector check: {offline_market} is currently offline."
                )
            return False

        self.application_warning()
        self._notify("  - All checks: Confirmed.")
        return True