Skip to content
This repository has been archived by the owner on Feb 13, 2024. It is now read-only.

Commit

Permalink
Now use fully_qualified_symbol for markets in most places, so Serum a…
Browse files Browse the repository at this point in the history
…nd Spot markets can be differentiated.
  • Loading branch information
Geoff Taylor committed Mar 3, 2022
1 parent f1ea12e commit 89e45e9
Show file tree
Hide file tree
Showing 25 changed files with 164 additions and 117 deletions.
4 changes: 3 additions & 1 deletion bin/cancel-my-orders
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ with mango.ContextBuilder.from_command_line_parameters(args) as context:
)
orders = market_operations.load_my_orders(include_expired=True)
if len(orders) == 0:
mango.output(f"No open orders on {market_operations.market.symbol}")
mango.output(
f"No open orders on {market_operations.market.fully_qualified_symbol}"
)
else:
if mango.PerpMarket.isa(market_operations.market):
cancel_all = mango.PerpMarketOperations.ensure(
Expand Down
18 changes: 11 additions & 7 deletions bin/marketmaker
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,12 @@ def cleanup(
dry_run: bool,
) -> None:
market_operations: mango.MarketOperations = mango.operations(
context, wallet, account, market.symbol, dry_run
context, wallet, account, market.fully_qualified_symbol, dry_run
)
market_instruction_builder: mango.MarketInstructionBuilder = (
mango.instruction_builder(context, wallet, account, market.symbol, dry_run)
mango.instruction_builder(
context, wallet, account, market.fully_qualified_symbol, dry_run
)
)
cancels: mango.CombinableInstructions = mango.CombinableInstructions.empty()
orders = market_operations.load_my_orders(include_expired=True)
Expand Down Expand Up @@ -221,7 +223,7 @@ with mango.ContextBuilder.from_command_line_parameters(args) as context:
# The market index is also the index of the base token in the group's token list.
if market.quote != group.shared_quote_token:
raise Exception(
f"Group {group.name} uses shared quote token {group.shared_quote_token.symbol}/{group.shared_quote_token.mint}, but market {market.symbol} uses quote token {market.quote.symbol}/{market.quote.mint}."
f"Group {group.name} uses shared quote token {group.shared_quote_token.symbol}/{group.shared_quote_token.mint}, but market {market.fully_qualified_symbol} uses quote token {market.quote.symbol}/{market.quote.mint}."
)

cleanup(context, wallet, account, market, args.dry_run)
Expand All @@ -230,7 +232,7 @@ with mango.ContextBuilder.from_command_line_parameters(args) as context:
if args.hedging_market is not None:
if not mango.PerpMarket.isa(market):
raise Exception(
f"Cannot hedge - market {market.symbol} is not a perp market."
f"Cannot hedge - market {market.fully_qualified_symbol} is not a perp market."
)

underlying_market = mango.PerpMarket.ensure(market)
Expand All @@ -243,7 +245,7 @@ with mango.ContextBuilder.from_command_line_parameters(args) as context:
f"MarketOperations for {args.hedging_market} is not a SpotMarketOperations."
)

logging.info(f"Hedging on {hedging_ops.market.symbol}")
logging.info(f"Hedging on {hedging_ops.market.fully_qualified_symbol}")

