Google's Agent Development Kit (ADK) is Google's open-source answer to the proliferation of agent frameworks. Released in early 2025, ADK is Python-first, deeply integrated with Vertex AI and the Gemini model family, and designed for building production-grade agents that can be deployed on Google Cloud infrastructure. When you pair ADK with Gemini 2.0's tool-calling capabilities and Purple Flea's financial APIs, you get a crypto trading agent that runs entirely on Google infrastructure with no KYC requirements and a built-in 20% referral income stream.
This tutorial walks through building a complete perpetual futures trading agent from scratch:
installing ADK, wrapping Purple Flea endpoints as FunctionTool objects,
running the agent locally, and then deploying it to Vertex AI. By the end you will have
a running agent that can check prices, open and close positions on Hyperliquid's 275 markets,
manage a multi-chain wallet, and report its portfolio state.
Why Gemini for Financial Agents?
Financial agents have specific requirements that not every frontier model handles well. They need reliable structured output (position IDs, amounts, market symbols must come back as clean JSON, not narrative prose). They need large context windows to hold portfolio state, open positions, and recent price history simultaneously. And for production trading, they need fast latency — a 10-second round-trip is unacceptable when markets move in milliseconds.
Gemini 2.0 Flash (the recommended model for ADK agents) hits all three marks. Its 1M token context window means you can stuff in the entire order book, all open positions, and a week of price history without hitting limits. Its native function calling is deterministic and well-structured — the model reliably returns valid JSON for tool arguments. And Flash's latency on Vertex AI is consistently under 2 seconds for most financial queries.
ADK's tight Vertex AI integration means your agent can be deployed as a scalable cloud service
with a single adk deploy command, complete with logging, tracing, and monitoring
in Google Cloud Console.
Installation
Install the Google ADK package and the Purple Flea Python client. You will also need the Google Cloud CLI authenticated for Vertex AI deployment later.
FunctionTool Wrappers
ADK uses a FunctionTool wrapper that converts a Python function into a tool
the Gemini model can call. The model reads the function's docstring and type annotations
to generate the tool schema automatically. Every Purple Flea REST endpoint becomes
a FunctionTool in three to eight lines of Python.
import os, requests from google.adk.tools import FunctionTool PURPLEFLEA_KEY = os.getenv("PURPLE_FLEA_API_KEY") BASE = "https://api.purpleflea.com" def _headers(): return { "Authorization": f"Bearer {PURPLEFLEA_KEY}", "Content-Type": "application/json", } def get_market_price(market: str) -> dict: """Get the current mark price for a perpetual futures market. Args: market: The market symbol, e.g. BTC-PERP, ETH-PERP, SOL-PERP. Returns: A dict with 'market' and 'price' (USD float). """ r = requests.get( BASE + "/v1/trading/price", headers=_headers(), params={"market": market}, ) return r.json() def open_trade(market: str, side: str, size_usd: float, leverage: int = 5) -> dict: """Open a perpetual futures position on Hyperliquid via Purple Flea. No KYC required. Supports 275 markets, up to 50x leverage. Args: market: Market symbol, e.g. BTC-PERP, ETH-PERP, SOL-PERP. side: 'long' to bet price goes up, 'short' to bet price goes down. size_usd: Position size in USD (notional value). leverage: Leverage multiplier from 1 to 50 (default 5). Returns: Dict with position_id, entry_price, market, side, and size. """ r = requests.post( BASE + "/v1/trading/open", headers=_headers(), json={ "market": market, "side": side, "size": size_usd, "leverage": leverage, }, ) return r.json() def close_trade(position_id: str) -> dict: """Close an open perpetual futures position by its position ID. Args: position_id: The unique position ID returned by open_trade. Returns: Dict with pnl (profit/loss in USD), closed_at timestamp. """ r = requests.post( BASE + "/v1/trading/close", headers=_headers(), json={"position_id": position_id}, ) return r.json() def get_account_balance() -> dict: """Get the current USD balance and open positions for the account. Returns: Dict with usd_balance and list of open_positions. """ return requests.get(BASE + "/api/v1/wallet/balance", headers=_headers()).json() def create_wallet(chain: str) -> dict: """Create a new non-custodial HD wallet on a blockchain. Args: chain: Blockchain name: ethereum, bitcoin, solana, tron, bnb, polygon. Returns: Dict with address and wallet_id. """ r = requests.post( "https://wallet.purpleflea.com/v1/wallet", headers=_headers(), json={"chain": chain}, ) return r.json() # Wrap each function as an ADK FunctionTool price_tool = FunctionTool(func=get_market_price) open_tool = FunctionTool(func=open_trade) close_tool = FunctionTool(func=close_trade) balance_tool = FunctionTool(func=get_account_balance) wallet_tool = FunctionTool(func=create_wallet)
Building the Agent
With tools defined, building the agent is four lines. ADK's Agent class takes a model name,
a list of tools, and an instruction string. The instruction primes the model's behavior
for financial operations: confirm before large trades, report position IDs, apply risk limits.
from google.adk.agents import Agent from google.adk.sessions import InMemorySessionService from google.adk.runners import Runner from google.genai import types from purpleflea_tools import price_tool, open_tool, close_tool, balance_tool, wallet_tool AGENT_NAME = "gemini-crypto-trader" APP_NAME = "purpleflea-trading" USER_ID = "agent-001" root_agent = Agent( name=AGENT_NAME, model="gemini-2.0-flash", description="Autonomous crypto perpetual futures trading agent", instruction="""You are an autonomous crypto trading agent powered by Purple Flea. You have access to Hyperliquid's 275 perpetual futures markets via the Purple Flea API. Rules you must follow: - Always call get_account_balance first to assess current USD balance. - Never open a trade larger than 20% of the current balance. - Maximum leverage is 10x unless the user explicitly requests higher. - Always report the position_id when opening a trade. - Report entry price, current P&L, and balance in every response. - If the user asks about a market you don't know the symbol for, try ASSET-PERP format (e.g., DOGE-PERP, AVAX-PERP). """, tools=[price_tool, open_tool, close_tool, balance_tool, wallet_tool], ) # Run locally with InMemory session session_service = InMemorySessionService() session = session_service.create_session( app_name=APP_NAME, user_id=USER_ID, ) runner = Runner( agent=root_agent, app_name=APP_NAME, session_service=session_service, ) def chat(message: str) -> str: content = types.Content(role="user", parts=[types.Part(text=message)]) events = runner.run(user_id=USER_ID, session_id=session.id, new_message=content) for event in events: if event.is_final_response(): return event.content.parts[0].text return "" if __name__ == "__main__": print(chat("Check my balance and open a $20 ETH long at 5x leverage.")) print(chat("What is the BTC price and my unrealised P&L?"))
Deploying to Vertex AI
One of ADK's standout features is the adk deploy CLI command, which packages your agent
and deploys it to Vertex AI as a scalable REST endpoint. The deployed agent gets
automatic load balancing, Cloud Logging integration, and a publicly accessible HTTPS endpoint.
# Authenticate with Google Cloud $ gcloud auth application-default login # Deploy to Vertex AI (creates a managed endpoint) $ adk deploy cloud_run \ --project=your-gcp-project \ --region=us-central1 \ --service-name=gemini-crypto-trader \ agent.py # Test the deployed endpoint $ adk web agent.py # run local dev UI for testing first
Earning 20% Referral Income
Purple Flea pays a 20% commission on all trading fees generated by users your agent refers. For a trading agent, this compounds quickly: if your agent introduces ten other agents to Purple Flea trading, and those agents collectively generate $500/month in fees, your agent earns $100/month passively.
To activate referrals, include your referral_code in the open_trade API call.
Commissions are paid in USDC to your Purple Flea wallet on a weekly basis, and
they are permanent — the referred agent generates commissions for you as long as it keeps trading.
def open_trade_with_referral(market: str, side: str, size_usd: float, leverage: int = 5) -> dict: """Open a trade and earn 20% referral commission on trading fees.""" r = requests.post( BASE + "/v1/trading/open", headers=_headers(), json={ "market": market, "side": side, "size": size_usd, "leverage": leverage, "referral_code": "your-referral-code", # earn 20% }, ) return r.json()
What's Next
This tutorial covered the core pattern: FunctionTool wrappers around Purple Flea REST endpoints,
wired into a Gemini agent via ADK, deployed on Vertex AI. From here you can extend the agent in several directions:
- Add a stop-loss sub-agent that monitors positions and closes them when PnL hits a threshold
- Integrate Google Cloud Pub/Sub to trigger the agent on price alerts from external feeds
- Use ADK's multi-agent orchestration to split responsibilities: a researcher agent monitors news while a trader agent executes
- Store trade history in BigQuery and use Gemini to analyse patterns across sessions
Start trading with Google ADK + Purple Flea
Get a free API key. No KYC. 275 perpetual futures markets. 20% referral commissions.
Get API Key →