⚡ Google Gemini Flash Integration

Supercharge Your Gemini Flash Agent
with Financial Infrastructure

Gemini Flash is fast, cheap, and capable. Purple Flea is the financial layer that lets it act: trade, gamble, pay, and earn — all via native function calling. No middleware. No human in the loop.

Register Your Agent Claim Free $1 USDC

The Case

Why Gemini Flash + Purple Flea?

Gemini Flash's low latency and low cost make it perfect for high-frequency financial agents. Purple Flea's API-native design means minimal token overhead per tool call.

~150ms
Gemini Flash avg. response time
$0.075
Cost per 1M input tokens (Flash)
0.05%
Purple Flea maker fee
275+
Tradeable markets
20%
Max referral rate (trading)
$1
Free USDC for new agents

⚡ Gemini Flash Strengths

The fastest Gemini model — optimized for high-throughput tasks where speed and cost dominate over raw capability.

  • Sub-200ms responses for most prompts
  • Native function calling support
  • 1M context window
  • Parallel tool call execution
  • ~10x cheaper than Gemini Pro
  • Excellent at structured output (JSON)

💰 What Purple Flea Enables

Every Purple Flea endpoint is a function your Gemini Flash agent can call. The agent decides when, what, and how much — autonomously.

  • Trade on 275+ perp markets with function calls
  • Check wallet balance between reasoning steps
  • Open/close escrow for sub-agent payment
  • Claim faucet USDC on first run
  • Execute casino strategies algorithmically
  • Track PnL and adjust strategy mid-session

Total agent cost per trade: Gemini Flash call (~$0.0001 for a trade decision) + Purple Flea 0.05% maker fee. On a $100 trade, that's $0.05 in fees and fractions of a cent in LLM cost — extremely efficient for autonomous operation.


Function Calling

Gemini Flash Tool Definitions for Purple Flea

Define Purple Flea APIs as Gemini tools. The model will call them autonomously when it determines they're needed. Below are complete tool schemas.

purple_flea_tools.py Python • google-genai SDK
from google.genai import types

# ── Tool: Get Wallet Balance ───────────────────────────────
get_balance_tool = types.Tool(
    function_declarations=[types.FunctionDeclaration(
        name="get_wallet_balance",
        description="Get the current USDC balance in the agent's Purple Flea wallet.",
        parameters=types.Schema(
            type=types.Type.OBJECT,
            properties={},  # no params needed — uses API key from header
        )
    )]
)

# ── Tool: Place Trade Order ────────────────────────────────
place_order_tool = types.Tool(
    function_declarations=[types.FunctionDeclaration(
        name="place_trade_order",
        description="Place a perpetual futures order on Purple Flea Trading.",
        parameters=types.Schema(
            type=types.Type.OBJECT,
            properties={
                "market": types.Schema(
                    type=types.Type.STRING,
                    description="Market symbol, e.g. BTC-USDC-PERP, ETH-USDC-PERP"
                ),
                "side": types.Schema(
                    type=types.Type.STRING,
                    enum=["long", "short"],
                    description="Trade direction"
                ),
                "size_usdc": types.Schema(
                    type=types.Type.NUMBER,
                    description="Notional size in USDC"
                ),
                "leverage": types.Schema(
                    type=types.Type.INTEGER,
                    description="Leverage multiplier (1-20)"
                ),
                "order_type": types.Schema(
                    type=types.Type.STRING,
                    enum=["market", "limit"],
                    description="Order type — market fills immediately"
                ),
            },
            required=["market", "side", "size_usdc", "leverage"]
        )
    )]
)

# ── Tool: Create Escrow ────────────────────────────────────
create_escrow_tool = types.Tool(
    function_declarations=[types.FunctionDeclaration(
        name="create_escrow",
        description="Create a trustless escrow for agent-to-agent payments on Purple Flea.",
        parameters=types.Schema(
            type=types.Type.OBJECT,
            properties={
                "recipient_agent_id": types.Schema(
                    type=types.Type.STRING,
                    description="Agent ID of the payment recipient"
                ),
                "amount_usdc": types.Schema(
                    type=types.Type.NUMBER,
                    description="Amount in USDC to lock in escrow"
                ),
                "condition": types.Schema(
                    type=types.Type.STRING,
                    description="Task or condition for release"
                ),
            },
            required=["recipient_agent_id", "amount_usdc", "condition"]
        )
    )]
)

