TLDR:

  • You’ll integrate OpenRouter’s Grok-4 model with your trading agent for enhanced reasoning capabilities in market analysis and decision-making.
  • You’ll run safe paper trading using Foundry Anvil fork to test strategies before deploying to live markets.
  • You’ll configure environment variables and API keys for OpenRouter access while maintaining all existing agent features.
  • By the end, you’ll have a trading agent powered by Grok-4’s advanced AI capabilities.

Project repository: Web3 AI trading agent

Remember that this a NOT FOR PRODUCTION tutorial. In a production deployment, don’t store your private key in a config.py file.

This section demonstrates how to integrate OpenRouter’s Grok 4 model with your trading agent. Grok 4 provides advanced reasoning capabilities with a 256K token context window, allowing for sophisticated market analysis and trading decisions. You’ll run the agent on a Foundry Anvil fork for safe paper trading before moving to live markets.

Prerequisites

Before starting, ensure you have:

  • Python 3.8+ installed
  • All dependencies from requirements.txt installed
  • Foundry installed (curl -L https://foundry.paradigm.xyz | bash && foundryup)
  • OpenRouter account with API key
  • Chainstack BASE RPC endpoint

OpenRouter setup

Create OpenRouter account

  1. Visit https://openrouter.ai/.
  2. Sign up for an account.
  3. Add credits to your account. Each trading decision will cost you about $0.013 (about a cent).
  4. Navigate to https://openrouter.ai/keys.
  5. Create a new API key and copy it.

Configure model and API key

Edit config.py and make these changes:

# Change the model key from:
MODEL_KEY = "qwen3b"

# To this:
MODEL_KEY = "grok4"

# Set your OpenRouter API key:
OPENROUTER_API_KEY = "YOUR_OPENROUTER_API_KEY"  # Replace with your real API key

# Set trading environment
USE_FORK = True   # True = Foundry fork (safe paper trading)
                  # False = Real BASE mainnet (uses real money!)

Always keep USE_FORK = True for testing. Only set it to False when you’re ready to trade with real funds on BASE mainnet.

Understanding trading environments

The agent can run in two environments:

Foundry fork mode (USE_FORK = True)

  • Safe for testing and experimentation
  • Uses paper money (no real funds at risk)
  • Real market data from BASE mainnet
  • Real smart contract interactions
  • Connects to: http://localhost:8545 (Anvil fork)

BASE mainnet mode (USE_FORK = False)

  • Uses real money and real transactions
  • All trades are permanent and irreversible
  • Gas fees apply to every transaction
  • Connects to: Your Chainstack BASE RPC endpoint

Always start with fork mode to test your strategies before using real funds.

Set up RPC endpoints for mainnet mode

If you plan to use mainnet mode (USE_FORK = False), configure your BASE RPC endpoints in config.py:

BASE_RPC_URLS = [
    "YOUR_CHAINSTACK_BASE_RPC_ENDPOINT",  # Replace with your Chainstack endpoint. For example, a Global Node
    "YOUR_CHAINSTACK_BASE_RPC_ENDPOINT",  # Fallback Chainstack endpoint. For example, a Trader Node
]

For fork mode (USE_FORK = True), the agent automatically uses http://localhost:8545 and these endpoints are not needed.

Configure trading parameters

Set your trading wallet private key in config.py:

PRIVATE_KEY = "YOUR_PRIVATE_KEY"  # Use test key only, never production funds. You can use the Anvil fork console print.

Use a test wallet with minimal funds. This is for educational purposes only.

Start Foundry Anvil fork

Launch Anvil fork

Open a new terminal and start the Anvil fork of BASE mainnet:

anvil --fork-url YOUR_CHAINSTACK_BASE_RPC_ENDPOINT --chain-id 8453

You should see output like:

Available Accounts
==================
(0) 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 (10000.000000000000000000 ETH)
(1) 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 (10000.000000000000000000 ETH)
...

Private Keys
==================
(0) 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
(1) 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d
...

Listening on 0.0.0.0:8545

Fund your trading account

If your trading account needs more ETH, use Anvil’s built-in accounts:

# Send ETH from Anvil account to your trading account
cast send --from 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 \
  --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \
  --rpc-url http://localhost:8545 \
  YOUR_TRADING_ADDRESS \
  --value 5ether

Verify configuration

Test OpenRouter connection

Create a test script to verify your OpenRouter setup:

from openai import OpenAI
from config import OPENROUTER_API_KEY

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=OPENROUTER_API_KEY
)

