- Introduction
- Model Assumptions
- Simulation Structure
- Summary of Findings
- Setup Instructions
- Running the Model and API
- API Endpoints
- API Usage Examples
- Testing
This project implements a Decentralized Finance (DeFi) Automated Market Maker (AMM) model. It includes a basic AMM implementation, risk management features, and a simulation environment to test the model under various market conditions.
- Constant Product Formula: The AMM uses the constant product formula (x * y = k) for pricing and liquidity provision.
- Fee Structure: A base fee of 0.3% is applied to all trades, which can be adjusted based on market conditions up to a maximum of 1%.
- Impermanent Loss: The model accounts for impermanent loss in liquidity provision.
- Risk Management: Includes Value at Risk (VaR) calculation, stop-loss mechanisms, and dynamic position sizing.
- Market Simulation: Assumes normally distributed price changes for simulating market movements.
- Liquidity Incentives: Implements a rebalancing incentive mechanism to encourage liquidity provision that balances the pool.
The simulation is structured as follows:
- AMM Model (
amm.py): Core AMM functionality including pool creation, swaps, and liquidity management. - Liquidity Pool (
liquidity_pool.py): Represents individual liquidity pools and handles token reserves. - Risk Management (
risk_management.py): Implements risk assessment and mitigation strategies. - Market Simulator (
market_simulator.py): Simulates various market conditions to test the AMM model. - Metrics (
metrics.py): Calculates and tracks performance metrics during simulations.
The simulation runs through the following steps:
- Initialize AMM with liquidity pools
- Run multiple scenarios (stable market, high volatility, large trades)
- For each step in a scenario:
- Simulate price changes
- Execute random trades or liquidity events
- Update metrics
- Apply risk management strategies
- Generate reports for each scenario
Initial simulations suggest:
- The AMM model performs stably under normal market conditions.
- High volatility scenarios lead to increased impermanent loss for liquidity providers.
- Large trades can significantly impact pool balances, triggering rebalancing incentives.
- Risk management strategies, particularly dynamic fee adjustment and stop-loss mechanisms, help mitigate extreme market movements.
- The rebalancing incentive mechanism encourages more balanced liquidity provision over time.
Plain Python
-
Clone the repository:
git clone https://github.com/joaquinbejar/py-defi-amm.git cd py-defi-amm -
Create and activate a virtual environment:
make create-venv source venv/bin/activate -
Install dependencies:
make install-dep
Managed by uv
-
Clone the repository:
git clone https://github.com/joaquinbejar/py-defi-amm.git cd py-defi-amm -
Create and activate a virtual environment:
make create-venv-uv -
Install dependencies:
make install-dep-uv
-
To run the simulation:
python src/defi_amm/simulator_runner.py -
To start the API:
export FLASK_APP=src/defi_amm/main.py flask run # uv version uv run flask runThe API will be available at
http://127.0.0.1:5000/. -
To build and run the API using Docker:
Build the Docker image:
make docker-buildRun the Docker container:
make docker-runThis will build the Docker image using the Dockerfile in the Docker directory, tag it as "defi_amm:latest", and then run the container, mapping port 5000 from the container to port 5000 on your host machine.
The API will be available at
http://localhost:5000/when running through Docker.
- POST
/add_liquidity: Add liquidity to a pool - POST
/remove_liquidity: Remove liquidity from a pool - POST
/swap: Perform a token swap - GET
/pool_state: Get the current state of a pool - GET
/transaction_history: Retrieve transaction history for a pool - GET
/risk_metrics: Get risk metrics for a pool - POST
/activate_stop_loss: Activate stop-loss for a pool - GET
/dynamic_position_sizing: Get suggested position sizes based on risk
Here are examples of how to interact with the DeFi AMM API using curl commands:
curl -X POST http://127.0.0.1:5000/add_liquidity \
-H "Content-Type: application/json" \
-d '{
"token_a": "ETH",
"token_b": "USDC",
"amount_a": 1.0,
"amount_b": 1.0002
}'curl -X POST http://127.0.0.1:5000/remove_liquidity \
-H "Content-Type: application/json" \
-d '{
"token_a": "ETH",
"token_b": "USDC",
"lp_tokens": 44.72135954999579
}'curl -X POST http://127.0.0.1:5000/swap \
-H "Content-Type: application/json" \
-d '{
"token_from": "ETH",
"token_to": "USDC",
"amount": 0.1
}'curl -X GET "http://127.0.0.1:5000/pool_state?token_a=ETH&token_b=USDC"curl -X GET "http://127.0.0.1:5000/transaction_history?token_a=ETH&token_b=USDC"curl -X GET "http://127.0.0.1:5000/risk_metrics?token_a=ETH&token_b=USDC"curl -X POST http://127.0.0.1:5000/activate_stop_loss \
-H "Content-Type: application/json" \
-d '{
"token_a": "ETH",
"token_b": "USDC",
"stop_loss_percentage": 0.1
}'curl -X GET "http://127.0.0.1:5000/dynamic_position_sizing?token_a=ETH&token_b=USDC&risk_factor=0.02"To run unit tests:
make test
To run tests with coverage:
make run-unit-test-coverage
For more detailed information about the project structure and implementation details, please refer to the individual source files and their documentation.