mellow_sdk

Backtest

class mellow_sdk.backtest.Backtest(strategy: mellow_sdk.strategies.AbstractStrategy, portfolio: Optional[mellow_sdk.portfolio.Portfolio] = None)
Backtest emulate portfolio behavior on historical data.
Collects and process portfolio state for each event in historical data.
Returns in a convenient form for analyzing the results
backtest(df: polars.internals.frame.DataFrame) Tuple[mellow_sdk.history.PortfolioHistory, mellow_sdk.history.RebalanceHistory, mellow_sdk.history.UniPositionsHistory]
1) Calls AbstractStrategy.rebalance for every market action with.
2) The return of AbstractStrategy.rebalance is a name of strategy action e.g.
‘init’, ‘rebalance’, ‘stop’, ‘some_cool_action’, None. When there is no strategy action rebalance returns None.
3) Add Strategy action to RebalanceHistory
4) Add Porfolio snapshot to PortfolioHistory
5) Add Porfolio snapshot to UniPositionsHistory

You can call AbstractStrategy.rebalance with any arguments, as it takes *args, **kwargs.
Note that ‘timestamp’, ‘price’ and ‘portfolio’ is required.
df

df with pool events, or df with market data. df format is [(‘timestamp’: datetime, ‘price’ : float)]

Returns

History classes that store different portfolio stapshots.

PortfolioHistory - keeps portfolio snapshots such as: value, fees, etc.
RebalanceHistory - keeps strategy actions, such as init ot rebalances.
UniPositionsHistory - keeps information about opened UniV3 positions.

Data

class mellow_sdk.data.PoolDataUniV3(pool: mellow_sdk.primitives.Pool, mints: Optional[polars.internals.frame.DataFrame] = None, burns: Optional[polars.internals.frame.DataFrame] = None, swaps: Optional[polars.internals.frame.DataFrame] = None, full_df: Optional[polars.internals.frame.DataFrame] = None)

PoolDataUniV3 contains data for backtesting.

pool

UniswapV3 Pool data.

mints

UniswapV3 mints data.

burns

UniswapV3 burns data.

swaps

UniswapV3 swaps data.

full_df

All UniswapV3 events data.

class mellow_sdk.data.DownloadFromS3(data_dir: str, bucket_name: str = 'mellow-public-data')

DownloadFromS3 downloads data from S3 bucket.

data_dir

Directory where data will be downloaded.

bucket_name

S3 bucket name.

check_dir() None

Check if data directory exists. If not, create it.

download_files() None

Download all files from S3 bucket.

get_file_from_s3(file: str) None

Download file from S3 bucket and save it to directory.

Parameters

file – File name.

get_last_files() List[str]

Get last files from S3 bucket.

Returns

List of latest files.

class mellow_sdk.data.RawDataUniV3(pool: mellow_sdk.primitives.Pool, data_dir: str, reload_data: bool = False)

Load data from folder, preprocess and Return PoolDataUniV3 instance.

pool

UniswapV3 Pool meta information.

data_dir

Directory of data.

reload_data

If True, reload data from S3.

check_files() bool

Check if all files are in the directory.

Returns

True if all files are in the directory.

load_burns() polars.internals.frame.DataFrame

Read burns events from csv and preprocess.

Returns

Preprocessed burns events data as dataframe.

load_from_folder() mellow_sdk.data.PoolDataUniV3

Check if directory exists and load data from it. If not, create it. Load mints, burns, swaps events from folder and preprocess them. Create all UniV3 events dataframe. Create PoolDataUniV3 object.

Returns

