Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored master branch #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions bin/hummingbot_quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,12 @@ async def quick_start(args):
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()
if (
hb.strategy_name
and hb.strategy_file_name
and not all_configs_complete(hb.strategy_name)
):
hb.status()
Comment on lines -99 to +104
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function quick_start refactored with the following changes:


with patch_stdout(log_field=hb.app.log_field):
dev_mode = check_dev_mode()
Expand Down Expand Up @@ -135,9 +138,8 @@ def main():
args.config_password = os.environ["CONFIG_PASSWORD"]

# If no password is given from the command line, prompt for one.
if args.config_password is None:
if not login_prompt():
return
if args.config_password is None and not login_prompt():
return
Comment on lines -138 to +142
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:


asyncio.get_event_loop().run_until_complete(quick_start(args))

Expand Down
3 changes: 1 addition & 2 deletions bin/path_util.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#!/usr/bin/python

import sys
if "hummingbot-dist" in __file__:
# Dist environment.
import os
import sys
Comment on lines +3 to -6
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 6-15 refactored with the following changes:

sys.path.append(sys.path.pop(0))
sys.path.insert(0, os.getcwd())

Expand All @@ -12,5 +12,4 @@
else:
# Dev environment.
from os.path import join, realpath
import sys
sys.path.insert(0, realpath(join(__file__, "../../")))
7 changes: 3 additions & 4 deletions hummingbot/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@ def format_decimal(n):
with decimal.localcontext() as ctx:
if isinstance(n, float):
n = ctx.create_decimal(n)
if isinstance(n, decimal.Decimal):
n = round(n, FLOAT_PRINTOUT_PRECISION)
return format(n.normalize(), 'f')
else:
if not isinstance(n, decimal.Decimal):
return str(n)
n = round(n, FLOAT_PRINTOUT_PRECISION)
return format(n.normalize(), 'f')
Comment on lines -17 to +20
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function format_decimal refactored with the following changes:

except Exception as e:
logging.getLogger().error(str(e))

