DeHedge
Overview
Liquidity providers on DeUnity-DePerp's insurance vaults may face the risk of PnL imbalance. Insurers cover the imbalance of virtual PnL-book and make payouts from the insurance vault when a risk event occurs. To ensure the insurer can continue supporting liquidity, they are offered the DeHedge service, which automatically hedges the insurer and their liquidity when risk signals are triggered in the vault.
DeHedge is responsible for managing position hedging on another exchanges. It automates the process of opening and closing hedging positions based on risk analysis at DeUnity-DePerp protocol.
Data Structure
- Main structure:
hedgedPositions
object - Keys: combination of
market
and unique position identifier - Values: objects representing hedged positions
Main Functions
processHedgePosition
Processes hedging for an individual position:
- Checks for risks (hedge, vault decrease, PNL risk)
- If risks exist and the position is not hedged:
- Prepares order data
- Places a new order on the Exchange
- Saves information about the hedged position
- If the position is already hedged, updates the placement time
- If there are no risks and the position is hedged:
- Checks if the position has expired (60 seconds)
- If expired, closes the position on the Exchange
processClosedHedgePositions
Processes the closure of hedged positions:
- Iterates through all hedged positions
- If a position is fully closed (absent in the main storage):
- Prepares data for closure
- Places a closing order on the CEX
Helper Functions
setHedgedPosition
: Adds or updates a hedged positioncheckIfHedgePositionIsExpired
: Checks if a position has expiredremoveHedgedPosition
: Removes a hedged positionhasHedgedPosition
: Checks for the existence of a hedged positiongetHedgedPosition
: Retrieves information about a hedged positiongetAllHedgedPosition
: Returns all hedged positions
Integration
The module uses functions from other system components for:
- Placing orders on the CEX
- Checking position status
- Risk analysis
Operational Logic
- Continuous monitoring of open positions
- Risk analysis for each position
- Automatic opening of hedging positions when risks are present
- Closing hedging positions when risks disappear or time expires
- Synchronization with the main position storage to close outdated hedges
The module ensures automatic and timely hedging of risks, maintaining a balance between loss protection and efficient resource utilization.
Risk Assessment Logic
The module assesses three main types of risks for each position:
1. Vault Drawdown Risk (isVaultDrawdown)
- Calculated based on the remaining balance in the vault after accounting for the position's PNL and shield balance.
- Risk is triggered if:
vaultBalanceRisk > remainingVault
- Where
vaultBalanceRisk = vaultBalance * riskFactors.vaultFactor
- And
remainingVault = vaultBalance + shieldBalance - pnl
- Where
2. Shield PNL Risk (isShieldPNLRisk)
- Triggered if the shield balance is insufficient to cover the position's PNL.
- Risk is triggered if:
shieldBalance - pnl <= 0
3. Hedge Risk (isHedge)
- Related to the profit limit interest and remaining vault balance.
- Risk is triggered if:
vaultProfitLimitRisk > remainingProfitLimit
- Where
vaultProfitLimitRisk = vaultBalance * riskFactors.vaultProfitLimitFactor * profitLimitInterest
- And
remainingProfitLimit = remainingVault * profitLimitInterest
- Where
Risk Calculation Process
- For each position, the module calculates the current PNL, taking into account:
- Price changes
- Funding fees (if applicable)
- The module then checks the current balances of the shield and vault.
- Using these values, it calculates the three risk factors mentioned above.
- If any of these risks are triggered, the position is considered for hedging.
Hedging Decision
- If any of the three risks (isVaultDrawdown, isShieldPNLRisk, or isHedge) are true, and the position is not already hedged, a new hedging position will be opened.
- If all risks are false and the position is currently hedged, the hedging position may be closed (subject to expiration checks).
This risk assessment ensures that hedging actions are taken only when necessary, balancing between risk mitigation and efficient use of resources.
Installation
Setup environment:
Instructions:
NETWORKS
: Add a comma-separated list of network RPC URLs.KEY
: Add your private key for executing orders.NODE_ENV
: Set toproduction
for production environment.DATAREGISTRY
andUSDC
: These are preset contract addresses. Do not change unless instructed.BINANCE_API_KEY
andBINANCE_API_SECRET
: Add your Binance API credentials.BPS_FACTOR
: Set to 10000 (basis points factor).PYTH_PRICE_SERVICE
: URL for the Pyth price service.
Base
NETWORKS
:https://mainnet.base.org
Rate limited and not for production systems.DATAREGISTRY
:0x5Dc939df0cf253873cf77B786A24d51BaA72cF75
USDC
:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
PYTH_PRICE_SERVICE
:https://hermes.pyth.network
Note: Keep your .env
file secure and never share or commit it to version control systems. Some values are pre-filled; only change them if you're certain about the new values.
Note: Keep your .env
file secure and never share or commit it to version control systems.
Setup Markets:
The market configuration is typically defined in a separate file (e.g., marketsEnum.js
) within each connector's directory. It provides a mapping between internal market identifiers and exchange-specific symbols.
export const mapBinanceMarkets = {
"BTC-USD": "BTCUSDT",
"ETH-USD": "ETHUSDT"
};
Connectors Overview
Connectors in our system serve as interfaces between our core hedging logic and various external platforms or exchanges. They play a crucial role in executing trades, fetching market data, and managing positions across different venues. Here's a brief overview of our connector system:
Purpose of Connectors
- Provide a standardized interface for interacting with different exchanges or platforms.
- Abstract away the complexities and differences in APIs of various exchanges.
- Enable the core system to operate seamlessly across multiple trading venues.
Key Features
- Abstraction: Each connector implements a common interface, allowing the core system to interact with different exchanges in a uniform manner.
- Data Fetching: Retrieve real-time market data, including prices, order book information, and account balances.
- Order Execution: Place, modify, and cancel orders on the respective exchange.
- Position Management: Track and manage open positions, including fetching current position details and historical data.
- Error Handling: Implement robust error handling and retry mechanisms to deal with API issues or network problems.
Current Connectors
- Binance Connector: Interfaces with Binance exchange, supporting futures trading.
- Implements USDT-M Futures API.
- Handles order placement, position fetching, and market data retrieval.
Connector Structure
Each connector typically includes:
- Authentication methods
- Market data retrieval functions
- Order management functions
- Position tracking methods
- Utility functions for data conversion and formatting
Future Expansion
The connector system is designed to be easily expandable. New connectors can be added to support additional exchanges or trading platforms as needed, following the established interface pattern.
Best Practices
- Keep API keys and secrets secure, preferably using environment variables.
- Implement rate limiting to comply with exchange API restrictions.
- Use websockets where available for real-time data to reduce latency.
- Regularly update connectors to accommodate changes in exchange APIs.
Connectors are a critical component of our hedging system, enabling flexible and efficient interaction with various trading platforms while maintaining a consistent internal interface.
Run up:
yarn i -g pm2
yarn i
yarn dev
This will run and watch the guardian process using pm2. To automatically run it on system reboot, run pm2 save
.
Installation Guide and Repo
For detailed instructions on how to install and set up the deHedge module, please refer to the installation guide.