PoolDataUniV3` object.

load_mints() polars.internals.frame.DataFrame

Read mints events from csv and preprocess.

Returns

Preprocessed mints events data as dataframe.

load_swaps() polars.internals.frame.DataFrame

Read burns events from csv and preprocess.

Returns

Preprocessed swaps events data as dataframe.

class mellow_sdk.data.SyntheticData(pool: mellow_sdk.primitives.Pool, start_date: datetime.datetime = datetime.datetime(2022, 1, 1, 0, 0), end_date: datetime.datetime = datetime.datetime(2022, 12, 31, 0, 0), frequency: str = '1d', init_price: float = 1.0, mu: float = 0, sigma: float = 0.1, seed: int = 42)
SyntheticData generates UniswapV3 synthetic exchange data (swaps df).
Generates by sampling Geometric Brownian Motion.
pool

UniswapV3 Pool meta information.

start_date

Generating starting date. (example ‘1-1-2022’)

end_date

Generating ending date. (example ‘31-12-2022’)

frequency

Generating frequency. (example ‘1d’)

init_price

Initial price.

mu

Expectation of normal distribution.

sigma

Variance of normal distribution.

seed

Seed for random generator.

generate_data() mellow_sdk.data.PoolDataUniV3

Generate synthetic UniswapV3 exchange data.

Returns

PoolDataUniV3 instance with synthetic swaps data.

class mellow_sdk.data.DownloaderBinanceData(pair_name: str, interval: str, start_date: str, end_date: str, config_path: str, data_dir: str)

Download pair data from binance and write csv to data folder.

pair_name

‘ethusdc’ or other

interval

Binance interval string, e.g.: ‘1m’, ‘3m’, ‘5m’, ‘15m’, ‘30m’, ‘1h’, ‘2h’, ‘4h’, ‘6h’, ‘8h’, ‘12h’, ‘1d’, ‘3d’, ‘1w’

start_date

String in format ‘%d-%M-%Y’ (utc time format), (example ‘05-12-2018’)

end_date

String in format ‘%d-%M-%Y’ (utc time format)

config_path

path to yml config with config[‘binance’][‘api_key’], config[‘binance’][‘api_secret’]

data_dir

path to data folder

get() pandas.DataFrame

Get market data from Binance.

Returns

pandas dataframe that was written to the /data/f’{pair_name}_{interval}_{start_str}_{end_str}.csv’

History

class mellow_sdk.history.PortfolioHistory
PortfolioHistory accumulate snapshots and can calculate stats over time from snapshots.
Each time add_snapshot method is called it remembers current state in time.
All tracked values then can be accessed via to_df method that will return a pl.Dataframe.
add_snapshot(snapshot: dict) None

Add portfolio snapshot to history.

Parameters

snapshot – Dict of portfolio params.

calculate_apy_for_col(df: polars.internals.frame.DataFrame, from_col: str, to_col: str) polars.internals.frame.DataFrame

Calculate APY for metric.

Parameters
  • df – Dataframe with metrics.

  • from_col – Metric column name.

  • to_col – Name for new column with metric’s APY.

Returns

Dataframe consisting APY metric.

calculate_fees(df: polars.internals.frame.DataFrame) polars.internals.frame.DataFrame
Calculate X and Y fees of Uniswap positions as sum over all positions.
Parameters

df – Portfolio history DataFrame.

Returns

Dataframe consisting of two columns total_fees_x, total_fees_y.

calculate_g_apy(df: polars.internals.frame.DataFrame) polars.internals.frame.DataFrame

Calculate gAPY. gAPY is a strategy profitability metric, which means how much a portfolio value is better than simple holding. More details can be found here: https://twitter.com/0xAlexEuler/status/1503444182257393666?s=20&t=VyzSBZEemZZIxc3AalXqQA

Parameters

df – Dataframe with total_value_to, hold_to_x.

Returns

Dataframe consisting gAPY metric.

calculate_ils(df: polars.internals.frame.DataFrame) polars.internals.frame.DataFrame
Calculate impermanent loss separately in X and Y currencies as sum of positions IL.
Parameters

df – Portfolio history DataFrame.

Returns

Dataframe consisting of two columns total_il_x, total_il_y.

calculate_stats() polars.internals.frame.DataFrame

Calculate all statistics for portfolio. Main function of class.

Returns

Portfolio statistics dataframe.

calculate_value_to(df: polars.internals.frame.DataFrame) polars.internals.frame.DataFrame
Calculates:
total_value_to_x - total_value denominated in X,
total_value_to_y - total_value denominated in Y,
total_fees_to_x - total_fees denominated in X,
total_fees_to_y - total_fees denominated in Y,
hold_to_x - total_value denominated in X for corresponding hold strategy,
hold_to_y - total_value denominated in Y for corresponding hold strategy.
Parameters

df – Portfolio history DataFrame with cols from PortfolioHistory.calculate_values, PortfolioHistory.calculate_ils, PortfolioHistory.calculate_fees.

Returns

Dataframe consisting of ‘total_value_…’ columns.

calculate_values(df: polars.internals.frame.DataFrame) polars.internals.frame.DataFrame

Calculate amount of X and amount of Y in Portfolio.

Parameters

df – Portfolio history DataFrame.

Returns

dataframe consisting of two columns total_value_x, total_value_y.

to_df() polars.internals.frame.DataFrame

Transform list of portfolio snapshots to data frame.

Returns

Portfolio history data frame.

class mellow_sdk.history.RebalanceHistory
RebalanceHistory tracks Strategy actions (portfolio rebalances) over time.
Each time add_snapshot method is called class remembers action.
All actions can be accessed via to_df method that will return a pl.Dataframe.
add_snapshot(timestamp: datetime.datetime, portfolio_action: Optional[str])

Add portfolio action to memory.

Parameters
  • timestamp – Timestamp of snapshot.

  • portfolio_action – Name of portfolio action or None. Usually it takes from ‘’AbstractStrategy.rebalance`` output.

to_df() pandas.DataFrame
Transform list of strategy actions to data frame.
Returns

Data frame of strategy actions, except None actions.

class mellow_sdk.history.UniPositionsHistory

UniPositionsHistory tracks UniswapV3 positions over time. Each time add_snapshot method is called it remembers all UniswapV3 positions at current time. All tracked values then can be accessed via to_df method that will return a pl.Dataframe.

add_snapshot(timestamp: datetime.datetime, positions: dict) None

Add Uniswap position snapshot to history.

Parameters
  • timestamp – Timestamp of snapshot.

  • positions – List of Uniswap positions.

to_df() polars.internals.frame.DataFrame

Transform list of Uniswap positions snapshots to data frame.

Returns

Uniswap positions history data frame.

Portfolio

class mellow_sdk.portfolio.Portfolio(name: str, positions: Optional[List[mellow_sdk.positions.AbstractPosition]] = None)

Portfolio is a container for several open positions.

name

Unique name for the position.

positions

List of initial positions.

append(position: mellow_sdk.positions.AbstractPosition) None

Add position to portfolio.

Parameters

position – Any AbstractPosition instance.

get_last_position() mellow_sdk.positions.AbstractPosition

Get last position from portfolio.

Returns

Last position in portfolio.

get_position(name: str) mellow_sdk.positions.AbstractPosition

Get position from portfolio by name.

Parameters

name – Position name.

Returns

AbstractPosition instance.

position_names() List[str]

Get list of position names in portfolio.

Returns

List of all position names in portfolio.

positions_list() List[mellow_sdk.positions.AbstractPosition]

Get list of all positions in portfolio.

Returns

List of all positions in portfolio.

remove(name: str) None

Remove position from portfolio by its name.

Parameters

name – Position name.

rename_position(current_name: str, new_name: str) None

Rename position in portfolio by its name.

Parameters
  • current_name – Current name of position.

  • new_name – New name for position.

snapshot(timestamp: datetime.datetime, price: float) dict
Get portfolio snapshot.
Used in PortfolioHistory.add_snapshot() to collect backtest data.
Parameters
  • timestamp – Timestamp of snapshot.

  • price – Current price of X in Y currency.

Returns: Positions snapshot.

to_x(price: float) float

Get total value of portfolio denominated to X.

Parameters

price – Current price of X in Y currency.

Returns

Total value of portfolio denominated in X.

to_xy(price: float) Tuple[float, float]

Get amount of X and amount of Y in portfolio.

Parameters

price – Current price of X in Y currency.

Returns

(amount of X, amount of Y)

to_y(price: float) float

Get total value of portfolio expressed in Y.

Parameters

price – Current price of X in Y currency.

Returns

Total value of portfolio denominated in Y.

Positions

class mellow_sdk.positions.AbstractPosition(name: str)

AbstractPosition is an abstract class for Position and Portfolio classes.

name

Unique name for the position.

rename(new_name: str) None

Rename position.

Parameters

position. (New name for) –

abstract snapshot(timestamp: datetime.datetime, price: float) dict
Get a snapshot of the position. Used in Portfolio.snapshot to create a snapshot
of the entire portfolio when backtesting.
Parameters
  • timestamp – Timestamp of snapshot.

  • price – Current price of X in Y currency.

Returns: Position snapshot.

abstract to_x(price: float) float

Return amount of X and Y in vault expressed in X currency.

Parameters

price – Current price of X in Y currency.

Returns

Total value of vault expressed in X.

abstract to_xy(price: float) Tuple[float, float]

Get amount of X and amount of Y in vault.

Parameters

price – Current price of X in Y currency.

Returns

(amount of X, amount of Y)

abstract to_y(price: float) float

Return amount of X and Y in vault expressed in Y currency.

Parameters

price – Current price of X in Y currency.

Returns

Total value of vault expressed in Y.

class mellow_sdk.positions.BiCurrencyPosition(name: str, swap_fee: float, gas_cost: float, x: Optional[float] = None, y: Optional[float] = None, x_interest: Optional[float] = None, y_interest: Optional[float] = None)

BiCurrencyPosition is a class corresponding to currency pair vault.

name

Unique name for the position.

swap_fee

Exchange fee expressed as a percentage.

gas_cost

Gas costs, expressed in Y currency.

x

Amount of asset X.

y

Amount of asset Y.

x_interest

Interest on currency X deposit expressed as a daily percentage yield.

y_interest

Interest on currency Y deposit expressed as a daily percentage yield.

deposit(x: float, y: float) None

Deposit X currency and Y currency to position.

Parameters
  • x – Value of X currency.

  • y – Value of Y currency.

interest_gain(date: datetime.datetime) None

Gain interest on deposit X, deposit Y. Note that you can only gain one time per day.

Parameters

date – Gaining date.

rebalance(x_fraction: float, y_fraction: float, price: float) None

Rebalance bi-currency vault with respect to their proportion. Note that the sum of x_fraction and y_fraction must be equal to 1.

Parameters
  • x_fraction – Fraction of X after rebalance. from 0 to 1.

  • y_fraction – Fraction of Y after rebalance. from 0 to 1.

  • price – Current price of X in Y currency.

snapshot(timestamp: datetime.datetime, price: float) dict
Get a snapshot of the position. Used in Portfolio.snapshot to create a snapshot
of the entire portfolio when backtesting.
Parameters
  • timestamp – Timestamp of snapshot.

  • price – Current price of X in Y currency.

Returns: Position snapshot.

swap_x_to_y(dx: float, price: float) float

Swap some X to Y.

Parameters
  • dx – Amount of X to be swapped.

  • price – Current price of X in Y currency.

Returns

Amount of Y was got.

swap_y_to_x(dy: float, price: float) float

Swap some Y to X.

Parameters
  • dy – Amount of Y to be swapped.

  • price – Current price of X in Y currency.

Returns

Amount of X was got.

to_x(price: float) float

Return amount of X and Y in vault expressed in X currency.

Parameters

price – Current price of X in Y currency

Returns

Total value of vault expessed in X

to_xy(price: float) Tuple[float, float]

Get amount of X and amount of Y in vault

Parameters

price – Current price of X in Y currency.

Returns

(amount of X, amount of Y)

to_y(price: float) float

Return amount of X and Y in vault expressed in Y currency.

Parameters

price – Current price of X in Y currency.

Returns

Total value of vault expessed in Y.

withdraw(x: float, y: float) Tuple[float, float]

Withdraw x amount of X currency and y amount of Y currency from position.

Parameters
  • x – Value of X currency.

  • y – Value of Y currency.

Returns

x amount withdrawn, y amount withdrawn.

withdraw_fraction(fraction: float) Tuple[float, float]

Withdraw percent of X currency and percent of Y currency from position.

Parameters

fraction – Percent from 0 to 1.

Returns

X amount withdrawn, Y amount withdrawn.

class mellow_sdk.positions.UniV3Position(name: str, lower_price: float, upper_price: float, fee_percent: float, gas_cost: float)

UniV3Position is a class corresponding to one open UniswapV3 interval. It’s defined by lower and upper bounds lower_price, upper_price and pool fee percent fee_percent.

name

Unique name for the position.

lower_price

Lower bound of the interval (price).

upper_price

Upper bound of the interval (price).

fee_percent

Amount of fee expressed as a percentage.

gas_cost

Gas costs, expressed in Y currency.

burn(liq: float, price: float) Tuple[float, float]

Burn some liquidity from UniswapV3 position.

Parameters
  • liq – Value of liquidity to burn.

  • price – Current price of X in Y currency.

Returns

(X received after burn, Y received after burn).

charge_fees(price_0: float, price_1: float) None

Charge fees for swap.

Parameters
  • price_0 – Price before swap.

  • price_1 – Price after swap.

collect_fees() Tuple[float, float]

Collect all gained fees.

Returns

Value of X fees, value of Y fees.

deposit(x: float, y: float, price: float) None

Deposit X and Y to position.

Parameters
  • x – Value of X currency.

  • y – Value of Y currency.

  • price – Current price of X in Y currency.

impermanent_loss(price: float) Tuple[float, float]

Calculate impermanent loss separately in X and Y currencies.

Parameters

price – Current price of X in Y currency.

Returns

Value of X il, value of Y il.

impermanent_loss_to_x(price: float) float

Calculate impermanent loss denominated in X.

Parameters

price – Current price of X in Y currency.

Returns

Value of X il.

impermanent_loss_to_y(price: float) float

Calculate impermanent loss denominated in Y.

Parameters

price – Current price of X in Y currency.

Returns

Value of Y il.

mint(x: float, y: float, price: float) None

Mint X and Y to UniswapV3 interval.

Parameters
  • x – Value of X currency.

  • y – Value of Y currency.

  • price – Current price of X in Y currency.

snapshot(timestamp: datetime.datetime, price: float) dict
Get a snapshot of the position. Used in Portfolio.snapshot to create a snapshot
of the entire portfolio when backtesting.
Parameters
  • timestamp – Timestamp of snapshot

  • price – Current price of X in Y currency

Returns: Position snapshot

to_x(price: float) float

Get value of UniswapV3 position expressed in X.

Parameters

price – Current price of X in Y currency.

Returns

Total value of UniswapV3 position expressed in X.

to_xy(price) Tuple[float, float]

Get amount of X and amount of Y in position.

Parameters

price – Current price of X in Y currency.

Returns

amount of X and amount of Y in position.

to_y(price: float) float

Get value of UniswapV3 position expressed in Y.

Parameters

price – Current price of X in Y currency.

Returns

Total value of UniswapV3 position expressed in Y.

withdraw(price: float) Tuple[float, float]

Withdraw all liquidity from UniswapV3 position.

Parameters

price – Current price of X in Y currency.

Returns

X amount withdrawn, Y amount withdrawn.

Primitives

class mellow_sdk.primitives.Fee(value)

Fee Enum class defines available fees for UniV3 pools. Currently 3 values are available: 0.05%, 0.3%, 1%. The actual enum values are fee * 1_000_000, i.e. 0.05% enum value is integer 500.

property percent: float

Returns: UniswapV3 fee in form of 0.0005, 0.003, 0.01.

property spacing: int

Returns: Tick spacing for this fee 10, 60 or 200

class mellow_sdk.primitives.Token(value)

Token represents one of mainnet tokens and contains some additional data line address and decimals. This class is ordered according to token address. E.g. Token.WBTC < Token.USDC.

property address: str

Returns: Mainnet address of the token.

property decimals: int

Returns: Decimals of the token.

class mellow_sdk.primitives.Pool(tokenA: mellow_sdk.primitives.Token, tokenB: mellow_sdk.primitives.Token, fee: mellow_sdk.primitives.Fee)

Pool represents a mainnet UniV3 pool.

tokenA

First token of the pool.

tokenB

Second token of the pool.

fee

Pool fee.

property address: str

Returns: Pool mainnet address.

property decimals_diff: int

Difference between token0 and token1 decimals. Used for conversion of price from wei to eth.

Returns

Decimal difference between Tokens.

property fee: mellow_sdk.primitives.Fee

Returns: Fee of the pool.

property l_decimals_diff: float

Used for conversion of liquidity from wei to eth.

Returns

Decimal difference between Tokens in Eth.

property name: str

Unique name for the pool.

Returns

Pool unique name for the pool.

property tick_diff: int

Used for conversion of tick from wei to eth.

Returns

Tick diff. tick(eth/btc) - tick(wei/satoshi)

property token0: mellow_sdk.primitives.Token

Returns: First token name.

property token1: mellow_sdk.primitives.Token

Returns: Second token name.

Strategies

class mellow_sdk.strategies.AbstractStrategy(name: Optional[str] = None)

AbstractStrategy is an abstract class for Strategies.

name

Unique name for the instance.

abstract rebalance(*args, **kwargs) Optional[str]

Rebalance implementation.

Parameters
  • args – Any args.

  • kwargs – Any kwargs.

Returns

Name of event or None if there was no event.

class mellow_sdk.strategies.UniV3Passive(lower_price: float, upper_price: float, pool: mellow_sdk.primitives.Pool, gas_cost: float, name: Optional[str] = None)

UniV3Passive is the passive strategy on UniswapV3, i.e. mint one interval and wait.

lower_price

Lower bound of the interval

upper_price

Upper bound of the interval

gas_cost

Gas costs, expressed in currency

pool

UniswapV3 Pool instance

name

Unique name for the instance

rebalance(*args, **kwargs) str

Rebalance implementation.

Parameters
  • args – Any args.

  • kwargs – Any kwargs.

Returns

Name of event or None if there was no event.

class mellow_sdk.strategies.StrategyByAddress(address: str, pool: mellow_sdk.primitives.Pool, gas_cost: float, name: Optional[str] = None)

StrategyByAddress is the strategy on UniswapV3 that follows the actions of certain address.

address

The address to follow.

pool

UniswapV3 Pool instance.

gas_cost

Gas costs, expressed in currency.

name

Unique name for the instance.

rebalance(*args, **kwargs)

Rebalance implementation.

Parameters
  • args – Any args.

  • kwargs – Any kwargs.

Returns

Name of event or None if there was no event.

UniswapUtils

class mellow_sdk.uniswap_utils.UniswapLiquidityAligner(lower_price, upper_price)

UniswapLiquidityAligner this is a class with standard Uniswap V3 formulas and transformations related to liquidity on the interval.

lower_price

Left bound for the UniswapV3 interval.

upper_price

Right bound for the UniswapV3 interval.

check_xy_is_optimal(price, x, y)

Check if the given amount of X and Y tokens are optimal for a given price and a price range.

Parameters
  • price – Current market price.

  • x – Amount of X tokens.

  • y – Amount of Y tokens.

Returns

is_optimal:

True: if given amount of X and given amount of Y token can be fully minted on given interval at given price. False: otherwise.

x_liq:

The amount of liquidity for the given price range and amount of tokens X.

y_liq:

The amount of liquidity for the given price range and amount of tokens Y.

Return type

(is_optimal, x_liq, y_liq)

get_amounts_after_optimal_swap(x: float, y: float, price: float, swap_fee: float) Tuple[float, float]

Calculate the amount of X and Y tokens after optimal swap. The amount of X and Y tokens is optimal for a given price and a price range for minting them to UniV3.

Parameters
  • x – Amount of X tokens.

  • y – Amount of Y tokens.

  • price – Current market price.

  • swap_fee – Swap fee.

Returns

x_after_swap: Amount of X tokens after optimal swap. y_after_swap: Amount of Y tokens after optimal swap.

Return type

(x_after_swap, y_after_swap)

get_amounts_for_swap_to_optimal(x: float, y: float, price: float, swap_fee: float) Tuple[float, float]

Calculate the amount of X or Y tokens that must be swapped to provide optimal liquidity at a given price.

Parameters
  • x – Amount of X tokens.

  • y – Amount of Y tokens.

  • price – Current market price.

  • swap_fee – Swap fee.

Returns

x_swap: Amount of X tokens that must be swapped to provide optimal liquidity at a given price. y_swap: Amount of Y tokens that must be swapped to provide optimal liquidity at a given price.

Return type

(x_swap, y_swap)

liq_to_x(price, liq)

Calculate the amount of X tokens for a given amount of liquidity, price and a price range.

Parameters
  • price – Current market price.

  • liq – Given amount of liquidity

Returns

The amount of token X for a given amount of liquidity and a price range.

liq_to_xy(price, liq)

Calculate the amount of X and Y tokens for a given amount of liquidity, price and a price range.

Parameters
  • price – Current market price.

  • liq – Amount of liquidity to be allocated.

Returns

The amount of X tokens and the amount of Y tokens that must be allocated to provide required amount of liquidity at a given interval and price.

liq_to_y(price, liq)

Calculate the amount of Y tokens for a given amount of liquidity, price and a price range.

Parameters
  • price – Current market price.

  • liq – Given amount of liquidity.

Returns

The amount of token Y for a given amount of liquidity and market price.

real_price(price: float) float
Parameters

price – Current price on market.

Returns

real_price = y / x

x_to_liq(price, x)

Calculate the liquidity for a given amount of tokens X, price and a price range.

Parameters
  • price – Current market price.

  • x – Amount of X tokens.

Returns

The amount of liquidity for the given price and amount of tokens X.

xy_to_liq(price, x, y)

Calculate the liquidity for a given amount of tokens X and Y, price and a price range.

Parameters
  • price – Current market price.

  • x – Amount of X tokens.

  • y – Amount of Y tokens.

Returns

Maximum liquidity that can be obtained for amounts, interval and current price, without swap.

y_to_liq(price, y)

Calculate the liquidity for a given amount of tokens Y, price and a price range.

Parameters
  • price – Current market price.

  • y – Amount of Y tokens.

Returns

The amount of liquidity for the given price and amount of tokens Y.

Viewers

class mellow_sdk.viewers.PortfolioViewer(portfolio_history: mellow_sdk.history.PortfolioHistory, pool: mellow_sdk.primitives.Pool, offset: int = 30)

PortfolioViewer is class for backtesting result visualisation.

portfolio_history

PortfolioHistory instance returned from backtest.

pool

Uniswap V3``Pool``.

offset

Offset for time axis.

draw_gapy(portfolio_df: polars.internals.frame.DataFrame) plotly.graph_objects.Figure

Plot portfolio value and gAPY in Y. Note that gAPY in X equals gAPY in Y.

Parameters

portfolio_df – result of PortfolioHistory.calculate_stats().

Returns

Plotly plot.

draw_performance_x(portfolio_df: polars.internals.frame.DataFrame) plotly.graph_objects.Figure

Plot portfolio value in X, portfolio APY in X.

Parameters

portfolio_df – Dataframe from PortfolioHistory.calculate_stats().

Returns: Plotly plot.

draw_performance_y(portfolio_df: polars.internals.frame.DataFrame) plotly.graph_objects.Figure

Plot portfolio value in Y, portfolio APY in Y.

Parameters

portfolio_df – Dataframe from PortfolioHistory.calculate_stats().

Returns: Plotly plot.

draw_portfolio()

Main function of the class. Create main plots to track portfolio behavior.

Returns: plotly plots
fig1: Portfolio value in X, fees in X, IL in X.
fig2: Portfolio value in Y, fees in Y, IL in Y.
fig3: Portfolio value in X, portfolio APY in X.
fig4: Portfolio value in Y, portfolio APY in Y.
fig5: Amount of X asset in portfolio, amount of Y asset in portfolio.
fig6: Value and gAPY.
draw_portfolio_to_x(portfolio_df: polars.internals.frame.DataFrame) plotly.graph_objects.Figure

Plot portfolio value in X, fees in X, IL in X.

Parameters

portfolio_df – result of PortfolioHistory.calculate_stats()

Returns

Plotly plot.

draw_portfolio_to_y(portfolio_df: polars.internals.frame.DataFrame) plotly.graph_objects.Figure

Plot portfolio value and fees in Y.

Parameters

portfolio_df – Dataframe from PortfolioHistory.calculate_stats().

Returns: Plotly plot.

draw_x_y(portfolio_df: polars.internals.frame.DataFrame) plotly.graph_objects.Figure

Plot amount of X asset and amount of Y asset in portfolio.

Parameters

portfolio_df – Dataframe from PortfolioHistory.calculate_stats().

Returns: Plotly plot.

class mellow_sdk.viewers.UniswapViewer(uni_postition_history: mellow_sdk.history.UniPositionsHistory)

UniswapViewer is class for visualizing UniswapV3 intervals in time.

uni_postition_history

UniswapV3 positions history object.

draw_intervals(swaps_df: polars.internals.frame.DataFrame) plotly.graph_objects.Figure

Plot price and uniswap positions intervals in time.

Parameters

swaps_df – UniswapV3 swap data.

Returns

Plot with UniswapV3 position intervals and market price.

class mellow_sdk.viewers.RebalanceViewer(rebalance_history: mellow_sdk.history.RebalanceHistory)

RebalanceViewer class to visualize strategy actions that occurred during the backtest.

rebalance_history

RebalanceHistory instance returned from backtest.

draw_rebalances(swaps_df: polars.internals.frame.DataFrame) plotly.graph_objects.Figure

Draws a price chart with portfolio action points.

Parameters

swaps_df – Price data. [(timestamp, price)].

Returns: Plot with portfolio actions.

class mellow_sdk.viewers.LiquidityViewer(pool: mellow_sdk.primitives.Pool, pool_data: mellow_sdk.data.PoolDataUniV3)

LiquidityViewer is class for liquidity visualisation.

pool_data

PoolData object.

draw_plot() plotly.graph_objects.Figure

Plot liquidity and price in pool in time.

Returns

Plot with Pool liquidity and price.