9horsemenStart building

Why AI Trading Bots Fail: How to Code a Pine Script Volume Auditor

An essay from 9horsemen's founder. For practical help running a business, see the blog. More thinking like this on our podcast, Why Your Software Sucks.

A dark computer monitor displays custom Pine Script code and a candlestick chart next to a physical ledger book, illustrating the disciplined, quantitative approach to financial screening and market analysis.

TL;DR:

  • The Core Problem: Retail investors treat AI like a financial crystal ball, building bots that trade on news sentiment, leading to massive capital destruction.
  • The Structural Reality: Retail brokerages promote gamified, hyperactive trading features to harvest transaction fees, intentionally ignoring the rigorous fundamental screening tools that actually protect wealth.
  • The Solution: Smart operators use AI coding assistants to build custom technical indicators (like Pine Script volume auditors). Moving from prototype to live automation takes hardened code that protects your capital and API keys.

Do AI trading bots work? Bots that trade on news and social media sentiment mostly lose money, because a language model can’t predict markets. Where AI does help is as a coding assistant that builds tools to screen the market for you. Here’s how to build one.

Do AI trading bots work?

Not the way they’re sold: a chatbot reading headlines and sentiment is matching patterns, not predicting prices, and trading on it is gambling.

If you spend five minutes on YouTube or financial Twitter, you will be bombarded by teenagers selling the exact same dream: “I built an AI trading bot with ChatGPT and made $10,000 this week.”

The hype machine insists that artificial intelligence is a financial crystal ball. The pitch is that you can wire a Large Language Model to read social media sentiment, parse news headlines, and automatically trade options while you sleep. The industry is marketing generative AI as an omniscient hedge fund manager that can out-predict Wall Street.

This is financial suicide. A language model is a pattern-matching engine, not a psychic. Giving a chatbot your brokerage API keys because it read a positive tweet about a tech stock is a guaranteed way to liquidate your portfolio.

How can you use AI for trading without gambling?

Use it to write the code for a screening tool, like a Pine Script indicator that flags unusual trading volume, and keep the decisions to yourself.

The visceral pain happens when an independent retail investor realises they lost 20% of their net worth because their “AI bot” bought a stock right before a massive institutional dump. The friction is the brutal reality that digital AI has zero understanding of actual financial risk, liquidity, or market structure.

The elite operators—the ones actually protecting and growing their capital—do not ask AI to predict the future. They use AI as a coding assistant to automate the brutal, boring logic of quantitative screening.

A smart investor doesn’t ask an LLM, “What stock should I buy?” Instead, they open an AI coding environment and instruct it to build a highly specific tool. They say: “Write a TradingView Pine Script that tracks volume friction. I want to measure the mathematical effort a stock exerts, and flag anomalies where the physical price doesn’t match the projected effort. Show me where whales are hiding.”

The result isn’t a magic 8-ball. It is a surgical, mechanical auditor. Here is the exact code a sharp operator generates to spot artificial market manipulation:

//@version=5 indicator("V5 The Complete Auditor + V4 Target", overlay=true)// ================================================================================
// HOW THIS TOOL WORKS: THE ANOMALY DETECTOR
// 1. The Math vs. Reality Gap: This script calculates where a stock SHOULD be trading // based on the raw volume (effort) pumped into it over the last 20 days.
// 2. The Red Flag (Suppressed): If the math expects a massive price spike due to
// high buying volume, but the actual price stays flat, reality was capped.
// An institution is quietly selling (distributing) into the retail hype.
// 3. The Green Flag (Supported): If the math expects a sharp drop due to selling
// pressure, but the price refuses to break support, someone is quietly buying
// (accumulating) the dip.
// We are not predicting the news. We are hunting for footprints in the volume. // ================================================================================
--- 1. THE MEMORY DIALS ---
fric_len = input.int(20, "Historical Effort Lookback (Days)") macro_len = input.int(130, "Macro Reality Memory (Days)") cb_mult = input.float(10.0, "Circuit Breaker (Max ATR Multiplier)") div_mult = input.float(1.25, "Anomaly Std Dev Multiplier") div_len = input.int(20, "Anomaly Lookback Length")

// --- 2. CANDLE ANATOMY: MEASURING THE BATTLEFIELD ---
prev_close = close[1] current_vol = nz(volume) true_range = math.max(nz(ta.tr(true)), 1e-5) is_green = close >= open is_red = close < open

