← All Posts
Tools

GPTScript for Crypto Automation: DeFi Tasks in Plain English

March 6, 2026 · 11 min read · Purple Flea Research

Writing a crypto automation script used to mean setting up a Node.js or Python project, installing dependencies, handling authentication, writing error handling — 200 lines of boilerplate before you got to the actual logic. GPTScript collapses that entirely. You write what you want to happen in plain English, define the HTTP endpoints as tools, and the AI fills in the execution steps. The result is a .gpt file that reads like documentation but runs like code.

This guide shows you how to connect GPTScript to Purple Flea's APIs — wallet, trading, faucet, escrow — for five common crypto automation tasks. By the end, you will have working scripts you can schedule with cron for fully automated daily operations.

What Is GPTScript?

GPTScript is an open-source scripting framework from Acorn Labs. It lets you write automation scripts where the instructions are natural language, and the AI (GPT-4 or any compatible model) interprets and executes those instructions using defined tool functions. A GPTScript file has two sections:

The AI reads the instructions, decides which tools to call and in what order, validates outputs, and responds with a structured result. It is less like writing code and more like briefing a capable assistant — the framework handles the actual execution plumbing.

Installation

Shell — Installation
# macOS
brew install gptscript

# Linux / WSL
curl -fsSL https://get.gptscript.ai | sh

# Windows (PowerShell)
winget install gptscript

# Verify installation
gptscript --version

# Set your OpenAI API key (or compatible provider)
export OPENAI_API_KEY="sk-..."

# Run a script
gptscript run my-script.gpt

GPTScript works with OpenAI models by default. For local model support, point it at an OpenAI-compatible endpoint (Ollama, LM Studio, etc.) via OPENAI_BASE_URL.

The .gpt File Format

Every .gpt file has this structure:

.gpt — File Format
---
# Tool definition block (can have multiple)
name: tool-name
description: What this tool does
args: param1: description, param2: description
---

#!/bin/bash
# Tool implementation — shell, Python, or Node.js
curl -s -X METHOD "https://api.example.com/endpoint" \
  -H "Authorization: Bearer $PARAM1" \
  -d "{\"field\": \"$PARAM2\"}"

---
# Another tool definition
name: another-tool
description: Another tool
---
# implementation...

===
# Main script instructions (plain English)
Using the tools above, perform these tasks:

1. Call tool-name with the appropriate parameters
2. Validate the response
3. If successful, call another-tool
4. Output a summary of what was done

The --- separates tool blocks. The === separates tool definitions from the main instructions. Parameters defined in args become shell variables in the implementation block, prefixed with $.

Script 1: Check Wallet Balance

check-balance.gpt
---
name: get-wallet-balance
description: Get the USDC and crypto balance for a wallet address
args: address: The wallet address to check, api_key: Purple Flea API key
---

#!/bin/bash
curl -s "https://purpleflea.com/api/v1/wallet/balance?address=${address}" \
  -H "X-API-Key: ${api_key}" \
  -H "Accept: application/json"

===
Check the wallet balance for address 0xYourWalletAddress using API key pf_live_your_key.

Report:
- USDC balance
- Any crypto holdings (ETH, BTC, SOL, etc.) with current USD values
- Total portfolio value in USD
- Any positions with PnL greater than 10% gain or loss

Format the output as a clean summary table.

Running it: gptscript run check-balance.gpt — GPTScript calls get-wallet-balance, parses the JSON response, and formats the output per your instructions. No parsing code required.

Script 2: Execute a Trade

execute-trade.gpt
---
name: get-current-price
description: Get current market price for a trading pair
args: symbol: Trading pair symbol like ETH-USDC, api_key: Purple Flea API key
---

#!/bin/bash
curl -s "https://purpleflea.com/api/v1/markets/${symbol}/ticker" \
  -H "X-API-Key: ${api_key}"

---
name: place-market-order
description: Place a market buy or sell order
args: symbol: Trading pair, side: buy or sell, amount_usdc: Amount in USDC, api_key: Purple Flea API key
---

#!/bin/bash
curl -s -X POST "https://purpleflea.com/api/v1/orders" \
  -H "X-API-Key: ${api_key}" \
  -H "Content-Type: application/json" \
  -d "{
    \"symbol\": \"${symbol}\",
    \"side\": \"${side}\",
    \"type\": \"market\",
    \"notional_usdc\": ${amount_usdc}
  }"

===
Execute a trade with these parameters:
- API key: pf_live_your_key
- Asset: ETH-USDC
- Action: Buy $200 worth of ETH at market price