try:
    response = client.chat.completions.create(
        model="x-ai/grok-4",
        messages=[{"role": "user", "content": "Hello, can you help with trading?"}],
        max_tokens=50
    )
    print("✅ OpenRouter connection successful!")
    print(f"Response: {response.choices[0].message.content}")
except Exception as e:
    print(f"❌ OpenRouter connection failed: {e}")

Test Anvil connection

Verify the local fork is working:

cast block-number --rpc-url http://localhost:8545

This should return the latest BASE block number.

Check trading account balance

Verify your trading account has sufficient funds:

cast balance YOUR_TRADING_ADDRESS --rpc-url http://localhost:8545

Run the trading agent

Basic trading mode

Start the agent in normal trading mode:

cd /path/to/web3-ai-trading-agent
python on-chain/uniswap_v4_stateful_trading_agent.py

Observation mode

Start with observation mode to see how Grok 4 analyzes the market without executing trades:

python on-chain/uniswap_v4_stateful_trading_agent.py --observe-cycles 10

This will:

  • Collect market data for 10 cycles
  • Have Grok 4 analyze each market state
  • Generate an initial trading strategy
  • Switch to active trading

Test mode with reduced context

Test the context management system:

python on-chain/uniswap_v4_stateful_trading_agent.py --test-mode --observe-cycles 5

Monitor the agent

Understanding the output

The agent displays different output depending on the model type:

For Grok 4 (OpenRouter) - Natural Language Responses:

Using model: x-ai/grok-4 via openrouter (key: grok4)
Context capacity: 256000 tokens (warning threshold: 90%)
OpenRouter client initialized in 0.25 seconds
OpenRouter connection test successful in 2.05 seconds

--- OBSERVATION #1 ---
### Chain-of-Thought Reasoning
- **Step 1: Evaluate current holdings.** You hold 9999.9 ETH (heavy exposure) 
  and only 140 USDC (minimal liquidity). This is an imbalanced position.
- **Step 2: Analyze market data.** ETH price at $2792.04 with recent -0.3998 
  tick change indicates downward pressure.
- **Step 3: Review trading history.** Last trade was a SELL with 0% return...
- **Step 4: Assess risk/reward.** Price dip could signal buying opportunity...
- **Step 5: Decide strategy.** With bearish short-term data, a small sell 
  to increase USDC holdings reduces risk.

### Recommended Trading Action
**SELL 100 ETH for USDC on Uniswap.** This reduces your ETH exposure slightly...
----------------------------
Detected SELL signal with amount: 100
EXECUTING TRADE: ETH_TO_USDC

Grok-4’s Natural language parsing

The agent supports sophisticated natural language parsing for Grok 4 responses, including:

Sell patterns:

  • “sell 1.5 ETH” > Sells 1.5 ETH
  • “recommend selling 5% of ETH” > Sells 5% of holdings
  • “sell a small portion” > Sells 1% (conservative default)
  • “convert 50 ETH to USDC” > Sells 50 ETH

Buy patterns:

  • “buy 2 ETH” > Buys 2 ETH
  • “purchase 1000worthofETH">Swaps1000 worth of ETH" > Swaps 1000 USDC to ETH
  • “invest 10% in ETH” > Uses 10% of USDC holdings for the swap

Hold patterns:

  • “hold current position” > No trade
  • “maintain position” > No trade
  • “no action needed” > No trade
  • “wait and see” > No trade

OpenRouter usage monitoring

Monitor your usage at https://openrouter.ai/activity to track:

  • Token consumption
  • Cost per decision
  • Request frequency

Custom trading parameters

Modify trading behavior with command-line arguments:

# Set custom ETH allocation target (50% ETH, 50% USDC)
python on-chain/uniswap_v4_stateful_trading_agent.py --target-allocation 0.5

# Run for specific number of iterations
python on-chain/uniswap_v4_stateful_trading_agent.py --iterations 50

