# Greenhelix Strategy Marketplace Playbook

> The Agent Strategy Marketplace Playbook. Complete guide to selling verified trading strategies with escrow-protected subscriptions. Covers marketplace listing, performance verification, subscription management, and dispute resolution.

- Skill: `lord1egypt/greenhelix-strategy-marketplace-playbook` (Agent Skill)
- Install (CLI): `npx skillmds@latest add lord1egypt/greenhelix-strategy-marketplace-playbook`
- Raw SKILL.md: https://api.skillmd.com/api/skills/lord1egypt/greenhelix-strategy-marketplace-playbook/raw
- Safety review: pending (external: skill-scanner WARNING, skillspector PASS)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- License: MIT
- Author: Lord1Egypt (https://skillmd.com/u/lord1egypt)
- Updated: 2026-09-08
- Page: https://skillmd.com/skills/lord1egypt/greenhelix-strategy-marketplace-playbook

---

# The Agent Strategy Marketplace Playbook

> **Notice**: This is an educational guide with illustrative code examples.
> It does not execute code or install dependencies.
> All examples use the GreenHelix sandbox (https://sandbox.greenhelix.net) which
> provides 500 free credits — no API key required to get started.
>
> **Referenced credentials** (you supply these in your own environment):
> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read/write access to purchased API tools only)
> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)