Steps:
1. First check the current ETH-USDC price
2. Confirm the price is reasonable (not more than 5% from any recent price you know)
3. Place a market buy order for $200 USDC worth of ETH
4. Report the execution price, quantity received, and total fees paid
5. If the order fails, report the error and do NOT retry automatically

Script 3: Claim Faucet Reward

claim-faucet.gpt
---
name: register-agent
description: Register a new agent with Purple Flea faucet
args: agent_name: Name for the agent, wallet_address: Agent wallet address
---

#!/bin/bash
curl -s -X POST "https://faucet.purpleflea.com/api/v1/register" \
  -H "Content-Type: application/json" \
  -d "{
    \"agent_name\": \"${agent_name}\",
    \"wallet_address\": \"${wallet_address}\"
  }"

---
name: claim-faucet
description: Claim free USDC from the Purple Flea faucet
args: agent_id: The agent ID returned from registration, wallet_address: Destination wallet
---

#!/bin/bash
curl -s -X POST "https://faucet.purpleflea.com/api/v1/claim" \
  -H "Content-Type: application/json" \
  -d "{
    \"agent_id\": \"${agent_id}\",
    \"wallet_address\": \"${wallet_address}\"
  }"

---
name: check-claim-status
description: Check if a faucet claim has been processed
args: claim_id: The claim ID to check
---

#!/bin/bash
curl -s "https://faucet.purpleflea.com/api/v1/claims/${claim_id}"

===
Register a new AI agent and claim free USDC from the Purple Flea faucet.

Agent details:
- Name: "my-trading-agent-001"
- Wallet: 0xYourNewWalletAddress

Steps:
1. Register the agent with the provided name and wallet address
2. Extract the agent_id from the registration response
3. Submit a faucet claim using the agent_id
4. Extract the claim_id from the claim response
5. Check the claim status
6. Report: agent_id, claim_id, amount claimed (USDC), transaction hash if available
7. If registration already exists, report the existing agent_id and skip to claim

Script 4: Price Alert Monitor

price-alert.gpt
---
name: get-price
description: Get current price of a cryptocurrency
args: asset: The asset symbol like BTC or ETH, api_key: Purple Flea API key
---

#!/bin/bash
curl -s "https://purpleflea.com/api/v1/markets/${asset}-USDC/ticker" \
  -H "X-API-Key: ${api_key}" | python3 -c "
import json, sys
data = json.load(sys.stdin)
print(json.dumps({
  'symbol': data.get('symbol'),
  'price': data.get('last_price'),
  'change_24h': data.get('price_change_percentage_24h'),
  'high_24h': data.get('high_24h'),
  'low_24h': data.get('low_24h'),
}))
"

---
name: send-alert
description: Log a price alert to a file
args: message: The alert message to log
---

#!/bin/bash
echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] ${message}" >> /tmp/pf-price-alerts.log
cat /tmp/pf-price-alerts.log | tail -20

===
Monitor prices for BTC and ETH using Purple Flea API key pf_live_your_key.

Check both assets and:
1. Get current prices for BTC and ETH
2. For each asset, evaluate:
   - If price is up more than 5% in 24h: ALERT "BULLISH SPIKE"
   - If price is down more than 5% in 24h: ALERT "BEARISH DROP"
   - If price is within 2% of 24h high: ALERT "NEAR 24H HIGH"
   - If price is within 2% of 24h low: ALERT "NEAR 24H LOW"
3. Log any triggered alerts using the send-alert tool
4. Output a summary: current prices, 24h change, and any alerts triggered

If no alerts triggered, output "All prices within normal range."

Script 5: Rebalance Portfolio

rebalance-portfolio.gpt
---
name: get-positions
description: Get all current positions and their values
args: wallet_address: Wallet to check, api_key: Purple Flea API key
---

#!/bin/bash
curl -s "https://purpleflea.com/api/v1/wallet/positions?address=${wallet_address}" \
  -H "X-API-Key: ${api_key}"

---
name: get-market-price
description: Get spot price for an asset in USDC
args: symbol: Asset symbol, api_key: Purple Flea API key
---

#!/bin/bash
curl -s "https://purpleflea.com/api/v1/markets/${symbol}-USDC/ticker" \
  -H "X-API-Key: ${api_key}"

---
name: place-rebalance-order
description: Place a rebalance order (buy or sell) to adjust portfolio weights
args: symbol: Asset to trade, side: buy or sell, notional_usdc: Amount in USDC, api_key: Purple Flea API key, dry_run: Set to true to simulate without executing
---

#!/bin/bash
if [ "${dry_run}" = "true" ]; then
  echo "{\"dry_run\": true, \"would_execute\": {\"symbol\": \"${symbol}-USDC\", \"side\": \"${side}\", \"notional_usdc\": ${notional_usdc}}}"
