2021-10-08 10:15:40 -07:00
|
|
|
#!/usr/bin/env python3
|
2021-04-26 09:09:35 -07:00
|
|
|
|
2021-04-27 02:53:43 -07:00
|
|
|
import argparse
|
2021-04-29 02:53:01 -07:00
|
|
|
import logging
|
2021-06-07 07:10:18 -07:00
|
|
|
import os
|
2021-04-26 09:09:35 -07:00
|
|
|
import os.path
|
2021-06-17 08:30:40 -07:00
|
|
|
import rx
|
|
|
|
import rx.operators as ops
|
2021-06-07 07:10:18 -07:00
|
|
|
import sys
|
2021-06-18 05:50:33 -07:00
|
|
|
import threading
|
2021-04-26 09:09:35 -07:00
|
|
|
import traceback
|
2021-06-21 03:06:26 -07:00
|
|
|
import typing
|
2021-04-26 09:09:35 -07:00
|
|
|
|
2021-05-06 06:21:40 -07:00
|
|
|
from decimal import Decimal
|
|
|
|
|
2021-06-07 07:10:18 -07:00
|
|
|
sys.path.insert(0, os.path.abspath(
|
2021-06-25 02:33:40 -07:00
|
|
|
os.path.join(os.path.dirname(__file__), "..")))
|
2021-06-07 07:10:18 -07:00
|
|
|
import mango # nopep8
|
2021-04-26 09:09:35 -07:00
|
|
|
|
2021-04-28 10:36:48 -07:00
|
|
|
# We explicitly want argument parsing to be outside the main try-except block because some arguments
|
2021-05-11 11:24:02 -07:00
|
|
|
# (like --help) will cause an exit, which our except: block traps.
|
2021-05-07 02:47:01 -07:00
|
|
|
parser = argparse.ArgumentParser(description="Run a liquidator for a Mango Markets group.")
|
2021-07-23 02:20:44 -07:00
|
|
|
mango.ContextBuilder.add_command_line_parameters(parser)
|
2021-06-17 04:06:39 -07:00
|
|
|
mango.Wallet.add_command_line_parameters(parser)
|
2021-05-27 09:07:02 -07:00
|
|
|
parser.add_argument("--throttle-reload-to-seconds", type=Decimal, default=Decimal(60),
|
2021-05-12 02:52:26 -07:00
|
|
|
help="minimum number of seconds between each full margin account reload loop (including time taken processing accounts)")
|
2021-05-27 09:07:02 -07:00
|
|
|
parser.add_argument("--throttle-ripe-update-to-seconds", type=Decimal, default=Decimal(5),
|
2021-05-12 02:52:26 -07:00
|
|
|
help="minimum number of seconds between each ripe update loop (including time taken processing accounts)")
|
2021-09-06 13:38:12 -07:00
|
|
|
parser.add_argument("--target", type=mango.parse_target_balance, action="append",
|
2021-08-27 12:37:23 -07:00
|
|
|
help="token symbol plus target value or percentage, separated by a colon (e.g. 'ETH:2.5')")
|
2021-05-06 06:21:40 -07:00
|
|
|
parser.add_argument("--action-threshold", type=Decimal, default=Decimal("0.01"),
|
|
|
|
help="fraction of total wallet value a trade must be above to be carried out")
|
2021-06-24 08:36:11 -07:00
|
|
|
parser.add_argument("--worthwhile-threshold", type=Decimal, default=Decimal("0.01"),
|
|
|
|
help="value a liquidation must be above to be carried out")
|
2021-05-06 06:21:40 -07:00
|
|
|
parser.add_argument("--adjustment-factor", type=Decimal, default=Decimal("0.05"),
|
|
|
|
help="factor by which to adjust the SELL price (akin to maximum slippage)")
|
2021-10-28 04:19:18 -07:00
|
|
|
parser.add_argument("--notify-liquidations", type=mango.parse_notification_target, action="append", default=[],
|
2021-05-18 10:08:38 -07:00
|
|
|
help="The notification target for liquidation events")
|
2021-10-28 04:19:18 -07:00
|
|
|
parser.add_argument("--notify-successful-liquidations", type=mango.parse_notification_target,
|
2021-05-21 12:02:54 -07:00
|
|
|
action="append", default=[], help="The notification target for successful liquidation events")
|
2021-10-28 04:19:18 -07:00
|
|
|
parser.add_argument("--notify-failed-liquidations", type=mango.parse_notification_target,
|
2021-05-21 12:02:54 -07:00
|
|
|
action="append", default=[], help="The notification target for failed liquidation events")
|
2021-10-28 04:19:18 -07:00
|
|
|
parser.add_argument("--notify-errors", type=mango.parse_notification_target, action="append", default=[],
|
2021-05-18 10:08:38 -07:00
|
|
|
help="The notification target for error events")
|
2021-05-07 02:47:01 -07:00
|
|
|
parser.add_argument("--dry-run", action="store_true", default=False,
|
2021-05-06 07:27:25 -07:00
|
|
|
help="runs as read-only and does not perform any transactions")
|
2021-09-13 06:05:19 -07:00
|
|
|
args: argparse.Namespace = mango.parse_args(parser)
|
2021-04-26 09:09:35 -07:00
|
|
|
|
2021-10-28 04:19:18 -07:00
|
|
|
handler = mango.NotificationHandler(mango.CompoundNotificationTarget(args.notify_errors))
|
|
|
|
handler.setLevel(logging.ERROR)
|
|
|
|
logging.getLogger().addHandler(handler)
|
2021-05-18 10:08:38 -07:00
|
|
|
|
2021-06-21 03:06:26 -07:00
|
|
|
|
2021-11-09 05:23:36 -08:00
|
|
|
def start_subscriptions(context: mango.Context, liquidation_processor: mango.LiquidationProcessor, fetch_prices: typing.Callable[[typing.Any], typing.Any], fetch_accounts: typing.Callable[[typing.Any], typing.Any], throttle_reload_to_seconds: Decimal, throttle_ripe_update_to_seconds: Decimal) -> typing.Tuple[rx.core.typing.Disposable, rx.core.typing.Disposable]:
|
2021-06-21 03:06:26 -07:00
|
|
|
liquidation_processor.state = mango.LiquidationProcessorState.STARTING
|
|
|
|
|
|
|
|
logging.info("Starting margin account fetcher subscription")
|
2021-07-12 10:26:35 -07:00
|
|
|
account_subscription = rx.interval(float(throttle_reload_to_seconds)).pipe(
|
2021-09-02 00:30:06 -07:00
|
|
|
ops.observe_on(context.create_thread_pool_scheduler()),
|
2021-06-21 03:06:26 -07:00
|
|
|
ops.start_with(-1),
|
2021-07-12 10:26:35 -07:00
|
|
|
ops.map(fetch_accounts(context)),
|
2021-06-21 03:06:26 -07:00
|
|
|
ops.catch(mango.observable_pipeline_error_reporter),
|
|
|
|
ops.retry()
|
2021-07-12 10:26:35 -07:00
|
|
|
).subscribe(mango.create_backpressure_skipping_observer(on_next=liquidation_processor.update_accounts, on_error=mango.log_subscription_error))
|
2021-06-21 03:06:26 -07:00
|
|
|
|
|
|
|
logging.info("Starting price fetcher subscription")
|
|
|
|
price_subscription = rx.interval(float(throttle_ripe_update_to_seconds)).pipe(
|
2021-09-02 00:30:06 -07:00
|
|
|
ops.observe_on(context.create_thread_pool_scheduler()),
|
2021-06-21 03:06:26 -07:00
|
|
|
ops.map(fetch_prices(context)),
|
|
|
|
ops.catch(mango.observable_pipeline_error_reporter),
|
|
|
|
ops.retry()
|
|
|
|
).subscribe(mango.create_backpressure_skipping_observer(on_next=lambda piped: liquidation_processor.update_prices(piped[0], piped[1]), on_error=mango.log_subscription_error))
|
|
|
|
|
2021-07-12 10:26:35 -07:00
|
|
|
return account_subscription, price_subscription
|
2021-06-21 03:06:26 -07:00
|
|
|
|
|
|
|
|
2021-04-28 10:36:48 -07:00
|
|
|
try:
|
2021-07-23 02:20:44 -07:00
|
|
|
context = mango.ContextBuilder.from_command_line_parameters(args)
|
2021-06-17 04:06:39 -07:00
|
|
|
wallet = mango.Wallet.from_command_line_parameters_or_raise(args)
|
|
|
|
|
2021-05-06 06:21:40 -07:00
|
|
|
action_threshold = args.action_threshold
|
2021-06-24 08:36:11 -07:00
|
|
|
worthwhile_threshold = args.worthwhile_threshold
|
2021-05-06 06:21:40 -07:00
|
|
|
adjustment_factor = args.adjustment_factor
|
2021-05-12 02:52:26 -07:00
|
|
|
throttle_reload_to_seconds = args.throttle_reload_to_seconds
|
|
|
|
throttle_ripe_update_to_seconds = args.throttle_ripe_update_to_seconds
|
2021-05-21 12:02:54 -07:00
|
|
|
liquidator_name = args.name
|
2021-04-28 10:36:48 -07:00
|
|
|
|
|
|
|
logging.info(f"Wallet address: {wallet.address}")
|
|
|
|
|
2021-06-07 07:10:18 -07:00
|
|
|
group = mango.Group.load(context)
|
2021-06-25 07:50:37 -07:00
|
|
|
tokens = [token_info.token for token_info in group.tokens if token_info is not None]
|
2021-04-28 10:36:48 -07:00
|
|
|
|
|
|
|
logging.info("Checking wallet accounts.")
|
2021-06-07 07:10:18 -07:00
|
|
|
scout = mango.AccountScout()
|
2021-04-29 08:33:04 -07:00
|
|
|
report = scout.verify_account_prepared_for_group(context, group, wallet.address)
|
|
|
|
logging.info(f"Wallet account report: {report}")
|
|
|
|
if report.has_errors:
|
|
|
|
raise Exception(f"Account '{wallet.address}' is not prepared for group '{group.address}'.")
|
|
|
|
|
2021-04-28 10:36:48 -07:00
|
|
|
logging.info("Wallet accounts OK.")
|
|
|
|
|
2021-06-07 07:10:18 -07:00
|
|
|
liquidations_publisher = mango.EventSource[mango.LiquidationEvent]()
|
2021-11-09 05:23:36 -08:00
|
|
|
liquidations_publisher.subscribe(on_next=mango.CompoundNotificationTarget(
|
|
|
|
args.notify_liquidations).send) # type: ignore[call-arg]
|
2021-10-28 04:19:18 -07:00
|
|
|
|
|
|
|
on_success = mango.FilteringNotificationTarget(
|
|
|
|
mango.CompoundNotificationTarget(args.notify_successful_liquidations),
|
|
|
|
lambda item: isinstance(item, mango.LiquidationEvent) and item.succeeded)
|
2021-11-09 05:23:36 -08:00
|
|
|
liquidations_publisher.subscribe(on_next=on_success.send) # type: ignore[call-arg]
|
2021-10-28 04:19:18 -07:00
|
|
|
|
|
|
|
on_failed = mango.FilteringNotificationTarget(
|
|
|
|
mango.CompoundNotificationTarget(args.notify_failed_liquidations),
|
|
|
|
lambda item: isinstance(item, mango.LiquidationEvent) and not item.succeeded)
|
2021-11-09 05:23:36 -08:00
|
|
|
liquidations_publisher.subscribe(on_next=on_failed.send) # type: ignore[call-arg]
|
2021-05-21 06:28:42 -07:00
|
|
|
|
2021-06-25 07:50:37 -07:00
|
|
|
# TODO: Add proper liquidator classes here when they're written for V3
|
2021-05-06 07:27:25 -07:00
|
|
|
if args.dry_run:
|
2021-06-25 07:50:37 -07:00
|
|
|
account_liquidator: mango.AccountLiquidator = mango.NullAccountLiquidator()
|
2021-05-06 07:27:25 -07:00
|
|
|
else:
|
2021-06-25 07:50:37 -07:00
|
|
|
account_liquidator = mango.NullAccountLiquidator()
|
2021-05-06 07:27:25 -07:00
|
|
|
|
|
|
|
if args.dry_run or (args.target is None) or (len(args.target) == 0):
|
2021-06-07 07:10:18 -07:00
|
|
|
wallet_balancer: mango.WalletBalancer = mango.NullWalletBalancer()
|
2021-05-06 06:21:40 -07:00
|
|
|
else:
|
2021-09-06 13:38:12 -07:00
|
|
|
targets = args.target
|
2021-08-07 07:07:19 -07:00
|
|
|
trade_executor = mango.ImmediateTradeExecutor(context, wallet, None, adjustment_factor)
|
2021-06-08 06:38:28 -07:00
|
|
|
wallet_balancer = mango.LiveWalletBalancer(
|
2021-11-08 03:39:09 -08:00
|
|
|
wallet, group.shared_quote_token, trade_executor, targets, action_threshold)
|
2021-05-06 06:21:40 -07:00
|
|
|
|
2021-06-22 01:43:31 -07:00
|
|
|
# These (along with `context`) are captured and read by `load_updated_price_details()`.
|
|
|
|
group_address = group.address
|
2021-06-25 07:50:37 -07:00
|
|
|
oracle_addresses = group.oracles
|
2021-06-22 01:43:31 -07:00
|
|
|
|
2021-11-08 03:39:09 -08:00
|
|
|
def load_updated_price_details() -> typing.Tuple[mango.Group, typing.Sequence[mango.InstrumentValue]]:
|
2021-08-03 10:32:12 -07:00
|
|
|
oracles = [oracle_address for oracle_address in oracle_addresses if oracle_address is not None]
|
|
|
|
all_addresses = [group_address, *oracles]
|
2021-06-22 01:43:31 -07:00
|
|
|
all_account_infos = mango.AccountInfo.load_multiple(context, all_addresses)
|
|
|
|
group_account_info = all_account_infos[0]
|
|
|
|
group = mango.Group.parse(context, group_account_info)
|
|
|
|
|
2021-06-25 07:50:37 -07:00
|
|
|
# TODO - fetch prices when code available in V3.
|
|
|
|
return group, []
|
2021-06-22 01:43:31 -07:00
|
|
|
|
2021-11-09 05:23:36 -08:00
|
|
|
def fetch_prices(context: mango.Context) -> typing.Callable[[typing.Any], typing.Any]:
|
|
|
|
def _fetch_prices(_: typing.Any) -> typing.Any:
|
2021-06-17 08:30:40 -07:00
|
|
|
with mango.retry_context("Price Fetch",
|
2021-11-09 05:23:36 -08:00
|
|
|
lambda _: load_updated_price_details(),
|
2021-06-17 08:30:40 -07:00
|
|
|
context.retry_pauses) as retrier:
|
|
|
|
return retrier.run()
|
|
|
|
|
|
|
|
return _fetch_prices
|
2021-05-17 12:43:16 -07:00
|
|
|
|
2021-11-09 05:23:36 -08:00
|
|
|
def fetch_accounts(context: mango.Context) -> typing.Callable[[typing.Any], typing.Any]:
|
|
|
|
def _actual_fetch() -> typing.Sequence[mango.Account]:
|
|
|
|
# group = mango.Group.load(context)
|
|
|
|
# return mango.Account.load_ripe(context, group)
|
|
|
|
return []
|
2021-06-17 08:30:40 -07:00
|
|
|
|
2021-11-09 05:23:36 -08:00
|
|
|
def _fetch_accounts(_: typing.Any) -> typing.Any:
|
2021-06-07 07:10:18 -07:00
|
|
|
with mango.retry_context("Margin Account Fetch",
|
2021-11-09 05:23:36 -08:00
|
|
|
lambda _: _actual_fetch(),
|
2021-06-17 08:30:40 -07:00
|
|
|
context.retry_pauses) as retrier:
|
|
|
|
return retrier.run()
|
2021-07-12 10:26:35 -07:00
|
|
|
return _fetch_accounts
|
2021-06-17 08:30:40 -07:00
|
|
|
|
2021-06-21 03:06:26 -07:00
|
|
|
class LiquidationProcessorSubscriptions:
|
2021-11-09 05:23:36 -08:00
|
|
|
def __init__(self, account: rx.core.typing.Disposable, price: rx.core.typing.Disposable) -> None:
|
2021-07-12 10:26:35 -07:00
|
|
|
self.account: rx.core.typing.Disposable = account
|
2021-06-21 03:06:26 -07:00
|
|
|
self.price: rx.core.typing.Disposable = price
|
|
|
|
|
2021-06-24 08:36:11 -07:00
|
|
|
liquidation_processor = mango.LiquidationProcessor(
|
|
|
|
context, liquidator_name, account_liquidator, wallet_balancer, worthwhile_threshold)
|
2021-07-12 10:26:35 -07:00
|
|
|
account_subscription, price_subscription = start_subscriptions(
|
|
|
|
context, liquidation_processor, fetch_prices, fetch_accounts, throttle_reload_to_seconds, throttle_ripe_update_to_seconds)
|
2021-06-21 03:06:26 -07:00
|
|
|
|
2021-07-12 10:26:35 -07:00
|
|
|
subscriptions = LiquidationProcessorSubscriptions(account=account_subscription,
|
2021-06-21 03:06:26 -07:00
|
|
|
price=price_subscription)
|
|
|
|
|
2021-11-09 05:23:36 -08:00
|
|
|
def on_unhealthy(liquidation_processor: mango.LiquidationProcessor) -> None:
|
2021-06-21 03:06:26 -07:00
|
|
|
if liquidation_processor.state != mango.LiquidationProcessorState.UNHEALTHY:
|
|
|
|
logging.info(
|
|
|
|
f"Ignoring LiquidationProcessor state change - state is: {liquidation_processor.state}")
|
|
|
|
return
|
|
|
|
|
|
|
|
logging.warning("Liquidation processor has been marked as unhealthy so recreating subscriptions.")
|
|
|
|
try:
|
2021-07-12 10:26:35 -07:00
|
|
|
subscriptions.account.dispose()
|
2021-06-21 03:06:26 -07:00
|
|
|
except Exception as exception:
|
|
|
|
logging.warning(f"Ignoring problem disposing of margin account subscription: {exception}")
|
|
|
|
try:
|
|
|
|
subscriptions.price.dispose()
|
|
|
|
except Exception as exception:
|
|
|
|
logging.warning(f"Ignoring problem disposing of margin account subscription: {exception}")
|
|
|
|
|
2021-07-12 10:26:35 -07:00
|
|
|
account_subscription, price_subscription = start_subscriptions(
|
|
|
|
context, liquidation_processor, fetch_prices, fetch_accounts, throttle_reload_to_seconds, throttle_ripe_update_to_seconds)
|
|
|
|
subscriptions.account = account_subscription
|
2021-06-21 03:06:26 -07:00
|
|
|
subscriptions.price = price_subscription
|
|
|
|
|
2021-11-09 05:23:36 -08:00
|
|
|
liquidation_processor.state_change.subscribe(on_next=on_unhealthy) # type: ignore[call-arg]
|
2021-06-17 08:30:40 -07:00
|
|
|
|
2021-06-18 05:50:33 -07:00
|
|
|
# Wait - don't exit. Exiting will be handled by signals/interrupts.
|
|
|
|
waiter = threading.Event()
|
|
|
|
waiter.wait()
|
2021-06-17 08:30:40 -07:00
|
|
|
except KeyboardInterrupt:
|
|
|
|
logging.info("Liquidator stopping...")
|
2021-04-26 09:09:35 -07:00
|
|
|
except Exception as exception:
|
|
|
|
logging.critical(f"Liquidator stopped because of exception: {exception} - {traceback.format_exc()}")
|
|
|
|
except:
|
|
|
|
logging.critical(f"Liquidator stopped because of uncatchable error: {traceback.format_exc()}")
|
|
|
|
finally:
|
|
|
|
logging.info("Liquidator completed.")
|