agent0 ====== .. py:module:: agent0 .. autoapi-nested-parse:: Agent0 repo. This file expose specific functions and classes. .. !! processed by numpydoc !! Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/agent0/chainsync/index /autoapi/agent0/core/index /autoapi/agent0/ethpy/index /autoapi/agent0/hyperfuzz/index /autoapi/agent0/hyperlogs/index /autoapi/agent0/test_fixtures/index /autoapi/agent0/utils/index Classes ------- .. autoapisummary:: agent0.Chain agent0.Hyperdrive agent0.LocalChain agent0.LocalHyperdrive agent0.HyperdriveBasePolicy agent0.PolicyZoo Functions --------- .. autoapisummary:: agent0.add_liquidity_trade agent0.close_long_trade agent0.close_short_trade agent0.open_long_trade agent0.open_short_trade agent0.redeem_withdraw_shares_trade agent0.remove_liquidity_trade Package Contents ---------------- .. py:function:: add_liquidity_trade(trade_amount: fixedpointmath.FixedPoint, base_fee_multiple: float | None = None, priority_fee_multiple: float | None = None, gas_limit: int | None = None, min_apr: fixedpointmath.FixedPoint | None = None, max_apr: fixedpointmath.FixedPoint | None = None) -> agent0.core.base.Trade[HyperdriveMarketAction] Return a trade object for adding liquidity. :param trade_amount: The amount of liquidity you wish to add to the pool. :type trade_amount: FixedPoint :param base_fee_multiple: The base fee multiple for the transaction. :type base_fee_multiple: float | None, optional :param priority_fee_multiple: The priority fee multiple for the transaction. :type priority_fee_multiple: float | None, optional :param gas_limit: The maximum amount of gas used by the transaction. Defaults to `eth_estimateGas` RPC output. :type gas_limit: int | None, optional :param min_apr: Minimum allowable APR after liquidity is added. If this is not met, the trade will not execute. Defaults to the minimum solidity FixedPoint (1e-18) :type min_apr: FixedPoint, optional :param max_apr: Maximum allowable APR after liquidity is added. If this is not met, the trade will not execute. Defaults to the maximum solidity FixedPoint (2**256-1) :type max_apr: FixedPoint, optional :returns: The trade object for adding liquidity to a Hyperdrive pool. :rtype: Trade[HyperdriveMarketAction] .. !! processed by numpydoc !! .. py:function:: close_long_trade(trade_amount: fixedpointmath.FixedPoint, maturity_time: int, slippage_tolerance: fixedpointmath.FixedPoint | None = None, base_fee_multiple: float | None = None, priority_fee_multiple: float | None = None, gas_limit: int | None = None) -> agent0.core.base.Trade[HyperdriveMarketAction] Return a trade object for closing a long. :param trade_amount: The amount of bonds you wish to close. :type trade_amount: FixedPoint :param maturity_time: The token maturity time in seconds. :type maturity_time: int :param slippage_tolerance: Amount of slippage allowed from the trade. If given, then the trade will not execute unless the slippage is below this value. If not given, then execute the trade regardless of the slippage. :type slippage_tolerance: FixedPoint, optional :param base_fee_multiple: The base fee multiple for the transaction. :type base_fee_multiple: float | None, optional :param priority_fee_multiple: The priority fee multiple for the transaction. :type priority_fee_multiple: float | None, optional :param gas_limit: The maximum amount of gas used by the transaction. Defaults to `eth_estimateGas` RPC output. :type gas_limit: int | None, optional :returns: The trade object for closing a long in a Hyperdrive pool. :rtype: Trade[HyperdriveMarketAction] .. !! processed by numpydoc !! .. py:function:: close_short_trade(trade_amount: fixedpointmath.FixedPoint, maturity_time: int, slippage_tolerance: fixedpointmath.FixedPoint | None = None, base_fee_multiple: float | None = None, priority_fee_multiple: float | None = None, gas_limit: int | None = None) -> agent0.core.base.Trade[HyperdriveMarketAction] Return a trade object for closing a short. :param trade_amount: The amount of bonds you wish to close. :type trade_amount: FixedPoint :param maturity_time: The token maturity time in seconds. :type maturity_time: int :param slippage_tolerance: Amount of slippage allowed from the trade. If given, then the trade will not execute unless the slippage is below this value. If not given, then execute the trade regardless of the slippage. :type slippage_tolerance: FixedPoint, optional :param base_fee_multiple: The base fee multiple for the transaction. :type base_fee_multiple: float | None, optional :param priority_fee_multiple: The priority fee multiple for the transaction. :type priority_fee_multiple: float | None, optional :param gas_limit: The maximum amount of gas used by the transaction. Defaults to `eth_estimateGas` RPC output. :type gas_limit: int | None, optional :returns: The trade object for closing a short in a Hyperdrive pool. :rtype: Trade[HyperdriveMarketAction] .. !! processed by numpydoc !! .. py:function:: open_long_trade(trade_amount: fixedpointmath.FixedPoint, slippage_tolerance: fixedpointmath.FixedPoint | None = None, base_fee_multiple: float | None = None, priority_fee_multiple: float | None = None, gas_limit: int | None = None) -> agent0.core.base.Trade[HyperdriveMarketAction] Return a trade object for opening a long. :param trade_amount: The amount of base you wish to use to open a long. :type trade_amount: FixedPoint :param slippage_tolerance: Amount of slippage allowed from the trade. If given, then the trade will not execute unless the slippage is below this value. If not given, then execute the trade regardless of the slippage. :type slippage_tolerance: FixedPoint, optional :param base_fee_multiple: The base fee multiple for the transaction. :type base_fee_multiple: float | None, optional :param priority_fee_multiple: The priority fee multiple for the transaction. :type priority_fee_multiple: float | None, optional :param gas_limit: The maximum amount of gas used by the transaction. Defaults to `eth_estimateGas` RPC output. :type gas_limit: int | None, optional :returns: The trade object for opening a long in a Hyperdrive pool. :rtype: Trade[HyperdriveMarketAction] .. !! processed by numpydoc !! .. py:function:: open_short_trade(trade_amount: fixedpointmath.FixedPoint, slippage_tolerance: fixedpointmath.FixedPoint | None = None, base_fee_multiple: float | None = None, priority_fee_multiple: float | None = None, gas_limit: int | None = None) -> agent0.core.base.Trade[HyperdriveMarketAction] Return a trade object for opening a short. :param trade_amount: The amount of bonds you wish to short. :type trade_amount: FixedPoint :param slippage_tolerance: Amount of slippage allowed from the trade. If given, then the trade will not execute unless the slippage is below this value. If not given, then execute the trade regardless of the slippage. :type slippage_tolerance: FixedPoint, optional :param base_fee_multiple: The base fee multiple for the transaction. :type base_fee_multiple: float | None, optional :param priority_fee_multiple: The priority fee multiple for the transaction. :type priority_fee_multiple: float | None, optional :param gas_limit: The maximum amount of gas used by the transaction. Defaults to `eth_estimateGas` RPC output. :type gas_limit: int | None, optional :returns: The trade object for opening a short in a Hyperdrive pool. :rtype: Trade[HyperdriveMarketAction] .. !! processed by numpydoc !! .. py:function:: redeem_withdraw_shares_trade(trade_amount: fixedpointmath.FixedPoint, base_fee_multiple: float | None = None, priority_fee_multiple: float | None = None, gas_limit: int | None = None) -> agent0.core.base.Trade[HyperdriveMarketAction] Return a trade object for redeeming withdraw shares. :param trade_amount: The amount of withdraw shares you wish to redeem from the pool. :type trade_amount: FixedPoint :param base_fee_multiple: The base fee multiple for the transaction. :type base_fee_multiple: float | None, optional :param priority_fee_multiple: The priority fee multiple for the transaction. :type priority_fee_multiple: float | None, optional :param gas_limit: The maximum amount of gas used by the transaction. Defaults to `eth_estimateGas` RPC output. :type gas_limit: int | None, optional :returns: The trade object for redeeming withdraw shares from a Hyperdrive pool. :rtype: Trade[HyperdriveMarketAction] .. !! processed by numpydoc !! .. py:function:: remove_liquidity_trade(trade_amount: fixedpointmath.FixedPoint, slippage_tolerance: fixedpointmath.FixedPoint | None = None, base_fee_multiple: float | None = None, priority_fee_multiple: float | None = None, gas_limit: int | None = None) -> agent0.core.base.Trade[HyperdriveMarketAction] Return a trade object for removing liquidity. :param trade_amount: The amount of liquidity you wish to remove from the pool. :type trade_amount: FixedPoint :param slippage_tolerance: Amount of slippage allowed from the trade. If given, then the trade will not execute unless the slippage is below this value. If not given, then execute the trade regardless of the slippage. :type slippage_tolerance: FixedPoint, optional :param base_fee_multiple: The base fee multiple for the transaction. :type base_fee_multiple: float | None, optional :param priority_fee_multiple: The priority fee multiple for the transaction. :type priority_fee_multiple: float | None, optional :param gas_limit: The maximum amount of gas used by the transaction. Defaults to `eth_estimateGas` RPC output. :type gas_limit: int | None, optional :returns: * *Trade[HyperdriveMarketAction]* -- The trade object for removing liquidity from a Hyperdrive pool. * *.. warning::* -- Slippage tolerance is not implemented for remove liquidity trades, field will be ignored. .. !! processed by numpydoc !! .. py:class:: Chain(rpc_uri: str, config: Config | None = None) A class that represents a ethereum node. .. !! processed by numpydoc !! .. py:class:: Config The configuration for the chain object. .. !! processed by numpydoc !! .. py:attribute:: log_filename :type: str | None :value: None Path and name of the log file. Won't log to file if None. Defaults to None. .. !! processed by numpydoc !! .. py:attribute:: log_max_bytes :type: int | None :value: None Maximum size of the log file in bytes. Defaults to hyperlogs.DEFAULT_LOG_MAXBYTES. .. !! processed by numpydoc !! .. py:attribute:: log_level_threshold :type: int | None :value: None Threshold for log level in logging. Defaults to hyperlogs.DEFAULT_LOG_LEVEL. .. !! processed by numpydoc !! .. py:attribute:: delete_previous_logs :type: bool :value: False Whether to delete previous log file if it exists. Defaults to False. .. !! processed by numpydoc !! .. py:attribute:: log_to_stdout :type: bool :value: True Whether to log to standard output. Defaults to True. .. !! processed by numpydoc !! .. py:attribute:: log_format_string :type: str | None :value: None Log formatter object. Defaults to None. .. !! processed by numpydoc !! .. py:attribute:: keep_previous_handlers :type: bool :value: False Whether to keep previous handlers. Defaults to False. .. !! processed by numpydoc !! .. py:attribute:: exception_on_policy_error :type: bool :value: True When executing agent policies, whether to raise an exception if an error is encountered. Defaults to True. .. !! processed by numpydoc !! .. py:attribute:: exception_on_policy_slippage :type: bool :value: False When executing agent policies, whether to raise an exception if the slippage is too large. Defaults to False. .. !! processed by numpydoc !! .. py:attribute:: preview_before_trade :type: bool :value: False Whether to preview the position before executing a trade. Defaults to False. .. !! processed by numpydoc !! .. py:attribute:: crash_log_level :type: int :value: 40 The log level to log crashes at. Defaults to error. .. !! processed by numpydoc !! .. py:attribute:: crash_report_stdout_summary :type: bool :value: True Whether to print a summary of the crash report to stdout (if True), or print out the full report (if False). Defaults to True. .. !! processed by numpydoc !! .. py:attribute:: log_to_rollbar :type: bool :value: False Whether to log crash reports to rollbar. Defaults to False. .. !! processed by numpydoc !! .. py:attribute:: rollbar_log_level_threshold :type: int :value: 10 Threshold for log level in rollbar. Defaults to debug (i.e., log all to rollbar). .. !! processed by numpydoc !! .. py:attribute:: rollbar_log_prefix :type: str | None :value: None Additional prefix for this hyperdrive to log to rollbar. .. !! processed by numpydoc !! .. py:attribute:: rollbar_log_filter_func :type: Callable[[Exception], bool] | None :value: None A function that filters exceptions to log to rollbar. The function should return `True` for exceptions that should be filtered from rollbar logging. Defaults to logging all exceptions. .. !! processed by numpydoc !! .. py:attribute:: crash_report_additional_info :type: dict[str, Any] | None :value: None Additional information to include in the crash report. .. !! processed by numpydoc !! .. py:attribute:: always_execute_policy_post_action :type: bool :value: False Whether to execute the policy `post_action` function after non-policy trades. If True, the policy `post_action` function always be called after any agent trade. If False, the policy `post_action` function will only be called after `execute_policy_action`. Defaults to False. .. !! processed by numpydoc !! .. py:attribute:: log_anvil_state_dump :type: bool :value: False Whether to log the anvil state dump in crash reports. Defaults to False. .. !! processed by numpydoc !! .. py:attribute:: calc_pnl :type: bool :value: True Whether to calculate pnl. Defaults to True. .. !! processed by numpydoc !! .. py:attribute:: no_postgres :type: bool :value: False Don't launch postgres connection at all. Expect things to break if this is set to True. .. !! processed by numpydoc !! .. py:attribute:: use_existing_postgres :type: bool :value: False If True, will connect to a remote postgres instance using environmental variables (see env.sample). If False, will manage a local postgres instance. Defaults to False. .. !! processed by numpydoc !! .. py:attribute:: db_port :type: int :value: 5433 The port to bind for the postgres container. Will fail if this port is being used. Defaults to 5433. Not used if `use_existing_postgres` is True. .. !! processed by numpydoc !! .. py:attribute:: remove_existing_db_container :type: bool :value: True Whether to remove the existing container if it exists on container launch. Defaults to True. Not used if `use_existing_postgres` is True. .. !! processed by numpydoc !! .. py:attribute:: backfill_pool_info :type: bool :value: True Determines if we keep the pool info for every block in the database. Defaults to True. .. !! processed by numpydoc !! .. py:attribute:: rng_seed :type: int | None :value: None The seed for the random number generator. Defaults to None. .. !! processed by numpydoc !! .. py:attribute:: rng :type: numpy.random.Generator | None :value: None The experiment's stateful random number generator. Defaults to creating a generator from the provided random seed if not set. .. !! processed by numpydoc !! .. py:attribute:: txn_receipt_timeout :type: float | None :value: None The timeout for waiting for a transaction receipt in seconds. Defaults to 120. .. !! processed by numpydoc !! .. py:attribute:: gas_limit :type: int | None :value: None The maximum gas to use when executing transactions. This gas limit controls any transactions that are executed on the chain. NOTE: the policies `gas_limit` overwrites this value if it is set. .. !! processed by numpydoc !! .. py:attribute:: txn_signature :type: bytes | None :value: None The signature for transactions. Defaults to `0xa0`. .. !! processed by numpydoc !! .. py:attribute:: rpc_uri .. py:attribute:: docker_client :value: None .. py:attribute:: postgres_container :value: None .. py:attribute:: db_session :value: None .. py:attribute:: config :value: None .. py:method:: cleanup() General cleanup of resources of interactive hyperdrive. .. !! processed by numpydoc !! .. py:method:: block_number() -> eth_typing.BlockNumber Get the current block number on the chain. :returns: The current block number :rtype: int .. !! processed by numpydoc !! .. py:method:: block_data(block_identifier: web3.types.BlockIdentifier = 'latest') -> web3.types.BlockData Get the current block on the chain. :param block_identifier: The identifier of the block to get. Defaults to 'latest'. :returns: The current block number :rtype: int .. !! processed by numpydoc !! .. py:method:: block_time() -> web3.types.Timestamp Get the current block time on the chain. :returns: The current block number :rtype: int .. !! processed by numpydoc !! .. py:property:: is_local_chain :type: bool Returns if this object is a local chain. .. !! processed by numpydoc !! .. py:property:: name :type: str Returns the name of the chain, which is the base hostname of the rpc uri. .. !! processed by numpydoc !! .. py:property:: chain_id :type: int Returns the chain id of the chain. .. !! processed by numpydoc !! .. py:method:: init_agent(private_key: str | None = None, public_address: str | None = None, pool: agent0.core.hyperdrive.interactive.hyperdrive.Hyperdrive | None = None, policy: Type[agent0.core.hyperdrive.policies.HyperdriveBasePolicy] | None = None, policy_config: agent0.core.hyperdrive.policies.HyperdriveBasePolicy.Config | None = None, name: str | None = None) -> agent0.core.hyperdrive.interactive.hyperdrive_agent.HyperdriveAgent Initialize an agent object given a private key. .. note:: Due to the underlying bookkeeping, each agent object needs a unique private key. :param private_key: The private key of the associated account. Must be supplied to allow this agent to do any transactions. :type private_key: str, optional :param public_address: The public address of the associated account. This allows this agent to be used for analyzing data. Can't be used in conjunction with private_key. :type public_address: str | None, optional :param pool: An optional pool to set as the active pool. :type pool: LocalHyperdrive, optional :param policy: An optional policy to set as the active policy. :type policy: HyperdrivePolicy, optional :param policy_config: The configuration for the attached policy. :type policy_config: HyperdrivePolicy, optional :param name: The name of the agent. Defaults to the wallet address. :type name: str, optional :returns: The agent object for a user to execute trades with. :rtype: HyperdriveAgent .. !! processed by numpydoc !! .. py:method:: dump_db(save_dir: pathlib.Path) -> None Export the managed database to file. :param save_dir: The output directory to dump the data to. :type save_dir: Path .. !! processed by numpydoc !! .. py:method:: load_db(load_dir: pathlib.Path) -> None Import the managed database from file. :param load_dir: The directory that contains the exported database. :type load_dir: Path .. !! processed by numpydoc !! .. py:class:: Hyperdrive(chain: agent0.core.hyperdrive.interactive.chain.Chain, hyperdrive_address: eth_typing.ChecksumAddress, config: Config | None = None, name: str | None = None) Interactive Hyperdrive class that supports connecting to an existing hyperdrive deployment. .. !! processed by numpydoc !! .. py:class:: Config The configuration for the interactive hyperdrive class. .. !! processed by numpydoc !! .. py:method:: get_hyperdrive_addresses_from_registry(chain: agent0.core.hyperdrive.interactive.chain.Chain, registry_address: str) -> dict[str, eth_typing.ChecksumAddress] :classmethod: Gather deployed Hyperdrive pool addresses. :param chain: The Chain object connected to a chain. :type chain: Chain :param registry_address: The address of the Hyperdrive factory contract. :type registry_address: str :returns: A dictionary keyed by the pool's name, valued by the pool's address :rtype: dict[str, ChecksumAddress] .. !! processed by numpydoc !! .. py:method:: get_hyperdrive_pools_from_registry(chain: agent0.core.hyperdrive.interactive.chain.Chain, registry_address: str) -> Sequence[Hyperdrive] :classmethod: Gather deployed Hyperdrive pool addresses. :param chain: The Chain object connected to a chain. :type chain: Chain :param registry_address: The address of the Hyperdrive registry contract. :type registry_address: str :returns: The hyperdrive objects for all registered pools :rtype: Sequence[Hyperdrive] .. !! processed by numpydoc !! .. py:method:: get_positions(show_closed_positions: bool = False, calc_pnl: bool = False, coerce_float: bool = False) -> pandas.DataFrame :abstractmethod: Gets all current positions of this pool and their corresponding pnl and returns as a pandas dataframe. This function is not implemented for remote hyperdrive, as gathering this data is expensive. In the future, we can explicitly make this call gather data from the remote chain. :param coerce_float: If True, will coerce underlying Decimals to floats. :type coerce_float: bool :param calc_pnl: If the chain config's `calc_pnl` flag is False, passing in `calc_pnl=True` to this function allows for a one-off pnl calculation for the current positions. Ignored if the chain's `calc_pnl` flag is set to True, as every position snapshot will return pnl information. :type calc_pnl: bool, optional :param show_closed_positions: Whether to show positions closed positions (i.e., positions with zero balance). Defaults to False. When False, will only return currently open positions. Useful for gathering currently open positions. When True, will also return any closed positions. Useful for calculating overall pnl of all positions. :type show_closed_positions: bool :returns: A dataframe consisting of currently open positions and their corresponding pnl. :rtype: pd.Dataframe .. !! processed by numpydoc !! .. py:method:: get_trade_events(all_token_deltas: bool = False, coerce_float: bool = False) -> pandas.DataFrame Gets the ticker history of all trades and the corresponding token deltas for each trade. :param all_token_deltas: When removing liquidity that results in withdrawal shares, the events table returns two entries for this transaction to keep track of token deltas (one for lp tokens and one for withdrawal shares). If this flag is true, will return all entries in the table, which is useful for calculating token positions. If false, will drop the duplicate withdrawal share entry (useful for returning a ticker). :type all_token_deltas: bool :param coerce_float: If True, will coerce underlying Decimals to floats. :type coerce_float: bool :returns: A dataframe of trade events. :rtype: pd.Dataframe .. !! processed by numpydoc !! .. py:method:: get_historical_positions(coerce_float: bool = False) -> pandas.DataFrame :abstractmethod: Gets the history of all positions over time and their corresponding pnl and returns as a pandas dataframe. This function is not implemented for remote hyperdrive, as gathering this data is expensive. In the future, we can explicitly make this call gather data from the remote chain. :param coerce_float: If True, will coerce underlying Decimals to floats. :type coerce_float: bool :returns: A dataframe consisting of positions over time and their corresponding pnl. :rtype: pd.Dataframe .. !! processed by numpydoc !! .. py:method:: get_historical_pnl(coerce_float: bool = False) -> pandas.DataFrame :abstractmethod: Gets total pnl for each wallet for each block, aggregated across all open positions. This function is not implemented for remote hyperdrive, as gathering this data is expensive. In the future, we can explicitly make this call gather data from the remote chain. :param coerce_float: If True, will coerce underlying Decimals to floats. :type coerce_float: bool :returns: A dataframe of aggregated wallet pnl per block :rtype: pd.Dataframe .. !! processed by numpydoc !! .. py:property:: hyperdrive_address :type: eth_typing.ChecksumAddress Returns the hyperdrive addresses for this pool. :returns: The hyperdrive addresses for this pool :rtype: ChecksumAddress .. !! processed by numpydoc !! .. py:class:: LocalChain(config: Config | None = None, fork_uri: str | None = None, fork_block_number: int | None = None) Bases: :py:obj:`agent0.core.hyperdrive.interactive.chain.Chain` Launches a local anvil chain in a subprocess, along with a postgres container. .. !! processed by numpydoc !! .. py:class:: Config Bases: :py:obj:`agent0.core.hyperdrive.interactive.chain.Chain.Config` The configuration for the local chain object. .. !! processed by numpydoc !! .. py:attribute:: verbose :type: bool :value: False If True, will print underlying subprocess output to stdout. Defaults to suppressing output. .. !! processed by numpydoc !! .. py:attribute:: dashboard_port :type: int | None :value: None The URL port for the deployed dashboard. Defaults to finding an open port. .. !! processed by numpydoc !! .. py:attribute:: block_time :type: int | None :value: None If None, mines per transaction. Otherwise mines every `block_time` seconds. .. !! processed by numpydoc !! .. py:attribute:: block_timestamp_interval :type: int | None :value: 12 Number of seconds to advance time for every mined block. Uses real time if None. .. !! processed by numpydoc !! .. py:attribute:: chain_host :type: str | None :value: None The host to bind for the anvil chain. Defaults to `127.0.0.1`. .. !! processed by numpydoc !! .. py:attribute:: chain_id :type: int | None :value: None The chain ID for the local anvil chain. .. !! processed by numpydoc !! .. py:attribute:: chain_port :type: int :value: 10000 The port to bind for the anvil chain. Will fail if this port is being used. .. !! processed by numpydoc !! .. py:attribute:: chain_genesis_timestamp :type: int | None :value: None The genesis timestamp (in epoch seconds) for the anvil chain. If None, uses the current time. .. !! processed by numpydoc !! .. py:attribute:: transaction_block_keeper :type: int :value: 10000 The number of blocks to keep transaction records for. Undocumented in Anvil, we're being optimistic here. .. !! processed by numpydoc !! .. py:attribute:: snapshot_dir :type: str | None :value: None The directory where the snapshot will be stored. Defaults to `.interactive_state/snapshot/chain_`. .. !! processed by numpydoc !! .. py:attribute:: load_rng_on_snapshot :type: bool :value: True If True, loading a snapshot also loads the RNG state of the underlying policy. This results in the same RNG state as when the snapshot was taken. If False, will use the existing RNG state before load. Defaults to False. .. !! processed by numpydoc !! .. py:attribute:: manual_database_sync :type: bool :value: False If True, depends on the user to sync the database against the chain by calling `pool.sync_database()`. NOTE if this is `True`, the caller must call `pool.sync_database()` before any references to getting the user's wallet, including any policy actions that require a wallet. Otherwise, the wallet may be out of date. Use this at your own risk. .. !! processed by numpydoc !! .. py:attribute:: crash_log_ticker :type: bool :value: False Whether to log the trade ticker in crash reports. Defaults to False. .. !! processed by numpydoc !! .. py:attribute:: config :value: None .. py:attribute:: dashboard_subprocess :type: subprocess.Popen | None :value: None .. py:method:: cleanup() Kills the subprocess in this class' destructor. .. !! processed by numpydoc !! .. py:method:: get_deployer_account_private_key() -> str Get the private key of the deployer account. :returns: The private key for the deployer account. :rtype: str .. !! processed by numpydoc !! .. py:method:: get_deployer_account() -> eth_account.signers.local.LocalAccount Get the public key of the deployer account. :returns: The public key for the deployer account. :rtype: src .. !! processed by numpydoc !! .. py:method:: get_deployer_address() -> str Get the public key of the deployer account. :returns: The public key for the deployer account. :rtype: src .. !! processed by numpydoc !! .. py:property:: is_local_chain :type: bool Returns if this object is a local chain. .. !! processed by numpydoc !! .. py:method:: mine_blocks(num_blocks: int = 1) -> None Advance time for this chain using the `anvil_mine` RPC call. This function mines the specified amount of blocks with the chain config specified time between blocks. .. note:: This advances the chain for all pool connected to this chain. .. todo:: Add support for minting checkpoints. :param num_blocks: The amount of blocks to advance. Defaults to 1. :type num_blocks: int .. !! processed by numpydoc !! .. py:method:: advance_time(time_delta: int | datetime.timedelta, create_checkpoints: bool = True) -> dict[agent0.core.hyperdrive.interactive.local_hyperdrive.LocalHyperdrive, list[hyperdrivetypes.CreateCheckpointEventFP]] Advance time for this chain using the `evm_mine` RPC call. This function looks at the timestamp of the current block, then mines a block explicitly setting the timestamp to the current block timestamp + time_delta. If create_checkpoints is True, it will also create intermediate checkpoints when advancing time. .. note:: This advances the chain for all pool connected to this chain. .. note:: This function is a best effort attempt at being exact in advancing time, but the final result may be off by a second. :param time_delta: The amount of time to advance. Can either be a `datetime.timedelta` object or an integer in seconds. :type time_delta: int | timedelta :param create_checkpoints: If set to true, will create intermediate checkpoints between advance times. Defaults to True. :type create_checkpoints: bool, optional :returns: Returns a dictionary keyed by the interactive hyperdrive object, with a value of a list of emitted `CreateCheckpoint` events called from advancing time. :rtype: dict[InteractiveHyperdrive, list[CreateCheckpoint]] .. !! processed by numpydoc !! .. py:method:: save_state(save_dir: pathlib.Path | None = None, save_prefix: str | None = None) -> pathlib.Path Saves the interactive state using the `anvil_dumpState` RPC call. Saving/loading state can be done across chains. :param save_dir: The directory to save the state to. Defaults to `{Config.save_state_dir}/{save_prefix}_{current_time}/`, where `Config.save_state_dir` defaults to `./.interactive_state/`. :type save_dir: Path, optional :param save_prefix: If save_dir wasn't provided, prepends an optional prefix to the time suffix for this state. :type save_prefix: str, optional :returns: The path to the saved state. :rtype: str .. !! processed by numpydoc !! .. py:method:: load_state(load_dir: pathlib.Path) -> None :abstractmethod: Loads the interactive state from the `save_state` function. Saving/loading state can be done across chains. .. note:: This feature is currently unavailable. There are issues around load_state, namely: - Anvil load state doesn't load the block number and timestamp. - Anvil load state only loads the current state, not all previous states. - There exists an issue with the underlying yield contract, as there is a `last_updated` var that gets saved, but anvil doesn't load the original timestamp, so the yield contract throws an error. (May be able to solve if we're able to solve issue 1 to correctly load the block number and previous states.) - To load the state in another chain, we need this function to load all original objects created from the saved chain, e.g., interactive_hyperdrive and all agents they contain, and return them from this function. :param load_dir: The directory to load the state from. :type load_dir: Path .. !! processed by numpydoc !! .. py:method:: save_snapshot() -> None Saves a snapshot using the `evm_snapshot` RPC call. The chain can store one snapshot at a time, saving another snapshot overwrites the previous snapshot. Saving/loading snapshot only persist on the same chain, not across chains. .. !! processed by numpydoc !! .. py:method:: load_snapshot() -> None Loads the previous snapshot using the `evm_revert` RPC call. Can load the snapshot multiple times. .. note:: Saving/loading snapshot only persist on the same chain, not across chains. .. note:: Loading a snapshot affects any agent's active pools and policies, and will revert both to the state of the saved snapshot. .. !! processed by numpydoc !! .. py:method:: init_agent(private_key: str | None = None, public_address: str | None = None, pool: agent0.core.hyperdrive.interactive.hyperdrive.Hyperdrive | None = None, policy: Type[agent0.core.hyperdrive.policies.HyperdriveBasePolicy] | None = None, policy_config: agent0.core.hyperdrive.policies.HyperdriveBasePolicy.Config | None = None, name: str | None = None, base: fixedpointmath.FixedPoint | None = None, eth: fixedpointmath.FixedPoint | None = None) -> agent0.core.hyperdrive.interactive.local_hyperdrive_agent.LocalHyperdriveAgent Initializes an agent with initial funding and a logical name. :param private_key: The private key of the associated account. Default is auto-generated. :type private_key: str, optional :param public_address: Must be None for local agents. :type public_address: str | None, optional :param pool: An optional pool to set as the active pool. :type pool: LocalHyperdrive, optional :param policy: An optional policy to set as the active policy. :type policy: HyperdrivePolicy, optional :param policy_config: The configuration for the attached policy. :type policy_config: HyperdrivePolicy, optional :param name: The name of the agent. Defaults to the wallet address. :type name: str, optional :param base: The amount of base to fund the agent with. Defaults to 0. If a private key is provided then the base amount is added to their previous balance. :type base: FixedPoint | None, optional :param eth: The amount of ETH to fund the agent with. Defaults to 0. If a private key is provided then the eth amount is added to their previous balance. :type eth: FixedPoint | None, optional :returns: The agent object for a user to execute trades with. :rtype: LocalHyperdriveAgent .. !! processed by numpydoc !! .. py:method:: get_dashboard_iframe(width: int = 1000, height: int = 800) -> IPython.display.IFrame Embeds the streamlit dashboard into a Jupyter notebook as an IFrame. .. note:: The interactive hyperdrive script must be in a paused state (before cleanup) for the dashboard to connect with the underlying database, otherwise `cleanup` and/or the main thread executed will kill the streamlit server. Passing ``blocking=True`` will block execution of the main script in this function until a keypress is registered. :param width: Width, in pixels, of the IFrame. Defaults to 1000. :type width: int :param height: Height, in pixels, of the IFrame. Defaults to 800. :type height: int :returns: A dashboard IFrame that can be shown in a Jupyter notebook with the `display` command. :rtype: IFrame .. !! processed by numpydoc !! .. py:method:: run_dashboard(blocking: bool = False) -> None Runs the streamlit dashboard in a subprocess connected to interactive hyperdrive. .. note:: The interactive hyperdrive script must be in a paused state (before cleanup) for the dashboard to connect with the underlying database, otherwise `cleanup` and/or the main thread executed will kill the streamlit server. Passing ``blocking=True`` will block execution of the main script in this function until a keypress is registered. :param blocking: If True, will block execution of the main script in this function until a keypress is registered. When in blocking mode, the server will be killed upon return of control to caller. If False, will clean up subprocess in cleanup. :type blocking: bool .. !! processed by numpydoc !! .. py:class:: LocalHyperdrive(chain: agent0.core.hyperdrive.interactive.local_chain.LocalChain, config: Config | None = None, name: str | None = None, deploy: bool = True, hyperdrive_address: eth_typing.ChecksumAddress | str | None = None, backfill_data_start_block: int | None = None, backfill_sample_period: int | None = None) Bases: :py:obj:`agent0.core.hyperdrive.interactive.hyperdrive.Hyperdrive` Interactive Hyperdrive class that supports an interactive interface for running tests and experiments. .. !! processed by numpydoc !! .. py:attribute:: DeployType .. py:class:: Config Bases: :py:obj:`agent0.core.hyperdrive.interactive.hyperdrive.Hyperdrive.Config` The configuration for the local hyperdrive pool. .. !! processed by numpydoc !! .. py:attribute:: data_pipeline_timeout :type: int :value: 60 The timeout for the data pipeline. Defaults to 60 seconds. .. !! processed by numpydoc !! .. py:attribute:: initial_liquidity :type: fixedpointmath.FixedPoint The amount of money to be provided by the `deploy_account` for initial pool liquidity. .. !! processed by numpydoc !! .. py:attribute:: initial_variable_rate :type: fixedpointmath.FixedPoint The starting variable rate for an underlying yield source. .. !! processed by numpydoc !! .. py:attribute:: initial_fixed_apr :type: fixedpointmath.FixedPoint The fixed rate of the pool on initialization. .. !! processed by numpydoc !! .. py:attribute:: initial_time_stretch_apr :type: fixedpointmath.FixedPoint The rate to target for the time stretch. .. !! processed by numpydoc !! .. py:attribute:: factory_checkpoint_duration_resolution :type: int :value: 3600 The resolution for checkpoint durations. .. !! processed by numpydoc !! .. py:attribute:: factory_min_checkpoint_duration :type: int :value: 3600 The factory's minimum checkpoint duration. .. !! processed by numpydoc !! .. py:attribute:: factory_max_checkpoint_duration :type: int :value: 86400 The factory's maximum checkpoint duration. .. !! processed by numpydoc !! .. py:attribute:: factory_min_position_duration :type: int :value: 86400 The factory's minimum position duration. .. !! processed by numpydoc !! .. py:attribute:: factory_max_position_duration :type: int :value: 315360000 The factory's maximum position duration. .. !! processed by numpydoc !! .. py:attribute:: factory_min_circuit_breaker_delta :type: fixedpointmath.FixedPoint The factory's minimum circuit breaker delta. .. !! processed by numpydoc !! .. py:attribute:: factory_max_circuit_breaker_delta :type: fixedpointmath.FixedPoint The factory's maximum circuit breaker delta. .. !! processed by numpydoc !! .. py:attribute:: factory_min_fixed_apr :type: fixedpointmath.FixedPoint The factory's minimum fixed APR. .. !! processed by numpydoc !! .. py:attribute:: factory_max_fixed_apr :type: fixedpointmath.FixedPoint The factory's maximum fixed APR. .. !! processed by numpydoc !! .. py:attribute:: factory_min_time_stretch_apr :type: fixedpointmath.FixedPoint The factory's minimum time stretch rate. .. !! processed by numpydoc !! .. py:attribute:: factory_max_time_stretch_apr :type: fixedpointmath.FixedPoint The factory's maximum time stretch rate. .. !! processed by numpydoc !! .. py:attribute:: factory_min_curve_fee :type: fixedpointmath.FixedPoint The lower bound on the curve fee that governance can set. .. !! processed by numpydoc !! .. py:attribute:: factory_min_flat_fee :type: fixedpointmath.FixedPoint The lower bound on the flat fee that governance can set. .. !! processed by numpydoc !! .. py:attribute:: factory_min_governance_lp_fee :type: fixedpointmath.FixedPoint The lower bound on the governance lp fee that governance can set. .. !! processed by numpydoc !! .. py:attribute:: factory_min_governance_zombie_fee :type: fixedpointmath.FixedPoint The lower bound on the governance zombie fee that governance can set. .. !! processed by numpydoc !! .. py:attribute:: factory_max_curve_fee :type: fixedpointmath.FixedPoint The upper bound on the curve fee that governance can set. .. !! processed by numpydoc !! .. py:attribute:: factory_max_flat_fee :type: fixedpointmath.FixedPoint The upper bound on the flat fee that governance can set. .. !! processed by numpydoc !! .. py:attribute:: factory_max_governance_lp_fee :type: fixedpointmath.FixedPoint The upper bound on the governance lp fee that governance can set. .. !! processed by numpydoc !! .. py:attribute:: factory_max_governance_zombie_fee :type: fixedpointmath.FixedPoint The upper bound on the governance zombie fee that governance can set. .. !! processed by numpydoc !! .. py:attribute:: deploy_type :type: agent0.ethpy.hyperdrive.HyperdriveDeployType The type of deployment to use. If not specified, it will default to ERC4626. .. !! processed by numpydoc !! .. py:attribute:: minimum_share_reserves :type: fixedpointmath.FixedPoint | None :value: None The minimum share reserves. .. !! processed by numpydoc !! .. py:attribute:: minimum_transaction_amount :type: fixedpointmath.FixedPoint The minimum amount of tokens that a position can be opened or closed with. .. !! processed by numpydoc !! .. py:attribute:: circuit_breaker_delta :type: fixedpointmath.FixedPoint The circuit breaker delta defines the maximum delta between the last checkpoint's weighted spot rate and the current spot rate to allow an LP to add liquidity. .. !! processed by numpydoc !! .. py:attribute:: position_duration :type: int :value: 604800 The duration of a position prior to maturity (in seconds). .. !! processed by numpydoc !! .. py:attribute:: checkpoint_duration :type: int :value: 3600 The duration of a checkpoint (in seconds). .. !! processed by numpydoc !! .. py:attribute:: curve_fee :type: fixedpointmath.FixedPoint The LP fee applied to the curve portion of a trade. .. !! processed by numpydoc !! .. py:attribute:: flat_fee :type: fixedpointmath.FixedPoint The LP fee applied to the flat portion of a trade in annualized rates. .. !! processed by numpydoc !! .. py:attribute:: governance_lp_fee :type: fixedpointmath.FixedPoint The portion of the LP fee that goes to governance. .. !! processed by numpydoc !! .. py:attribute:: governance_zombie_fee :type: fixedpointmath.FixedPoint The portion of the zombie interest that is given to governance as a fee. The portion of the zombie interest that will go to LPs is 1 - governance_zombie_fee. .. !! processed by numpydoc !! .. py:method:: get_hyperdrive_pools_from_registry(chain: agent0.core.hyperdrive.interactive.chain.Chain, registry_address: str) -> Sequence[LocalHyperdrive] :classmethod: Gather deployed Hyperdrive pool addresses. :param chain: The Chain object connected to a chain. :type chain: Chain :param registry_address: The address of the Hyperdrive registry contract. :type registry_address: str :returns: The hyperdrive objects for all registered pools :rtype: Sequence[LocalHyperdrive] .. !! processed by numpydoc !! .. py:attribute:: calc_pnl .. py:attribute:: chain .. py:attribute:: data_pipeline_timeout :value: 60 .. py:method:: sync_database(start_block: int | None = None, progress_bar: bool = False, force_backfill: bool = False, backfill_sample_period: int | None = None) -> None Explicitly syncs the database with the chain. This function doesn't need to be explicitly called if `manual_database_sync = False`. The database itself will determine how to append new data to ensure non-duplicated data. We call this function with a start block if we want to skip intermediate blocks. Subsequent calls after can again be `self._deploy_block_number` as long as the call with skipping blocks wrote a row, as the data pipeline checks the latest block entry and starts from there. TODO these functions are not thread safe, need to fix if we expose async functions :param start_block: The block number to start syncing from. Only used if we want to skip blocks in the database. Defaults to ensuring all blocks are synced. :type start_block: int | None, optional :param progress_bar: If True, will show a progress bar. :type progress_bar: bool, optional :param force_backfill: If True, will force backfilling pool info data. Otherwise will look for `chain.config.backfill_pool_info` in the chain config. :type force_backfill: bool, optional :param backfill_sample_period: The sample period to use when backfilling data. Defaults to every block. :type backfill_sample_period: int | None, optional .. !! processed by numpydoc !! .. py:method:: set_variable_rate(variable_rate: fixedpointmath.FixedPoint) -> None Sets the underlying variable rate for this pool. :param variable_rate: The new variable rate for the pool. :type variable_rate: FixedPoint .. !! processed by numpydoc !! .. py:method:: get_pool_config(coerce_float: bool = False) -> pandas.Series Get the pool config and returns as a pandas series. :param coerce_float: If True, will coerce underlying Decimals to floats. :type coerce_float: bool :returns: A pandas series that consists of the deployed pool config. :rtype: pd.Series .. !! processed by numpydoc !! .. py:method:: get_pool_info(coerce_float: bool = False) -> pandas.DataFrame Get the pool info (and additional info) per block and returns as a pandas dataframe. :param coerce_float: If True, will coerce underlying Decimals to floats. :type coerce_float: bool :returns: A pandas dataframe that consists of the pool info per block. :rtype: pd.Dataframe .. !! processed by numpydoc !! .. py:method:: get_checkpoint_info(coerce_float: bool = False) -> pandas.DataFrame Get the previous checkpoint infos per block and returns as a pandas dataframe. :param coerce_float: If True, will coerce underlying Decimals to floats. :type coerce_float: bool :returns: A pandas dataframe that consists of previous checkpoints made on this pool. :rtype: pd.Dataframe .. !! processed by numpydoc !! .. py:method:: get_positions(show_closed_positions: bool = False, calc_pnl: bool = False, coerce_float: bool = False) -> pandas.DataFrame Gets all current positions of this pool and their corresponding pnl and returns as a pandas dataframe. This function only exists in local hyperdrive as only sim pool keeps track of all positions of all wallets. :param show_closed_positions: Whether to show positions closed positions (i.e., positions with zero balance). Defaults to False. When False, will only return currently open positions. Useful for gathering currently open positions. When True, will also return any closed positions. Useful for calculating overall pnl of all positions. Defaults to False. :type show_closed_positions: bool, optional :param calc_pnl: If the chain config's `calc_pnl` flag is False, passing in `calc_pnl=True` to this function allows for a one-off pnl calculation for the current positions. Ignored if the chain's `calc_pnl` flag is set to True, as every position snapshot will return pnl information. :type calc_pnl: bool, optional :param coerce_float: If True, will coerce underlying Decimals to floats. Defaults to False. :type coerce_float: bool :returns: A dataframe consisting of currently open positions and their corresponding pnl. :rtype: pd.Dataframe .. !! processed by numpydoc !! .. py:method:: get_historical_positions(coerce_float: bool = False) -> pandas.DataFrame Gets the history of all positions over time and their corresponding pnl and returns as a pandas dataframe. :param coerce_float: If True, will coerce underlying Decimals to floats. :type coerce_float: bool :returns: A dataframe consisting of positions over time and their corresponding pnl. :rtype: pd.Dataframe .. !! processed by numpydoc !! .. py:method:: get_trade_events(all_token_deltas: bool = False, coerce_float: bool = False) -> pandas.DataFrame Gets the ticker history of all trades and the corresponding token deltas for each trade. :param all_token_deltas: When removing liquidity that results in withdrawal shares, the events table returns two entries for this transaction to keep track of token deltas (one for lp tokens and one for withdrawal shares). If this flag is true, will return all entries in the table, which is useful for calculating token positions. If false, will drop the duplicate withdrawal share entry (useful for returning a ticker). :type all_token_deltas: bool :param coerce_float: If True, will coerce underlying Decimals to floats. :type coerce_float: bool :returns: A dataframe of trade events. :rtype: pd.Dataframe .. !! processed by numpydoc !! .. py:method:: get_historical_pnl(coerce_float: bool = False) -> pandas.DataFrame Gets total pnl for each wallet for each block, aggregated across all open positions. :param coerce_float: If True, will coerce underlying Decimals to floats. :type coerce_float: bool :returns: A dataframe of aggregated wallet pnl per block :rtype: pd.Dataframe .. !! processed by numpydoc !! .. py:class:: HyperdriveBasePolicy(policy_config: Config) Bases: :py:obj:`agent0.core.base.policies.BasePolicy`\ [\ :py:obj:`agent0.ethpy.hyperdrive.HyperdriveReadInterface`\ , :py:obj:`agent0.core.hyperdrive.agent.HyperdriveWallet`\ ] Hyperdrive policy. .. !! processed by numpydoc !! .. py:method:: close_matured_positions(wallet: agent0.core.hyperdrive.agent.HyperdriveWallet, pool_state: agent0.ethpy.hyperdrive.state.PoolState, minimum_trade_amount: fixedpointmath.FixedPoint = FixedPoint(0)) -> list[agent0.core.base.Trade[agent0.core.hyperdrive.HyperdriveMarketAction]] Generate actions to close longs and shorts that have matured. :param wallet: The agent's wallet. :type wallet: HyperdriveWallet :param pool_state: The current state of the Hyperdrive pool. :type pool_state: PoolState :param minimum_trade_amount: A mimimum amount to trade; if the matured position is smaller than this amount then it will not be closed. Defaults to 0. :type minimum_trade_amount: FixedPoint, optional :returns: Is a list of Hyperdrive trade actions for closing matured longs and shorts. :rtype: list[MarketAction] .. !! processed by numpydoc !! .. py:method:: action(interface: agent0.ethpy.hyperdrive.HyperdriveReadInterface, wallet: agent0.core.hyperdrive.agent.HyperdriveWallet) -> tuple[list[agent0.core.base.Trade[agent0.core.hyperdrive.HyperdriveMarketAction]], bool] :abstractmethod: Return an empty list, indicating no action. :param interface: Interface for the market on which this agent will be executing trades (MarketActions). :type interface: HyperdriveReadInterface :param wallet: The agent's wallet. :type wallet: HyperdriveWallet :returns: A tuple where the first element is a list of actions, and the second element defines if the agent is done trading. :rtype: tuple[list[MarketAction], bool] .. !! processed by numpydoc !! .. py:method:: post_action(interface: agent0.ethpy.hyperdrive.HyperdriveReadInterface, trade_results: list[agent0.core.hyperdrive.TradeResult]) -> None Execute any behavior after after the actions specified by the `action` function have been executed. This allows the policy to e.g., do additional bookkeeping based on the results of the executed actions. :param interface: The trading market interface. :type interface: MarketInterface :param trade_results: A list of HyperdriveTradeResult objects, one for each trade made by the agent. The order of the list matches the original order of `agent.action`. HyperdriveTradeResult contains any information about the trade, as well as any errors that the trade resulted in. :type trade_results: list[HyperdriveTradeResult] .. !! processed by numpydoc !! .. py:class:: PolicyZoo Bases: :py:obj:`NamedTuple` All policies in agent0. .. !! processed by numpydoc !! .. py:attribute:: random .. py:attribute:: random_hold .. py:attribute:: smart_long .. py:attribute:: simple_lp .. py:attribute:: lp_and_arb .. py:attribute:: deterministic .. py:method:: describe(policies: list | str | None = None) -> str Describe policies, either specific ones provided, or all of them. :param policies: A policy name string or list of policy names to describe. If not provided, then all available policies are described. :type policies: list | str | None, optional :returns: A string containing the policy descriptions joined by new-lines. :rtype: str .. !! processed by numpydoc !!