Not ready for live trading

Supertrend Strategy Analysis

Pine Script v4 β€’ Binance BTC/USDT

Roadmap to Autonomous Trading Bot

Six phases from broken code to fully automated trading.

Current: Step 1 Est. timeline: ~6 months

Step 1: Fix Critical Issues (Week 1-2)

Goal: Make the strategy functionally correct and safe to test

  • βœ… Fix position sizing calculation to properly convert USD risk to BTC quantity
  • βœ… Add stop loss and take profit to every trade
  • βœ… Implement daily loss limit ($500 recommended)
  • βœ… Add maximum trades per day (5 recommended)
  • βœ… Add minimum bars between trades (10-20 bars)
  • βœ… Improve EMA filter with buffer zone (0.5% recommended)
  • βœ… Review and adjust risk parameters ($230 max loss needs revision)

Deliverable: Updated Pine Script with all critical fixes implemented

Step 2: Backtest & Optimize (Week 3-4)

Goal: Validate strategy performance and optimize parameters

  • πŸ“Š Backtest on 2-3 years of BTC data (include 2022 bear, 2024 bull)
  • πŸ“Š Test parameter variations (ATR period: 8-14, Multiplier: 3.0-5.0)
  • πŸ“Š Include realistic trading costs (0.1-0.2% per round trip)
  • πŸ“Š Calculate key metrics: Sharpe ratio, max drawdown, win rate, profit factor
  • πŸ“Š Test across different market conditions (trending vs ranging)
  • πŸ“Š Out-of-sample validation (test on data not used for optimization)
  • πŸ“Š Monte Carlo simulation for robustness testing

Success Criteria: Sharpe ratio > 1.0, Max DD < 25%, Profit factor > 1.3

Deliverable: Comprehensive backtest report with optimized parameters

Step 3: Paper Trading (Week 5-12)

Goal: Test strategy in real-time without risking capital

  • πŸ“ Set up paper trading account (TradingView, Binance testnet)
  • πŸ“ Connect to real-time data feed
  • πŸ“ Track all signals and simulated trades
  • πŸ“ Document performance weekly
  • πŸ“ Monitor slippage and execution differences vs backtest
  • πŸ“ Test during various market conditions (volatile, quiet, trending)
  • πŸ“ Compare paper results to backtest expectations
  • πŸ“ Identify any bugs or unexpected behavior

Success Criteria: 2-3 months of profitable paper trading, performance within 80% of backtest

Deliverable: Paper trading journal with all trades documented and analyzed

Step 4: Build Trading Bot (Week 13-16)

Goal: Create autonomous system for order execution

Technical Stack Options:

  • Python: ccxt library for exchange API, pandas for data, backtrader/zipline for backtesting
  • JavaScript/Node: ccxt, tulind for indicators, lightweight and fast
  • Hosting: VPS (AWS, DigitalOcean) or dedicated server with 99.9% uptime

Core Components to Build:

  • πŸ€– Data Feed Manager: Connect to Binance WebSocket for real-time price data
  • πŸ€– Indicator Calculator: ATR, Supertrend, 200 EMA calculation engine
  • πŸ€– Signal Generator: Detect crossovers and entry/exit conditions
  • πŸ€– Order Executor: Place, modify, cancel orders via Binance API
  • πŸ€– Position Manager: Track open positions, P&L, exposure
  • πŸ€– Risk Manager: Enforce daily loss limits, max position size, trade frequency
  • πŸ€– Error Handler: Reconnection logic, API rate limit management
  • πŸ€– Logging System: Record all decisions, orders, errors for debugging
  • πŸ€– Alert System: Telegram/email notifications for trades and errors
  • πŸ€– Dashboard: Web interface to monitor bot status and performance

Security Considerations:

  • API keys with IP whitelist and withdraw restrictions
  • Encrypted storage of credentials
  • Rate limiting to avoid API bans
  • Kill switch mechanism for emergency shutdown

Deliverable: Fully functional trading bot tested on testnet

Step 5: Live Testing with Small Capital (Week 17-24)