Expand Down
54 changes: 32 additions & 22 deletions hummingbot/client/command/balance_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def balance(self,
file_path = GLOBAL_CONFIG_PATH
if option == "limit":
config_var = config_map["balance_asset_limit"]
if args is None or len(args) == 0:
if args is None or not args:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BalanceCommand.balance refactored with the following changes:

safe_ensure_future(self.show_asset_limits())
return
if len(args) != 3 or validate_exchange(args[0]) is not None or validate_decimal(args[2]) is not None:
Expand All @@ -68,7 +68,7 @@ def balance(self,

elif option == "paper":
config_var = config_map["paper_trade_account_balance"]
if args is None or len(args) == 0:
if args is None or not args:
safe_ensure_future(self.show_paper_account_balance())
return
if len(args) != 2 or validate_decimal(args[1]) is not None:
Expand Down Expand Up @@ -108,7 +108,7 @@ async def show_balances(self):
if df.empty:
self._notify("You have no balance on this exchange.")
else:
lines = [" " + line for line in df.to_string(index=False).split("\n")]
lines = [f" {line}" for line in df.to_string(index=False).split("\n")]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BalanceCommand.show_balances refactored with the following changes:

self._notify("\n".join(lines))
self._notify(f"\n Total: {RateOracle.global_token_symbol} {PerformanceMetrics.smart_round(df[total_col_name].sum())} "
f"Allocated: {allocated_total / df[total_col_name].sum():.2%}")
Expand All @@ -122,7 +122,7 @@ async def show_balances(self):
if not CeloCLI.unlocked:
await self.validate_n_connect_celo()
df = await self.celo_balances_df()
lines = [" " + line for line in df.to_string(index=False).split("\n")]
lines = [f" {line}" for line in df.to_string(index=False).split("\n")]
self._notify("\ncelo:")
self._notify("\n".join(lines))
except Exception as e:
Expand All @@ -131,13 +131,13 @@ async def show_balances(self):
eth_address = global_config_map["ethereum_wallet"].value
if eth_address is not None:
eth_df = await self.ethereum_balances_df()
lines = [" " + line for line in eth_df.to_string(index=False).split("\n")]
lines = [f" {line}" for line in eth_df.to_string(index=False).split("\n")]
self._notify("\nethereum:")
self._notify("\n".join(lines))

# XDAI balances
xdai_df = await self.xdai_balances_df()
lines = [" " + line for line in xdai_df.to_string(index=False).split("\n")]
lines = [f" {line}" for line in xdai_df.to_string(index=False).split("\n")]
self._notify("\nxdai:")
self._notify("\n".join(lines))

Expand Down Expand Up @@ -167,10 +167,12 @@ async def exchange_balances_extra_df(self, # type: HummingbotApplication

async def celo_balances_df(self, # type: HummingbotApplication
):
rows = []
bals = CeloCLI.balances()
for token, bal in bals.items():
rows.append({"Asset": token.upper(), "Amount": round(bal.total, 4)})
rows = [
{"Asset": token.upper(), "Amount": round(bal.total, 4)}
for token, bal in bals.items()
]

Comment on lines -170 to +175
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BalanceCommand.celo_balances_df refactored with the following changes:

df = pd.DataFrame(data=rows, columns=["Asset", "Amount"])
df.sort_values(by=["Asset"], inplace=True)
return df
Expand All @@ -180,8 +182,11 @@ async def ethereum_balances_df(self, # type: HummingbotApplication
rows = []
if ethereum_required_trading_pairs():
bals = await UserBalances.eth_n_erc20_balances()
for token, bal in bals.items():
rows.append({"Asset": token, "Amount": round(bal, 4)})
rows.extend(
{"Asset": token, "Amount": round(bal, 4)}
for token, bal in bals.items()
)

Comment on lines -183 to +189
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BalanceCommand.ethereum_balances_df refactored with the following changes:

else:
eth_bal = UserBalances.ethereum_balance()
rows.append({"Asset": "ETH", "Amount": round(eth_bal, 4)})
Expand All @@ -191,19 +196,22 @@ async def ethereum_balances_df(self, # type: HummingbotApplication

async def xdai_balances_df(self, # type: HummingbotApplication
):
rows = []
bals = await UserBalances.xdai_balances()
for token, bal in bals.items():
rows.append({"Asset": token, "Amount": round(bal, 4)})
rows = [
{"Asset": token, "Amount": round(bal, 4)}
for token, bal in bals.items()
]

Comment on lines -194 to +204
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BalanceCommand.xdai_balances_df refactored with the following changes:

df = pd.DataFrame(data=rows, columns=["Asset", "Amount"])
df.sort_values(by=["Asset"], inplace=True)
return df

async def asset_limits_df(self,
asset_limit_conf: Dict[str, str]):
rows = []
for token, amount in asset_limit_conf.items():
rows.append({"Asset": token, "Limit": round(Decimal(amount), 4)})
rows = [
{"Asset": token, "Limit": round(Decimal(amount), 4)}
for token, amount in asset_limit_conf.items()
]
Comment on lines -204 to +214
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BalanceCommand.asset_limits_df refactored with the following changes:


df = pd.DataFrame(data=rows, columns=["Asset", "Limit"])
df.sort_values(by=["Asset"], inplace=True)
Expand All @@ -229,15 +237,17 @@ async def show_asset_limits(self):
if df.empty:
self._notify("You have no limits on this exchange.")
else:
lines = [" " + line for line in df.to_string(index=False).split("\n")]
lines = [f" {line}" for line in df.to_string(index=False).split("\n")]
Comment on lines -232 to +240
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BalanceCommand.show_asset_limits refactored with the following changes:

self._notify("\n".join(lines))
self._notify("\n")
return

async def paper_acccount_balance_df(self, paper_balances: Dict[str, Decimal]):
rows = []
for asset, balance in paper_balances.items():
rows.append({"Asset": asset, "Balance": round(Decimal(str(balance)), 4)})
rows = [
{"Asset": asset, "Balance": round(Decimal(str(balance)), 4)}
for asset, balance in paper_balances.items()
]

Comment on lines -238 to +250
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BalanceCommand.paper_acccount_balance_df refactored with the following changes:

df = pd.DataFrame(data=rows, columns=["Asset", "Balance"])
df.sort_values(by=["Asset"], inplace=True)
return df
Expand All @@ -260,7 +270,7 @@ async def show_paper_account_balance(self):
return
self._notify("Paper account balances:")
df = await self.paper_acccount_balance_df(paper_balances)
lines = [" " + line for line in df.to_string(index=False).split("\n")]
lines = [f" {line}" for line in df.to_string(index=False).split("\n")]
Comment on lines -263 to +273
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BalanceCommand.show_paper_account_balance refactored with the following changes:

self._notify("\n".join(lines))
self._notify("\n")
return
31 changes: 22 additions & 9 deletions hummingbot/client/command/config_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,21 +87,33 @@ def list_configs(self, # type: HummingbotApplication
if cv.key in global_configs_to_display and not cv.is_secure]
df = map_df_to_str(pd.DataFrame(data=data, columns=columns))
self._notify("\nGlobal Configurations:")
lines = [" " + line for line in df.to_string(index=False, max_colwidth=50).split("\n")]
lines = [
f" {line}"
for line in df.to_string(index=False, max_colwidth=50).split("\n")
]

self._notify("\n".join(lines))

data = [[cv.key, cv.value] for cv in global_config_map.values()
if cv.key in color_settings_to_display and not cv.is_secure]
df = map_df_to_str(pd.DataFrame(data=data, columns=columns))
self._notify("\nColor Settings:")
lines = [" " + line for line in df.to_string(index=False, max_colwidth=50).split("\n")]
lines = [
f" {line}"
for line in df.to_string(index=False, max_colwidth=50).split("\n")
]

self._notify("\n".join(lines))

if self.strategy_name is not None:
data = [[cv.printable_key or cv.key, cv.value] for cv in self.strategy_config_map.values() if not cv.is_secure]
df = map_df_to_str(pd.DataFrame(data=data, columns=columns))
self._notify("\nStrategy Configurations:")
lines = [" " + line for line in df.to_string(index=False, max_colwidth=50).split("\n")]
lines = [
f" {line}"
for line in df.to_string(index=False, max_colwidth=50).split("\n")
]

Comment on lines -90 to +116
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ConfigCommand.list_configs refactored with the following changes:

self._notify("\n".join(lines))

def config_able_keys(self # type: HummingbotApplication
Expand All @@ -118,11 +130,10 @@ def config_able_keys(self # type: HummingbotApplication
async def check_password(self, # type: HummingbotApplication
):
password = await self.app.prompt(prompt="Enter your password >>> ", is_password=True)
if password != Security.password:
self._notify("Invalid password, please try again.")
return False
else:
if password == Security.password:
return True
self._notify("Invalid password, please try again.")
return False
Comment on lines -121 to +136
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ConfigCommand.check_password refactored with the following changes:


# Make this function static so unit testing can be performed.
@staticmethod
Expand Down Expand Up @@ -177,8 +188,10 @@ async def _config_single_key(self, # type: HummingbotApplication
self.app.app.style = load_style()
for config in missings:
self._notify(f"{config.key}: {str(config.value)}")
if isinstance(self.strategy, PureMarketMakingStrategy) or \
isinstance(self.strategy, PerpetualMarketMakingStrategy):
if isinstance(
self.strategy,
(PureMarketMakingStrategy, PerpetualMarketMakingStrategy),
):
Comment on lines -180 to +194
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ConfigCommand._config_single_key refactored with the following changes:

updated = ConfigCommand.update_running_mm(self.strategy, key, config_var.value)
if updated:
self._notify(f"\nThe current {self.strategy_name} strategy has been updated "
Expand Down
9 changes: 5 additions & 4 deletions hummingbot/client/command/connect_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ async def connect_exchange(self, # type: HummingbotApplication
to_connect = True
if Security.encrypted_file_exists(exchange_configs[0].key):
await Security.wait_til_decryption_done()
api_key_config = [c for c in exchange_configs if "api_key" in c.key]
if api_key_config:
if api_key_config := [
c for c in exchange_configs if "api_key" in c.key
]:
Comment on lines -45 to +47
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ConnectCommand.connect_exchange refactored with the following changes:

api_key_config = api_key_config[0]
api_key = Security.decrypted_value(api_key_config.key)
prompt = f"Would you like to replace your existing {exchange} API key {api_key} (Yes/No)? >>> "
Expand Down Expand Up @@ -87,10 +88,10 @@ async def show_connections(self # type: HummingbotApplication
self._notify("\nTesting connections, please wait...")
await Security.wait_til_decryption_done()
df, failed_msgs = await self.connection_df()
lines = [" " + line for line in df.to_string(index=False).split("\n")]
lines = [f" {line}" for line in df.to_string(index=False).split("\n")]
if failed_msgs:
lines.append("\nFailed connections:")
lines.extend([" " + k + ": " + v for k, v in failed_msgs.items()])
lines.extend([f" {k}: {v}" for k, v in failed_msgs.items()])
Comment on lines -90 to +94
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ConnectCommand.show_connections refactored with the following changes:

self._notify("\n".join(lines))

async def connection_df(self # type: HummingbotApplication
Expand Down
5 changes: 1 addition & 4 deletions hummingbot/client/command/create_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,7 @@ async def prompt_for_configuration(self, # type: HummingbotApplication
f"while setting up these below configuration.")
# assign default values and reset those not required
for config in config_map.values():
if config.required:
config.value = config.default
else:
config.value = None
config.value = config.default if config.required else None
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CreateCommand.prompt_for_configuration refactored with the following changes:

for config in config_map.values():
if config.prompt_on_new and config.required:
if not self.app.to_stop_config:
Expand Down
2 changes: 1 addition & 1 deletion hummingbot/client/command/exit_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ async def exit_loop(self, # type: HummingbotApplication
force: bool = False):
if self.strategy_task is not None and not self.strategy_task.cancelled():
self.strategy_task.cancel()
if force is False and self._trading_required:
if not force and self._trading_required:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ExitCommand.exit_loop refactored with the following changes:

success = await self._cancel_outstanding_orders()
if not success:
self._notify('Wind down process terminated: Failed to cancel all outstanding orders. '
Expand Down
4 changes: 2 additions & 2 deletions hummingbot/client/command/export_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ async def prompt_new_export_file_name(self, # type: HummingbotApplication
self._notify("Value is required.")
return await self.prompt_new_export_file_name(path)
if "." not in input:
input = input + ".csv"
input = f'{input}.csv'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ExportCommand.prompt_new_export_file_name refactored with the following changes:

file_path = os.path.join(path, input)
if os.path.exists(file_path):
self._notify(f"{input} file already exists, please enter a new name.")
Expand All @@ -72,7 +72,7 @@ async def export_trades(self, # type: HummingbotApplication
trades: List[TradeFill] = self._get_trades_from_session(
int(self.init_time * 1e3),
session=session)
if len(trades) == 0:
if not trades:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ExportCommand.export_trades refactored with the following changes:

self._notify("No past trades to export.")
return
self.placeholder_mode = True
Expand Down
23 changes: 17 additions & 6 deletions hummingbot/client/command/gateway_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,14 @@ async def _api_request(self,
url = f"{base_url}/{path_url}"
client = await self._http_client()
if method == "get":
if len(params) > 0:
if params:
response = await client.get(url, params=params)
else:
response = await client.get(url)
elif method == "post":
response = await client.post(url, data=params)

parsed_response = json.loads(await response.text())
return parsed_response
return json.loads(await response.text())
Comment on lines -77 to +84
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GatewayCommand._api_request refactored with the following changes:


async def _http_client(self) -> aiohttp.ClientSession:
"""
Expand All @@ -102,7 +101,7 @@ async def _update_gateway(self, key, value):

try:
config = await self.get_gateway_connections()
core_keys = [key for key in sorted(config["config"]['CORE'])]
core_keys = list(sorted(config["config"]['CORE']))
Comment on lines -105 to +104
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GatewayCommand._update_gateway refactored with the following changes:

other_keys = [key for key in sorted(config["config"]) if key not in ["CORE"]]
all_keys = core_keys + other_keys
except Exception:
Expand Down Expand Up @@ -174,12 +173,24 @@ async def _show_gateway_connections(self):
columns = ["Parameter", " Value"]
core_data = data = [[key, config['CORE'][key]] for key in sorted(config['CORE'])]
core_df = pd.DataFrame(data=core_data, columns=columns)
lines = [" " + line for line in core_df.to_string(index=False, max_colwidth=50).split("\n")]
lines = [
f" {line}"
for line in core_df.to_string(
index=False, max_colwidth=50
).split("\n")
]

self._notify("\n".join(lines))
self._notify("\nOther parameters:")
data = [[key, config[key]] for key in sorted(config) if key not in ['CORE']]
df = pd.DataFrame(data=data, columns=columns)
lines = [" " + line for line in df.to_string(index=False, max_colwidth=50).split("\n")]
lines = [
f" {line}"
for line in df.to_string(index=False, max_colwidth=50).split(
"\n"
)
]

Comment on lines -177 to +193
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GatewayCommand._show_gateway_connections refactored with the following changes:

self._notify("\n".join(lines))
else:
self._notify("\nError: Invalid return result")
Expand Down
Loading