Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AMM scenario #703

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions vega_query/service/utils/party.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def historic_balances(
self,
party_id: str,
asset_id: str,
asset_decimals: int,
market_id: Optional[str] = None,
account_types: Optional[List[protos.vega.vega.AccountType.Value]] = None,
date_range_start_timestamp: Optional[int] = None,
Expand Down Expand Up @@ -102,4 +103,6 @@ def historic_balances(

df = pd.DataFrame.from_dict(data, orient="index").sort_index().ffill()
df["total"] = df.sum(axis=1)
df["total"] = df["total"]* 10**-asset_decimals
return df

10 changes: 8 additions & 2 deletions vega_query/visualisations/overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def overlay_mark_price(
ax: Axes,
market_data_history: List[protos.vega.vega.MarketData],
price_decimals: int,
):
)-> pd.DataFrame:
x = []
y = []
for market_data in market_data_history:
Expand All @@ -39,13 +39,19 @@ def overlay_mark_price(
y.append(price if price != 0 else np.nan)
ax.step(x, y, label="mark_price", where="post")

# Create a DataFrame from the extracted data
df_mark_price = pd.DataFrame({'timestamp': x, 'last_traded_price': y})

# Return the DataFrame
return df_mark_price


def overlay_last_traded_price(
ax: Axes,
market_data_history: List[protos.vega.vega.MarketData],
price_decimals: int,
**kwargs,
):
) :
x = []
y = []
for market_data in market_data_history:
Expand Down
21 changes: 13 additions & 8 deletions vega_query/visualisations/plots/amm.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,22 +69,23 @@ def create(

party_colors = __party_colors(party_ids)

fig = plt.figure(figsize=(15, 8))
fig = plt.figure(figsize=(16, 9))
gs = fig.add_gridspec(2, 2)
ymin = ymax = 0
axes: List[Axes] = []

axn0l = fig.add_subplot(gs[0, 0])
axn0r: Axes = axn0l.twinx()
if market_data_history is not None:
overlay_mark_price(axn0l, market_data_history, market.decimal_places)
df_markPrice=overlay_mark_price(axn0l, market_data_history, market.decimal_places)
df_markPrice.to_csv("mark_price_data.csv", index=False)
overlay_last_traded_price(axn0l, market_data_history, market.decimal_places)
overlay_trading_mode(axn0r, market_data_history)
# overlay_auction_starts(axn0r, market_data_history)
# overlay_auction_ends(axn0r, market_data_history)

axn0l.set_ylabel("USDT")
axn0l.set_title(
"Market Price: Ornstein–Uhlenbeck ($\\theta=0.01$, $\\sigma=0.5$)",
# "Market Price: Ornstein–Uhlenbeck ($\\theta=0.01$, $\\sigma=0.5$)",
"Market Price: Ornstein–Uhlenbeck",
loc="left",
)

Expand All @@ -106,7 +107,7 @@ def create(
axes.append(ax11)
ax21 = fig.add_subplot(gs[1, 1])
ax21.set_title("AMM: Aggregated Account Balances [USDT]", loc="left")
ax21.set_ylabel("$\\Delta$ USDT")
ax21.set_ylabel("USDT")
ax21.sharex(axn0l)
axes.append(ax21)

Expand Down Expand Up @@ -141,16 +142,20 @@ def create(
party_id=amm_party_id,
size_decimals=market.position_decimal_places,
)
ax11.get_lines()[-1].set_label(amm_party_id[:7])
# ax11.get_lines()[-1].set_label(amm_party_id[:7])
ax11.get_lines()[-1].set_label("AMM")

# Reconstruct the AMMs aggregated balance from balance changes
df = service.utils.party.historic_balances(
party_id=amm_party_id,
asset_id=asset.id,
date_range_start_timestamp=start_timestamp,
date_range_end_timestamp=end_timestamp,
asset_decimals=asset.details.decimals,
)
ax21.step(df.index, df.total, where="post", label="total")
ax21.step(df.index, df.total, where="post", label="AMM portfolio")
df.to_csv("AMM_Portfolio_data.csv", index=False)


ax11.legend()
ax21.legend()
Expand Down
11 changes: 6 additions & 5 deletions vega_sim/scenario/amm/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@
benchmark_configs=[
BenchmarkConfig(
market_config=configs.mainnet.BTCUSDT.CONFIG,
initial_price=70000,
annualised_volatility=0.5,
notional_trade_volume=100,
process_theta=0.01,
process_drift=-10,
initial_price=60000,
annualised_volatility=0.28,
notional_trade_volume=10,
process_theta=0.0001,
process_drift=-5,
risky_trader_funds=1,
),
],
amm_liquidity_fee=0.0001,
Expand Down
23 changes: 20 additions & 3 deletions vega_sim/scenario/amm/scenario.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
from vega_sim.scenario.common.agents import (
StateAgent,
AutomatedMarketMaker,
MarketOrderTrader,
LimitOrderTrader,
ExponentialShapedMarketMaker,
)


class AMMScenario(BenchmarkScenario):
def __init__(
self,
Expand Down Expand Up @@ -58,6 +59,22 @@ def configure_agents(
# Set commitment amount to 0 to avoid benchmark market maker from
# providing liquidity, they should only supply volume through orders.
agent.fee_amount = self.amm_liquidity_fee
agent.commitment_amount = 0.000001
agent.supplied_amount = 0

# if isinstance(agent, MarketOrderTrader):
# # Set commitment amount to 0 to avoid benchmark market maker from
# # providing liquidity, they should only supply volume through orders.
# agent.fee_amount = self.amm_liquidity_fee
# agent.commitment_amount =10
# agent.supplied_amount = 50

# if isinstance(agent, LimitOrderTrader):
# # Set commitment amount to 0 to avoid benchmark market maker from
# # providing liquidity, they should only supply volume through orders.
# agent.spread = 0
# agent.mean = -7.5
# agent.sigma = 0.3

# For each market, add an AMM agent.
for benchmark_config in self.benchmark_configs:
Expand All @@ -67,8 +84,8 @@ def configure_agents(
wallet_name="AutomatedMarketMaker",
key_name=f"AutomatedMarketMaker_{benchmark_config.market_config.instrument.code}_{str(i_agent).zfill(3)}",
market_name=benchmark_config.market_config.instrument.name,
initial_asset_mint=1e6,
commitment_amount=7000,
initial_asset_mint=1e5,
commitment_amount=6000,
slippage_tolerance=0.05,
proposed_fee=self.amm_liquidity_fee,
price_process=iter(benchmark_config.price_process),
Expand Down
28 changes: 28 additions & 0 deletions vega_sim/scenario/ammV2/registryV2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import vega_sim.configs as configs
from vega_sim.scenario.benchmark.configs import BenchmarkConfig
from vega_sim.scenario.ammV2.scenarioV2 import AMMScenarioV2


REGISTRYV2 = {
"static": AMMScenarioV2(
block_length_seconds=1,
step_length_seconds=30,
benchmark_configs=[
BenchmarkConfig(
market_config=configs.mainnet.BTCUSDT.CONFIG,
initial_price=60000,
annualised_volatility=0.28,
notional_trade_volume=800,
process_theta=0.0001,
process_drift=-5,
risky_trader_funds=1,
),
],
amm_liquidity_fee=0.0001,
amm_update_frequency=0,
initial_network_parameters={
"validators.epoch.length": "1h",
"market.fee.factors.makerFee": "0",
},
),
}
107 changes: 107 additions & 0 deletions vega_sim/scenario/ammV2/runV2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import os
import logging
import pathlib
import datetime
import argparse


from vega_sim.null_service import VegaServiceNull, Ports
from vega_sim.scenario.constants import Network
from vega_sim.scenario.ammV2.scenarioV2 import AMMScenarioV2
from vega_sim.scenario.ammV2.registryV2 import REGISTRYV2

from vega_query.service.service import Service
from vega_query.service.networks.constants import Network

import vega_query.visualisations as vis
from matplotlib.figure import Figure


def _run(
scenario: AMMScenarioV2,
pause: bool = False,
console: bool = False,
output: bool = False,
wallet: bool = False,
output_dir: str = "plots",
core_metrics_port: int = 2723,
data_node_metrics_port: int = 3651,
):

with VegaServiceNull(
warn_on_raw_data_access=False,
seconds_per_block=scenario.block_length_seconds,
transactions_per_block=scenario.transactions_per_block,
retain_log_files=True,
use_full_vega_wallet=wallet,
run_with_console=console,
port_config={
Ports.METRICS: core_metrics_port,
Ports.DATA_NODE_METRICS: data_node_metrics_port,
},
) as vega:
scenario.run_iteration(
vega=vega,
log_every_n_steps=100,
output_data=False,
run_with_snitch=False,
)

if output:
if not os.path.exists(output_dir):
os.mkdir(output_dir)
output_dir = output_dir + f"/{datetime.datetime.now()}"
if not os.path.exists(output_dir):
os.mkdir(output_dir)

# Use vegapy package to produce plots
service = Service(
network=Network.NETWORK_LOCAL,
port_data_node=vega.data_node_grpc_port,
)

for benchmark_config in scenario.benchmark_configs:
fig: Figure = vis.plots.amm.create(
service,
market_code=benchmark_config.market_config.instrument.code,
)
fig.savefig(
f"{output_dir}/{benchmark_config.market_config.instrument.code.replace('/','-')}_amm.png"
)

if pause:
input("Waiting after run finished.")


if __name__ == "__main__":

parser = argparse.ArgumentParser()
parser.add_argument("-m", "--market", required=True, type=str)
parser.add_argument("-s", "--steps", default=600, type=int)
parser.add_argument("-p", "--pause", action="store_true")
parser.add_argument("-d", "--debug", action="store_true")
parser.add_argument("-o", "--output", action="store_true")
parser.add_argument("-c", "--console", action="store_true")
parser.add_argument("-w", "--wallet", action="store_true")
parser.add_argument("--core-metrics-port", default=2723, type=int)
parser.add_argument("--data-node-metrics-port", default=3651, type=int)
args = parser.parse_args()

logging.basicConfig(
level=logging.DEBUG if args.debug else logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)

if args.market not in REGISTRYV2:
raise ValueError(f"Market {args.market} not found")
scenario = REGISTRYV2[args.market].num_steps = args.steps

_run(
scenario=REGISTRYV2[args.market],
wallet=args.wallet,
console=args.console,
pause=args.pause,
output=args.output,
core_metrics_port=args.core_metrics_port,
data_node_metrics_port=args.data_node_metrics_port,
)
83 changes: 83 additions & 0 deletions vega_sim/scenario/ammV2/scenarioV2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import itertools
import numpy as np
import re
from typing import Optional, List, Dict, Any

from vega_sim.null_service import VegaServiceNull
from vega_sim.scenario.benchmark.configs import BenchmarkConfig
from vega_sim.scenario.benchmark.scenario_Informed import BenchmarkScenario_Informed
from vega_sim.scenario.common.agents import (
StateAgent,
AutomatedMarketMaker,
MarketOrderTrader,
LimitOrderTrader,
InformedTrader,
)

class AMMScenarioV2(BenchmarkScenario_Informed):
def __init__(
self,
benchmark_configs: List[BenchmarkConfig],
num_steps: int = 60 * 24 * 30 * 3,
transactions_per_block: int = 4096,
block_length_seconds: float = 1,
step_length_seconds: Optional[float] = None,
amm_liquidity_fee: float = 0.0001,
amm_update_frequency: float = 0.1,
output: bool = True,
initial_network_parameters: Optional[Dict[str, Any]] = None,
):
super().__init__(
benchmark_configs=benchmark_configs,
num_steps=num_steps,
transactions_per_block=transactions_per_block,
block_length_seconds=block_length_seconds,
step_length_seconds=step_length_seconds,
output=output,
initial_network_parameters=initial_network_parameters,
)

self.amm_liquidity_fee = amm_liquidity_fee
self.amm_update_frequency = amm_update_frequency

def configure_agents(
self,
vega: VegaServiceNull,
tag: str,
random_state: Optional[np.random.RandomState],
**kwargs,
) -> Dict[str, StateAgent]:
self.random_state = (
random_state if random_state is not None else np.random.RandomState()
)
agents = super().configure_agents(vega, tag, random_state, **kwargs)
extra_agents = []

agents = super().configure_agents(vega, tag, random_state, **kwargs)

# For each market, add an AMM agent.
for benchmark_config in self.benchmark_configs:
i_agent = 0
extra_agents.append(
AutomatedMarketMaker(
wallet_name="AutomatedMarketMaker",
key_name=f"AutomatedMarketMaker_{benchmark_config.market_config.instrument.code}_{str(i_agent).zfill(3)}",
market_name=benchmark_config.market_config.instrument.name,
initial_asset_mint=1e5,
commitment_amount=6000,
slippage_tolerance=0.05,
proposed_fee=self.amm_liquidity_fee,
price_process=iter(benchmark_config.price_process),
lower_bound_scaling=1 - 0.02,
upper_bound_scaling=1 + 0.02,
leverage_at_lower_bound=20,
leverage_at_upper_bound=20,
update_bias=self.amm_update_frequency,
tag=f"{benchmark_config.market_config.instrument.code}_{str(i_agent).zfill(3)}",
random_state=self.random_state,
)
)

extra_agents = {agent.name(): agent for agent in extra_agents}
agents.update(extra_agents)
return agents
Loading
Loading