Goal: Validate bot in production with minimal risk

  • πŸ’° Start with 10-20% of intended total capital
  • πŸ’° Use minimum position sizes (0.5-1% risk per trade)
  • πŸ’° Monitor bot 24/7 for first week
  • πŸ’° Check-in twice daily minimum afterward
  • πŸ’° Compare live performance to paper trading
  • πŸ’° Document all trades and analyze discrepancies
  • πŸ’° Test bot recovery from connection issues
  • πŸ’° Verify all risk controls are working (daily loss, max trades)
  • πŸ’° Calculate actual slippage and fee impact

What to Watch For:

  • Execution delays causing different entry prices
  • Slippage higher than expected
  • Orders failing or getting rejected
  • Bot making unexpected decisions
  • Performance degradation vs paper trading

Success Criteria: 2 months profitable, max DD < 15%, no critical bugs

Deliverable: Proven bot operation with real money, full trade log analysis

Step 6: Full Autonomous Operation (Week 25+)

Goal: Scale to full intended capital with confidence

  • πŸš€ Gradually increase capital allocation (25% β†’ 50% β†’ 75% β†’ 100%)
  • πŸš€ Increase position sizes proportionally
  • πŸš€ Continue monitoring daily but reduce intervention
  • πŸš€ Weekly performance reviews and strategy adjustments
  • πŸš€ Monthly comprehensive analysis
  • πŸš€ Set up automated monitoring and alerts
  • πŸš€ Build redundancy (backup server, failover system)
  • πŸš€ Maintain detailed audit trail

Ongoing Maintenance:

  • Monitor for market regime changes
  • Adjust parameters if strategy starts underperforming
  • Update code for exchange API changes
  • Regular system health checks
  • Keep capital aside for exchange outages or API issues

When to Pause or Stop:

  • Drawdown exceeds 25%
  • Strategy stops working as expected
  • Market structure changes fundamentally
  • Major regulatory or exchange issues
Reality Check: Most traders quit during Step 3 or Step 5. The ones who succeed are those who methodically follow each step, document everything, and maintain discipline through drawdowns.

Total Timeline Summary

  • Weeks 1-2: Fix code
  • Weeks 3-4: Backtest thoroughly
  • Weeks 5-12: Paper trade (2-3 months)
  • Weeks 13-16: Build bot infrastructure
  • Weeks 17-24: Live test with small capital (2 months)
  • Week 25+: Full autonomous operation

Total: ~6 months minimum from current broken state to full autonomous trading.

Critical Success Factor: Don't skip steps. Each phase builds on the previous. Rushing to live trading without proper testing is the #1 reason most trading bots fail.

1. Broken Position Sizing Logic

Critical β€” The strategy calculates position size in "contracts" without accounting for BTC's actual price, causing zero or incorrect positions.

The Problem: At BTC = $95,000 with $500 risk distance, it calculates 0.46 contracts. After floor(0.46) = 0 contracts = NO POSITION

Why it fails: The formula divides USD risk by USD distance, giving a ratio, not BTC quantity. It needs to convert to actual BTC units.

2. Missing Risk Controls

Critical β€” No safety mechanisms protecting your capital:

  • No stop loss orders β€” Relies only on Supertrend crossover to exit
  • No take profit levels β€” Trades run indefinitely until reversal
  • No daily loss limit β€” Could lose entire account in bad streak
  • No maximum drawdown protection β€” No circuit breaker
  • No trade frequency caps β€” Could overtrade in choppy markets

3. Risk Parameters Don't Match BTC

Critical β€” $230 max loss with 20 max contracts creates dangerous misalignment:

  • Typical Supertrend stop distance: $1,500 - $3,000
  • With $230 risk β†’ position size: 0.08-0.15 BTC = $7,600-$14,250
  • But 20 contracts (if = 20 BTC) = $1,900,000 exposure
  • Either positions are too small to be viable, or max contracts is dangerously high

4. Immediate Reversal Creates Whipsaw Risk

High Priority β€” Strategy instantly flips long↔short on every signal, causing:

  • Death by fees: 0.1-0.2% per round trip Γ— many trades = substantial drag
  • Choppy market carnage: Price oscillating near 200 EMA triggers multiple reversals
  • Slippage compounds losses: Market orders on volatile BTC = poor fills
  • No cooldown period: Can enter, exit, reverse all within minutes

1. Fix Position Sizing for Crypto