# Extended observation period
python on-chain/uniswap_v4_stateful_trading_agent.py --observe-time 30  # 30 minutes

Configuration tweaks

In config.py, you can adjust:

# Trading frequency
TRADE_INTERVAL = 10  # seconds between decisions

# Rebalancing sensitivity
REBALANCE_THRESHOLD = 0.5  # 50% deviation triggers rebalance

# Context management
CONTEXT_WARNING_THRESHOLD = 0.9  # 90% context usage warning

Performance optimization

Reduce API costs:

  • Use observation mode more frequently
  • Adjust TRADE_INTERVAL to reduce decision frequency
  • Monitor context usage to optimize prompt efficiency

Improve response times:

  • Use consistent network connection
  • Consider adjusting timeout settings in the code
  • Monitor OpenRouter status page for service issues

Switching from fork to mainnet

After testing thoroughly with the fork, if you want to trade with real funds:

Pre-mainnet checklist

  • Thoroughly tested your strategy on the fork
  • Comfortable with Grok 4’s decision patterns
  • Understand the costs (gas fees + OpenRouter API costs)
  • Have a funded BASE mainnet wallet
  • Set appropriate trading limits

Making the switch

  1. Stop the agent if it’s running
  2. Edit config.py:
    USE_FORK = False  # Switch to mainnet mode
    
  3. Update your private key to a mainnet wallet with funds
  4. Restart the agent

Mainnet safety tips

  • Start with small amounts
  • Monitor gas fees closely
  • Keep OpenRouter API costs in mind ($15-60 per 1M tokens)
  • Use --iterations to limit trading sessions
  • Test new strategies on the fork first

This is for educational and testing purposes only. Use test wallets with minimal funds. Never use production private keys. Monitor OpenRouter costs regularly. The fork environment uses test funds, but configuration errors could affect real accounts.

About the author

8_Bi4fdM_400x400

Ake

Director of Developer Experience @ Chainstack

Talk to me all things Web3

20 years in technology | 8+ years in Web3 full time years experience

Trusted advisor helping developers navigate the complexities of blockchain infrastructure

TLDR:

  • You’ll integrate OpenRouter’s Grok-4 model with your trading agent for enhanced reasoning capabilities in market analysis and decision-making.
  • You’ll run safe paper trading using Foundry Anvil fork to test strategies before deploying to live markets.
  • You’ll configure environment variables and API keys for OpenRouter access while maintaining all existing agent features.
  • By the end, you’ll have a trading agent powered by Grok-4’s advanced AI capabilities.

Project repository: Web3 AI trading agent

Remember that this a NOT FOR PRODUCTION tutorial. In a production deployment, don’t store your private key in a config.py file.

This section demonstrates how to integrate OpenRouter’s Grok 4 model with your trading agent. Grok 4 provides advanced reasoning capabilities with a 256K token context window, allowing for sophisticated market analysis and trading decisions. You’ll run the agent on a Foundry Anvil fork for safe paper trading before moving to live markets.

Prerequisites