target_balance: typing.Optional[
mango.TargetBalance
Expand Down Expand Up @@ -287,7 +289,9 @@ with mango.ContextBuilder.from_command_line_parameters(args) as context:
logging.info(f"Desired orders chain: {desired_orders_chain}")

market_instruction_builder: mango.MarketInstructionBuilder = (
mango.instruction_builder(context, wallet, account, market.symbol, args.dry_run)
mango.instruction_builder(
context, wallet, account, market.fully_qualified_symbol, args.dry_run
)
)

market_maker = mango.marketmaking.MarketMaker(
Expand All @@ -310,7 +314,7 @@ with mango.ContextBuilder.from_command_line_parameters(args) as context:
oracle = oracle_provider.oracle_for_market(context, oracle_market)
if oracle is None:
raise Exception(
f"Could not find oracle for market {oracle_market.symbol} from provider {args.oracle_provider}."
f"Could not find oracle for market {oracle_market.fully_qualified_symbol} from provider {args.oracle_provider}."
)

model_state_builder: mango.marketmaking.ModelStateBuilder = (
Expand Down
2 changes: 1 addition & 1 deletion bin/show-model-state
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ with mango.ContextBuilder.from_command_line_parameters(
oracle = oracle_provider.oracle_for_market(context, market)
if oracle is None:
raise Exception(
f"Could not find oracle for market {market.symbol} from provider {args.oracle_provider}."
f"Could not find oracle for market {market.fully_qualified_symbol} from provider {args.oracle_provider}."
)

health_check = mango.HealthCheck()
Expand Down
2 changes: 1 addition & 1 deletion bin/show-price
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ with mango.ContextBuilder.from_command_line_parameters(args) as context:
oracle = oracle_provider.oracle_for_market(context, market)
if oracle is None:
mango.output(
f"Could not find oracle for market {market.symbol} from provider {args.provider}."
f"Could not find oracle for market {market.fully_qualified_symbol} from provider {args.provider}."
)
else:
if not args.stream:
Expand Down
2 changes: 1 addition & 1 deletion bin/show-serum-open-orders
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ with mango.ContextBuilder.from_command_line_parameters(args) as context:
market.quote,
)
mango.output(
f"Found {len(all_open_orders_for_market)} Serum OpenOrders account(s) for market {market.symbol}."
f"Found {len(all_open_orders_for_market)} Serum OpenOrders account(s) for market {market.fully_qualified_symbol}."
)
for open_orders in all_open_orders_for_market:
mango.output(open_orders)
12 changes: 6 additions & 6 deletions mango/hedging/perptospothedger.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ def __init__(
underlying_market.quote != hedging_market.quote
):
raise Exception(
f"Market {hedging_market.symbol} cannot be used to hedge market {underlying_market.symbol}."
f"Market {hedging_market.fully_qualified_symbol} cannot be used to hedge market {underlying_market.fully_qualified_symbol}."
)

if not mango.Instrument.symbols_match(
target_balance.symbol, hedging_market.base.symbol
):
raise Exception(
f"Cannot target {target_balance.symbol} when hedging on {hedging_market.symbol}"
f"Cannot target {target_balance.symbol} when hedging on {hedging_market.fully_qualified_symbol}"
)

self.underlying_market: mango.PerpMarket = underlying_market
Expand Down Expand Up @@ -124,7 +124,7 @@ def pulse(self, context: mango.Context, model_state: mango.ModelState) -> None:
perp_position_rounded + token_balance_rounded - self.target_balance
)
self._logger.debug(
f"Delta from {self.underlying_market.symbol} to {self.hedging_market.symbol} is {delta:,.8f} {basket_token.base_instrument.symbol}, action threshold is: {self.action_threshold}"
f"Delta from {self.underlying_market.fully_qualified_symbol} to {self.hedging_market.fully_qualified_symbol} is {delta:,.8f} {basket_token.base_instrument.symbol}, action threshold is: {self.action_threshold}"
)

if abs(delta) > self.action_threshold:
Expand All @@ -151,14 +151,14 @@ def pulse(self, context: mango.Context, model_state: mango.ModelState) -> None:
side, adjusted_price, quantity, mango.OrderType.IOC
)
self._logger.info(
f"Hedging perp position {perp_position} and token balance {token_balance} with {side} of {quantity:,.8f} at {up_or_down} ({model_state.price}) {adjusted_price:,.8f} on {self.hedging_market.symbol}\n\t{order}"
f"Hedging perp position {perp_position} and token balance {token_balance} with {side} of {quantity:,.8f} at {up_or_down} ({model_state.price}) {adjusted_price:,.8f} on {self.hedging_market.fully_qualified_symbol}\n\t{order}"
)
try:
self.market_operations.place_order(order)
self.pause_counter = 0
except Exception:
self._logger.error(
f"[{context.name}] Failed to hedge on {self.hedging_market.symbol} using order {order} - {traceback.format_exc()}"
f"[{context.name}] Failed to hedge on {self.hedging_market.fully_qualified_symbol} using order {order} - {traceback.format_exc()}"
)
raise

Expand All @@ -181,4 +181,4 @@ def pulse(self, context: mango.Context, model_state: mango.ModelState) -> None:
self.pulse_error.on_next(exception)

def __str__(self) -> str:
return f"« PerpToSpotHedger for underlying '{self.underlying_market.symbol}', hedging on '{self.hedging_market.symbol}' »"
return f"« PerpToSpotHedger for underlying '{self.underlying_market.fully_qualified_symbol}', hedging on '{self.hedging_market.fully_qualified_symbol}' »"
20 changes: 14 additions & 6 deletions mango/marketmaking/marketmaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def pulse(self, context: mango.Context, model_state: mango.ModelState) -> None:

existing_orders = model_state.current_orders()
self._logger.debug(
f"""Before reconciliation: all owned orders on current orderbook [{model_state.market.symbol}]:
f"""Before reconciliation: all owned orders on current orderbook [{model_state.market.fully_qualified_symbol}]:
{mango.indent_collection_as_str(existing_orders)}"""
)
reconciled = self.order_reconciler.reconcile(
Expand All @@ -106,14 +106,16 @@ def pulse(self, context: mango.Context, model_state: mango.ModelState) -> None:
):
ids = [f"{ord.id} / {ord.client_id}" for ord in reconciled.to_cancel]
self._logger.info(
f"Cancelling all orders on {self.market.symbol} - currently {len(ids)}: {ids}"
f"Cancelling all orders on {self.market.fully_qualified_symbol} - currently {len(ids)}: {ids}"
)
cancellations = (
self.market_instruction_builder.build_cancel_all_orders_instructions()
)
else:
for to_cancel in reconciled.to_cancel:
self._logger.info(f"Cancelling {self.market.symbol} {to_cancel}")
self._logger.info(
f"Cancelling {self.market.fully_qualified_symbol} {to_cancel}"
)
cancel = (
self.market_instruction_builder.build_cancel_order_instructions(
to_cancel, ok_if_missing=True
Expand All @@ -129,7 +131,7 @@ def pulse(self, context: mango.Context, model_state: mango.ModelState) -> None:
)

self._logger.info(
f"Placing {self.market.symbol} {to_place_with_client_id}"
f"Placing {self.market.fully_qualified_symbol} {to_place_with_client_id}"
)
place_order = (
self.market_instruction_builder.build_place_order_instructions(
Expand All @@ -138,8 +140,14 @@ def pulse(self, context: mango.Context, model_state: mango.ModelState) -> None:
)
place_orders += place_order

accounts_to_crank = list(model_state.accounts_to_crank)
if self.market_instruction_builder.open_orders_address is not None:
accounts_to_crank += [
self.market_instruction_builder.open_orders_address
]

crank = self.market_instruction_builder.build_crank_instructions(
model_state.accounts_to_crank
accounts_to_crank
)
settle = self.market_instruction_builder.build_settle_instructions()

Expand Down Expand Up @@ -176,7 +184,7 @@ def pulse(self, context: mango.Context, model_state: mango.ModelState) -> None:
self.pulse_error.on_next(exception)

def __str__(self) -> str:
return f"""« MarketMaker for market '{self.market.symbol}' »"""
return f"""« MarketMaker for market '{self.market.fully_qualified_symbol}' »"""

def __repr__(self) -> str:
return f"{self}"
10 changes: 4 additions & 6 deletions mango/marketmaking/modelstatebuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def build(self, context: mango.Context) -> ModelState:
return self.model_state

def __str__(self) -> str:
return f"« WebsocketModelStateBuilder for market '{self.model_state.market.symbol}' »"
return f"« WebsocketModelStateBuilder for market '{self.model_state.market.fully_qualified_symbol}' »"


# # 🥭 PollingModelStateBuilder class
Expand Down Expand Up @@ -247,9 +247,7 @@ def poll(self, context: mango.Context) -> ModelState:
)

def __str__(self) -> str:
return (
f"""« SerumPollingModelStateBuilder for market '{self.market.symbol}' »"""
)
return f"""« SerumPollingModelStateBuilder for market '{self.market.fully_qualified_symbol}' »"""


# # 🥭 SpotPollingModelStateBuilder class
Expand Down Expand Up @@ -372,7 +370,7 @@ def poll(self, context: mango.Context) -> ModelState:
)

def __str__(self) -> str:
return f"""« SpotPollingModelStateBuilder for market '{self.market.symbol}' »"""
return f"""« SpotPollingModelStateBuilder for market '{self.market.fully_qualified_symbol}' »"""


# # 🥭 PerpPollingModelStateBuilder class
Expand Down Expand Up @@ -490,4 +488,4 @@ def poll(self, context: mango.Context) -> ModelState:
)

def __str__(self) -> str:
return f"""« PerpPollingModelStateBuilder for market '{self.market.symbol}' »"""
return f"""« PerpPollingModelStateBuilder for market '{self.market.fully_qualified_symbol}' »"""
12 changes: 8 additions & 4 deletions mango/marketmaking/modelstatebuilderfactory.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ def _polling_model_state_builder_factory(
group, account, mango.PerpMarket.ensure(market), oracle
)
else:
raise Exception(f"Could not determine type of market {market.symbol}")
raise Exception(
f"Could not determine type of market {market.fully_qualified_symbol}: {market}"
)


def _polling_serum_model_state_builder_factory(
Expand Down Expand Up @@ -132,7 +134,7 @@ def _polling_serum_model_state_builder_factory(
)
if len(all_open_orders) == 0:
raise Exception(
f"Could not find serum openorders account owned by {wallet.address} for market {market.symbol}."
f"Could not find serum openorders account owned by {wallet.address} for market {market.fully_qualified_symbol}."
)
return SerumPollingModelStateBuilder(
all_open_orders[0].address,
Expand Down Expand Up @@ -160,7 +162,7 @@ def _polling_spot_model_state_builder_factory(
all_open_orders_addresses: typing.Sequence[PublicKey] = account.spot_open_orders
if open_orders_address is None:
raise Exception(
f"Could not find spot openorders in account {account.address} for market {market.symbol}."
f"Could not find spot openorders in account {account.address} for market {market.fully_qualified_symbol}."
)
return SpotPollingModelStateBuilder(
open_orders_address,
Expand Down Expand Up @@ -350,7 +352,9 @@ def _websocket_model_state_builder_factory(
context, websocket_manager, health_check, perp_market
)
else:
raise Exception(f"Could not determine type of market {market.symbol}")
raise Exception(
f"Could not determine type of market {market.fully_qualified_symbol} - {market}"
)

model_state = ModelState(
order_owner,
Expand Down
9 changes: 6 additions & 3 deletions mango/marketoperations.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
class MarketInstructionBuilder(metaclass=abc.ABCMeta):
def __init__(self) -> None:
self._logger: logging.Logger = logging.getLogger(self.__class__.__name__)
self.open_orders_address: typing.Optional[PublicKey] = None

@abc.abstractmethod
def build_cancel_order_instructions(
Expand Down Expand Up @@ -120,7 +121,7 @@ def __init__(self, market: LoadedMarket) -> None:

@property
def symbol(self) -> str:
return self.market.symbol
return self.market.fully_qualified_symbol

@property
def inventory_source(self) -> InventorySource:
Expand Down Expand Up @@ -269,7 +270,9 @@ def place_order(
return []

def load_orderbook(self) -> OrderBook:
return OrderBook(self.market.symbol, NullLotSizeConverter(), [], [])
return OrderBook(
self.market.fully_qualified_symbol, NullLotSizeConverter(), [], []
)

def load_my_orders(self, include_expired: bool = False) -> typing.Sequence[Order]:
return []
Expand All @@ -287,4 +290,4 @@ def ensure_openorders(self) -> PublicKey:
return SYSTEM_PROGRAM_ADDRESS

def __str__(self) -> str:
return f"""« NullMarketOperations [{self.market.symbol}] »"""
return f"""« NullMarketOperations [{self.market.fully_qualified_symbol}] »"""
7 changes: 7 additions & 0 deletions mango/markets.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ def symbol_matches(self, symbol: str) -> bool:
def symbol(self) -> str:
return f"{self.base.symbol}/{self.quote.symbol}"

@property
@abc.abstractproperty
def fully_qualified_symbol(self) -> str:
raise NotImplementedError(
"Market.fully_qualified_symbol is not implemented on the base type."
)

def __str__(self) -> str:
return f"« Market {self.symbol} »"

Expand Down
2 changes: 1 addition & 1 deletion mango/modelstate.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def current_orders(self) -> typing.Sequence[Order]:
)

def __str__(self) -> str:
return f"""« ModelState for market '{self.market.symbol}'
return f"""« ModelState for market '{self.market.fully_qualified_symbol}'
Group: {self.group_watcher.latest.address}
Account: {self.account_watcher.latest.address}
Price: {self.price_watcher.latest}
Expand Down
Loading

0 comments on commit 89e45e9

Please sign in to comment.