Trading strategy marketplaces like Cryptohopper, Collective2, and QuantConnect take 20-30% commission on strategy subscriptions while offering nothing more than self-reported, unverifiable performance numbers. Buyers have zero recourse when a strategy that claimed 85% win rate turns out to deliver 40%. Sellers with genuinely profitable strategies cannot differentiate themselves from curve-fitted backtests and outright scammers. The result is a low-trust marketplace where good strategy developers are systematically undervalued, buyers get burned repeatedly, and the platform extracts rent from both sides without adding trust. This guide shows you how to build a strategy selling business on the GreenHelix A2A Commerce Gateway, where performance is cryptographically verified, payments are protected by escrow that releases only when your strategy delivers, and your track record is an immutable Merkle tree that no one --- including you --- can falsify.
1. [Architecture Overview](#chapter-1-architecture-overview)
2. [Setting Up Your Strategy Seller Identity](#chapter-2-setting-up-your-strategy-seller-identity)

## What You'll Learn
- Chapter 1: Architecture Overview
- Chapter 2: Setting Up Your Strategy Seller Identity
- Chapter 3: Listing Your Strategy on the Marketplace
- Chapter 4: Setting Up Performance Escrow
- Chapter 5: Proving Your Performance
- Chapter 6: Handling Disputes
- Chapter 7: Scaling Your Strategy Business
- Chapter 8: Advanced Escrow Patterns
- Chapter 9: Multi-Strategy Portfolio Management
- Chapter 10: Dispute Resolution Workflows

## Full Guide

# The Agent Strategy Marketplace Playbook: Sell Verified Trading Strategies with Escrow-Protected Subscriptions

Trading strategy marketplaces like Cryptohopper, Collective2, and QuantConnect take 20-30% commission on strategy subscriptions while offering nothing more than self-reported, unverifiable performance numbers. Buyers have zero recourse when a strategy that claimed 85% win rate turns out to deliver 40%. Sellers with genuinely profitable strategies cannot differentiate themselves from curve-fitted backtests and outright scammers. The result is a low-trust marketplace where good strategy developers are systematically undervalued, buyers get burned repeatedly, and the platform extracts rent from both sides without adding trust. This guide shows you how to build a strategy selling business on the GreenHelix A2A Commerce Gateway, where performance is cryptographically verified, payments are protected by escrow that releases only when your strategy delivers, and your track record is an immutable Merkle tree that no one --- including you --- can falsify.

---

## Table of Contents

1. [Architecture Overview](#chapter-1-architecture-overview)
2. [Setting Up Your Strategy Seller Identity](#chapter-2-setting-up-your-strategy-seller-identity)
3. [Listing Your Strategy on the Marketplace](#chapter-3-listing-your-strategy-on-the-marketplace)
4. [Setting Up Performance Escrow](#chapter-4-setting-up-performance-escrow)
5. [Proving Your Performance](#chapter-5-proving-your-performance)
6. [Handling Disputes](#chapter-6-handling-disputes)
7. [Scaling Your Strategy Business](#chapter-7-scaling-your-strategy-business)
8. [Advanced Escrow Patterns](#chapter-8-advanced-escrow-patterns)
9. [Multi-Strategy Portfolio Management](#chapter-9-multi-strategy-portfolio-management)
10. [Dispute Resolution Workflows](#chapter-10-dispute-resolution-workflows)
12. [What's Next](#whats-next)

---

## Chapter 1: Architecture Overview

### How the Strategy Marketplace Works

The GreenHelix strategy marketplace operates on a simple loop with four participants: the seller (you), the buyer (a trading bot operator or agent), the escrow system, and the verification layer.

The flow works like this:

1. **Seller lists strategy** on the marketplace with defined performance criteria.
2. **Buyer discovers strategy** via search and subscribes by funding a performance escrow.
3. **Seller executes strategy** and submits signed trade metrics after each execution cycle.
4. **Verification layer** builds a Merkle tree (claim chain) from accumulated metrics.
5. **Escrow auto-releases** if performance criteria are met at the end of the evaluation period.
6. **If criteria are not met**, the buyer can open a dispute, and funds are returned or partially released based on evidence.

### System Flow Diagram

```
+------------------+         +---------------------+         +------------------+
|  Strategy Seller |         |   GreenHelix A2A    |         | Strategy Buyer   |
|  (Your Bot)      |         |   Commerce Gateway  |         | (Subscriber Bot) |
+--------+---------+         +---------+-----------+         +--------+---------+
         |                             |                              |
         | 1. register_agent           |                              |
         |---------------------------->|                              |
         |                             |                              |
         | 2. register_service         |                              |
         |---------------------------->|                              |
         |                             |                              |
         |                             |  3. search_services          |
         |                             |<-----------------------------|
         |                             |                              |
         |                             |  4. create_performance_escrow|
         |                             |<-----------------------------|
         |                             |                              |
         | 5. submit_metrics (daily)   |                              |
         |---------------------------->|                              |
         |                             |                              |
         | 6. build_claim_chain        |                              |
         |---------------------------->|                              |
         |                             |                              |
         |      7. Evaluation period ends                             |
         |         Criteria met? ------+----> release_escrow (auto)   |
         |         Criteria failed? ---+----> open_dispute            |
         |                             |                              |
```

### Why Performance Escrow Changes the Game

Traditional strategy marketplaces are adversarial. The seller's incentive is to overstate performance because there is no penalty for doing so. The buyer's only signal is reviews, which are easily gamed. Performance escrow flips this dynamic: the seller's revenue is directly tied to delivering on stated criteria. If you claim a 2.0 Sharpe ratio over 30 days, you get paid only when the verification layer confirms it. This means honest sellers earn more (because buyers trust the system and subscribe at higher prices), and dishonest sellers earn nothing.

---

## Chapter 2: Setting Up Your Strategy Seller Identity

### Generate an Ed25519 Keypair

Every agent on GreenHelix has a cryptographic identity. You sign your metric submissions with your private key, and anyone can verify them against your public key. This is what makes your track record tamper-proof.

```python
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives import serialization
import base64

# Generate a new Ed25519 keypair
private_key = Ed25519PrivateKey.generate()
public_key = private_key.public_key()

# Serialize the private key (store this securely --- never share it)
private_key_bytes = private_key.private_bytes(
    encoding=serialization.Encoding.Raw,
    format=serialization.PrivateFormat.Raw,
    encryption_algorithm=serialization.NoEncryption()
)

# Serialize the public key (this goes in your agent registration)
public_key_bytes = public_key.public_bytes(
    encoding=serialization.Encoding.Raw,
    format=serialization.PublicFormat.Raw
)

private_key_b64 = base64.b64encode(private_key_bytes).decode()
public_key_b64 = base64.b64encode(public_key_bytes).decode()

print(f"Private key (keep secret): {private_key_b64}")
print(f"Public key (share freely): {public_key_b64}")
```

Save your private key in an environment variable or secrets manager. Never commit it to version control.

### Register Your Agent on GreenHelix

With your keypair generated, register your identity on the gateway.

**curl:**

```bash
curl -s -X POST https://sandbox.greenhelix.net/v1 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GREENHELIX_API_KEY" \
  -d '{
    "tool": "register_agent",
    "input": {
      "agent_id": "strategy-seller-mrev-01",
      "public_key": "'"$PUBLIC_KEY_B64"'",
      "name": "Mean Reversion Strategy v1"
    }
  }'
```

**Python:**

```python
import requests
import os

BASE_URL = "https://api.greenhelix.net/v1"
API_KEY = os.environ["GREENHELIX_API_KEY"]

def execute_tool(tool: str, input_data: dict) -> dict:
    """Execute a tool on the GreenHelix gateway."""
    response = requests.post(
        f"{BASE_URL}/v1",
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {API_KEY}",
        },
        json={"tool": tool, "input": input_data},
    )
    response.raise_for_status()
    return response.json()

# Register your agent identity
result = execute_tool("register_agent", {
    "agent_id": "strategy-seller-mrev-01",
    "public_key": public_key_b64,
    "name": "Mean Reversion Strategy v1",
})
print(result)
```

### The Complete GreenHelixClient Class

You will use this client throughout the rest of the guide. It wraps every API call you need into a clean interface.

```python
import requests
import os
import base64
import json
import time
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
    Ed25519PrivateKey,
)
from cryptography.hazmat.primitives import serialization


class GreenHelixClient:
    """Client for the GreenHelix A2A Commerce Gateway."""

    def __init__(
        self,
        api_key: str,
        agent_id: str,
        private_key_b64: str,
        base_url: str = "https://api.greenhelix.net/v1",
    ):
        self.base_url = base_url
        self.agent_id = agent_id
        self.session = requests.Session()
        self.session.headers.update({
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}",
        })

        # Load Ed25519 private key for signing
        private_key_bytes = base64.b64decode(private_key_b64)
        self._private_key = Ed25519PrivateKey.from_private_bytes(
            private_key_bytes
        )
        self._public_key = self._private_key.public_key()

    def _execute(self, tool: str, input_data: dict) -> dict:
        """Execute a tool on the gateway."""
        resp = self.session.post(
            f"{self.base_url}/v1",
            json={"tool": tool, "input": input_data},
        )
        resp.raise_for_status()
        return resp.json()

    def sign_payload(self, payload: dict) -> str:
        """Sign a JSON payload with your Ed25519 private key."""
        payload_bytes = json.dumps(payload, sort_keys=True).encode()
        signature = self._private_key.sign(payload_bytes)
        return base64.b64encode(signature).decode()

    def register(self, name: str) -> dict:
        """Register this agent on the gateway."""
        public_key_bytes = self._public_key.public_bytes(
            encoding=serialization.Encoding.Raw,
            format=serialization.PublicFormat.Raw,
        )
        return self._execute("register_agent", {
            "agent_id": self.agent_id,
            "public_key": base64.b64encode(public_key_bytes).decode(),
            "name": name,
        })

    def register_service(
        self,
        name: str,
        description: str,
        endpoint: str,
        price: float,
        tags: list[str],
        category: str,
    ) -> dict:
        """List a service on the marketplace."""
        return self._execute("register_service", {
            "name": name,
            "description": description,
            "endpoint": endpoint,
            "price": price,
            "tags": tags,
            "category": category,
        })

    def search_services(self, query: str) -> dict:
        """Search the marketplace."""
        return self._execute("search_services", {"query": query})

    def create_performance_escrow(
        self,
        payer_agent_id: str,
        amount: float,
        currency: str,
        performance_criteria: dict,
        evaluation_period_days: int,
    ) -> dict:
        """Create a performance-based escrow."""
        return self._execute("create_performance_escrow", {
            "payer_agent_id": payer_agent_id,
            "payee_agent_id": self.agent_id,
            "amount": amount,
            "currency": currency,
            "performance_criteria": performance_criteria,
            "evaluation_period_days": evaluation_period_days,
        })

    def release_escrow(self, escrow_id: str) -> dict:
        """Manually release an escrow."""
        return self._execute("release_escrow", {"escrow_id": escrow_id})

    def submit_metrics(self, metrics: dict) -> dict:
        """Submit signed performance metrics."""
        return self._execute("submit_metrics", {
            "agent_id": self.agent_id,
            "metrics": metrics,
        })

    def build_claim_chain(self) -> dict:
        """Build a Merkle tree from your attestation history."""
        return self._execute("build_claim_chain", {
            "agent_id": self.agent_id,
        })

    def get_reputation(self, agent_id: str | None = None) -> dict:
        """Get trust score for an agent."""
        return self._execute("get_agent_reputation", {
            "agent_id": agent_id or self.agent_id,
        })

    def open_dispute(self, escrow_id: str, reason: str) -> dict:
        """Open a dispute on an escrow."""
        return self._execute("open_dispute", {
            "escrow_id": escrow_id,
            "reason": reason,
        })

    def resolve_dispute(self, dispute_id: str, resolution: str) -> dict:
        """Resolve a dispute."""
        return self._execute("resolve_dispute", {
            "dispute_id": dispute_id,
            "resolution": resolution,
        })
```

### Verify Registration

Confirm your agent is registered by checking your reputation endpoint (newly registered agents start with a baseline score).

```bash
curl -s -X POST https://sandbox.greenhelix.net/v1 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GREENHELIX_API_KEY" \
  -d '{
    "tool": "get_agent_reputation",
    "input": {
      "agent_id": "strategy-seller-mrev-01"
    }
  }'
```

```python
client = GreenHelixClient(
    api_key=os.environ["GREENHELIX_API_KEY"],
    agent_id="strategy-seller-mrev-01",
    private_key_b64=os.environ["GREENHELIX_PRIVATE_KEY"],
)

reputation = client.get_reputation()
print(f"Agent registered. Trust score: {reputation}")
```

---

## Chapter 3: Listing Your Strategy on the Marketplace

### Create a Compelling Service Listing

Your listing is the first thing a potential subscriber sees. It must communicate three things clearly: what the strategy does, what performance it targets, and what the subscription terms are.

Here is an example listing for a mean reversion strategy running on BTC/USDT 1-hour candles.

**curl:**

```bash
curl -s -X POST https://sandbox.greenhelix.net/v1 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GREENHELIX_API_KEY" \
  -d '{
    "tool": "register_service",
    "input": {
      "name": "BTC Mean Reversion (1H) - Verified Performance",
      "description": "Automated mean reversion strategy on BTC/USDT 1-hour timeframe. Targets 2.0+ Sharpe ratio with max 8% drawdown. All performance metrics are cryptographically signed and verified via escrow. 30-day evaluation period. Refund if criteria not met.",
      "endpoint": "https://my-bot.example.com/signals/mrev-btc-1h",
      "price": 49.00,
      "tags": ["trading-strategy", "btc", "mean-reversion", "verified-performance", "escrow-protected"],
      "category": "trading-strategies"
    }
  }'
```

**Python:**

```python
listing = client.register_service(
    name="BTC Mean Reversion (1H) - Verified Performance",
    description=(
        "Automated mean reversion strategy on BTC/USDT 1-hour timeframe. "
        "Targets 2.0+ Sharpe ratio with max 8% drawdown. All performance "
        "metrics are cryptographically signed and verified via escrow. "
        "30-day evaluation period. Refund if criteria not met."
    ),
    endpoint="https://my-bot.example.com/signals/mrev-btc-1h",
    price=49.00,
    tags=[
        "trading-strategy",
        "btc",
        "mean-reversion",
        "verified-performance",
        "escrow-protected",
    ],
    category="trading-strategies",
)
print(f"Strategy listed: {listing}")
```

### Pricing Your Strategy

The current market for trading strategy subscriptions runs from $10/month for basic indicator-based strategies up to $99/month or more for verified quantitative strategies. Because GreenHelix performance escrow gives buyers confidence that the numbers are real, you can typically price 20-40% higher than equivalent listings on traditional marketplaces. A strategy with a verified 2.0+ Sharpe ratio and 6+ months of immutable history commands a premium.

Pricing recommendations:
- **$10-25/month**: Simple trend-following or indicator-based strategies with modest performance claims.
- **$25-49/month**: Quantitative strategies with solid risk-adjusted returns and 30-day escrow evaluation.
- **$49-99/month**: Multi-asset or portfolio strategies with longer track records and tighter performance guarantees.

### Tagging for Discovery

Tags determine how buyers find your strategy. Use specific, descriptive tags. Avoid generic terms like "profitable" or "best." Effective tags include the asset pair, timeframe, strategy type, and differentiators like "verified-performance" or "escrow-protected."

### Verify Your Listing Appears in Search

After listing, verify that your strategy is discoverable.

```bash
curl -s -X POST https://sandbox.greenhelix.net/v1 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GREENHELIX_API_KEY" \
  -d '{
    "tool": "search_services",
    "input": {
      "query": "btc mean reversion verified"
    }
  }'
```

```python
results = client.search_services("btc mean reversion verified")
for service in results.get("services", []):
    print(f"  {service['name']} - ${service['price']}/mo")
```

---

## Chapter 4: Setting Up Performance Escrow

### How Performance Escrow Works

When a buyer subscribes to your strategy, they do not pay you directly. Instead, funds are locked in a performance escrow with explicit criteria that must be met over a defined evaluation period. At the end of the period, one of three things happens:

1. **Criteria met**: Escrow auto-releases to you. You get paid.
2. **Criteria partially met**: Buyer can accept and release, or dispute for partial refund.
3. **Criteria not met**: Buyer opens a dispute. Funds are returned or split based on evidence.

This is what makes the system work. Buyers subscribe with near-zero risk. Sellers with good strategies earn consistently. Sellers with bad strategies earn nothing --- which is exactly how it should be.

### Define Performance Criteria

Performance criteria are the contract between you and your subscriber. Be specific and conservative. It is far better to promise a 1.5 Sharpe and deliver 2.0 than to promise 3.0 and miss. Here is a well-structured performance criteria object:

```python
performance_criteria = {
    "min_sharpe_ratio": 1.5,
    "max_drawdown_pct": 10.0,
    "min_win_rate_pct": 55.0,
    "min_total_trades": 20,
}
```

- **min_sharpe_ratio**: Risk-adjusted return. 1.5+ is solid for a 30-day window.
- **max_drawdown_pct**: Maximum peak-to-trough decline. 10% gives you room for normal volatility.
- **min_win_rate_pct**: Percentage of winning trades. 55% is realistic for mean reversion.
- **min_total_trades**: Minimum number of trades. Prevents gaming by taking one lucky trade.

### Create Escrow When a Subscriber Signs Up

When a buyer agent subscribes, you (or your automation) create the performance escrow.

**curl:**

```bash
curl -s -X POST https://sandbox.greenhelix.net/v1 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GREENHELIX_API_KEY" \
  -d '{
    "tool": "create_performance_escrow",
    "input": {
      "payer_agent_id": "subscriber-bot-alpha",
      "payee_agent_id": "strategy-seller-mrev-01",
      "amount": 49.00,
      "currency": "USD",
      "performance_criteria": {
        "min_sharpe_ratio": 1.5,
        "max_drawdown_pct": 10.0,
        "min_win_rate_pct": 55.0,
        "min_total_trades": 20
      },
      "evaluation_period_days": 30
    }
  }'
```

**Python:**

```python
escrow = client.create_performance_escrow(
    payer_agent_id="subscriber-bot-alpha",
    amount=49.00,
    currency="USD",
    performance_criteria={
        "min_sharpe_ratio": 1.5,
        "max_drawdown_pct": 10.0,
        "min_win_rate_pct": 55.0,
        "min_total_trades": 20,
    },
    evaluation_period_days=30,
)
escrow_id = escrow["escrow_id"]
print(f"Escrow created: {escrow_id}")
print(f"Evaluation ends: {escrow['evaluation_end_date']}")
```

### Complete Escrow Creation Flow

In production, you will automate this entire flow. Here is the pattern: when your endpoint receives a subscription request, validate the buyer agent, create the escrow, and return the escrow ID so both parties can track it.

```python
def handle_subscription_request(buyer_agent_id: str, plan: str) -> dict:
    """Handle an incoming subscription request from a buyer agent."""
    plans = {
        "basic": {
            "amount": 29.00,
            "criteria": {
                "min_sharpe_ratio": 1.2,
                "max_drawdown_pct": 12.0,
                "min_win_rate_pct": 52.0,
                "min_total_trades": 15,
            },
            "evaluation_days": 30,
        },
        "premium": {
            "amount": 49.00,
            "criteria": {
                "min_sharpe_ratio": 1.5,
                "max_drawdown_pct": 10.0,
                "min_win_rate_pct": 55.0,
                "min_total_trades": 20,
            },
            "evaluation_days": 30,
        },
    }

    if plan not in plans:
        return {"error": f"Unknown plan: {plan}. Available: {list(plans)}"}

    config = plans[plan]
    escrow = client.create_performance_escrow(
        payer_agent_id=buyer_agent_id,
        amount=config["amount"],
        currency="USD",
        performance_criteria=config["criteria"],
        evaluation_period_days=config["evaluation_days"],
    )

    return {
        "status": "subscribed",
        "escrow_id": escrow["escrow_id"],
        "plan": plan,
        "evaluation_end_date": escrow["evaluation_end_date"],
        "criteria": config["criteria"],
    }
```

---

## Chapter 5: Proving Your Performance

### Submit Trade Metrics After Each Execution

Every time your strategy executes trades, submit the results to GreenHelix. These metrics are what the escrow system evaluates at the end of the period. Submit daily or after each significant trade batch.

**curl:**

```bash
curl -s -X POST https://sandbox.greenhelix.net/v1 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GREENHELIX_API_KEY" \
  -d '{
    "tool": "submit_metrics",
    "input": {
      "agent_id": "strategy-seller-mrev-01",
      "metrics": {
        "period_start": "2026-04-01T00:00:00Z",
        "period_end": "2026-04-01T23:59:59Z",
        "trades_executed": 7,
        "winning_trades": 5,
        "losing_trades": 2,
        "total_pnl_usd": 342.18,
        "max_drawdown_pct": 2.3,
        "sharpe_ratio": 2.14,
        "win_rate_pct": 71.4,
        "avg_trade_duration_minutes": 47,
        "pairs_traded": ["BTC/USDT"]
      }
    }
  }'
```

**Python:**

```python
from datetime import datetime, timezone

daily_metrics = {
    "period_start": "2026-04-01T00:00:00Z",
    "period_end": "2026-04-01T23:59:59Z",
    "trades_executed": 7,
    "winning_trades": 5,
    "losing_trades": 2,
    "total_pnl_usd": 342.18,
    "max_drawdown_pct": 2.3,
    "sharpe_ratio": 2.14,
    "win_rate_pct": 71.4,
    "avg_trade_duration_minutes": 47,
    "pairs_traded": ["BTC/USDT"],
}

result = client.submit_metrics(daily_metrics)
print(f"Metrics submitted: {result}")
```

### Automated Metrics Submission Pipeline

In production, you will run a daily job that computes your strategy's metrics from your trade log and submits them automatically. Here is a complete pipeline:

```python
import json
from datetime import datetime, timedelta, timezone


def compute_daily_metrics(trades: list[dict], date: str) -> dict:
    """Compute strategy metrics from a list of executed trades for a day."""
    if not trades:
        return None

    winning = [t for t in trades if t["pnl"] > 0]
    losing = [t for t in trades if t["pnl"] <= 0]
    total_pnl = sum(t["pnl"] for t in trades)

    # Compute rolling Sharpe from daily returns
    returns = [t["pnl"] / t["position_size"] for t in trades]
    avg_return = sum(returns) / len(returns)
    if len(returns) > 1:
        variance = sum((r - avg_return) ** 2 for r in returns) / (
            len(returns) - 1
        )
        std_return = variance ** 0.5
        sharpe = (avg_return / std_return) * (252 ** 0.5) if std_return > 0 else 0.0
    else:
        sharpe = 0.0

    # Compute max drawdown from cumulative P&L
    cumulative = []
    running = 0.0
    peak = 0.0
    max_dd = 0.0
    for t in trades:
        running += t["pnl"]
        cumulative.append(running)
        if running > peak:
            peak = running
        dd = (peak - running) / peak * 100 if peak > 0 else 0.0
        if dd > max_dd:
            max_dd = dd

    return {
        "period_start": f"{date}T00:00:00Z",
        "period_end": f"{date}T23:59:59Z",
        "trades_executed": len(trades),
        "winning_trades": len(winning),
        "losing_trades": len(losing),
        "total_pnl_usd": round(total_pnl, 2),
        "max_drawdown_pct": round(max_dd, 2),
        "sharpe_ratio": round(sharpe, 2),
        "win_rate_pct": round(len(winning) / len(trades) * 100, 1),
        "pairs_traded": list(set(t["pair"] for t in trades)),
    }


def daily_metrics_job(client: GreenHelixClient, trades: list[dict]):
    """Run as a daily cron job to submit metrics."""
    today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
    metrics = compute_daily_metrics(trades, today)
    if metrics:
        result = client.submit_metrics(metrics)
        print(f"[{today}] Metrics submitted: {result}")
    else:
        print(f"[{today}] No trades executed, skipping submission.")
```

### Build Claim Chains

After accumulating metric submissions, build your claim chain. This creates a Merkle tree from your attestation history --- an append-only, tamper-evident data structure that anyone can verify. Each new metric submission becomes a leaf node, and the root hash changes with every update, making historical falsification detectable.

**curl:**

```bash
curl -s -X POST https://sandbox.greenhelix.net/v1 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GREENHELIX_API_KEY" \
  -d '{
    "tool": "build_claim_chain",
    "input": {
      "agent_id": "strategy-seller-mrev-01"
    }
  }'
```

**Python:**

```python
claim_chain = client.build_claim_chain()
print(f"Claim chain root: {claim_chain.get('root_hash')}")
print(f"Total attestations: {claim_chain.get('attestation_count')}")
print(f"Chain depth: {claim_chain.get('depth')}")
```

Build your claim chain regularly --- at least weekly, ideally daily after metrics submission. A longer, unbroken chain is a stronger trust signal. Subscribers and potential buyers can verify any leaf in the tree independently, which is why this system is fundamentally different from self-reported numbers on traditional platforms.

### How Trust Scores Are Computed

Your reputation score on GreenHelix is derived from several factors:

- **Claim chain length and consistency**: Longer chains with regular submissions score higher.
- **Escrow completion rate**: The percentage of escrows that auto-release (criteria met) vs. disputed.
- **Metric variance**: Consistent performance across periods scores higher than volatile results.
- **Dispute history**: Disputes that resolve in your favor are neutral; disputes you lose drag the score down.

Check your trust score at any time:

```python
reputation = client.get_reputation()
print(f"Trust score: {reputation.get('score')}")
print(f"Escrow completion rate: {reputation.get('escrow_completion_rate')}")
print(f"Total escrows completed: {reputation.get('total_escrows')}")
```

---

## Chapter 6: Handling Disputes

### When a Subscriber Opens a Dispute

A subscriber can open a dispute on an active escrow if they believe your strategy has not met the stated performance criteria. Disputes are not adversarial by design --- they are a resolution mechanism.

```python
# From the subscriber's perspective:
dispute = client.open_dispute(
    escrow_id="escrow-abc123",
    reason=(
        "Strategy claimed min 1.5 Sharpe over 30 days. "
        "Actual Sharpe was 0.87 based on submitted metrics. "
        "Requesting full refund per escrow terms."
    ),
)
print(f"Dispute opened: {dispute['dispute_id']}")
```

### How to Respond with Evidence

When a dispute is opened against your escrow, your primary evidence is your claim chain. Because every metric submission is a signed, timestamped leaf in a Merkle tree, you can prove exactly what you submitted and when. If the metrics genuinely show you met the criteria, the evidence speaks for itself.

```python
# Build your claim chain as evidence
claim_chain = client.build_claim_chain()

# The claim chain contains all signed metric submissions
# The resolver can verify each leaf against your public key
print(f"Evidence submitted via claim chain: {claim_chain['root_hash']}")
print(f"Attestations available for review: {claim_chain['attestation_count']}")
```

### Resolution Outcomes

Disputes resolve in one of three ways:

1. **Full release to seller**: Metrics clearly show criteria were met. The subscriber's dispute was unfounded.
2. **Full refund to buyer**: Metrics show criteria were not met. Funds return to the subscriber.
3. **Partial release**: Performance was close to criteria but fell short on one metric. Funds are split proportionally.

```bash
# Resolve a dispute (typically done by the platform or arbitrator)
curl -s -X POST https://sandbox.greenhelix.net/v1 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GREENHELIX_API_KEY" \
  -d '{
    "tool": "resolve_dispute",
    "input": {
      "dispute_id": "dispute-xyz789",
      "resolution": "release_to_seller"
    }
  }'
```

### Best Practices for Avoiding Disputes

1. **Set conservative criteria.** Promise less, deliver more. A 1.5 Sharpe target with 2.0 delivery builds your reputation faster than a 3.0 target you occasionally miss.
2. **Submit metrics daily.** Gaps in your metric history look suspicious and weaken your position in disputes.
3. **Communicate proactively.** If your strategy hits a rough patch (high drawdown, low trade count), reach out to subscribers before the escrow evaluation period ends.
4. **Keep your claim chain current.** Build it after every metric submission. A stale chain is harder to defend with.

---

## Chapter 7: Scaling Your Strategy Business

### Multiple Strategies, Tiered Pricing

Once your first strategy has a solid track record (3+ months of verified performance, 90%+ escrow completion rate), expand. List multiple strategies with different risk profiles and price points.

```python
strategies = [
    {
        "name": "BTC Mean Reversion (1H) - Conservative",
        "price": 29.00,
        "criteria": {"min_sharpe_ratio": 1.2, "max_drawdown_pct": 8.0},
        "tags": ["btc", "mean-reversion", "conservative", "verified-performance"],
    },
    {
        "name": "BTC Mean Reversion (1H) - Aggressive",
        "price": 49.00,
        "criteria": {"min_sharpe_ratio": 2.0, "max_drawdown_pct": 15.0},
        "tags": ["btc", "mean-reversion", "aggressive", "verified-performance"],
    },
    {
        "name": "Multi-Asset Momentum Portfolio",
        "price": 99.00,
        "criteria": {"min_sharpe_ratio": 1.8, "max_drawdown_pct": 12.0},
        "tags": ["multi-asset", "momentum", "portfolio", "verified-performance"],
    },
]

for strat in strategies:
    result = client.register_service(
        name=strat["name"],
        description=f"Verified performance strategy. Escrow-protected with {strat['criteria']['min_sharpe_ratio']}+ Sharpe target.",
        endpoint="https://my-bot.example.com/signals/" + strat["name"].lower().replace(" ", "-"),
        price=strat["price"],
        tags=strat["tags"],
        category="trading-strategies",
    )
    print(f"Listed: {strat['name']} at ${strat['price']}/mo")
```

### Using Analytics to Track Subscriber Growth

Monitor your reputation and escrow metrics to understand your business trajectory.

```python
def print_business_dashboard(client: GreenHelixClient):
    """Print a summary of your strategy business metrics."""
    reputation = client.get_reputation()

    print("=== Strategy Business Dashboard ===")
    print(f"Trust Score:            {reputation.get('score', 'N/A')}")
    print(f"Escrow Completion Rate: {reputation.get('escrow_completion_rate', 'N/A')}")
    print(f"Total Escrows:          {reputation.get('total_escrows', 'N/A')}")
    print(f"Active Disputes:        {reputation.get('active_disputes', 0)}")
    print("===================================")

print_business_dashboard(client)
```

### Cross-Selling Between Strategies

Subscribers who are happy with one strategy are your best prospects for another. When a subscriber's escrow completes successfully (criteria met, funds released), that is the ideal moment to suggest your other strategies. The verified track record from the first subscription is your strongest sales tool for the second.

### Monitoring Your Reputation Score

Your trust score is the single most important metric for long-term strategy sales growth. It compounds: higher trust scores lead to more subscribers, more successful escrows lead to higher scores, and the cycle reinforces itself. Check your score weekly and investigate any dips immediately.

```python
# Weekly reputation check
reputation = client.get_reputation()
score = reputation.get("score", 0)
if score < 0.8:
    print(f"WARNING: Trust score dropped to {score}. Investigate recent escrows.")
elif score >= 0.95:
    print(f"Trust score: {score} - Excellent. Consider raising prices.")
else:
    print(f"Trust score: {score} - Healthy.")
```

---

## Chapter 8: Advanced Escrow Patterns

### Multi-Tier Escrow

Chapter 4 introduced a basic two-tier plan structure. In practice, you will want to define escrow criteria that scale with the subscription price and the buyer's risk appetite. Multi-tier escrow means each plan tier has its own performance criteria, evaluation period, and escrow amount --- and the criteria get progressively stricter as the price increases.

The key insight is that higher-tier subscribers are paying more because they expect tighter performance guarantees. A $99/month premium subscriber should not have the same 1.2 Sharpe threshold as a $29/month basic subscriber. The escrow criteria must reflect the price.

```python
TIER_CONFIGS = {
    "starter": {
        "amount": 19.00,
        "criteria": {
            "min_sharpe_ratio": 1.0,
            "max_drawdown_pct": 15.0,
            "min_win_rate_pct": 50.0,
            "min_total_trades": 10,
        },
        "evaluation_days": 14,
    },
    "standard": {
        "amount": 49.00,
        "criteria": {
            "min_sharpe_ratio": 1.5,
            "max_drawdown_pct": 10.0,
            "min_win_rate_pct": 55.0,
            "min_total_trades": 20,
        },
        "evaluation_days": 30,
    },
    "professional": {
        "amount": 99.00,
        "criteria": {
            "min_sharpe_ratio": 2.0,
            "max_drawdown_pct": 7.0,
            "min_win_rate_pct": 60.0,
            "min_total_trades": 30,
        },
        "evaluation_days": 30,
    },
    "institutional": {
        "amount": 249.00,
        "criteria": {
            "min_sharpe_ratio": 2.5,
            "max_drawdown_pct": 5.0,
            "min_win_rate_pct": 62.0,
            "min_total_trades": 40,
            "max_consecutive_losses": 4,
            "min_profit_factor": 1.8,
        },
        "evaluation_days": 60,
    },
}


def create_tiered_escrow(
    client: GreenHelixClient, buyer_agent_id: str, tier: str
) -> dict:
    """Create an escrow with tier-appropriate criteria."""
    if tier not in TIER_CONFIGS:
        raise ValueError(f"Unknown tier: {tier}. Available: {list(TIER_CONFIGS)}")

    config = TIER_CONFIGS[tier]
    escrow = client.create_performance_escrow(
        payer_agent_id=buyer_agent_id,
        amount=config["amount"],
        currency="USD",
        performance_criteria=config["criteria"],
        evaluation_period_days=config["evaluation_days"],
    )
    return {
        "tier": tier,
        "escrow_id": escrow["escrow_id"],
        "criteria": config["criteria"],
        "evaluation_end_date": escrow["evaluation_end_date"],
    }
```

Notice the institutional tier adds two additional criteria fields: `max_consecutive_losses` and `min_profit_factor`. Higher tiers can include stricter and more granular performance requirements. This is a competitive advantage --- no traditional marketplace can enforce these guarantees programmatically.

### Rolling Escrow

Fixed 30-day escrow periods create a problem: the subscriber pays on day 1 and waits 30 days for the evaluation. If the strategy fails on day 29, the subscriber wasted a month. Rolling escrow solves this by creating a continuous 30-day evaluation window that slides forward with each new metric submission. Instead of a single fixed window, the system evaluates the most recent 30 days of data at any point.

The implementation pattern is to create overlapping escrows that renew automatically. When one evaluation period completes successfully, a new escrow is created immediately for the next period, giving both parties continuous coverage.

```python
from datetime import datetime, timedelta, timezone


class RollingEscrowManager:
    """Manage continuous rolling escrow windows for a strategy subscription."""

    def __init__(self, client: GreenHelixClient, window_days: int = 30):
        self.client = client
        self.window_days = window_days
        self.active_escrows: dict[str, dict] = {}

    def start_subscription(
        self, buyer_agent_id: str, amount: float, criteria: dict
    ) -> dict:
        """Start a rolling escrow subscription."""
        escrow = self.client.create_performance_escrow(
            payer_agent_id=buyer_agent_id,
            amount=amount,
            currency="USD",
            performance_criteria=crit

…(truncated)
