Stop Writing Trading Scripts. Start Building Senses: How I Forged an Autonomous AI trading bot

Stop Writing Trading Scripts. Start Building Senses: How I Forged an Autonomous AI trading bot

Leader posted 5 min read

Forging Herakles-octobot: How I Built an Autonomous AI Crypto Trader (That Actually Understands Risk)

The crypto markets are a dark, unforgiving place. It is a realm of endless, 24/7 chaos where traditional algorithmic trading bots march blindly to their slaughter. You write a Python script, hook up some moving average crossovers, and watch your portfolio slowly bleed out like a foot soldier caught in the vanguard.

Traditional bots are rigid. They don't understand context. They don't know that a falling Taker Buy/Sell ratio matters more right now than a lagging MACD, or that Extreme Fear on Reddit combined with an oversold StochRSI is a contrarian powder keg waiting to ignite.

I needed to forge something stronger. Going from an aerospace engineering dropout to a telecom engineer, and ultimately finding my footing as a solo software developer here in Chicago, you learn a fundamental truth about complex, high-stakes systems: surviving the chaos requires dynamic reasoning, not just hardcoded if-statements.

So, I built an autonomous trading engine. I named it Herakles. I handed the cognitive heavy-lifting to Claude, gave it a $10k paper-trading portfolio to start, and fed it a firehose of real-time market data.

Here is a technical deep dive into how you force an LLM to stop acting like a helpful chatbot and start acting like a ruthless, calculated execution engine.

The Brain: One Prompt to Bind Them

You can't just ask an LLM, "Should I buy Bitcoin?" That is like asking a goblin to guard your gold—it will hallucinate, hedge, and give you a bulleted list of useless financial disclaimers. You have to box it in. You have to build an ironclad cognitive framework.

My system prompt doesn't ask for opinions. It dictates a strict Signal Hierarchy for 1-hour directional predictions. I force the model to weigh inputs in a very specific order.

SIGNAL HIERARCHY — what to trust for 1H predictions:

LEADING (these move price in 15-45 min — weight heavily):
  • Taker buy/sell ratio: >1.1=buy pressure, <0.9=sell pressure
  • Volume Delta (CVD): rising=buyers dominating, falling=sellers dominating
  • Orderbook imbalance: immediate supply/demand pressure at current price

CONFIRMING (validate the directional thesis):
  • Multi-TF trend alignment: 1H (45%) + 4H (35%) + 1D (20%). All aligned = high conviction
  • VWAP position: above=bullish institutional bias, below=bearish. Distance amplifies
  • RSI + StochRSI — trending: extremes = strength. Ranging: extremes = reversal

REVERSAL (these override trend signals when present):
  • RSI Divergence on 4H — strongest reversal signal in crypto
  • Extreme funding rate (>0.05%) — crowded trade will snap back

SHORT TRADE RULE:
Crypto has structural long bias. To predict DOWN, require at least 2 of:
taker ratio <0.85, CVD falling, bearish divergence, price below VWAP with declining momentum.

If the LLM wants to short a structurally long market like crypto, I require it to provide at least two heavy bearish indicators. It must prove its case mathematically before the backend allows the API call to fire.

The Nervous System: The All-Seeing Eye

An LLM is only as good as its context window. To make this work, the backend acts as an all-seeing eye, aggregating an absurd amount of data every hour. We aren't just looking at Binance price action. The bot ingests 25 data points across 3 timeframes, plus real-time derivatives flow.

Latency is the enemy. If you are trading 1-hour momentum, you need sub-second aggregation. Here is a snapshot of the internal routing matrix the script uses to build the context payload:

[
  {"Source": "Binance MTF (1H/4H/1D)", "Type": "technical", "Latency": "0ms", "Contribution": "95%"},
  {"Source": "Taker Buy/Sell Ratio", "Type": "derivatives", "Latency": "0ms", "Contribution": "90%"},
  {"Source": "Orderbook 3-Exchange", "Type": "orderbook", "Latency": "0ms", "Contribution": "80%"},
  {"Source": "VWAP", "Type": "technical", "Latency": "0ms", "Contribution": "80%"},
  {"Source": "ClankApp Whales", "Type": "onchain", "Latency": "0ms", "Contribution": "70%"},
  {"Source": "Fear & Greed Index", "Type": "sentiment", "Latency": "0ms", "Contribution": "70%"}
]

The Secret Weapon: Guarding the Hoard

Here is where 99% of experimental AI trading projects fail: they treat every trade in a vacuum.

Herakles is fully aware of its own wallet. I inject the PORTFOLIO STATE directly into the prompt alongside the market data. It knows exactly how much capital it has, its current win rate, and the exact P&L of open positions. It guards the hoard.

=== PORTFOLIO AWARENESS ===
Wallet Summary:
• Total Portfolio Value: $11,367.55 USDT
• Available Balance: $8,764.57 USDT (77.1% cash)