// --- 3. THE HISTORICAL WALL: FINDING THE COST OF BUSINESS ---
up_vol_sum = math.sum(is_green ? current_vol : 0, fric_len) up_tr_sum = math.sum(is_green ? true_range : 0, fric_len) down_vol_sum = math.sum(is_red ? current_vol : 0, fric_len) down_tr_sum = math.sum(is_red ? true_range : 0, fric_len)
total_vol = math.sum(current_vol, fric_len) total_tr = math.sum(true_range, fric_len) fallback_effort = total_tr > 0 ? (total_vol / total_tr) : 1e-5
avg_up_effort = up_tr_sum > 0 ? (up_vol_sum / up_tr_sum) : fallback_effort avg_down_effort = down_tr_sum > 0 ? (down_vol_sum / down_tr_sum) : fallback_effort

// --- 4. THE PROJECTION MATH: FINDING THE LIE ---
macro_atr = nz(ta.atr(20), true_range) max_allowed_distance = macro_atr * cb_mult
float daily_distance = 0.0 if is_green daily_distance := avg_up_effort > 0 ? (current_vol / avg_up_effort) : 0 else if is_red daily_distance := avg_down_effort > 0 ? (current_vol / avg_down_effort) : 0
daily_distance := math.min(daily_distance, max_allowed_distance) float daily_projected_price = is_green ? (prev_close + daily_distance) : (prev_close - daily_distance) float signed_distance = is_green ? daily_distance : (is_red ? -daily_distance : 0) float rolling_distance = math.sum(signed_distance, macro_len) float cumulative_projected_price = close[macro_len] + rolling_distance

// --- 5. THE DIVERGENCE ANOMALY ---
actual_avg_price = hlc3 micro_divergence = math.abs(daily_projected_price - actual_avg_price) mean_divergence = ta.sma(micro_divergence, div_len) std_divergence = ta.stdev(micro_divergence, div_len)
is_anomaly = micro_divergence > (mean_divergence + (div_mult * std_divergence))
// Suppressed: Math expected higher price, but reality was heavily capped. (Distribution) is_suppressed = is_anomaly and (daily_projected_price > actual_avg_price)
// Supported: Math expected lower price, but reality refused to drop. (Accumulation) is_supported = is_anomaly and (daily_projected_price < actual_avg_price)

// --- 6. THE DASHBOARD: PAINTING THE CHART ---
plot(cumulative_projected_price, title="Cumulative Reality (Macro)", color=color.new(color.orange, 0), style=plot.style_line, linewidth=2) plot(actual_avg_price, title="Actual Average Price", color=color.new(color.white, 0), style=plot.style_circles, linewidth=1)
plotshape(is_suppressed, title="Suppressed", style=shape.circle, location=location.abovebar, color=color.red, size=size.tiny) plotshape(is_supported, title="Supported", style=shape.circle, location=location.belowbar, color=color.green, size=size.tiny)

The AI didn’t predict anything. It simply did the heavy lifting of executing your unglamorous quantitative rules. You aren’t building a magic 8-ball; you are building a mechanised sieve that filters out financial garbage.

Why do trading apps push AI stock pickers?

Because brokers earn from every trade, so tools that keep you trading make them money, and a tool that tells you to sit still doesn’t.

If building a custom fundamental screener is the actual way to preserve capital, why do major retail trading platforms push “social sentiment” tools and gamified AI stock-pickers?

Because the economic model of retail brokerage relies on your hyperactivity. Brokers make money on order flow, spreads, and transaction fees. They want you trading frantically based on daily news cycles.

A surgical, AI-coded tool that tracks volume friction and tells you not to trade 99% of the time does not generate fees for the brokerage. Venture-backed fintech companies build platforms to keep your adrenaline high. They will never build the hyper-specific, boring, customised screener you actually need to protect your long-term wealth, because patience doesn’t pay their server bills.

What does it take to run a trading tool with real money?

Far more than a chart script: secure data feeds, reliable alerts and careful handling of your keys, because a bug costs real money.

Using AI tools to prototype a Pine Script indicator or model institutional volume anomalies offers immense speed. It allows quantitative operators and financial entrepreneurs to translate market logic into clean visual signals without getting bogged down in low-level syntax. It proves the maths holds on historical bars.

But when real capital and institutional risk parameters are on the line, execution cannot live inside a brittle browser tab. Plotting signals on a chart is merely step one. Building a localised, zero-leakage vault that normalises complex financial data feeds, triggers deterministic webhooks from TradingView alerts, and routes orders through private API pipelines without third-party exposure demands hardened systems engineering.

If you’re building tools like this, I write more about building software with AI in the other essays, talk about it on the podcast Why Your Software Sucks, and tell the long version in my story.