<jupyter_start><jupyter_text>⚠ WarningTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gl/OpinionatedGeek%2Fmango-explorer/HEAD?filepath=Liquidation.ipynb) _🏃‍♀️ To run this notebook press the ⏩ icon in the toolbar above._[🥭 Mango Markets](https://mango.markets/) support is available at: [Docs](https://docs.mango.markets/) | [Discord](https://discord.gg/67jySBhxrg) | [Twitter](https://twitter.com/mangomarkets) | [Github](https://github.com/blockworks-foundation) | [Email](mailto:<EMAIL>)  🥭 LiquidationMango Markets margin accounts must hold more assets than liabilities.If a margin account doesn't hold assets worth more than the _maintenance collateral ratio_ (currently 110%) of its liabilities, anyone can 'pay off' some of the liabilities in that account. In return, that payer receives 105% of their tokens back.This process - called '_liquidation_' - continues until the remaining assets are worth more than the _initial collateral ratio_ (currently 120%) of the remaining liabilities, or until there are no more collateral tokens to return to liquidators.<jupyter_code>import logging
import mango

from solana.publickey import PublicKey<jupyter_output><empty_output><jupyter_text>🦺 SafetyLiquidation is how Mango Markets protects accounts from systemic losses.If the collateralisation ratio were allowed to fall below 100%, that would represent a systemic risk to Mango Markets. Funds would have to be taken from the lending pools, affecting all lenders, which may in turn affect their collateralisation ratio and expose them to liquidation, possibly leading to a cascade of liquidations until the system stabilises.Liquidators promptly stepping in to 'buy' liquidatable accounts before they fall to less than 100% collateralisation prevent this instability.  📇 Collateralisation Ratios DetailsWhen trading with leverage on Mango Markets, you start by adding assets to your margin account. Your margin account must hold assets worth more than 120% of the liabilities. This ratio of assets to liabilities is called your '_collateralisation ratio_'.If a new trade would mean your assets would be worth less 120% of the libilities - that your collateralisation ratio would be less than 120% - you will not be allowed to place the trade. No existing trades are closed, you just can't place any new orders.The value of assets and liabilities is derived from the prices from on-chain oracles.Prices change, so even if no new trades are made the value of assets can fall and the liabilities can increase, changing the collateralisation ratio.**If the collateralisation ratio falls below 110%, your margin account can be '_liquidated_', resulting in the loss of some or a all assets in the account.**  💧 Liquidation Process  📇 StepsThe liquidation process involves paying off some or all of one of the liabilities in the under-collateralised margin account. Margin accounts can have liabilities in multiple tokens, but liquidation can only be performed on one token at a time.These are the basic steps to liquidate an account:1. (Optional) Force cancellation of all outstanding orders for the margin account in that market.2. Build and send the `PartialLiquidate` instruction.3. Repeat step 2 (if necessary) with fresh tokens.Step 1 is optional. Open orders can lock funds in an account, preventing liquidation, but it may be desirable for liquidators to optimise their liquidation process by only force-cancelling orders on that margin account's first partial-liquidation. The margin account is unlikely to have been able to open new orders between partial-liquidations if they happen quickly enough.To actually run a liquidator, however, there are probably some additional steps:1. Find all liquidatable margin accounts.2. Pick the most appropriate of these margin accounts, based on that account's collatoralisation and the liquidator's token balances.3. Pick the market with the most value in the margin account's openorders accounts.4. Force cancellation of all outstanding orders for the margin account in that market.5. Build and send the `PartialLiquidate` instruction.6. Convert the received tokens to your desired tokens.7. Repeat from step 2 (if necessary) with fresh tokens.  🏃 RunningThis section allows you to perform a liquidation on a specific `MarginAccount`.To do this you will need:* The `PublicKey` of the margin account - put this in the `MARGIN_ACCOUNT_TO_LIQUIDATE` variable below, and* A wallet with appropriate funds and accounts for Mango Markets liquidation (see [AccountScout](AccountScout.ipynb) for details). The private key for this wallet should be placed in the `id.json` file.You can then 🏃‍♀️ run this notebook by pressing the ⏩ icon in the toolbar at the top of the page.<jupyter_code>MARGIN_ACCOUNT_TO_LIQUIDATE = ""
if __name__ == "__main__":
    logging.getLogger().setLevel(logging.INFO)

    if MARGIN_ACCOUNT_TO_LIQUIDATE == "":
        raise Exception("No margin account to liquidate - try setting the variable MARGIN_ACCOUNT_TO_LIQUIDATE to a margin account public key.")

    context = mango.Context.default()

    # You'll need to load the wallet properly here to be able to liquidate.
    wallet = mango.Wallet([])

    print("Wallet Balances Before:")
    group = mango.Group.load(context)
    balances_before = group.fetch_balances(context, wallet.address)
    mango.TokenValue.report(balances_before)

    prices = group.fetch_token_prices(context)
    margin_account = mango.MarginAccount.load(context, PublicKey(MARGIN_ACCOUNT_TO_LIQUIDATE), group)
    intrinsic_balance_sheets_before = margin_account.get_intrinsic_balance_sheets(group)
    print("Margin Account Before:", intrinsic_balance_sheets_before)
    liquidator = mango.ForceCancelOrdersAccountLiquidator(context, wallet)
    transaction_id = liquidator.liquidate(group, margin_account, prices)
    if transaction_id is None:
        print("No transaction sent.")
    else:
        print("Transaction ID:", transaction_id)
        print("Waiting for confirmation...")

        context.wait_for_confirmation(transaction_id)

        group_after = mango.Group.load(context)
        margin_account_after_liquidation = mango.MarginAccount.load(context, PublicKey(MARGIN_ACCOUNT_TO_LIQUIDATE), group_after)
        intrinsic_balance_sheets_after = margin_account_after_liquidation.get_intrinsic_balance_sheets(group_after)
        print("Margin Account After:", intrinsic_balance_sheets_after)
        print("Wallet Balances After:")
        balances_after = group_after.fetch_balances(context, wallet.address)
        mango.TokenValue.report(balances_after)

        print("Wallet Balances Changes:")
        changes = mango.TokenValue.changes(balances_before, balances_after)
        mango.TokenValue.report(changes)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.06184428492545555, 'fraction_numerical': 0.006073992269464384, 'mean_word_length': 5.042535446205171, 'pattern_counts': {'":': 2, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 7, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '268304', 'license': 'MIT', 'n_tokens_mistral': 1977, 'n_tokens_neox': 1842, 'n_words': 831, 'path': 'Liquidation.ipynb', 'repo_name': 'aak-dev/mango-explorer', 'size': '7264'}