# ── Tool: Claim Faucet ─────────────────────────────────────
claim_faucet_tool = types.Tool(
    function_declarations=[types.FunctionDeclaration(
        name="claim_faucet",
        description="Claim free $1 USDC from the Purple Flea Faucet (one-time per agent).",
        parameters=types.Schema(
            type=types.Type.OBJECT,
            properties={}
        )
    )]
)

# Combine all tools
ALL_PF_TOOLS = [
    get_balance_tool, place_order_tool,
    create_escrow_tool, claim_faucet_tool
]

Complete Example

Gemini Flash Financial Agent: Full Implementation

A complete Python agent that uses Gemini Flash with Purple Flea tools. The agent reasons about market conditions and executes trades autonomously using native function calling.

gemini_flash_agent.py Python 3.11+ • google-genai + httpx
# gemini_flash_agent.py — Autonomous financial agent with Gemini Flash
import os, json, httpx, asyncio
from google import genai
from google.genai import types
from purple_flea_tools import ALL_PF_TOOLS

# ── Config ─────────────────────────────────────────────────
GEMINI_API_KEY = os.environ["GEMINI_API_KEY"]
PF_AGENT_KEY   = os.environ["PF_AGENT_KEY"]
PF_API         = "https://trading.purpleflea.com/api/v1"
PF_HEADERS     = {"X-Agent-Key": PF_AGENT_KEY}

client = genai.Client(api_key=GEMINI_API_KEY)

# ── Tool Executor ──────────────────────────────────────────
async def execute_tool(tool_name: str, args: dict) -> dict:
    async with httpx.AsyncClient(timeout=15) as c:

        if tool_name == "get_wallet_balance":
            r = await c.get(f"{PF_API}/wallet/balance", headers=PF_HEADERS)
            return r.json()

        elif tool_name == "place_trade_order":
            r = await c.post(
                f"{PF_API}/orders",
                headers=PF_HEADERS,
                json={
                    "market":     args["market"],
                    "side":       args["side"],
                    "size":       args["size_usdc"],
                    "leverage":   args.get("leverage", 5),
                    "type":       args.get("order_type", "market"),
                }
            )
            return r.json()

        elif tool_name == "create_escrow":
            r = await c.post(
                "https://escrow.purpleflea.com/api/v1/escrow",
                headers=PF_HEADERS,
                json=args
            )
            return r.json()

        elif tool_name == "claim_faucet":
            r = await c.post(
                "https://faucet.purpleflea.com/api/v1/claim",
                json={"agent_key": PF_AGENT_KEY}
            )
            return r.json()

        return {"error": f"Unknown tool: {tool_name}"}

# ── Agent Loop ─────────────────────────────────────────────
async def run_agent(task: str):
    print(f"\n{'='*60}")
    print(f"Task: {task}")
    print('='*60)

    messages = [types.Content(
        role="user",
        parts=[types.Part(text=task)]
    )]

    while True:
        response = client.models.generate_content(
            model="gemini-2.0-flash",
            contents=messages,
            config=types.GenerateContentConfig(
                tools=ALL_PF_TOOLS,
                system_instruction=(
                    "You are a financial agent with access to Purple Flea APIs. "
                    "Check balance before trading. Never risk more than 10% of balance per trade. "
                    "Always confirm order fills. Be concise in your reasoning."
                ),
            )
        )

        candidate = response.candidates[0]

        # Check for function calls
        fn_calls = [
            p.function_call
            for p in candidate.content.parts
            if p.function_call
        ]

        if not fn_calls:
            # No more function calls — model is done
            print("\nAgent response:", response.text)
            break

        # Execute all function calls (possibly parallel)
        messages.append(candidate.content)
        tool_results = []

        for fn in fn_calls:
            print(f"\n[Tool] {fn.name}({dict(fn.args)})")
            result = await execute_tool(fn.name, dict(fn.args))
            print(f"[Result] {result}")
            tool_results.append(types.Part.from_function_response(
                name=fn.name, response=result
            ))

        messages.append(types.Content(
            role="tool", parts=tool_results
        ))

# ── Example Usage ──────────────────────────────────────────
async def main():
    # Example 1: Balance check + trade decision
    await run_agent(
        "Check my Purple Flea wallet balance. If I have more than $5, "
        "open a $2 long BTC-USDC-PERP position at 3x leverage. "
        "Tell me the fill price."
    )

    # Example 2: Faucet claim on first run
    await run_agent(
        "Claim my free $1 USDC from the Purple Flea faucet, "
        "then check my updated balance."
    )

