Skip to content

Commit

Permalink
Merge pull request #2340 from vegaprotocol/chore/update_master_with_c…
Browse files Browse the repository at this point in the history
…olosseo_II

chore: merge colosseo_II into master
  • Loading branch information
cdummett authored Aug 13, 2024
2 parents 012ebdd + 5b5719b commit 090dc9c
Show file tree
Hide file tree
Showing 33 changed files with 2,729 additions and 732 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/quality_check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ name: "Quality checks"
- cosmicelevator
- palazzo
- colosseo
- colosseo_II

env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Expand Down Expand Up @@ -73,7 +74,7 @@ jobs:
- name: "Run Check file names"
run: |
npx github:vegaprotocol/approbation check-filenames --specs="{./non-protocol-specs/**/*.md,./protocol/**/*.md,./protocol/**/*.ipynb}"
npx github:vegaprotocol/approbation check-filenames --specs="{./non-protocol-specs/**/*.md,./protocol/**/*.md}"
- name: "Run Check Features"
run: |
Expand Down
4 changes: 4 additions & 0 deletions non-protocol-specs/0013-NP-POSE-position-estimate.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ The position estimate request has an additional `include_collateral_increase_in_

The endpoint request contains additional optional argument `scale_liquidation_price_to_market_decimals`. When set to `false` the liquidation price estimates are scaled to asset decimal places, when set to `true` these estimates are scaled to market decimal places.

### Price cap

When a price cap is specified it should be assumed that the estimate is to be provided for a [capped futures](./../protocol/0016-PFUT-product_builtin_future.md#1-product-parameters) market. Margin levels as well collateral increase estimate should be as per fully-collateralised margin [spec](./../protocol/0019-MCAL-margin_calculator.md#fully-collateralised). If in addition to a price cap the `fully_collateralised` flag is set to `true` then the liquidation price estimate should be `nil`.

## Acceptance criteria

1. In isolated margin mode the request with `0` open volume and one or more limit orders specified results in a non-zero order margin in the margin level estimate and margin mode correctly representing isolated margin mode. (<a name="0013-NP-POSE-001" href="#0013-NP-POSE-001">0013-NP-POSE-001</a>)
Expand Down
125 changes: 125 additions & 0 deletions non-protocol-specs/0014-NP-VAMM-bounds-estimations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@

# vAMM Bounds Estimation Calculator


## Summary

The protocol contains the ability for users to create vAMMs which will automatically trade and manage a position on a given market with no further interaction from the user. These are configured through a few different parameters, which uniquely specify the behaviour and volume profile of the vAMM as the price of the market moves, however are not always immediately obvious and intuitive for a user given the set of inputs. As such, it is necessary to provide an API giving canonical conversions between these values.

The API should take a pool's specification parameters and output various metrics useful for a user deciding on vAMM configuration. Concretely, the API should take the parameters:

1. Base Price
1. Upper Price
1. Lower Price
1. Leverage At Upper Price
1. Leverage At Lower Price
1. Commitment Amount
1. Market ID
1. Optional: Party Key

And then return the metrics:

1. Loss on Commitment at Upper Bound
1. Loss on Commitment at Lower Bound
1. Position Size at Upper Bound
1. Position Size at Lower Bound
1. Liquidation Price at Upper Bound
1. Liquidation Price at Lower Bound
1. If `party key` is specified:
1. Approximate trade size on amendment (immediate)
1. Approximate crystallised loss from position rebalancing (immediate)
1. Change in Size at Upper Bound vs current specification
1. Change in Size at Lower Bound vs current specification
1. Change in Loss at Upper Bound vs current specification
1. Change in Loss at Lower Bound vs current specification


## Calculations

There are a few values which are generally useful to calculate many of the above required outputs, so these will be calculated first.

Starting with the average entry price, this value for a given range is equal no matter the absolute volume committed, so can be calculated without reference to the bond or leverage at bounds values. This is taken from the unit liquidity, $L_u$

$$
L_u = \frac{\sqrt{p_u} \sqrt{p_l}}{\sqrt{p_u} - \sqrt{p_l}} ,
$$

where $p_u$ is the price at the upper end of the range (`upper price` for the upper range and `base price` for the lower range) and $p_l$ is the corresponding lower price for the range. With this, the average entry price can be found to be

$$
p_a = L_u \sqrt{p_u} (1 - \frac{L_u}{L_u + \sqrt{p_u}}) ,
$$

where $p_a$ is the average execution price across the range and other values are as defined above. Finally, the risk factor which will be used for calculating leverage at bounds

$$
r_f = \min(l_b, \frac{1}{ (f_s + f_l) \cdotp f_i}) ,
$$

where $l_b$ is the sided value `leverage_at_bounds` (`upper ratio` if the upper band is being considered and `lower ratio` if the lower band is), $f_s$ is the market's sided risk factor (different for long and short positions), $f_l$ is the market's linear slippage component and $f_i$ is the market's initial margin factor. This will result in two separate values to use for $r_f$, one for the lower range and one for the upper range.


### Position at Bounds

With this, the volumes required to trade to the bounds of the ranges are:

$$
P_{v_l} = \frac{r_f b}{p_l (1 - r_f) + r_f p_a} ,
$$
$$
P_{v_u} = \frac{r_f b}{p_u (1 + r_f) - r_f p_a} ,
$$

where $r_f$ is the `short` factor for the upper range and the `long` factor for the lower range, `b` is the current total balance of the vAMM across all accounts, $p_u$ and $p_l$ are as defined above, $P_{v_l}$ is the theoretical volume and the bottom of the lower bound and $P_{v_u}$ is the (absolute value of the) theoretical volume at the top of the upper bound.


### Loss on Commitment at Bound

For the loss on commitment at bound, one needs to use the average entry price, bound price and the position at the bounds

$$
l_c = |(p_a - p_b) \cdot P_b |,
$$

where $P_b$ is the position at bounds (Either $P_{v_l}$ or $P_{v_u}$), $p_a$ is the average entry price and $p_b$ is the price at the corresponding outer bound. Note that this is an absolute value of loss, so outstanding balance at bounds would be `initial balance - $L_c$`.


### Liquidation Prices

Using a similar methodology to the standard estimations for liquidation price and the above calculated values, an estimate for liquidation prices above and below the range can be obtained with

$$
p_{liq} = \frac{b - l_c - P_b \cdot p_b}{|P_b| \cdot (f_l + m_r) - P_b} ,
$$

where $p_{liq}$ is the liquidation price (above or below the specified ranges), $b$ is the original commitment balance, $l_c$ is the loss on commitment at the relevant bound, $P_b$ is the position at the relevant bound, $p_b$ is the price at the bound, $f_l$ is the linear slippage factor for the market and $m_r$ is the market's long or short risk factor (short for the upper price bound as the position will be negative and long for the lower).


## Specified Key

When a key is specified, the existence of any current vAMM should be checked and, if one exists, the above values also calculated for it and populated in the requisite areas of the response to allow easy comparison.


## Acceptance criteria

- For a request specifying (base, upper, lower, leverage_upper, leverage_lower, commitment, short risk factor, long risk factor, market slippage factor) as (1000, 1100, 900, 2, 2, 100, 0.01, 0.01, 0) the response is (<a name="0014-NP-VAMM-001" href="#0014-NP-VAMM-001">0014-NP-VAMM-001</a>):

1. Loss on Commitment at Upper Bound: 8.515
1. Loss on Commitment at Lower Bound: 9.762
1. Position Size at Upper Bound: -0.166
1. Position Size at Lower Bound: 0.201
1. Liquidation Price at Upper Bound: 1633.663
1. Liquidation Price at Lower Bound: 454.545


- For a request specifying (base, upper, lower, leverage_upper, leverage_lower, commitment, short risk factor, long risk factor, market slippage factor) as (1000, 1300, 900, 1, 5, 100, 0.01, 0.01, 0) the response is (<a name="0014-NP-VAMM-004" href="#0014-NP-VAMM-004">0014-NP-VAMM-004</a>):

1. Loss on Commitment at Upper Bound: 10.948
1. Loss on Commitment at Lower Bound: 21.289
1. Position Size at Upper Bound: -0.069
1. Position Size at Lower Bound: 0.437
1. Liquidation Price at Upper Bound: 2574.257
1. Liquidation Price at Lower Bound: 727.273

- A request with an empty upper *or* lower bound price is valid and will return the metrics for the bound which *was* specified with the metrics for the unspecified bound empty. (<a name="0014-NP-VAMM-002" href="#0014-NP-VAMM-002">0014-NP-VAMM-002</a>)
- A request with an empty upper *and* lower bound is invalid and receives an error code back. (<a name="0014-NP-VAMM-003" href="#0014-NP-VAMM-003">0014-NP-VAMM-003</a>)
33 changes: 33 additions & 0 deletions non-protocol-specs/0015-NP-OBES-order-book-estimations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

# AMM Order Book Levels Estimator

Whilst generating a limit order book shape, i.e. the prices and associated volumes available at each price, is trivially achievable by simply aggregating the various component limit orders, this is harder to achieve for the active AMMs on a market. This is due to the fact that the volumes at which they would trade each price level within their range is not immediately obtainable without some calculations. Whilst these calculations are not heavy, and are routinely performed as part of trading, expanding out the entire range of an AMM with a large range may be prohibitive both in time taken (when updating frequently) and also in storage space, as there may be a non-zero volume at every possible tick level over a large range, necessitating a large array in which to store it.

In order to alleviate these issues, a heuristic should be used to govern how these AMMs are expanded out into levels for display, both in terms of how frequently these levels are updated and how far away from the mid price levels are calculated at each price level vs a larger gap. This spec aims to codify that heuristic.

## Update Frequency

The largest improvement to processing requirements from update frequency heuristics comes from the fact that an AMM will only update it's price levels when it is either amended or someone trades with it. Therefore the calculations generating a curve of volumes from AMM prices should be cached between these points and only updated when an AMM is amended or when a trade with an AMM occurs. This can be further improved if all curves from individual AMMs are stored separately alongside an aggregate volume in which case only the impacted AMM curve can be updated whilst all others remain static.

## Update Depth

The second consideration is the depth to which markets should be expanded at every individual price level, and what should be done after this point. As this information is purely used for informational purposes these options can be set (including some sensible defaults) at a per-datanode level rather than mandating a single set across the network. These values should be applicable across markets, so are defined in percentage terms:

1. **amm_full_expansion_percentage**: This is the percentage difference above and below the market mid price to which the AMMs should be fully expanded at each price level.
1. **amm_estimate_step_percentage**: Once above (or below) these bounds the calculation should only occur at larger steps. These step sizes are governed in percentage terms again (and are in reference to a percentage of the mid price).
1. **amm_max_estimated_steps**: The maximum number of estimated steps to return. Once this number have been calculated nothing further is returned.

The calculation of the order book shape should combine these three values by using the `volume to trade between two price levels` calculations utilised by the core engine to iteratively calculate the volume quoted by a given AMM at each price level outwards from the centre. (Note that AMMs which were outside of range at the initial mid price may come into range during the iteration and should be included if so.) Once the percentage full expansion bounds have been reached the gaps between prices become those specified by the step percentage value, however the calculation remains the same beyond that.


## Acceptance criteria

- With `amm_full_expansion_percentage` set to `5%`, `amm_estimate_step_percentage` set to `1%`and `amm_max_estimated_steps` set to `10`, when the mid-price is 100 then the order book expansion should return (<a name="0015-NP-OBES-001" href="#0015-NP-OBES-001">0015-NP-OBES-001</a>):
- Volume levels at every valid tick between `95` and `105`
- Volume levels outside that at every `1` increment from `106` to `115` and `94` to `85`
- No volume levels above `115` or below `85`

- With `amm_full_expansion_percentage` set to `3%`, `amm_estimate_step_percentage` set to `5%`and `amm_max_estimated_steps` set to `2`, when the mid-price is 100 then the order book expansion should return (<a name="0015-NP-OBES-002" href="#0015-NP-OBES-002">0015-NP-OBES-002</a>):
- Volume levels at every valid tick between `97` and `103`
- Volume levels outside that at every `1` increment from `108` to `116` and `92` to `87`
- No volume levels above `116` or below `87`
3 changes: 2 additions & 1 deletion protocol/0001-MKTF-market_framework.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ Data:
- If this is negative e.g. -3 this means that the smallest order and position is of size 1000.
- Accepted values are `-6,...,-1,0,1,2,...,6`.
- **Tick size**: the minimum change in quote price for the market. Order prices and offsets for pegged orders must be given as an exact multiple of the tick size. For example if the tick size is 0.02 USD. then a price of 100.02 USD is acceptable and a price of 100.03 USD is not. The tick size of a market can be updated through governance. Note, the tick size should be specified in terms of the market decimals, e.g. for a scaled tick size of `0.02` (USDT) in a market using `5` decimal places, the tick size would be set to `2000`.
- **Liquidation strategy**: A field specifying the liquidation strategy for the market. Please refer to [0012-POSR-position_resolution](./0012-POSR-position_resolution.md#managing-networks-position) for supported strategies.
- **Liquidation strategy**: A field specifying the liquidation strategy for the market. Please refer to [0012-POSR-position_resolution](./0012-POSR-position_resolution.md#managing-networks-position) for supported strategies.
- **Transaction Prioritisation**: A boolean, whether to enable [transaction prioritisation](./0092-TRTO-trading_transaction_ordering.md).

Note: it is agreed that initially the integer representation of the full precision of both order and positions can be required to fit into an int64, so this means that the largest position/order size possible reduces by a factor of ten for every extra decimal place used. This also means that, for instance, it would not be possible to create a `BTCUSD` market that allows order/position sizes equivalent to 1 sat.

Expand Down
1 change: 1 addition & 0 deletions protocol/0004-AMND-amends.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
- Attempting to alter details on a cancelled order will cause the amend to be rejected (<a name="0004-AMND-018" href="#0004-AMND-018">0004-AMND-018</a>). For product spot: (<a name="0004-AMND-046" href="#0004-AMND-046">0004-AMND-046</a>)
- Attempting to alter details on an expired order will cause the amend to be rejected (<a name="0004-AMND-019" href="#0004-AMND-019">0004-AMND-019</a>). For product spot: (<a name="0004-AMND-047" href="#0004-AMND-047">0004-AMND-047</a>)
- Amending expiry time of an active GTT order to a past time whilst also simultaneously amending the price of the order will cause the order to immediately expire with the order details updated to reflect the order details requiring amendment (<a name="0004-AMND-029" href="#0004-AMND-029">0004-AMND-029</a>). For product spot: (<a name="0004-AMND-048" href="#0004-AMND-048">0004-AMND-048</a>)
- An amendment which would result in the margin requirement for the order being smaller than `spam.order.minimalMarginQuantumMultiple` should fail with the order remaining unchanged (<a name="0004-AMND-061" href="#0004-AMND-061">0004-AMND-061</a>)

For a party with no position on a given market:

Expand Down
2 changes: 1 addition & 1 deletion protocol/0012-POSR-position_resolution.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ Currently only one liquidation strategy is supported and its defined by the foll
- `disposal time step` (min: `1s`, max: `1h`): network attempts to unload its position in a given market every time it goes out of auction and then every `disposal time step` seconds as long as market is not in auction mode and while the network's position is not equal to `0`,
- `disposal fraction` (min: `0.01`, max: `1`): fraction of network's current open volume that it will try to reduce in a single disposal attempt,
- `full disposal size` (min: `0`, max: `max int`): once net absolute value of network's open volume is at or below that value, the network will attempt to dispose the remaining amount in one go,
- `disposal slippage range` (decimal `>0` with a value of `0.1` interpreted as `10%`, existing markets to default to their current SLA range). Just like [SLA range](./0044-LIME-lp_mechanics.md) these are taken from `mid_price` during continuous trading or indicative uncrossing price during auctions so the lower bound becomes `max(0,price x (1-range)` and upper bound `price x (1+range)`.
- `disposal slippage range` (decimal `>0` with default of `0.1` which is interpreted as `10%`, existing markets to default to their current SLA range). Just like [SLA range](./0044-LIME-lp_mechanics.md) these are taken from `mid_price` during continuous trading or indicative uncrossing price during auctions so the lower bound becomes `max(0,price x (1-range)` and upper bound `price x (1+range)`.
- `max fraction of book side within bounds consumed` (min: `0`, max: `1`): once the network chooses the size of its order (`s_candidate`) the effective size will be calculated as `s_effective=min(m*N, s_candidate)`, where `N` is the sum of volume (on the side of the book with which the network's order will be matching) that falls within the range implied by the `disposal slippage range` and `m` is the `max fraction of book side within liquidity bounds consumed`.
When vAMMs are implemented and provide liquidity then volume implied by vAMMs that lies within the relevant range must be included in the calculation.

Expand Down
7 changes: 5 additions & 2 deletions protocol/0014-ORDT-order_types.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ Therefore the trigger level of a stop order moves with the market allowing the t

- In markets which allow leverage. If the trader's position size moves to zero exactly, and they have no open orders, all stop orders will be cancelled.

- In spot markets, as their is no concept of a position, the trader will need to lock the funds required to execute the wrapped order in the holding account even before the stop order is triggered. Refer to section [spot trading](./0080-SPOT-product_builtin_spot.md#7-trading) for the calculation of the required funds.


### Iceberg / transparent iceberg orders

On centralised exchanges, icebergs are a type of order that enables a trader to make an order with a relatively small visible "display quantity" and a larger hidden total size.
Expand Down Expand Up @@ -426,8 +429,8 @@ In Spot market, for multiple iceberg orders submitted as a batch of orders with

## Spot

- A wrapped buy order will be rejected when triggered if the party doesn't have enough of the required quote asset to cover the order. (<a name="0014-ORDT-163" href="#0014-ORDT-163">0014-ORDT-163</a>)
- A wrapped sell order will be rejected when triggered if the party doesn't have enough of the required base asset to cover the order. (<a name="0014-ORDT-164" href="#0014-ORDT-164">0014-ORDT-164</a>)
- A trader submitting a stop order wrapping a buy limit order will have the funds required to execute that order locked in the relevant holding account for the quote asset. (<a name="0014-ORDT-163" href="#0014-ORDT-163">0014-ORDT-163</a>)
- A trader submitting a stop order wrapping a sell limit order will have the funds required to execute that order locked in the relevant holding account for the base asset (<a name="0014-ORDT-164" href="#0014-ORDT-164">0014-ORDT-164</a>)

### See also

Expand Down
Loading

0 comments on commit 090dc9c

Please sign in to comment.