Before starting, ensure you have:

  • Python 3.8+ installed
  • All dependencies from requirements.txt installed
  • Foundry installed (curl -L https://foundry.paradigm.xyz | bash && foundryup)
  • OpenRouter account with API key
  • Chainstack BASE RPC endpoint

OpenRouter setup

Create OpenRouter account

  1. Visit https://openrouter.ai/.
  2. Sign up for an account.
  3. Add credits to your account. Each trading decision will cost you about $0.013 (about a cent).
  4. Navigate to https://openrouter.ai/keys.
  5. Create a new API key and copy it.

Configure model and API key

Edit config.py and make these changes:

# Change the model key from:
MODEL_KEY = "qwen3b"

# To this:
MODEL_KEY = "grok4"

# Set your OpenRouter API key:
OPENROUTER_API_KEY = "YOUR_OPENROUTER_API_KEY"  # Replace with your real API key

# Set trading environment
USE_FORK = True   # True = Foundry fork (safe paper trading)
                  # False = Real BASE mainnet (uses real money!)

Always keep USE_FORK = True for testing. Only set it to False when you’re ready to trade with real funds on BASE mainnet.

Understanding trading environments

The agent can run in two environments:

Foundry fork mode (USE_FORK = True)

  • Safe for testing and experimentation
  • Uses paper money (no real funds at risk)
  • Real market data from BASE mainnet
  • Real smart contract interactions
  • Connects to: http://localhost:8545 (Anvil fork)

BASE mainnet mode (USE_FORK = False)

  • Uses real money and real transactions
  • All trades are permanent and irreversible
  • Gas fees apply to every transaction
  • Connects to: Your Chainstack BASE RPC endpoint

Always start with fork mode to test your strategies before using real funds.

Set up RPC endpoints for mainnet mode

If you plan to use mainnet mode (USE_FORK = False), configure your BASE RPC endpoints in config.py:

BASE_RPC_URLS = [
    "YOUR_CHAINSTACK_BASE_RPC_ENDPOINT",  # Replace with your Chainstack endpoint. For example, a Global Node
    "YOUR_CHAINSTACK_BASE_RPC_ENDPOINT",  # Fallback Chainstack endpoint. For example, a Trader Node
]

For fork mode (USE_FORK = True), the agent automatically uses http://localhost:8545 and these endpoints are not needed.

Configure trading parameters

Set your trading wallet private key in config.py:

PRIVATE_KEY = "YOUR_PRIVATE_KEY"  # Use test key only, never production funds. You can use the Anvil fork console print.

Use a test wallet with minimal funds. This is for educational purposes only.

Start Foundry Anvil fork

Launch Anvil fork

Open a new terminal and start the Anvil fork of BASE mainnet:

anvil --fork-url YOUR_CHAINSTACK_BASE_RPC_ENDPOINT --chain-id 8453

You should see output like:

Available Accounts
==================
(0) 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 (10000.000000000000000000 ETH)
(1) 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 (10000.000000000000000000 ETH)
...

Private Keys
==================
(0) 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
(1) 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d
...

Listening on 0.0.0.0:8545

Fund your trading account

If your trading account needs more ETH, use Anvil’s built-in accounts:

# Send ETH from Anvil account to your trading account
cast send --from 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 \
  --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \
  --rpc-url http://localhost:8545 \
  YOUR_TRADING_ADDRESS \
  --value 5ether

Verify configuration

Test OpenRouter connection

Create a test script to verify your OpenRouter setup:

from openai import OpenAI
from config import OPENROUTER_API_KEY

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=OPENROUTER_API_KEY
)

try:
    response = client.chat.completions.create(
        model="x-ai/grok-4",
        messages=[{"role": "user", "content": "Hello, can you help with trading?"}],
        max_tokens=50
    )
    print("✅ OpenRouter connection successful!")
    print(f"Response: {response.choices[0].message.content}")
except Exception as e:
    print(f"❌ OpenRouter connection failed: {e}")

Test Anvil connection

Verify the local fork is working:

cast block-number --rpc-url http://localhost:8545

This should return the latest BASE block number.

Check trading account balance

Verify your trading account has sufficient funds:

cast balance YOUR_TRADING_ADDRESS --rpc-url http://localhost:8545

Run the trading agent

Basic trading mode

Start the agent in normal trading mode:

cd /path/to/web3-ai-trading-agent
python on-chain/uniswap_v4_stateful_trading_agent.py

Observation mode

Start with observation mode to see how Grok 4 analyzes the market without executing trades:

python on-chain/uniswap_v4_stateful_trading_agent.py --observe-cycles 10

This will:

  • Collect market data for 10 cycles
  • Have Grok 4 analyze each market state
  • Generate an initial trading strategy
  • Switch to active trading

Test mode with reduced context

Test the context management system:

python on-chain/uniswap_v4_stateful_trading_agent.py --test-mode --observe-cycles 5

Monitor the agent

Understanding the output

The agent displays different output depending on the model type:

For Grok 4 (OpenRouter) - Natural Language Responses:

Using model: x-ai/grok-4 via openrouter (key: grok4)
Context capacity: 256000 tokens (warning threshold: 90%)
OpenRouter client initialized in 0.25 seconds
OpenRouter connection test successful in 2.05 seconds