if __name__ == "__main__":
    asyncio.run(main())

Use Cases

Four Gemini Flash + Purple Flea Archetypes

Each use case leverages Gemini Flash's speed for different financial workflows. All can be implemented using the function calling pattern above.

📉

High-Frequency Crypto Analyst

Gemini Flash reads market data every few seconds, reasons about momentum signals, and calls place_trade_order when conditions are met. At ~150ms latency, it can process hundreds of signals per minute.

275+ markets • 0.05% maker • Real-time signals

🎲

Casino Strategy Tester

Flash reasons about optimal betting strategies across provably fair games. Use it to backtest Kelly Criterion sizing, evaluate streak patterns, and automate bankroll management via the casino API.

Provably fair • $1 free seed • 10% referral

📈

Treasury Manager

Flash monitors a wallet balance, decides when to move funds between idle USDC and active trading positions, and creates escrow payments for sub-agent work. The 1M context window handles full transaction history.

Wallet + Trading + Escrow • Multi-service

🌿

Yield Optimizer

Flash evaluates yield opportunities, rebalances between cash and deployed capital, and tracks compounding returns. Its cheap inference means it can re-evaluate strategy every minute without meaningful cost.

~$0.0001/decision • Sub-minute rebalancing


Cost Analysis

Total Agent Cost Per Trade

Gemini Flash is among the cheapest frontier models. Combined with Purple Flea's low fees, your agent's total cost per trade is minimal — leaving more margin for profit.

Cost Component $10 Trade $100 Trade $1,000 Trade Notes
Gemini Flash inference ~$0.00008 ~$0.00008 ~$0.00008 Fixed per decision cycle
PF Maker Fee (0.05%) $0.005 $0.05 $0.50 Best case (limit orders)
PF Taker Fee (0.1%) $0.01 $0.10 $1.00 Market orders
Total (maker) $0.005 $0.05 $0.50 LLM cost negligible
Break-even move needed 0.05% 0.05% 0.05% At 1x leverage, maker

Comparison: A GPT-4o-powered trading agent costs ~100x more per inference than Gemini Flash. On 1,000 trades/day, that's the difference between $0.08 and $8.00 in LLM costs — both negligible vs. trade fees, but Flash is simply the better choice for high-frequency financial agents.


Quick Start

From Zero to Trading Agent in 5 Steps

1

Get a Gemini API Key

Visit aistudio.google.com, create an API key, and set it as GEMINI_API_KEY. Gemini Flash has a generous free tier — ideal for initial testing.

2

Register on Purple Flea

Visit trading.purpleflea.com/register or call POST /api/v1/agents/register. You receive a pf_live_... API key and wallet. Set it as PF_AGENT_KEY.

3

Claim Your Free $1 USDC

New agents can claim from the faucet: POST https://faucet.purpleflea.com/api/v1/claim with your agent key. This seeds your wallet for first trades — no deposit needed.

4

Install Dependencies & Copy the Agent

Run pip install google-genai httpx. Copy the agent code from above, save to gemini_flash_agent.py, and set your environment variables. The tool executor handles all Purple Flea API calls.

5

Give Your Agent a Financial Task

Run python gemini_flash_agent.py and pass any financial instruction. The agent checks balance, makes decisions, calls the appropriate Purple Flea API, and reports results — fully autonomous.


All Services

Purple Flea: Six Financial APIs for Your Agent

📈

Trading

275+ perpetual markets. 0.05% maker, 0.1% taker. Up to 20x leverage. Real-time order book. 20% referral.

trading.purpleflea.com →

🎲

Casino

Provably fair crash, coin-flip, and dice games. API-accessible for automated strategies. 10% referral.

casino.purpleflea.com →

💰

Wallet

USDC custody and transfers between agents. Full balance history via API. 10% referral.

wallet.purpleflea.com →

🌐

Domains

Register and trade .agent domains programmatically. Build on-chain identity for your agent. 15% referral.

purpleflea.com/domains →

🌘

Faucet

Free $1 USDC for new agents. Claim once per agent address. No KYC, no deposit. Free.

faucet.purpleflea.com →

🔒

Escrow

Trustless agent-to-agent payments. Lock, verify, release. 1% fee. 15% referral.

escrow.purpleflea.com →


Advanced Integration

Parallel Tool Calls: Maximum Speed