Replace the broken contract calculation with proper BTC quantity calculation:

// Option A: Risk percentage of equity
risk_percent = input(2.0, title="Risk % Per Trade") / 100
equity = strategy.equity
risk_amount = equity * risk_percent

// Calculate USD position size based on risk
position_size_usd = risk_amount / risk_per_unit_long

// Convert to BTC quantity
btc_qty = position_size_usd / close

strategy.entry("Long", strategy.long, qty=btc_qty)
// Option B: Fixed USD notional
usd_position_size = input(1000, title="Position Size USD")
btc_qty = usd_position_size / close

strategy.entry("Long", strategy.long, qty=btc_qty)

2. Add Stop Loss & Take Profit

Protect every trade with proper risk management:

// Stop loss at Supertrend line
stop_loss_long = up
stop_loss_short = dn

// Take profit at 2:1 risk/reward ratio
risk_long = close - stop_loss_long
take_profit_long = close + (risk_long * 2.0)

risk_short = stop_loss_short - close
take_profit_short = close - (risk_short * 2.0)

// Apply to entry orders
strategy.entry("Long", strategy.long, qty=btc_qty)
strategy.exit("Exit Long", "Long",
    stop=stop_loss_long, limit=take_profit_long)

3. Implement Daily Loss Limit

Prevent catastrophic losing streaks:

// Track daily P&L
max_daily_loss = input(500, title="Max Daily Loss USD")
var float daily_pnl = 0.0
var int current_day = dayofmonth

// Reset at start of new day
if (dayofmonth != current_day)
    daily_pnl := 0.0
    current_day := dayofmonth

// Update with closed trade results
if (strategy.closedtrades > 0)
    last_trade = strategy.closedtrades.profit(strategy.closedtrades - 1)
    daily_pnl := daily_pnl + last_trade

// Block new trades if limit hit
allow_trades = daily_pnl > -max_daily_loss

if (longCondition and allow_trades)
    strategy.entry("Long", strategy.long, qty=btc_qty)

4. Add Trade Frequency Filter

Prevent overtrading in choppy conditions:

// Minimum bars between trades
min_bars_between = input(10, title="Min Bars Between Trades")
var int last_trade_bar = 0

can_trade = bar_index - last_trade_bar >= min_bars_between

if (longCondition and can_trade)
    strategy.entry("Long", strategy.long, qty=btc_qty)
    last_trade_bar := bar_index
// Maximum trades per day
var int trades_today = 0
var int last_day = 0

if (dayofmonth != last_day)
    trades_today := 0
    last_day := dayofmonth

max_daily_trades = input(5, title="Max Trades Per Day")

if (longCondition and trades_today < max_daily_trades)
    strategy.entry("Long", strategy.long, qty=btc_qty)
    trades_today := trades_today + 1

5. Improve EMA Filter Logic

Add buffer zone to reduce whipsaws around 200 EMA:

// Create buffer zone around EMA
ema_buffer_percent = input(0.5, title="EMA Buffer %") / 100
ema_upper = ema200 * (1 + ema_buffer_percent)
ema_lower = ema200 * (1 - ema_buffer_percent)

// Stricter entry conditions
longCondition = crossover(close, dn) and close > ema_upper
shortCondition = crossunder(close, up) and close < ema_lower

// Optional: Add trend strength confirmation
ema_slope = ema200 - ema200[10]
strong_uptrend = ema_slope > 0
strong_downtrend = ema_slope < 0

longCondition = longCondition and strong_uptrend
shortCondition = shortCondition and strong_downtrend

How the Strategy Works

This is a trend-following reversal system that aims to stay in the market at all times, flipping between long and short positions based on Supertrend crossovers filtered by the 200 EMA.

Core Components

  • Supertrend Indicator: ATR-based dynamic support/resistance bands (Period: 6, Multiplier: 4.2)
  • 200 EMA Filter: Major trend indicator β€” only longs above, only shorts below
  • Position Sizing: Dynamic based on distance to Supertrend line (risk per trade)
  • Entry Logic: Crossover signals combined with EMA filter confirmation
  • Exit Logic: Immediate reversal on opposite signal (no flat periods)

Entry Conditions

Long Entry: Price crosses above lower Supertrend band AND price is above 200 EMA

