Skip to content

Commit

Permalink
feat: add informed trader
Browse files Browse the repository at this point in the history
  • Loading branch information
Jiajia-Cui committed Sep 27, 2024
1 parent 64b59a5 commit 70013cd
Show file tree
Hide file tree
Showing 4 changed files with 454 additions and 0 deletions.
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

0 comments on commit 70013cd

Please sign in to comment.