Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
<!doctype html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Build an autonomous trading agent · Learn Robinhood Chain</title>
<meta name="description" content="A paper-mode trading agent with a real strategy, hard spend caps, and a kill switch — risk-first framing before a single lira of real capital.">
<meta property="og:title" content="Build an autonomous trading agent · Learn Robinhood Chain">
<meta property="og:description" content="A paper-mode trading agent with a real strategy, hard spend caps, and a kill switch — risk-first framing before a single lira of real capital.">
<meta property="og:type" content="article">
<meta name="theme-color" content="#0b0d10">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%2300c805'/%3E%3Cpath d='M9 22V10h4.4c2.6 0 4.2 1.4 4.2 3.7 0 1.7-.9 2.9-2.4 3.4l2.9 4.9h-2.8l-2.5-4.4h-1.4V22H9zm2.4-6.3h1.8c1.2 0 1.9-.6 1.9-1.7s-.7-1.7-1.9-1.7h-1.8v3.4z' fill='%23000'/%3E%3C/svg%3E">
<link rel="stylesheet" href="../assets/styles.css">
<link rel="stylesheet" href="../assets/hljs.css">
</head>
<body class="page-doc">
<a class="skip-link" href="#main">Skip to content</a>
<script>(function(){try{var t=localStorage.getItem('theme');if(t)document.documentElement.setAttribute('data-theme',t);}catch(e){}})();</script>
<header class="topbar">
<div class="topbar-inner">
<a class="brand" href="../">
<span class="brand-mark" aria-hidden="true">R</span>
<span class="brand-text">Learn <strong>Robinhood Chain</strong></span>
</a>
<div class="topbar-actions">
<button class="search-open" type="button" aria-label="Search tutorials" aria-keyshortcuts="/">
<span class="search-open-label">Search</span><kbd>/</kbd>
</button>
<a class="ghost-link" href="https://github.com/nirholas/learn-robinhood-chain" target="_blank" rel="noopener noreferrer">GitHub</a>
<button class="theme-toggle" type="button" aria-label="Toggle color theme" title="Toggle theme"></button>
<button class="menu-toggle" type="button" aria-label="Toggle navigation" aria-expanded="false"></button>
</div>
</div>
</header>
<div class="layout">
<aside class="sidebar" id="sidebar" aria-label="Tutorials">
<nav class="sidebar-nav"><div class="nav-section"><p class="nav-section-title">Foundations</p><ul><li><a href="../01-what-is-robinhood-chain/"><span class="nav-idx">01</span>What it actually is</a></li><li><a href="../02-connect-and-read/"><span class="nav-idx">02</span>Connect & read</a></li><li><a href="../03-stock-tokens-explained/"><span class="nav-idx">03</span>Stock Tokens</a></li></ul></div><div class="nav-section"><p class="nav-section-title">Building</p><ul><li><a href="../04-live-price-ticker/"><span class="nav-idx">04</span>Live price ticker</a></li><li><a href="../05-portfolio-tracker/"><span class="nav-idx">05</span>Portfolio tracker</a></li><li><a href="../06-swapping-on-chain/"><span class="nav-idx">06</span>Swapping on-chain</a></li><li><a href="../07-streaming-the-chain/"><span class="nav-idx">07</span>Streaming the chain</a></li></ul></div><div class="nav-section"><p class="nav-section-title">Monetizing & agents</p><ul><li><a href="../08-sell-your-api-for-usdg/"><span class="nav-idx">08</span>Sell your API</a></li><li><a href="../09-ai-agent-chain-access/"><span class="nav-idx">09</span>AI agent access (MCP)</a></li><li><a href="../10-autonomous-trading-agent/" class="active" aria-current="page"><span class="nav-idx">10</span>Autonomous agent</a></li><li><a href="../11-launch-a-coin/"><span class="nav-idx">11</span>Launch a coin</a></li></ul></div><div class="nav-section"><p class="nav-section-title">Capstone</p><ul><li><a href="../12-ship-it/"><span class="nav-idx">12</span>Ship it</a></li></ul></div></nav>
</aside>
<div class="sidebar-scrim" hidden></div>
<main class="doc" id="main" data-slug="10-autonomous-trading-agent">
<article class="doc-article">
<nav class="breadcrumb" aria-label="Breadcrumb"><a href="../">Home</a><span aria-hidden="true">/</span><span>Monetizing & agents</span></nav>
<header class="doc-header">
<h1>Build an autonomous trading agent</h1>
<div class="doc-meta">
<span class="doc-meta-item">30 min</span>
<span class="doc-meta-sep">·</span>
<span class="doc-meta-item">4 min read</span>
<span class="doc-meta-sep">·</span>
<label class="done-toggle"><input type="checkbox" class="done-check"> Mark complete</label>
</div>
</header>
<aside class="whatbuild"><p class="whatbuild-title">What you'll build</p><p>An agent that loops over live quotes, evaluates a strategy, and would trade — running safely in paper mode with real market data.</p></aside>
<aside class="prereq"><p class="prereq-title">Prerequisites</p><ul><li><a href="../06-swapping-on-chain/">Tutorial 6</a> — quotes and execution</li><li>You have read the risk section. Twice.</li></ul></aside>
<div class="doc-body"><div class="callout callout-danger"><p class="callout-title">Read this section before the code</p><p>An autonomous trading agent is software that spends money without asking you first, every time it runs. Every idea below is built with a <strong>hard spend cap</strong>, a <strong>kill switch</strong>, and <strong>paper mode as the default</strong> — not as afterthoughts, but as the first things written. If you take nothing else from this page: never remove the spend cap "just to test something real," and never run an agent with a live wallet key until you've watched it behave correctly in paper mode for longer than you think is necessary.</p>
<p>This is not investment advice, and nothing here is a strategy anyone should expect to be profitable. It's a template for the <em>engineering</em> of an agent that spends — the risk controls transfer to any strategy you actually design.</p>
</div>
<h2 id="design-the-risk-controls-first"><a class="anchor" href="#design-the-risk-controls-first" aria-label="Link to this section">#</a>Design the risk controls first</h2><p>Before a single line reads a price, decide three things:</p>
<ol>
<li><strong>Per-trade spend cap</strong> — the maximum a single trade can move, regardless of what the strategy wants.</li>
<li><strong>Period spend cap</strong> — a rolling limit (daily is typical) that trips even if every individual trade was within its own cap.</li>
<li><strong>Kill switch</strong> — a way to stop the agent immediately and safely, mid-loop, without corrupting state.</li>
</ol>
<figure class="code-block" data-lang="TypeScript"><figcaption><span class="code-lang">TypeScript</span><button class="copy-btn" type="button" aria-label="Copy code to clipboard">Copy</button></figcaption><pre><code class="hljs language-typescript"><span class="hljs-keyword">const</span> <span class="hljs-variable constant_">MAX_SPEND_USDG_PER_TRADE</span> = <span class="hljs-number">25</span> <span class="hljs-comment">// hard ceiling per trade</span>
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">DAILY_SPEND_CAP_USDG</span> = <span class="hljs-number">100</span> <span class="hljs-comment">// hard ceiling per rolling day</span>
<span class="hljs-keyword">let</span> spentToday = <span class="hljs-number">0</span>
<span class="hljs-keyword">let</span> running = <span class="hljs-literal">true</span>
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'kill switch: SIGINT received, stopping after this tick'</span>)
running = <span class="hljs-literal">false</span> <span class="hljs-comment">// finish the in-flight tick, then exit the loop — never abort mid-transaction</span>
})</code></pre></figure><p>Notice the kill switch doesn't <code>process.exit(0)</code> immediately. If the agent is mid-way through building a transaction when <code>SIGINT</code> fires, you want it to either finish that operation cleanly or not have started it — never leave a half-sent transaction or a corrupted spend counter. Setting a flag and checking it at loop boundaries is the safe pattern.</p>
<h2 id="a-minimal-strategy-dip-detection-paper-mode"><a class="anchor" href="#a-minimal-strategy-dip-detection-paper-mode" aria-label="Link to this section">#</a>A minimal strategy: dip detection, paper mode</h2><p>This agent watches a basket of Stock Tokens, and on a mainnet dip beyond a threshold, logs what it <em>would</em> buy — respecting both spend caps — without ever building or sending a transaction:</p>
<figure class="code-block" data-lang="TypeScript"><figcaption><span class="code-lang">TypeScript</span><button class="copy-btn" type="button" aria-label="Copy code to clipboard">Copy</button></figcaption><pre><code class="hljs language-typescript"><span class="hljs-keyword">import</span> { createHoodClient, getQuote } <span class="hljs-keyword">from</span> <span class="hljs-string">'hoodchain'</span>
<span class="hljs-keyword">const</span> hood = <span class="hljs-title function_">createHoodClient</span>()
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">SYMBOLS</span> = [<span class="hljs-string">'AAPL'</span>, <span class="hljs-string">'TSLA'</span>, <span class="hljs-string">'NVDA'</span>, <span class="hljs-string">'SPY'</span>]
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">DIP_THRESHOLD_PCT</span> = <span class="hljs-number">0.5</span> <span class="hljs-comment">// paper-buy if price drops >0.5% vs the last observed price</span>
<span class="hljs-keyword">const</span> lastPrice = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span><<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>>()
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">tick</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> <span class="hljs-built_in">symbol</span> <span class="hljs-keyword">of</span> <span class="hljs-variable constant_">SYMBOLS</span>) {
<span class="hljs-keyword">const</span> q = <span class="hljs-keyword">await</span> <span class="hljs-title function_">getQuote</span>(hood, <span class="hljs-built_in">symbol</span>, { <span class="hljs-attr">maxAgeSeconds</span>: <span class="hljs-number">7</span> * <span class="hljs-number">24</span> * <span class="hljs-number">60</span> * <span class="hljs-number">60</span> })
<span class="hljs-keyword">const</span> prev = lastPrice.<span class="hljs-title function_">get</span>(<span class="hljs-built_in">symbol</span>)
lastPrice.<span class="hljs-title function_">set</span>(<span class="hljs-built_in">symbol</span>, q.<span class="hljs-property">priceUsd</span>)
<span class="hljs-keyword">if</span> (prev === <span class="hljs-literal">undefined</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`[<span class="hljs-subst">${<span class="hljs-built_in">symbol</span>}</span>] baseline $<span class="hljs-subst">${q.priceUsd.toFixed(<span class="hljs-number">2</span>)}</span>`</span>)
<span class="hljs-keyword">continue</span>
}
<span class="hljs-keyword">const</span> changePct = ((q.<span class="hljs-property">priceUsd</span> - prev) / prev) * <span class="hljs-number">100</span>
<span class="hljs-keyword">if</span> (changePct <= -<span class="hljs-variable constant_">DIP_THRESHOLD_PCT</span>) {
<span class="hljs-keyword">if</span> (spentToday + <span class="hljs-variable constant_">MAX_SPEND_USDG_PER_TRADE</span> > <span class="hljs-variable constant_">DAILY_SPEND_CAP_USDG</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`[<span class="hljs-subst">${<span class="hljs-built_in">symbol</span>}</span>] dip <span class="hljs-subst">${changePct.toFixed(<span class="hljs-number">3</span>)}</span>% -- SKIPPED, daily cap reached`</span>)
<span class="hljs-keyword">continue</span>
}
spentToday += <span class="hljs-variable constant_">MAX_SPEND_USDG_PER_TRADE</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`[<span class="hljs-subst">${<span class="hljs-built_in">symbol</span>}</span>] dip <span class="hljs-subst">${changePct.toFixed(<span class="hljs-number">3</span>)}</span>% -- PAPER BUY $<span class="hljs-subst">${MAX_SPEND_USDG_PER_TRADE}</span> (spent today: $<span class="hljs-subst">${spentToday}</span>/$<span class="hljs-subst">${DAILY_SPEND_CAP_USDG}</span>)`</span>)
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`[<span class="hljs-subst">${<span class="hljs-built_in">symbol</span>}</span>] $<span class="hljs-subst">${q.priceUsd.toFixed(<span class="hljs-number">2</span>)}</span> (<span class="hljs-subst">${changePct >= <span class="hljs-number">0</span> ? <span class="hljs-string">'+'</span> : <span class="hljs-string">''</span>}</span><span class="hljs-subst">${changePct.toFixed(<span class="hljs-number">3</span>)}</span>%) -- hold`</span>)
}
}
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'paper-trading agent started -- Ctrl-C to stop (kill switch)'</span>)
<span class="hljs-keyword">while</span> (running) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">tick</span>()
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'---'</span>)
<span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">r</span>) =></span> <span class="hljs-built_in">setTimeout</span>(r, <span class="hljs-number">5000</span>))
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'stopped cleanly.'</span>)</code></pre></figure><p>Run it against real mainnet quotes:</p>
<figure class="code-block" data-lang="bash"><figcaption><span class="code-lang">bash</span><button class="copy-btn" type="button" aria-label="Copy code to clipboard">Copy</button></figcaption><pre><code class="hljs language-bash">npx tsx agent.ts</code></pre></figure><p>A real, unedited capture from a 15-second run:</p>
<figure class="code-block" data-lang="text"><figcaption><span class="code-lang">text</span><button class="copy-btn" type="button" aria-label="Copy code to clipboard">Copy</button></figcaption><pre><code class="hljs language-plaintext">paper-trading agent started -- Ctrl-C to stop (kill switch)
[AAPL] baseline $315.50
[TSLA] baseline $407.82
[NVDA] baseline $210.19
[SPY] baseline $753.62
---
[AAPL] $315.50 (+0.000%) -- hold
[TSLA] $407.82 (+0.000%) -- hold
[NVDA] $210.19 (+0.000%) -- hold
[SPY] $753.62 (+0.000%) -- hold
---
[AAPL] $315.50 (+0.000%) -- hold
[TSLA] $407.82 (+0.000%) -- hold
[NVDA] $210.19 (+0.000%) -- hold
[SPY] $753.62 (+0.000%) -- hold</code></pre></figure><p>Notice what this <strong>doesn't</strong> show: a fabricated trade. This capture ran over a weekend, when Chainlink stock feeds are closed (Tutorial 3) — the prices genuinely didn't move between ticks, so the agent correctly held every time. That's the right behavior, not a disappointing demo. <strong>Never fake a trade to make a tutorial look more exciting than the real market was at the time you wrote it</strong> — that habit is exactly how you end up trusting an agent's logs that lie to you.</p>
<h2 id="going-from-paper-to-real-the-parts-that-change-and-don39t"><a class="anchor" href="#going-from-paper-to-real-the-parts-that-change-and-don39t" aria-label="Link to this section">#</a>Going from paper to real (the parts that change, and don't)</h2><p>When you're ready to let the agent actually spend, the strategy logic above is untouched. What changes is narrow and specific:</p>
<figure class="code-block" data-lang="TypeScript"><figcaption><span class="code-lang">TypeScript</span><button class="copy-btn" type="button" aria-label="Copy code to clipboard">Copy</button></figcaption><pre><code class="hljs language-typescript"><span class="hljs-keyword">import</span> { privateKeyToAccount } <span class="hljs-keyword">from</span> <span class="hljs-string">'viem/accounts'</span>
<span class="hljs-keyword">import</span> { createHoodClient, executeSwap, parseUsdg, <span class="hljs-variable constant_">MAINNET_ADDRESSES</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'hoodchain'</span>
<span class="hljs-keyword">const</span> hood = <span class="hljs-title function_">createHoodClient</span>({
<span class="hljs-attr">account</span>: <span class="hljs-title function_">privateKeyToAccount</span>(process.<span class="hljs-property">env</span>.<span class="hljs-property">ROBINHOOD_CHAIN_PRIVATE_KEY</span> <span class="hljs-keyword">as</span> <span class="hljs-string">`0x<span class="hljs-subst">${<span class="hljs-built_in">string</span>}</span>`</span>),
<span class="hljs-attr">acknowledgeStockTokenEligibility</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// only if you are actually eligible — see Tutorial 1</span>
})
<span class="hljs-comment">// replace the PAPER BUY console.log with:</span>
<span class="hljs-keyword">const</span> { hash, receipt } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">executeSwap</span>(hood, {
<span class="hljs-attr">tokenIn</span>: <span class="hljs-variable constant_">MAINNET_ADDRESSES</span>.<span class="hljs-property">usdg</span>,
<span class="hljs-attr">tokenOut</span>: token.<span class="hljs-property">address</span>,
<span class="hljs-attr">amountIn</span>: <span class="hljs-title function_">parseUsdg</span>(<span class="hljs-title class_">String</span>(<span class="hljs-variable constant_">MAX_SPEND_USDG_PER_TRADE</span>)),
}, { <span class="hljs-attr">slippageBps</span>: <span class="hljs-number">100</span> }) <span class="hljs-comment">// wider slippage — an unattended agent can't react to a failed fill</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`REAL BUY <span class="hljs-subst">${<span class="hljs-built_in">symbol</span>}</span>: tx <span class="hljs-subst">${hash}</span>, status <span class="hljs-subst">${receipt.status}</span>`</span>)</code></pre></figure><p>The spend caps, the kill switch, and the strategy decision are <strong>identical code</strong> — only the final action (<code>console.log</code> vs. <code>executeSwap</code>) changed. That's by design: if your paper-mode agent and your live agent share every line except the actual send, you can trust that what you watched in paper mode is what will happen live. If they're structurally different code paths, you're testing something you're not shipping.</p>
<div class="callout callout-warning"><p class="callout-title">Start with an amount you'd be fine losing entirely</p><p>Even with caps and a kill switch, a strategy can be wrong, a feed can behave unexpectedly, or a bug can exist in code you wrote an hour ago. <code>DAILY_SPEND_CAP_USDG = 100</code> is a ceiling, not a promise of safety. Fund the live wallet with exactly what you're prepared to lose, and nothing more, for at least the first several days of live operation.</p>
</div>
<h2 id="logging-and-observability"><a class="anchor" href="#logging-and-observability" aria-label="Link to this section">#</a>Logging and observability</h2><p>An agent with no audit trail is an agent you can't debug after the fact. At minimum, persist (to a file or a database, not just stdout) every: quote observed, decision made and why, transaction sent with its hash, and cap-triggered skip. When something looks wrong three days from now, you want to reconstruct exactly what the agent saw and decided, not just what it did.</p>
<h2 id="troubleshooting"><a class="anchor" href="#troubleshooting" aria-label="Link to this section">#</a>Troubleshooting</h2><p><strong>Agent never trades, even during a volatile market</strong> — check <code>DIP_THRESHOLD_PCT</code> isn't set unreasonably high for the volatility of your basket, and confirm <code>getQuote</code> isn't throwing <code>StaleFeedError</code> silently (wrap the tick loop's body in a try/catch per symbol so one bad feed doesn't kill the whole tick).</p>
<p><strong>Kill switch doesn't stop it</strong> — confirm you're checking the <code>running</code> flag at the top of the <code>while</code> loop, not just setting it. A <code>SIGINT</code> handler that sets a flag nobody reads does nothing.</p>
<p><strong>Daily cap never resets</strong> — the example above never resets <code>spentToday</code>; add a check against a stored date and reset the counter on a new day, ideally persisted so a restart doesn't reset the cap early and let the agent double-spend the "daily" limit.</p>
<h2 id="what-you-built"><a class="anchor" href="#what-you-built" aria-label="Link to this section">#</a>What you built</h2><p>A strategy loop with the risk controls built in from the first line, verified against a real (honestly reported, not fabricated) run — and the exact, minimal diff between its paper and live modes. Next: the other side of an autonomous agent's toolkit — creating things on-chain, not just trading them.</p>
</div>
<nav class="pager-nav" aria-label="Tutorial pagination"><a class="pager pager-prev" href="../09-ai-agent-chain-access/"><span class="pager-dir">← Previous</span><span class="pager-title">Give your AI agent chain access with MCP</span></a><a class="pager pager-next" href="../11-launch-a-coin/"><span class="pager-dir">Next →</span><span class="pager-title">Launch a coin programmatically</span></a></nav>
<footer class="doc-footer">
<p>Question or correction? <a href="https://github.com/nirholas/learn-robinhood-chain/issues" target="_blank" rel="noopener noreferrer">Open an issue</a>.</p>
<p>Built by <a href="https://x.com/nichxbt" target="_blank" rel="noopener noreferrer">nirholas</a> · <a href="https://three.ws" target="_blank" rel="noopener noreferrer">three.ws</a></p>
</footer>
</article>
<nav class="toc" aria-label="On this page"><p class="toc-title">On this page</p><ul><li class="toc-l2"><a href="#design-the-risk-controls-first">Design the risk controls first</a></li><li class="toc-l2"><a href="#a-minimal-strategy-dip-detection-paper-mode">A minimal strategy: dip detection, paper mode</a></li><li class="toc-l2"><a href="#going-from-paper-to-real-the-parts-that-change-and-don39t">Going from paper to real (the parts that change, and don&#39;t)</a></li><li class="toc-l2"><a href="#logging-and-observability">Logging and observability</a></li><li class="toc-l2"><a href="#troubleshooting">Troubleshooting</a></li><li class="toc-l2"><a href="#what-you-built">What you built</a></li></ul></nav>
</main>
</div>
<div class="search-modal" id="search-modal" hidden role="dialog" aria-modal="true" aria-label="Search">
<div class="search-panel">
<input type="search" id="search-input" placeholder="Search tutorials…" autocomplete="off" spellcheck="false" aria-label="Search query">
<ul class="search-results" id="search-results" aria-live="polite"></ul>
<p class="search-hint"><kbd>↑</kbd><kbd>↓</kbd> to navigate · <kbd>↵</kbd> to open · <kbd>esc</kbd> to close</p>
</div>
</div>
<script defer src="../assets/app.js"></script><script defer src="../assets/search.js"></script>
</body>
</html>