OPEN POSITIONS:
#1 BTC/USDT 
  ├─ Size: 0.03657800 BTC ($2,602.97 / 22.9% of portfolio)
  └─ P&L:  $+97.40 (+3.89%)

I gave it strict exposure rules. If a position is profitable >20%, it must lock in gains. If the portfolio is >70% exposed, it has to minimize new entries. It is programmed for survival first, profit second.

The Crucible: Holding the Line

Let's look at a live execution. The other day, BTC was sitting at $71,168. The macro trend was up. Traditional bots would have likely sounded the horns and slammed the "BUY" button because the price was above the VWAP and the daily MACD was glowing green.

But Herakles saw something else in the shadows. Look at the strict JSON it returned:

{
  "step_analysis": {
    "flow": "BEARISH LEADING SIGNALS: Taker ratio 0.819 (<0.9 = sell pressure), CVD falling (sellers dominating). Orderbook +18.9% provides minor support. Leading indicators conflict with uptrend - suggests pullback in progress.",
    "momentum": "MIXED. StochRSI=15 OVERSOLD suggests bounce imminent. CRITICAL: 1H bearish RSI divergence detected - reversal warning but not on 4H.",
    "context": "Funding 0.0056% healthy. Fear index 17 = EXTREME FEAR (strong contrarian buy). Whale activity extreme at $2.3B."
  },
  "prediction": "up",
  "confidence": 54,
  "signal_strength": "neutral_long",
  "invalidation_condition": "Price breaks below S1 $70,496 with increasing volume, or taker ratio drops below 0.75",
  "suggested_levels": {
    "stop_loss": "$70,496 (S1 pivot)",
    "take_profit_1": "$71,540 (R1 pivot)"
  },
  "reasoning": "Uptrend intact but short-term flow is bearish (taker 0.819, CVD falling). However, StochRSI oversold + extreme fear suggests pullback nearing exhaustion. Low confidence due to conflicting leading indicators. Already hold 22.9% BTC at +3.89% profit - no need to add with mixed signals. Hold existing position.",
  "position_action": null
}

It decided to do nothing. It recognized the bullish macro structure but saw the leading bearish flow (falling CVD, low taker ratio). More importantly, it looked at its portfolio, saw it already had 22% exposure in a profitable position, and decided the risk/reward simply wasn't there to throw more capital into the fray.

That level of restraint—choosing to HOLD the line in the face of conflicting data—is something most human traders take years and thousands of dollars in liquidations to learn.

The Execution: Raising the Shield Wall

But deciding to "HOLD" doesn't mean the system is sleeping. It means it switches from acquisition mode to defense mode.

While it declined to allocate new capital, the engine autonomously calculated and placed a protective shield wall around the existing position, dispatching OCO (One-Cancels-the-Other) orders to the exchange:

[
  {
    "Pair": "BTC/USDT",
    "Type": "STOP LOSS",
    "Price": 69016.99,
    "Quantity": 0.018874,
    "TotalValue": "1302.62 USDT"
  },
  {
    "Pair": "BTC/USDT",
    "Type": "SELL LIMIT",
    "Price": 72019.58,
    "Quantity": 0.018874,
    "TotalValue": "1359.29 USDT"
  }
]

Notice the mechanical precision. It didn't just throw a blind 5% stop loss into the void. It dynamically placed the stop at $69,016—safely tucked beneath the 4H EMA50 ($68,673) and the S1 pivot to avoid getting wicked out by localized volatility. Simultaneously, it set a limit sell above to automatically lock in partial gains if the RSI divergence resolved in a quick liquidity grab.

The Road Goes Ever On

We are moving past the era of LLMs as simple code-assistants and entering the era of LLMs as autonomous execution engines. When you give an AI structured rules, massive context, and the ability to execute real API calls, the results are slightly terrifying and deeply inspiring.

I'm continuing to refine the architecture, tweaking the weights, and hunting for more alpha in the data streams. The journey is far from over.

I'm curious for the devs out there building agentic workflows:

  1. How are you handling hallucination when the output must be strict JSON for execution? Do you use a secondary validation script before pushing to the API?
  2. Are you using smaller, fine-tuned models for speed, or relying on heavyweights for the raw reasoning capabilities?

Let's talk about it!

see some of my other projects at https://github.com/herakles-dev

1 Comment

0 votes
0
0
0

More Posts

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

Understanding Basic Data Structures for Web Development

MasterCraft - Feb 16

How I Built a React Portfolio in 7 Days That Landed ₹1.2L in Freelance Work

Dharanidharan - Feb 9

Breaking the AI Data Bottleneck: How Hammerspace's AI Data Platform Eliminates Migration Nightmares

Tom Smithverified - Mar 16

What Is an Availability Zone Explained Simply

Ijay - Feb 12
chevron_left

Related Jobs

Commenters (This Week)

2 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!