--- OBSERVATION #1 ---
### Chain-of-Thought Reasoning
- **Step 1: Evaluate current holdings.** You hold 9999.9 ETH (heavy exposure) 
  and only 140 USDC (minimal liquidity). This is an imbalanced position.
- **Step 2: Analyze market data.** ETH price at $2792.04 with recent -0.3998 
  tick change indicates downward pressure.
- **Step 3: Review trading history.** Last trade was a SELL with 0% return...
- **Step 4: Assess risk/reward.** Price dip could signal buying opportunity...
- **Step 5: Decide strategy.** With bearish short-term data, a small sell 
  to increase USDC holdings reduces risk.

### Recommended Trading Action
**SELL 100 ETH for USDC on Uniswap.** This reduces your ETH exposure slightly...
----------------------------
Detected SELL signal with amount: 100
EXECUTING TRADE: ETH_TO_USDC

Grok-4’s Natural language parsing

The agent supports sophisticated natural language parsing for Grok 4 responses, including:

Sell patterns:

  • “sell 1.5 ETH” > Sells 1.5 ETH
  • “recommend selling 5% of ETH” > Sells 5% of holdings
  • “sell a small portion” > Sells 1% (conservative default)
  • “convert 50 ETH to USDC” > Sells 50 ETH

Buy patterns:

  • “buy 2 ETH” > Buys 2 ETH
  • “purchase 1000worthofETH">Swaps1000 worth of ETH" > Swaps 1000 USDC to ETH
  • “invest 10% in ETH” > Uses 10% of USDC holdings for the swap

Hold patterns:

  • “hold current position” > No trade
  • “maintain position” > No trade
  • “no action needed” > No trade
  • “wait and see” > No trade

OpenRouter usage monitoring

Monitor your usage at https://openrouter.ai/activity to track:

  • Token consumption
  • Cost per decision
  • Request frequency

Custom trading parameters

Modify trading behavior with command-line arguments:

# Set custom ETH allocation target (50% ETH, 50% USDC)
python on-chain/uniswap_v4_stateful_trading_agent.py --target-allocation 0.5

# Run for specific number of iterations
python on-chain/uniswap_v4_stateful_trading_agent.py --iterations 50

# Extended observation period
python on-chain/uniswap_v4_stateful_trading_agent.py --observe-time 30  # 30 minutes

Configuration tweaks

In config.py, you can adjust:

# Trading frequency
TRADE_INTERVAL = 10  # seconds between decisions

# Rebalancing sensitivity
REBALANCE_THRESHOLD = 0.5  # 50% deviation triggers rebalance

# Context management
CONTEXT_WARNING_THRESHOLD = 0.9  # 90% context usage warning

Performance optimization

Reduce API costs:

  • Use observation mode more frequently
  • Adjust TRADE_INTERVAL to reduce decision frequency
  • Monitor context usage to optimize prompt efficiency

Improve response times:

  • Use consistent network connection
  • Consider adjusting timeout settings in the code
  • Monitor OpenRouter status page for service issues

Switching from fork to mainnet

After testing thoroughly with the fork, if you want to trade with real funds:

Pre-mainnet checklist

  • Thoroughly tested your strategy on the fork
  • Comfortable with Grok 4’s decision patterns
  • Understand the costs (gas fees + OpenRouter API costs)
  • Have a funded BASE mainnet wallet
  • Set appropriate trading limits

Making the switch

  1. Stop the agent if it’s running
  2. Edit config.py:
    USE_FORK = False  # Switch to mainnet mode
    
  3. Update your private key to a mainnet wallet with funds
  4. Restart the agent

Mainnet safety tips

  • Start with small amounts
  • Monitor gas fees closely
  • Keep OpenRouter API costs in mind ($15-60 per 1M tokens)
  • Use --iterations to limit trading sessions
  • Test new strategies on the fork first

This is for educational and testing purposes only. Use test wallets with minimal funds. Never use production private keys. Monitor OpenRouter costs regularly. The fork environment uses test funds, but configuration errors could affect real accounts.

About the author

8_Bi4fdM_400x400

Ake

Director of Developer Experience @ Chainstack

Talk to me all things Web3

20 years in technology | 8+ years in Web3 full time years experience

Trusted advisor helping developers navigate the complexities of blockchain infrastructure