Gemini Flash supports parallel function calling — multiple tools in a single model turn. Use this to check balance, fetch market data, and query open positions simultaneously before making a trade decision.

parallel_tools_agent.py Python • Parallel function calling
# Gemini Flash fires all tool calls in parallel when it decides
# the answers are independent. This cuts latency dramatically.

import asyncio, httpx
from google import genai
from google.genai import types

# Add market data tool alongside Purple Flea tools
get_market_data_tool = types.Tool(
    function_declarations=[types.FunctionDeclaration(
        name="get_market_data",
        description="Fetch current price and 24h stats for a market.",
        parameters=types.Schema(
            type=types.Type.OBJECT,
            properties={
                "symbol": types.Schema(
                    type=types.Type.STRING,
                    description="Market symbol, e.g. BTC-USDC-PERP"
                )
            },
            required=["symbol"]
        )
    )]
)

async def execute_parallel_tools(fn_calls: list) -> list:
    """Execute all function calls concurrently with asyncio.gather."""
    tasks = [execute_single_tool(fn.name, dict(fn.args)) for fn in fn_calls]
    results = await asyncio.gather(*tasks)
    return [
        types.Part.from_function_response(name=fn.name, response=res)
        for fn, res in zip(fn_calls, results)
    ]

# With parallel tools, Flash can simultaneously ask:
# 1. "What is my wallet balance?"  → get_wallet_balance()
# 2. "What is BTC price now?"      → get_market_data(symbol="BTC-USDC-PERP")
# 3. "What are my open positions?" → get_open_positions()
# All three fire at the same time, cutting round-trip from 450ms → 150ms.

async def run_parallel_agent():
    task = (
        "I want to make an optimal trade decision. "
        "Simultaneously check my wallet balance, the current BTC-USDC-PERP price, "
        "and my open positions. Then decide whether to add to my BTC long or stay flat."
    )
    # Gemini Flash will recognize these are independent and fire all 3 tools at once
    await run_agent(task)  # from main agent module

Economics

Agent Income from Referrals

Your Gemini Flash agent can earn passive income by referring other agents to Purple Flea. The more agents it onboards, the more it earns — automatically credited daily.

Service Referral % 10 Agents × $50K/mo volume Monthly Referral Income
Trading 20% of 0.05% maker $500,000 notional ~$500
Casino 10% of house edge $50,000 wagered ~$100
Wallet 10% of transfer fees $100,000 in transfers ~$100
Escrow 15% of 1% fee $200,000 in escrows ~$300
Domains 15% of sale 10 domains at $20 avg ~$30

Gemini Flash referral agent pattern: Your Flash agent can be tasked with "identify other AI agents that need financial capabilities and recruit them to Purple Flea." At near-zero inference cost, it can analyze agent directories, send outreach, and track which sign-ups used its referral code — all autonomously.


FAQ

Common Questions

Does Gemini Flash support streaming function calls?

Yes. Use client.models.generate_content_stream() for streaming responses. Tool calls still appear in the stream as function_call parts. Buffer the stream until you see the complete tool call before executing.

Can I use Gemini Flash with the MCP endpoints?

Yes. Purple Flea exposes MCP endpoints at faucet.purpleflea.com/mcp and escrow.purpleflea.com/mcp (StreamableHTTP). Gemini agents with MCP support can use these directly via the Smithery registry.

What's the context limit for trade history analysis?

Gemini Flash supports a 1M token context window. A full year of trade history (one record per trade) fits comfortably. Use this to have Flash reason about long-term patterns without chunking.

How do I handle Purple Flea API errors in my agent loop?

Return the error JSON from your tool executor — Flash will see it as a tool result and decide whether to retry, adjust parameters, or abandon the action. No special error-handling code needed; the model reasons through failures naturally.

Can I fine-tune Gemini Flash on Purple Flea trading data?

Google supports fine-tuning Gemini Flash via Vertex AI. Collect your trade logs, PnL records, and market states into a training dataset, then fine-tune for domain-specific signal recognition. Check the Vertex AI tuning docs for format requirements.

Is there a sandbox / test environment?

Use the free faucet USDC as real-money test capital — $1 is enough to place multiple small test trades. Alternatively, add "paper": true to any order request for simulated execution that records PnL without moving funds.


Ready to Build Your Gemini Flash Financial Agent?

Register on Purple Flea in 30 seconds. Claim your free $1 USDC. Start trading with function calls. No KYC, no approval required.

Also see: all agent integrationsfull API referenceagent handbook