# MarginManager

`MarginManager` is the leveraged trading layer on top of the lending markets. It coordinates cross‑margin accounting, controller-backed borrows, and external swaps (path payments). Positions are recorded on-chain after swaps complete.

{% hint style="info" %}
Responsibilities

* Maintain cross‑margin positions (long/short).
* Borrow through `ReceiptVault` markets with controller checks.
* Validate margin requirements and health factors.
* Finalize positions after external swap completion.
* Coordinate liquidation via the controller.
  {% endhint %}

## Key Functions

* `deposit_collateral(user, asset, amount)`\
  Deposits collateral into the matching vault for the user.
* `withdraw_collateral(user, asset, amount)`\
  Withdraws collateral if health factor remains safe.
* `open_position(user, side, size, leverage)`\
  Initiates a long or short; borrows from the appropriate vault.
* `finalize_open(user, pending_id)`\
  Finalizes a pending open after swap proceeds are transferred in.
* `reduce_position(user, position_id, reduce_size)`\
  Partially closes a position (expects swap + finalize).
* `close_position(user, position_id)`\
  Initiates full close (expects swap + finalize).
* `finalize_close(user, position_id)`\
  Repays debt and settles P/L after swap proceeds are transferred in.
* `get_position(position_id)`\
  Read position details (side, base/quote amounts).
* `get_health_factor(user)`\
  Returns the user's cross‑margin health factor.
* `liquidate(position_id, liquidator)`\
  Liquidates an under‑margined position via the controller.

## Events

* `CollateralDeposited`
* `CollateralWithdrawn`
* `PositionOpened`
* `PositionReduced`
* `PositionClosed`
* `PositionLiquidated`