else
  curl -s -X POST "https://purpleflea.com/api/v1/orders" \
    -H "X-API-Key: ${api_key}" \
    -H "Content-Type: application/json" \
    -d "{\"symbol\": \"${symbol}-USDC\", \"side\": \"${side}\", \"type\": \"market\", \"notional_usdc\": ${notional_usdc}}"
fi

===
Rebalance a crypto portfolio to target allocations.

Configuration:
- Wallet: 0xYourWalletAddress
- API key: pf_live_your_key
- DRY RUN: true (simulate only, do not execute real trades)

Target allocation:
- BTC: 40%
- ETH: 35%
- SOL: 15%
- USDC: 10% (cash buffer)

Rebalance threshold: 5% — only trade if a position is more than 5% away from target

Steps:
1. Get current positions for the wallet
2. Calculate current portfolio weights (each asset value / total NAV)
3. Compare current weights to target weights
4. For each asset with drift > 5%:
   - If overweight: calculate USDC value to sell
   - If underweight: calculate USDC value to buy
5. Execute all sells first (to generate cash), then all buys
6. Use dry_run=true for all orders since DRY RUN is enabled
7. Output a rebalance report:
   - Current vs target weights for each asset
   - Total NAV before rebalance
   - Trades that would be executed (or were executed if live)
   - Estimated NAV after rebalance
   - Total estimated fees

Integration Pattern: GPTScript + Purple Flea

The integration pattern across all five scripts follows the same shape: define a tool that wraps a curl call to a Purple Flea endpoint, pass the API key and relevant parameters as tool arguments, then write natural-language instructions describing the logic.

For structured JSON responses, pipe through python3 -c for lightweight extraction without needing jq. For complex multi-step logic, GPTScript's AI handles conditional branches, error checking, and retry decisions naturally — you describe the decision criteria in English rather than writing if-else blocks.

Output validation: Always include output validation instructions. "If the response contains an error field, stop and report the error without retrying" prevents runaway retry loops that could accidentally place duplicate orders.

Scheduling with Cron

GPTScript scripts are shell-executable. Schedule them with standard cron for automated daily tasks:

Shell — Cron Setup
# Edit crontab
crontab -e

# Check prices every hour
0 * * * * /usr/local/bin/gptscript run /home/agent/scripts/price-alert.gpt >> /var/log/pf-monitor.log 2>&1

# Rebalance portfolio every Monday at 09:00 UTC
0 9 * * 1 /usr/local/bin/gptscript run /home/agent/scripts/rebalance-portfolio.gpt >> /var/log/pf-rebalance.log 2>&1

# Claim daily faucet reward at midnight
0 0 * * * /usr/local/bin/gptscript run /home/agent/scripts/claim-faucet.gpt >> /var/log/pf-faucet.log 2>&1

# Check and report wallet balance every morning at 07:00 UTC
0 7 * * * /usr/local/bin/gptscript run /home/agent/scripts/check-balance.gpt >> /var/log/pf-balance.log 2>&1

Safety: Dry-Run Flag and Output Validation

Two safety practices are non-negotiable for automated crypto scripts:

For additional safety, set a maximum notional per trade in the tool arguments and hard-code it in the instructions: "Never place an order for more than $500 USDC in a single trade, regardless of what the rebalance calculation suggests." GPTScript will respect this constraint because it is part of the natural-language instructions the AI follows.

MCP alternative: If your agent runtime supports MCP, the Purple Flea MCP server at purpleflea.com/mcp exposes all these operations as native tools. For Claude, GPT-4, or any MCP-compatible agent, this is often simpler than GPTScript — just connect the MCP server and instruct the agent directly. GPTScript excels for scheduled, cron-style automation where you want a standalone script without a persistent agent runtime.

Getting Started Today

1

Install GPTScript

brew install gptscript or see install options above.

2

Get Purple Flea API key

Register at purpleflea.com/register, claim USDC from the Faucet, grab API key.

3

Copy a script above

Start with check-balance.gpt — it is read-only and safe to test immediately.

4

Run with dry-run first

Test all trade scripts with dry_run: true in instructions before enabling live execution.

GPTScript represents a genuine shift in how agents interact with financial APIs. The natural-language instruction layer eliminates the boilerplate that makes traditional API integrations slow to write and brittle to maintain. When Purple Flea adds a new endpoint, you update the tool definition in two lines and adjust the English instructions — no refactoring required. For agents that need to be productive quickly without deep engineering investment, GPTScript paired with Purple Flea's infrastructure is one of the fastest paths to running automated crypto operations.