Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

Create a trading bot that analyzes 1D chart of SOLUSDT and, based on RSI, MACD, EMA 50,…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Kimikimi-k2-0711-preview’s answer.
  1. User

    Create a trading bot that analyzes 1D chart of SOLUSDT and, based on RSI, MACD, EMA 50, and EMA 200, decides whether to buy or sell. Then test it on the past 5 years of data.

  2. Assistant

    Below you’ll find a complete, self-contained Python notebook (just copy-paste into a .ipynb or .py file and run) that

    1. Downloads daily SOL/USDT candles from Binance (as far back as they exist – August 2020 → today, ≈3 years).
    2. Calculates RSI-14, MACD(12,26,9), EMA-50 and EMA-200.
    3. Generates LONG/FLAT signals with an intuitive rule-set: • Trend filter : go LONG only when EMA-50 > EMA-200 (golden-cross regime).
      • Entry trigger : RSI crosses up through 30 AND MACD line crosses above signal line.
      • Exit trigger : RSI crosses down through 70 OR MACD line crosses below signal OR EMA-50 falls below EMA-200 (death-cross).
    4. Back-tests the logic on the full history (one position at a time, all-in, no leverage, 0.1 % fee each side).
    5. Prints the key performance metrics & an equity-curve plot.

    You can naturally tweak the parameters or swap in another back-testing engine (Backtrader, vectorbt, zipline, etc.)—the core logic remains the same.

    # SOLUSDT_D1_RSI_MACD_EMA_BOT.py
    # ==============================================================
    # Requires: pandas, numpy, ta, matplotlib, ccxt (pip install ...)
    # ==============================================================
    
    import ccxt, pandas as pd, numpy as np, ta, matplotlib.pyplot as plt
    from datetime import datetime, timedelta, timezone
    
    PAIR      = 'SOL/USDT'
    TIMEFRAME = '1d'
    FEE       = 0.001      # 0.1 % per trade (Binance spot default)
    INITIAL_CASH = 10_000  # USDT
    
    # ------------------------------------------------------------------
    # 1. Pull daily candles (all available on Binance: Aug-2020 → today)
    # ------------------------------------------------------------------
    exchange = ccxt.binance({'rateLimit': 1200, 'enableRateLimit': True})
    
    # Binance limits 1,500 candles per request; loop until done
    def fetch_binance_ohlcv(pair, tf='1d', since=None):
        all_candles, since_ts = [], since
        while True:
            data = exchange.fetch_ohlcv(pair, tf, since=since_ts, limit=1500)
            if len(data) == 0:
                break
            all_candles += data
            since_ts = data[-1][0] + 1
            # stop if last candle is within 24 h
            if since_ts >= exchange.milliseconds():
                break
        return all_candles
    
    raw = fetch_binance_ohlcv(PAIR, TIMEFRAME, since=None)
    
    cols = ['timestamp','open','high','low','close','volume']
    df   = pd.DataFrame(raw, columns=cols)
    df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
    df.set_index('date', inplace=True)
    df = df[['open','high','low','close','volume']].astype(float)
    print(f'Downloaded {len(df)} candles: {df.index[0].date()} → {df.index[-1].date()}')
    
    # ------------------------------------------------------------------
    # 2. Indicator calculation
    # ------------------------------------------------------------------
    df['ema50'] = ta.trend.ema_indicator(df['close'], window=50)
    df['ema200'] = ta.trend.ema_indicator(df['close'], window=200)
    
    macd = ta.trend.macd(df['close'], window_slow=26, window_fast=12)
    signal = ta.trend.macd_signal(df['close'], window_slow=26, window_fast=12, window_sign=9)
    df['macd']   = macd
    df['macdsig']= signal
    
    df['rsi']    = ta.momentum.rsi(df['close'], window=14)
    
    # Drop leading NaNs
    df.dropna(inplace=True)
    
    # ------------------------------------------------------------------
    # 3. Generate trading signals
    # ------------------------------------------------------------------
    long_cond  = (df['ema50'] > df['ema200'])               # trend filter (must be true)
    entry_cond = (df['rsi'].shift(1) < 30) & (df['rsi'] > 30) & \
                 (df['macd'].shift(1) < df['macdsig'].shift(1)) & (df['macd'] > df['macdsig'])
    
    exit_cond  = (df['rsi'].shift(1) > 70) & (df['rsi'] < 70) | \
                 (df['macd'].shift(1) > df['macdsig'].shift(1)) & (df['macd'] < df['macdsig']) | \
                 (df['ema50'] < df['ema200'])
    
    df['signal'] = 0
    df.loc[ long_cond & entry_cond, 'signal'] =  1   # long
    df.loc[ exit_cond,                 'signal'] = -1   # flat/close
    
    # Forward-fill position (0 = flat, 1 = long)
    df['position'] = 0
    pos = 0
    for i,row in df.iterrows():
        if row['signal'] ==  1: pos = 1
        if row['signal'] == -1: pos = 0
        df.at[i,'position'] = pos
    
    # ------------------------------------------------------------------
    # 4. Simple vectorized back-test (all-in, no compounding during trade)
    # ------------------------------------------------------------------
    df['pct_change'] = df['close'].pct_change().fillna(0)
    df['strategy_ret'] = df['position'].shift(1) * df['pct_change']  # daily strategy return
    df['strategy_ret_after_fee'] = np.where(df['signal']!=0, df['strategy_ret'] - FEE*np.abs(df['signal']), df['strategy_ret'])
    
    df['equity'] = (1 + df['strategy_ret_after_fee']).cumprod() * INITIAL_CASH
    
    # Buy & hold equity for comparison
    df['bh_equity'] = (df['pct_change']+1).cumprod() * INITIAL_CASH
    
    # ------------------------------------------------------------------
    # 5. Performance summary
    # ------------------------------------------------------------------
    tot_ret    = df['equity'].iloc[-1] / INITIAL_CASH - 1
    bh_ret     = df['bh_equity'].iloc[-1] / INITIAL_CASH - 1
    max_dd = (df['equity'] / df['equity'].cummax() - 1).min()
    years = (df.index[-1] - df.index[0]).days / 365.25
    cagr  = (df['equity'].iloc[-1] / INITIAL_CASH) ** (1/years) - 1
    sharpe= (df['strategy_ret_after_fee'].mean() / df['strategy_ret_after_fee'].std()) * np.sqrt(365)
    
    print('\n===== RESULTS (Aug-2020 → {}) ====='.format(df.index[-1].date()))
    print(f'Total Return     : {tot_ret:>6.2%}')
    print(f'Buy & Hold Return: {bh_ret:>6.2%}')
    print(f'CAGR             : {cagr:>6.2%}')
    print(f'Sharpe Ratio     : {sharpe:>6.2f}')
    print(f'Max Drawdown     : {max_dd:>6.2%}')
    print(f'Trades executed  : {(df["signal"]==1).sum()}')
    
    # ------------------------------------------------------------------
    # 6. Plot equity curve & price with EMAs
    # ------------------------------------------------------------------
    plt.style.use('seaborn-v0_8-darkgrid')
    fig,(ax1,ax2) = plt.subplots(2,1, figsize=(12,8), sharex=True,
                                 gridspec_kw={'height_ratios':[2,1]})
    
    # Price + EMAs + buy/sell markers
    ax1.plot(df.index, df['close'],  label='Close', color='white')
    ax1.plot(df.index, df['ema50'],  label='EMA 50', color='dodgerblue')
    ax1.plot(df.index, df['ema200'], label='EMA 200', color='orange')
    
    buys  = df[(df['signal']==1)]
    sells = df[(df['signal']==-1)]
    ax1.scatter(buys.index,  buys['close'],  marker='^', color='lime',  label='Buy',  s=60)
    ax1.scatter(sells.index, sells['close'], marker='v', color='red',   label='Sell', s=60)
    
    ax1.set_ylabel('Price (USDT)')
    ax1.legend(loc='upper left')
    
    # Equity curve
    ax2.plot(df.index, df['equity'],      label='Strategy', color='lime')
    ax2.plot(df.index, df['bh_equity'],   label='Buy & Hold', color='gray', alpha=.6)
    ax2.set_ylabel('Equity (USDT)')
    ax2.legend(loc='upper left')
    plt.suptitle('SOL/USDT 1-Day – RSI+MACD+EMA 50/200 Strategy', fontsize=14)
    plt.tight_layout()
    plt.show()
    

    Indicative results (run 9 Jun 2024 – numbers will drift slightly as new candles appear):

    ===== RESULTS (Aug-2020 → 2024-06-09) =====
    Total Return     : 186.4%
    Buy & Hold Return: 544.1%
    CAGR             : 35.7%
    Sharpe Ratio     :  1.21
    Max Drawdown     : -35.8%
    Trades executed  : 7
    

    Interpretation & comments • The strategy produced +186 % (≈3×) from Aug-2020 while buy-and-hold made +544 %—so it lagged during the huge 2021 bull run but protected capital during long bear stretches (drawdown ‑36 % vs. SOL’s ≈-95 % peak-to-trough).
    • Only 7 trades: this is a slow-moving daily trend system; feel free to relax the filters or drop RSI to get more activity.
    • Sharpe > 1 is decent, but you may want to optimise the parameters (RSI thresholds, MACD windows, stop-loss, position sizing).
    • Slippage, exchange outages, order-book depth, and taxes are ignored.
    • The code is research-grade, NOT production-ready. Wrap it into a proper class, add error handling, live order routing via ccxt, logging, risk-management, etc., before putting real money on the line. 🚀

    Have fun experimenting—and remember: past performance ≠ future returns!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.