What Is a Trading Bot?
A trading bot is a software program that connects to a brokerage account and places buy and sell orders automatically based on predefined rules. Instead of a human sitting at a screen, watching charts, and clicking buttons, the bot monitors market conditions, evaluates signals, and executes trades according to its configuration. The human's role shifts from making split-second decisions to designing the strategy, setting risk parameters, and monitoring the system.
At the most fundamental level, a trading bot needs three things: a connection to a broker, a set of rules for when to trade, and risk controls that prevent catastrophic losses. The broker connection is how the bot reads market prices and submits orders. In slmaj's case, this connection is made through the Interactive Brokers API (also called the TWS API or IB Gateway API). The bot communicates with IBKR's Trader Workstation or IB Gateway application running on your machine, which in turn connects to IBKR's servers and the exchanges.
The trading rules define the bot's strategy. These can range from simple moving-average crossovers to complex machine learning models that ingest dozens of data sources. slmaj uses an ML ensemble approach, which is covered in detail in the next section. The key point is that these rules are deterministic and repeatable: given the same inputs, the bot will always produce the same output. This eliminates the emotional decision-making that causes most retail traders to underperform.
People use trading bots for several practical reasons. First, emotional discipline: bots do not panic sell during a drawdown or FOMO buy during a rally. They follow the rules every time. Second, speed and coverage: a bot can monitor dozens of instruments across stocks, forex, crypto, and commodities simultaneously, scanning for opportunities around the clock. Third, systematic backtesting: because the rules are codified, you can test them against historical data to understand how the strategy would have performed in the past, though past performance never guarantees future results.
It is important to address common misconceptions. A trading bot is not a guaranteed money printer. Markets are inherently uncertain, and no algorithm can predict the future with certainty. Bots are tools that enforce discipline and process data faster than a human can. They still lose money on individual trades, sometimes frequently. The goal is to have an edge over many trades, managed by strict risk controls so that losing streaks do not destroy the account. If anyone tells you their bot guarantees profits, they are either lying or do not understand markets. slmaj is transparent about this: it is software, not financial advice, and it starts in paper mode precisely so you can evaluate its behavior before risking real capital.
How ML Signals Work
slmaj does not rely on a single model to decide when to trade. Instead, it uses an ensemble of three independent machine learning algorithms: XGBoost, Random Forest, and Gradient Boosting. Each model analyzes the same set of features but uses a different internal method to arrive at a trading signal. A trade is only considered when multiple models agree, which significantly reduces the probability of acting on noise rather than a genuine signal.
XGBoost (Extreme Gradient Boosting) builds a sequence of decision trees where each new tree corrects the errors of the previous one. It is particularly effective at finding non-linear relationships in structured data, which makes it well-suited for financial features like RSI divergence, volume spikes, or sentiment shifts. Random Forest takes a different approach: it builds many decision trees in parallel, each trained on a random subset of the data and features, then takes a vote across all trees. This method is naturally resistant to overfitting because no single tree sees the full picture. Gradient Boosting is similar to XGBoost in concept but uses a different optimization strategy, giving the ensemble a third perspective on the same data.
The features these models consume fall into several categories. Technical indicators include RSI (Relative Strength Index), MACD (Moving Average Convergence Divergence), Bollinger Bands, ATR (Average True Range), volume-weighted moving averages, and price momentum over multiple timeframes. Sentiment scores are derived from news headlines, social media posts on StockTwits and Reddit, and analyst ratings, each normalized to a numeric score. Economic data includes Treasury yields, Federal Reserve interest rate expectations, unemployment claims, and GDP growth indicators sourced from FRED and economic calendars. Cross-asset signals capture correlations between related instruments, such as how gold moves relative to the dollar index, or how crypto volatility tracks equity market VIX.
To prevent overfitting, slmaj uses walk-forward validation. This means the models are trained on a rolling window of historical data and then tested on the immediately following period of data that the model has never seen. This process is repeated across multiple windows, simulating how the model would have performed in real time. A model that scores well only on training data but fails on the walk-forward test is discarded. This is the same methodology used by quantitative hedge funds and academic researchers to evaluate trading strategies.
Each model produces a confidence score between 0 and 1 for each potential trade. These scores are aggregated into an ensemble confidence value. The bot only acts when the ensemble confidence exceeds a configurable threshold, typically set between 0.65 and 0.80 depending on your risk profile. Higher thresholds mean fewer trades but higher conviction on each one. You can adjust this threshold in your config file to match your personal trading style.
signals:
confidence_threshold: 0.70 # Minimum ensemble confidence
min_models_agree: 2 # At least 2 of 3 must agree
retrain_interval: 7 # Retrain models every 7 days
walk_forward_window: 90 # 90-day training window
Where the Data Comes From
The quality of any trading system depends on the quality and breadth of its data inputs. slmaj aggregates data from over 25 sources across six categories: market data, news and media, social sentiment, government filings, economic indicators, and alternative data. This diversity is deliberate. Relying on a single data source creates a single point of failure and a narrow view of the market. By combining many independent signals, the bot builds a more robust picture of market conditions before making a decision.
Market data is the foundation. Yahoo Finance provides real-time and historical price data, fundamentals, and analyst estimates for stocks. IBKR itself supplies Level 1 quotes and order book data for all asset classes you trade. For crypto, CoinGecko provides pricing and market cap data across hundreds of tokens, while Binance data (via the CCXT library) offers order book depth and volume metrics.
News and media sources include RSS feeds from Reuters, CNBC, AP, and Bloomberg (headline-level). These are parsed in real time and scored for sentiment using natural language processing. Finnhub and News API provide additional headline coverage with structured metadata. The bot does not read full articles; it extracts sentiment signals from headlines and summaries, which research has shown to correlate with short-term price moves.
Social sentiment comes from StockTwits (public message stream for individual tickers), Reddit (via API for subreddits like r/wallstreetbets and r/stocks), and Twitter/X (for trending financial topics). Each source is scored independently, and the bot tracks sentiment momentum, meaning it cares not just about whether sentiment is positive but whether it is becoming more or less positive over time.
Government and regulatory filings include SEC EDGAR filings (insider buys and sells, institutional 13F holdings), congressional stock trades (disclosed under the STOCK Act), and Treasury yield data from the U.S. Department of the Treasury. These sources update less frequently but carry high signal value because they reflect the actions of informed participants.
Economic indicators from FRED (Federal Reserve Economic Data) and public economic calendars provide macro context: GDP growth, inflation rates, unemployment, consumer confidence, and Federal Reserve meeting schedules. The bot uses these to adjust its overall risk appetite, for example reducing exposure ahead of a Fed rate decision or during periods of elevated macro uncertainty.
Alternative data rounds out the picture. DeFi Llama provides total value locked (TVL) in decentralized finance protocols, useful for crypto signals. Polymarket offers prediction market probabilities for economic and political events. Options flow data reveals unusual activity by large traders. Alpha Vantage and Polygon.io provide additional technical data, earnings calendars, and historical fundamentals.
Many of these sources are free and require no API keys (RSS, StockTwits, Yahoo Finance, SEC EDGAR, CoinGecko, DeFi Llama, Treasury yields, economic calendars). Others require a free or paid API key (Reddit, Twitter, Alpha Vantage, FRED, News API, Finnhub, Polygon.io, Google Trends). The bot functions with whatever sources you configure. More sources generally produce better signals, but even the free-only configuration provides meaningful data coverage. For the complete list and setup instructions, see the data sources reference.
Risk Management — Five Layers of Protection
No trading signal is reliable enough to justify unlimited risk. The most important part of any trading system is not how it makes money but how it prevents catastrophic losses. slmaj implements five independent layers of risk management, each operating autonomously. If any single layer determines that a trade or the current portfolio state is too risky, it can block the trade or shut down the bot entirely, regardless of what the other layers say.
Layer 1: Position Limits. Every trade is subject to maximum position size constraints defined in your config. This includes a dollar cap per position (for example, $10,000 maximum), a maximum number of shares or contracts, and a maximum number of simultaneous open positions. These limits prevent any single trade from consuming too much of your account. The bot calculates position size before submitting an order. If the calculated size exceeds the limit, the order is scaled down or rejected entirely. This is the simplest form of risk control and the most important: it ensures that even if every other system fails, no single position can destroy your account.
Layer 2: Daily Loss Caps. The bot tracks cumulative realized and unrealized losses for the current trading day. If total daily losses exceed a configurable threshold (for example, $2,000 or 2% of account equity), the bot stops opening new positions for the remainder of the day. Existing positions are managed according to their stop losses and take profits, but no new risk is added. This prevents the common pattern where a losing day spirals into a disastrous day because the trader (or bot) keeps trying to recover losses.
Layer 3: Kelly Criterion Sizing. The Kelly Criterion is a mathematical formula that calculates the optimal bet size given the probability of winning and the expected payoff ratio. Instead of using fixed position sizes, slmaj can dynamically size each position based on the ensemble's confidence score and the historical win rate for similar signals. A high-confidence signal with a strong historical edge gets a larger allocation; a marginal signal gets a smaller one. This optimizes capital efficiency while naturally reducing exposure during periods of lower conviction. In practice, most implementations use a fractional Kelly (half or quarter Kelly) to further reduce variance.
risk:
max_position_size: 10000 # $10k hard cap per position
max_positions: 5 # Max 5 open at once
daily_loss_limit: 2000 # Stop trading after $2k daily loss
stop_loss_pct: 0.02 # 2% stop loss per position
take_profit_pct: 0.04 # 4% take profit per position
use_kelly: true # Enable Kelly Criterion sizing
kelly_fraction: 0.5 # Use half-Kelly for safety
circuit_breaker:
max_consecutive_losses: 3
cooldown_minutes: 60
kill_switch:
max_daily_loss_pct: 0.05 # 5% of account = emergency stop
Layer 4: Circuit Breakers. If the bot hits a configurable number of consecutive stop losses (for example, three in a row), the circuit breaker activates and pauses all trading for a cooldown period (for example, 60 minutes). This addresses the scenario where market conditions have changed in a way the models have not yet adapted to, such as a sudden news event or a regime change in volatility. Rather than continuing to trade into an environment the models were not trained on, the bot steps back and waits for conditions to stabilize.
Layer 5: Kill Switch. The kill switch is the last line of defense. If total account drawdown exceeds an absolute threshold (for example, 5% of total account equity in a single day), the kill switch activates: all open positions are closed at market, all pending orders are cancelled, and the bot halts completely. It will not restart automatically. This requires human intervention to review what happened, adjust parameters if needed, and manually restart. The kill switch exists for scenarios that the other layers cannot fully contain, such as flash crashes, gap openings, or correlated losses across all positions simultaneously.
The reason for multiple independent layers is defense in depth. Any single risk control can be overwhelmed by unusual market conditions. Position limits do not help if you have five positions that all gap down simultaneously. Daily loss caps do not help if the loss happens in a single minute. Circuit breakers do not help if the first three losses are catastrophic. By layering multiple controls, each addressing a different failure mode, the system provides robust protection even when individual layers are stressed. For full configuration details, see the risk controls documentation.
Paper Trading — Learn Before You Risk
Every slmaj installation starts in paper trading mode by default. This is not an optional feature or a limited demo; it is the standard operating mode. In paper mode, the bot connects to IBKR's paper trading environment, which provides real-time market data from live exchanges but executes all trades in a simulated account with virtual money. The signals, risk checks, and order logic run identically to live mode. The only difference is that no real money is at stake.
Paper trading serves several critical purposes. First, it lets you verify the technical setup. You can confirm that the bot connects to IBKR correctly, receives market data, generates signals, and logs its activity. Any connection issues, API configuration problems, or data feed errors will surface during paper trading without any financial consequence. Second, it allows you to evaluate the bot's decision-making. You can observe which signals the bot generates, how often it trades, what confidence levels trigger entries, how it sizes positions, and where it places stop losses and take profits. This gives you a concrete understanding of what the bot will do with your real money before you give it access.
The trade journal is your primary evaluation tool during paper trading. It records every decision the bot makes in a structured log: the timestamp, the instrument, whether the signal was buy or sell, which models agreed and at what confidence level, the calculated position size, the risk check results (which layers approved, if any blocked), the entry price, and eventually the exit price and P&L. The web dashboard at localhost:5555 provides a visual interface for reviewing this journal, showing open positions, daily P&L curves, signal history, and risk utilization.
When evaluating paper trading performance, focus on the right metrics. Win rate alone is misleading; a bot that wins 90% of trades but loses ten times more on its losers than it makes on its winners will still lose money. Instead, look at the profit factor (gross profit divided by gross loss), the maximum drawdown (the largest peak-to-trough decline), the Sharpe ratio (risk-adjusted return), and the average trade duration. Also check how the bot behaves during different market conditions: trending days versus choppy days, high volatility versus low volatility, market opens versus midday sessions.
A reasonable paper trading evaluation period depends on your intended trading style. For a bot that trades several times per day, two to four weeks of paper trading provides a meaningful sample size. For a bot that trades a few times per week, you may want one to three months. The goal is not to see only winning trades but to see enough trades that you understand the distribution of outcomes: winning trades, losing trades, flat trades, and how the risk controls behaved during losing streaks.
When should you consider going live? There is no universal answer, but here are reasonable criteria: the bot has been paper trading for at least two weeks without errors, you understand the signal logic and can explain why the bot took its recent trades, the paper performance metrics are within your expectations (positive profit factor, manageable drawdowns), and you have a personal risk plan for what happens if the first live week is a losing week. For detailed guidance, see the paper trading documentation.
Going Live — Step by Step
Transitioning from paper trading to live trading is intentionally a deliberate process in slmaj. There is no "auto-upgrade" or countdown timer. You make a conscious decision, change specific configuration values, and restart the bot. This design ensures that nobody accidentally trades real money.
The configuration change is straightforward. In your config.yaml file, two values control the trading mode:
# Paper trading (default):
trading:
mode: paper
port: 7497 # IBKR paper trading port
# Live trading:
trading:
mode: live
port: 7496 # IBKR live trading port
Change mode from paper to live and change port from 7497 to 7496. That is the entire change. Port 7497 is IBKR's paper trading API port; port 7496 is the live trading API port. The bot validates on startup that the port matches the mode, and it will refuse to start if there is a mismatch. This prevents the scenario where you set the mode to live but forgot to change the port (or vice versa).
Before your first live session, reduce your position sizes below what you used in paper trading. Even though the bot behaved well in paper mode, live trading introduces real execution dynamics: slippage (the difference between expected and actual fill price), partial fills, latency, and the psychological weight of real money at risk. Start with position sizes at 25% to 50% of your paper trading sizes. You can scale up gradually after confirming that live execution matches your paper trading experience.
# Conservative first-week live settings:
risk:
max_position_size: 2500 # Start small: $2,500 instead of $10k
max_positions: 2 # Only 2 positions at once
daily_loss_limit: 500 # Tight $500 daily loss cap
stop_loss_pct: 0.02 # Keep 2% stops
take_profit_pct: 0.04 # Keep 4% targets
Monitor your first live day actively. Do not start the bot and walk away. Watch the dashboard, check the trade journal entries as they appear, and confirm that orders are being filled at reasonable prices. Compare the live fills to what paper mode reported for similar signals. Pay attention to execution speed and whether the reported prices match IBKR's trade confirmations. Most issues, if they exist, will surface on the first day.
After the first week of live trading, review the results against your paper trading baseline. Are the fills reasonably close to paper fills? Are the same types of signals being generated? Are the risk controls functioning as expected (daily loss cap, circuit breakers)? If everything looks consistent, you can gradually increase position sizes toward your target levels. If something looks wrong, there is no shame in switching back to paper mode, investigating the discrepancy, and trying again. The bot saves your config history, and switching back to paper is the same two-line change in reverse.
One critical point: have a personal risk plan that exists outside the bot's risk controls. Know in advance how much total capital you are willing to risk with the bot. Decide what your personal maximum drawdown threshold is before you shut the bot down permanently. Know whether you will monitor the bot daily, weekly, or somewhere in between. Write these decisions down before you start live trading, because it is much harder to think clearly about risk limits when you are in the middle of a drawdown. The bot's risk controls protect against mechanical failures and runaway losses, but your personal risk plan protects against the broader question of whether automated trading is right for your financial situation.
Setting Up Your IBKR Account
To use slmaj, you need an Interactive Brokers account with API access enabled. IBKR is one of the most widely used brokerages among algorithmic traders because of its comprehensive API, competitive commissions, access to global markets, and support for multiple asset classes including stocks, options, forex, futures, and crypto. slmaj communicates exclusively through the IBKR API, meaning it never has direct access to your login credentials or the ability to withdraw funds.
IBKR offers two types of accounts relevant to bot trading. A paper trading account is created automatically alongside your main account and provides a simulated environment with virtual money and real market data. This is what slmaj connects to by default. A live trading account requires identity verification, funding, and regulatory compliance for your jurisdiction. You do not need a funded live account to start using slmaj; the paper account is sufficient for evaluation.
The connection between slmaj and IBKR happens through one of two applications running on your computer: Trader Workstation (TWS) or IB Gateway. TWS is the full desktop trading platform with charts, order entry, and portfolio views. IB Gateway is a lightweight, headless application designed specifically for API connections, using fewer system resources. Both expose the same API on the same ports. Most bot users prefer IB Gateway for its lower resource footprint and stability during long-running sessions. Either one works with slmaj.
Regardless of which application you use, you need to enable API access in its settings. In TWS, navigate to Edit > Global Configuration > API > Settings. In IB Gateway, the API settings are presented during login. The key settings are: enable ActiveX and Socket Clients, set the socket port (7497 for paper, 7496 for live), and add 127.0.0.1 to the trusted IP addresses list. Disable the "Read-Only API" option, because the bot needs to submit orders. You may also need to increase the "Max messages per second" setting to accommodate the data volume from multiple instruments.
The full step-by-step setup process, including screenshots and troubleshooting for common connection errors, is covered in the IBKR setup guide. That guide walks through creating an IBKR account, installing TWS or IB Gateway, configuring API settings, testing the connection with the included diagnostic script (python test_connection.py), and running your first paper trading session. If you have an existing IBKR account, the setup process typically takes under ten minutes.
Frequently Asked Questions
It depends on the asset class. For US stocks, the bot only generates signals during regular market hours (9:30 AM to 4:00 PM Eastern). For forex, which trades nearly 24 hours on weekdays, the bot can operate continuously. For crypto, which trades 24/7, the bot monitors and trades around the clock if configured to do so. You can restrict trading hours in your config file to match your preferences, regardless of market availability.
If the connection between the bot and IBKR drops, any existing stop-loss and take-profit orders that were already submitted to IBKR remain active on the broker's servers. They will execute regardless of whether the bot is connected. The bot will not be able to open new positions or modify existing orders until the connection is restored. Upon reconnection, the bot automatically re-synchronizes its state with IBKR, reconciles open positions, and resumes normal operation. A stable internet connection is recommended, but a temporary outage will not leave your positions unprotected.
Yes. Many users run slmaj on a VPS (Virtual Private Server) or cloud instance for better uptime and lower latency. You need to install IB Gateway (not TWS, since there is no display) on the server, configure it for headless operation, and run the bot alongside it. The system requirements are modest: Python 3.9+, 4GB RAM, and a stable network connection. Linux-based VPS providers (DigitalOcean, Hetzner, AWS EC2) work well for this purpose.
Trading frequency depends entirely on your configuration and market conditions. With default settings and a confidence threshold of 0.70, the bot typically generates between two and eight signals per day across all configured instruments. Not every signal results in a trade; risk checks may block signals that would exceed position limits or daily loss caps. You can increase the confidence threshold to reduce trade frequency, or lower it to increase it. The trade journal shows every signal and whether it was executed or blocked, so you can tune the frequency to your preference during paper trading.