Short Entry: Price crosses below upper Supertrend band AND price is below 200 EMA

Trade Execution Flow

  1. Supertrend identifies potential trend change (crossover)
  2. 200 EMA confirms we're on correct side of major trend
  3. Position size calculated based on distance to Supertrend line
  4. Trade entered immediately with no confirmation bar
  5. Position held until opposite crossover occurs
  6. On opposite signal, close current position and reverse
Key Characteristic: This is an "always in market" reversal system. It never sits in cash β€” every exit is immediately followed by a position in the opposite direction.

Best Market Conditions

βœ… Thrives in:

  • Strong trending markets (sustained 10%+ directional moves)
  • Clear breaks and holds above/below 200 EMA
  • High volatility with strong directional bias
  • Low frequency of false breakouts

❌ Struggles in:

  • Choppy/ranging markets (60-70% of the time for most assets)
  • Price oscillating around the 200 EMA
  • Low volatility consolidation periods
  • Multiple false breakouts and whipsaws
  • Weekend low liquidity periods (higher slippage)

Expected Trading Costs

Binance BTC/USDT Futures:

  • Maker fee: 0.02% (limit orders)
  • Taker fee: 0.04% (market orders)
  • Average slippage: 0.01-0.05% depending on size
  • Round trip cost: ~0.1-0.2%
Cost Impact Example: On a $10,000 position, each trade costs $10-$20. With 100 trades per month, that's $1,000-$2,000 in fees alone. This strategy uses market orders = higher costs.

Why This Strategy Needs Serious Work

The current implementation has fundamental flaws that could result in:

  • Zero positions being entered due to broken position sizing
  • Uncapped losses without stop losses or daily limits
  • Rapid account depletion from overtrading in choppy markets
  • Fee erosion eating 10-20% of returns even when profitable

Market Reality Check

Backtested β‰  Real Trading: Parameters optimized for past data often fail forward. Markets change, volatility regimes shift, and correlation structures break down.

60-70% Chop Time: Most markets spend the majority of time ranging or consolidating. Trend-following strategies make money 30-40% of the time and bleed slowly the rest.

Psychological Warfare: Following a system through a 30% drawdown requires discipline most traders don't have. Many abandon strategies right before they become profitable.

Technical & Operational Risks

  • API Failures: Exchange outages during volatile moves can trap you in positions
  • Slippage Surprises: Weekend or low liquidity periods = worse fills than backtested
  • Funding Costs: If using perpetual futures, funding rates can be 0.01-0.1% every 8 hours
  • Bugs & Errors: Code mistakes can enter wrong sizes, miss exits, or double-enter

Black Swan Events

Historical backtests can't account for:

  • Exchange hacks or insolvency (FTX, Mt.Gox)
  • Regulatory shocks (China ban, ETF news)
  • Flash crashes with 20-40% drops in minutes
  • Liquidity crises where you can't exit at any reasonable price
Golden Rule: Never risk more than you can afford to lose completely. Crypto can go to zero. Trading bots can have bugs. Exchanges can disappear overnight.

When to Stop Trading Immediately

Halt the strategy if any of these occur:

  • Daily loss limit exceeded (that's why you need one)
  • Drawdown exceeds 25% of account
  • 5+ consecutive losing trades
  • Strategy behavior appears abnormal or unexpected
  • Major market structure change (e.g., regulatory announcement)
  • Exchange experiencing technical difficulties

Recommended Approach

  1. Fix all critical issues documented in this report
  2. Backtest thoroughly on 2-3 years of data including crashes
  3. Paper trade for 2-3 months with real-time data and realistic fees
  4. Start with 10-20% of intended capital and tiny position sizes (0.5-1% risk)
  5. Scale up slowly only after 3+ months of consistent profitability
  6. Never increase risk after winning streaks (stay disciplined)
Final Warning: This is NOT financial advice. The strategy in its current form is fundamentally broken and will likely not work as expected. Even after fixes, systematic trading is extremely difficult and most retail traders lose money.

Report Generated: December 2025 β€’ Strategy: Supertrend with 200 EMA Filter (Pine Script v4) β€’ Target Market: Binance BTC/USDT

⚠️ Not financial advice. All trading carries risk of loss.