### Setup Notebook and Plotly Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/docs/source/tutorials/hyperliquid-read-vault.ipynb Configures pandas display options and Plotly for static image output. Ensure Plotly is installed. ```python import datetime import pandas as pd from plotly.offline import init_notebook_mode import plotly.io as pio import plotly.graph_objects as go pd.options.display.float_format = "{:,.2f}".format pd.options.display.max_columns = None pd.options.display.max_rows = None # Set up Plotly chart output image_format = "png" width = 1200 height = 600 init_notebook_mode() pio.renderers.default = image_format current_renderer = pio.renderers[image_format] current_renderer.width = width current_renderer.height = height ``` -------------------------------- ### Setup Forked Environment Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/tests/gmx/forked-env-example/QUICKSTART.md Installs dependencies and sets up the environment variables for running GMX fork tests. Ensure you have Forge installed. ```bash cd forked-env-example # Initialize git (required for forge install if setting up as a stand alone repo) git init # Install dependencies (just forge-std) forge install foundry-rs/forge-std --no-commit # Set Arbitrum RPC URL cp .env.example .env && source .env ``` -------------------------------- ### Uniswap Swap Example Setup Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/README.md This Python code sets up a connection to a Polygon RPC node and initializes a multi-provider Web3 instance for robust transaction handling. It defines addresses for quote and base tokens for a swap operation. ```python import datetime import decimal import os import sys from decimal import Decimal from eth_account import Account from eth_account.signers.local import LocalAccount from eth_defi.compat import construct_sign_and_send_raw_middleware from eth_defi.provider.multi_provider import create_multi_provider_web3 from eth_defi.revert_reason import fetch_transaction_revert_reason from eth_defi.token import fetch_erc20_details from eth_defi.confirmation import wait_transactions_to_complete from eth_defi.uniswap_v3.constants import UNISWAP_V3_DEPLOYMENTS from eth_defi.uniswap_v3.deployment import fetch_deployment from eth_defi.uniswap_v3.swap import swap_with_slippage_protection # The address of a token we are going to swap out # # Use https://tradingstrategy.ai/search to find your token # # For quote terminology see https://tradingstrategy.ai/glossary/quote-token # QUOTE_TOKEN_ADDRESS = "0x3c499c542cef5e3811e1192ce70d8cc03d5c3359" # USDC (native) # The address of a token we are going to receive # # Use https://tradingstrategy.ai/search to find your token # # For base terminology see https://tradingstrategy.ai/glossary/base-token # BASE_TOKEN_ADDRESS = "0x7ceb23fd6bc0add59e62ac25578270cff1b9f619" # WETH # Connect to JSON-RPC node rpc_env_var_name = "JSON_RPC_POLYGON" json_rpc_url = os.environ.get(rpc_env_var_name) assert json_rpc_url, f"You need to give {rpc_env_var_name} node URL. Check ethereumnodes.com for options" # Create a Web3 provider with ability to retry failed requests # and supporting fallback JSON-RPC nodes. RPC connections # are extremely flaky and for production grade usage you need to use multiple # JSON-RPC nodes. # create_multi_provider_web3() will also take care of any chain-specific ``` -------------------------------- ### Install web3-ethereum-defi with data extras Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/eth_defi/gmx/README.md Install the library with data extras for full functionality. Use this command in your terminal. ```bash pip install "web3-ethereum-defi[data]" ``` -------------------------------- ### Install web3-ethereum-defi with Poetry Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/eth_defi/gmx/README.md Install the library with data extras using Poetry. Add this to your project's dependencies. ```bash poetry add -E data web3-ethereum-defi ``` -------------------------------- ### Freqtrade GMX Wrapper Installation Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/eth_defi/gmx/README.md Commands to clone the repository, set up a virtual environment, install dependencies, and verify the installation of the freqtrade-gmx wrapper. ```bash # Clone the repository with submodules git clone --recurse-submodules https://github.com/tradingstrategy-ai/gmx-ccxt-freqtrade.git cd gmx-ccxt-freqtrade # Create virtual environment python3.11 -m venv .venv source .venv/bin/activate # Install dependencies pip install -r freqtrade-develop/requirements.txt pip install -e freqtrade-develop/ pip install -e "deps/web3-ethereum-defi[data]" # Verify installation ./freqtrade-gmx --version ``` -------------------------------- ### GMX CCXT Adapter Setup Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/eth_defi/gmx/README.md Example of setting up the GMX CCXT configuration within Freqtrade. Ensure correct RPC URL, private key, and execution buffer are set. ```json { "exchange": { "name": "gmx", "ccxt_config": { "rpcUrl": "${JSON_RPC_ARBITRUM}", "privateKey": "${PRIVATE_KEY}", "executionBuffer": 2.5, // This ensures that the multicalls on GMX doesn't run out of gas "options": { "graphql_only": false } }, "pair_whitelist": ["ETH/USDC:USDC", "BTC/USDC:USDC"] }, "stake_currency": "USDC", "trading_mode": "futures", "margin_mode": "isolated", "order_types": { "entry": "market", "exit": "market", "stoploss": "market", "stoploss_on_exchange": true } } ``` -------------------------------- ### Run Lagoon-Velora Example Script Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/docs/source/tutorials/lagoon-velora.rst Execute the Python script to deploy a new Lagoon vault with Velora integration enabled. Ensure you have Poetry installed and configured. ```shell # Run the script poetry run python scripts/lagoon/lagoon-velora-example.py ``` -------------------------------- ### Install web3-ethereum-defi with Uv Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/README.md Install the package with all extras using the uv package manager. This is an alternative to pip for faster dependency resolution. ```shell uv pip install "web3-ethereum-defi" --all-extras ``` -------------------------------- ### Install Make with Homebrew Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/docs/source/development.rst Install the Gnu Make utility using Homebrew. Make is required for recompiling smart contract artifacts. ```shell brew install make ``` -------------------------------- ### Scan Prices Output Example Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/docs/source/tutorials/erc-4626-scan-prices.rst Example output from the scan-prices.py script, showing progress and final statistics. ```none Scanning vault historical prices on chain 999: Hyperliquid Chain Hyperliquid has 12 vaults in the vault detection database After filtering vaults for non-interesting entries, we have 6 vaults left Loading token metadata for 6 addresses using 8 workers: 0%| | 0/1 [00:00"}, 'timeout': (3.0, 30.0)}, headers {'Content-Type': 'application/json', 'User-Agent': "web3.py/6.14.0/"} Created provider base-mainnet.g.alchemy.com, using request args {'headers': {'Content-Type': 'application/json', 'User-Agent': "web3.py/6.14.0/"}, 'timeout': (3.0, 30.0)}, headers {'Content-Type': 'application/json', 'User-Agent': "web3.py/6.14.0/"} Configuring MultiProviderWeb3. Call providers: ['lb.drpc.org', 'base-mainnet.g.alchemy.com'], transact providers - Using JSON RPC provider fallbacks lb.drpc.org, base-mainnet.g.alchemy.com for chain Base Forking Base with Anvil Attempting to allocate port 27388 to Anvil Multi RPC detected, using Anvil at the first RPC endpoint https://lb.drpc.org/ogrpc?network=base&dkey=AiWA4TvYpkijvapnvFlyx_UuJsZmMjkR8JUBzoXPVSjK Launching anvil: anvil --port 27388 --fork-url https://lb.drpc.org/ogrpc?network=base&dkey=AiWA4TvYpkijvapnvFlyx_UuJsZmMjkR8JUBzoXPVSjK --hardfork cancun --code-size-limit 99999 anvil forked network 8453, the current block is 31,815,357, Anvil JSON-RPC is http://localhost:27388 Making request with data: {'headers': {'Content-Type': 'application/json', 'User-Agent': "web3.py/6.14.0/"}, 'timeout': 3.0} Created provider localhost:27388, using request args {'headers': {'Content-Type': 'application/json', 'User-Agent': "web3.py/6.14.0/"}, 'timeout': (10.0, 60.0)}, headers {'Content-Type': 'application/json', 'User-Agent': "web3.py/6.14.0/"} Configuring MultiProviderWeb3. Call providers: ['localhost:27388'], transact providers - Synced nonce for 0x1A76D579415532C527485FC83FDBc954F9b67cE6 to 0 Creating a simulated wallet 0x1A76D579415532C527485FC83FDBc954F9b67cE6 with USDC and ETH funding for testing Will not retry, method eth_call, as not a retryable exception : {'code': 3, 'message': 'execution reverted: custom error 0x1425ea42', 'data': '0x1425ea42'} Using vault Autopilot USDC Base (0x0d877Dc7C8Fa3aD980DfDb18B48eC9F8768359C4) Gas balance: 11.0 ETH USDC balance: 15598593.712583 Depositing 10.00 USDC to vault 0x0d877dc7c8fa3ad980dfdb18b48ec9f8768359c4 Depositing... Depositing to vault 0x0d877Dc7C8Fa3aD980DfDb18B48eC9F8768359C4, amount 10.00, from 0x1A76D579415532C527485FC83FDBc954F9b67cE6 Broadcasting transaction approve(): 0x03d57ddb1cc2984a137565c1597227cc147844ba09bc220189e0fc4fdd591a01 Broadcasting transaction deposit(): 0xc297da0c345a41b2586229cba3fefb1c37a4663cd266279aa3f8beb51cfc99e9 We received 9.775728 bAutopilot_USDC Redeeming, simulated waiting for 1800 seconds Redeeming from vault 0x0d877Dc7C8Fa3aD980DfDb18B48eC9F8768359C4, amount 9.77572796, from 0x1A76D579415532C527485FC83FDBc954F9b67cE6 Broadcasting transaction approve(): 0x0c83593eec26c4c1dea4a8f4b7ceeb742d5be4bdd5f351d5d07e324590127672 Broadcasting transaction redeem(): 0x35973ecdf96ad79393a365cd6550ee9ccf6025af696b79e3bc1b95055fe38355 Deposit value: 10.00 USDC Redeem value: 9.999998 USDC Share count: 9.77572796 bAutopilot_USDC Slippage: -0.0000% All done ``` -------------------------------- ### Velora Integration Example Script Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/docs/claude-plans/velora.md An example script demonstrating the deployment of a Lagoon vault with Velora integration, including depositing WETH and swapping it for USDC.e via Velora on Arbitrum. Requires specific environment variables to be set. ```python # scripts/lagoon/lagoon-velora-example.py # Pattern: scripts/lagoon/lagoon-cowswap-example.py # Deploy vault with velora=True, deposit WETH, swap WETH -> USDC.e via Velora on Arbitrum # Env vars: JSON_RPC_ARBITRUM, PRIVATE_KEY, ETHERSCAN_API_KEY ``` -------------------------------- ### Read Native Token Price with Chainlink (Python) Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/docs/source/tutorials/chainlink-native-token.rst Use this function to get the current price of a blockchain's native token in USD. Ensure you have JSON-RPC API access and have installed the eth-defi library. ```python from eth_defi.chainlink.token_price import get_native_token_price_with_chainlink def main(): # Get the price of ETH in USD price = get_native_token_price_with_chainlink(chain_id=1, token_symbol="ETH") print(f"The chain native token price of is {price} ETH / USD") if __name__ == "__main__": main() ``` -------------------------------- ### Setup Charting and Output for Plotly Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/docs/source/tutorials/uniswap-v3-price-analysis.ipynb Configures Plotly for static image output (PNG) and adjusts font sizes for better readability in reports or static displays. Ensure necessary Plotly and eth_defi libraries are installed. ```python # To make the output a static image instead of dynamic, we need these 3 lines from eth_defi.research.notebook import setup_charting_and_output, OutputMode, set_large_plotly_chart_font setup_charting_and_output(OutputMode.static, image_format="png", width=1500, height=1000, increase_font_size=False) set_large_plotly_chart_font() ``` -------------------------------- ### Run Freqtrade for Live Trading Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/eth_defi/gmx/README.md Execute this command to start live trading with Freqtrade on GMX. This requires valid configuration and strategy files. ```bash ./freqtrade-gmx trade \ --config configs/my_config.json \ --config configs/my_config.secrects.json \ --strategy MyStrategy ``` -------------------------------- ### Setup Charting and Output Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/docs/source/tutorials/derive-open-interest-funding-rate.ipynb Configure static PNG chart output for research notebooks. This setup ensures charts are rendered as images with specified dimensions and font sizes for better presentation. ```python # Set up static PNG chart output from eth_defi.research.notebook import setup_charting_and_output, OutputMode, set_large_plotly_chart_font setup_charting_and_output(OutputMode.static, image_format="png", width=1500, height=800, increase_font_size=False) set_large_plotly_chart_font() ``` -------------------------------- ### Get Funding Rates as DataFrame Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/eth_defi/derive/README-derive.md Retrieve historical funding rates for a given instrument and start time. The data is returned as a Pandas DataFrame with columns for timestamp, instrument, and funding rate. Ensure datetime objects are used for start_time. ```python # Read funding rates as Pandas DataFrame # Columns: timestamp (datetime64), instrument (str), funding_rate (float64) fr_df = db.get_funding_rates_dataframe("ETH-PERP", start_time=datetime.datetime(2025, 1, 1)) ``` -------------------------------- ### Example Metrics Calculation Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/eth_defi/derive/README-derive.md Sample output displaying calculated metrics for BTC-PERP and ETH-PERP, including hours positive/negative, percentage positive, mean hourly rate, annualized rate, current, peak, and mean Open Interest (OI) in USD. ```text BTC-PERP ETH-PERP Hours positive 8,718 8,987 Hours negative 1,918 1,650 % hours positive 82.0% 84.5% Mean hourly rate 0.00001250 0.00001131 Annualised rate 10.95% 9.91% Current OI (USD) $25,622,330 $7,181,877 Peak OI (USD) $26,845,258 $22,495,469 Mean OI (USD) $11,685,941 $8,303,178 ``` -------------------------------- ### Get Open Interest as DataFrame Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/eth_defi/derive/README-derive.md Fetch historical open interest data for a specified instrument and start time. The output is a Pandas DataFrame containing timestamp, instrument, open interest, perp price, and index price. Use datetime objects for start_time. ```python # Read open interest as Pandas DataFrame # Columns: timestamp (datetime64), instrument (str), open_interest (float64), # perp_price (float64), index_price (float64) oi_df = db.get_open_interest_dataframe("ETH-PERP", start_time=datetime.datetime(2025, 1, 1)) ``` -------------------------------- ### Fetch Vaults from Hyperliquid Stats-Data Endpoint Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/scripts/hyperliquid/README-hyperliquid-copy-trading.md This is an example GET request to the undocumented Hyperliquid stats-data endpoint to retrieve vault information. This endpoint returns data for a large number of vaults, including leader addresses, and is used in the eth_defi library for fetching vault data. ```bash GET https://stats-data.hyperliquid.xyz/Mainnet/vaults ``` -------------------------------- ### Install and Run Uniswap Live Swap Monitor Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/docs/source/tutorials/live-swap.rst Installs necessary libraries and sets environment variables to run the Python script for monitoring Uniswap v2 live swaps. Ensure to set the LOG_LEVEL and JSON_RPC_POLYGON environment variables before execution. ```shell pip install coloredlogs export LOG_LEVEL=INFO export JSON_RPC_POLYGON="https://polygon-rpc.com" python scripts/read-uniswap-v2-swaps-live.py ``` -------------------------------- ### Install Dependencies for Google Sheets Integration Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/scripts/hyperliquid/README-hyperliquid-vaults.md Install the required Python packages for Google Sheets integration using poetry. This command installs the 'gsheets' extra, which includes 'gspread' and 'google-auth-oauthlib'. ```shell poetry install -E gsheets ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/docs/source/tutorials/gmx-freqtrade-lagoon.rst Clone the repository and install Python dependencies, including optional ones for CCXT and data handling. For Solidity contracts, navigate to the contracts directory and install dependencies using Forge. ```shell git clone --recurse-submodules https://github.com/tradingstrategy-ai/web3-ethereum-defi.git cd web3-ethereum-defi # Python dependencies poetry install -E ccxt -E data # Solidity dependencies for Lagoon vault contracts cd contracts/lagoon-v0 && forge soldeer install && cd ../.. ``` -------------------------------- ### Recommended Docker Debugging Setup Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/anvil-wtf.md This command demonstrates a comprehensive setup for debugging Anvil in a Dockerized environment. It enables simulation, verbose logging for both the RPC proxy and Anvil, direct stdio inheritance for Anvil, and the warm-up block feature. ```shell SIMULATE=true \ RPC_PROXY_VERBOSE=true \ ANVIL_VERBOSE=true \ ANVIL_INHERIT_STDIO=true \ ANVIL_WARM_UP_BLOCK=true \ deploy/deploy-hyper-ai.sh ``` -------------------------------- ### Install Forge Dependencies Source: https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/contracts/guard/README.md Install dependencies for Forge using the soldeer tool. Specify the configuration location. ```shell forge soldeer install --config-location foundry ```