r/algotrading wiki
r/algotrading is a place to discuss systematic trading, quantitative research, market data, backtesting, execution, and the software behind them. Share your methods, your results, and what you learned. Failed experiments are welcome when readers can see how you tested the idea.
Read the subreddit rules and search for similar threads before posting. The wiki is for education and discussion.
Start here
- Write a testable rule. Pick one instrument, one timeframe, and one signal. Write down exactly when the signal is available and when an order could fill.
- Build a baseline. Compare with a simple benchmark on the same dates. For a single-instrument long-or-cash exercise, buy-and-hold is a useful starting point.
- Test in time order. Use earlier data for development, then evaluate the frozen rule on a later period. Include fees, spread, and slippage. Keep a trade log so you can trace unexpected results.
- Try paper trading. Check whether your system handles the market clock, incoming data, and broker order states. Compare the orders and fills you observe with your backtest assumptions.
Before you post
Show what you tried and ask a specific question. Posts asking for a working strategy without prior research and P/L screenshots without a methodology are covered by the subreddit rules. Keep promotional and affiliate links out of submissions. Use modmail for moderation questions or to suggest a wiki correction.
Strategy or backtest discussion
- Question or hypothesis — What are you testing, and what feedback do you want?
- Setup — What instrument, venue, timeframe, data source, and dates did you use?
- Method — When are signals known and orders filled? What costs and fill assumptions did you use?
- Evaluation — What benchmark and out-of-sample period did you use? How did the strategy and benchmark perform? Label results as backtest, paper, or live.
- What you tried — What have you already checked? Include a small code sample, pseudocode, or example trades if they help readers reproduce the issue.
Broker or data question
- Market and instruments — Give the jurisdiction, market, and asset class.
- Requirements — For a broker, list order types, API or paper-trading needs, and any latency constraints. For data, list date range, resolution, feed coverage, and whether you need historical, delayed, or live data.
- Constraints and research — List your budget, what you have already evaluated, and the specific trade-off you need help with.
The community guide has worked examples. How to ask good questions about brokers and market data providers
User flair
User flair is an optional label next to your username in r/algotrading. Use it to give readers context about your experience, trading background, and broker. Reddit allows one user flair per community, so combine the details in one label.
Choose the editable template Experience | Hobby/Industry | Broker, then replace the text using this format:
Experience | Trading context | Broker
- Experience: Novice, Intermediate, or Veteran. Choose the description that best fits your experience with algorithmic trading; these are self-assessments, not formal ranks.
- Trading context: Hobbyist, Independent Trader, Industry Professional, or Student/Researcher.
- Broker: The broker or platform you use, such as IBKR, Alpaca, Schwab, or TradeStation. Use Other or omit this field if you prefer.
Examples:
Novice | Hobbyist | AlpacaIntermediate | Independent Trader | IBKRVeteran | Industry Professional
All fields are optional. Keep your flair within Reddit's 64-character limit and follow the subreddit rules. Do not include promotional links or private account details. Flair is self-reported and does not verify credentials, profitability, or moderator endorsement.
How to set it: On desktop, open r/algotrading, find User Flair in the community sidebar, and use the edit/pencil control. In the Reddit app, open the community menu and choose Change user flair (wording may vary). Select Experience | Hobby/Industry | Broker, choose Edit, enter your details, and save/apply. Enable the option to show your flair if prompted. You can update or remove it later.
Brokers with programmatic order entry
Use the broker name or short label below in your flair. Each listed broker offers an official API for submitting orders, rather than only a market-data or account-reporting API. This is a reference list, not a ranking or endorsement.
| Flair label | Broker and official trading API |
|---|---|
| IBKR | Interactive Brokers — TWS and Web APIs |
| Alpaca | Alpaca — Trading API |
| Schwab | Charles Schwab — Trader API, Individual |
| E*TRADE | E*TRADE — API |
| TradeStation | TradeStation — Trading API |
| tastytrade | tastytrade — Open API |
| Tradier | Tradier — Brokerage API |
| Tradovate | Tradovate — futures API access |
| OANDA | OANDA — v20 REST API |
| Saxo | Saxo Bank — OpenAPI order placement |
| IG | IG — REST trading API |
| Zerodha | Zerodha — Kite Connect |
| Upstox | Upstox — order placement API |
API availability depends on your country, account type, trading permissions, and the broker's approval requirements. Supported instruments through an API may differ from those in the broker's app. Fees, funding requirements, market-data subscriptions, and automation rules can apply; check the linked official documentation. In particular, Tradovate requires eligible live-account API access and treats market-data access separately.
This list is not exhaustive. If you use another broker with an official order-entry API, use its name; for multiple brokers, use a short combination such as IBKR/Alpaca or Multi-broker. Broker disclosure remains optional.
Reading and community resources
- Statistics and machine learning — Free R and Python editions with exercises on regression, resampling, and model evaluation. An Introduction to Statistical Learning
- Quantitative research — Archived notebooks on returns, factor analysis, and portfolio construction. Some cells use the original Quantopian environment, so expect to adapt them. Quantopian lecture notebooks
- Market microstructure — Larry Harris covers order types, liquidity, and how markets match trades. Trading and Exchanges, Oxford University Press
- Strategy examples — Ernest P. Chan discusses mean reversion and momentum, with examples of how to formulate and test rules. Algorithmic Trading, Wiley
- Community case studies — Browse the subreddit archive for practitioner write-ups and discussions. Treat reported performance as the author's account and look for the underlying methodology. Hall of Fame threads
Run a first backtest in Python
Copy the block into first_backtest.py and run python3 first_backtest.py. It uses synthetic daily prices and only the Python standard library. At each open, the strategy uses the previous close and its 20-session moving average to choose whether to hold the asset or cash. The benchmark buys at the first open of each period and holds.
import random
from statistics import mean
rng = random.Random(42)
opens, closes = [], []
last_close = 100.0
for _ in range(181):
session_open = last_close * (1 + rng.uniform(-0.01, 0.01))
last_close = session_open * (1 + rng.uniform(-0.02, 0.02))
opens.append(session_open)
closes.append(last_close)
window = 20
cost_per_trade = 0.001 # 10 basis points on entry or exit
split = 120
def backtest(start, stop, buy_and_hold=False):
equity = peak = 1.0
max_drawdown = 0.0
position = trades = 0
for session in range(start, stop):
recent_closes = closes[session - window:session]
target = int(buy_and_hold or recent_closes[-1] > mean(recent_closes))
if target != position:
equity *= 1 - cost_per_trade
trades += 1
position = target
asset_return = opens[session + 1] / opens[session] - 1
equity *= 1 + position * asset_return
peak = max(peak, equity)
max_drawdown = max(max_drawdown, 1 - equity / peak)
return equity - 1, max_drawdown, trades
for period, start, stop in [
("Development", window, split),
("Holdout", split, len(opens) - 1),
]:
for name, buy_and_hold in [("Rule", False), ("Buy and hold", True)]:
total_return, drawdown, trades = backtest(start, stop, buy_and_hold)
print(f"{period} | {name} | return {total_return:+.2%} | "
f"max drawdown {drawdown:.2%} | trades {trades}")Each period starts in cash and is valued at its last open without forcing a sale. Drawdown is sampled at opens. The cost is a simplified charge for switching position. The example illustrates timing and accounting using synthetic data. Try increasing the cost and check how much the result changes. When you switch to real data, choose and document the rule using the development period before looking at the holdout.
Prefer R? The quantstrat project includes strategy demos. Try applying the same timing assumptions and checking a few trades by hand.
Backtesting checklist
- Look-ahead bias. If a signal uses the final close, a fill at that same close may be impossible. Write down the earliest time each input is available and the first realistic fill after that.
- Survivorship bias. Testing yesterday's market with today's index members drops companies that left the index. Use historical membership and include delistings when your hypothesis needs them.
- Costs and fills. Document commissions, spread, slippage, and any relevant borrow or funding costs. For limit orders, explain how you model orders that fill partially or never fill.
- Data splits. Use chronological development and evaluation periods. If you tune on an evaluation window, reserve a fresh holdout or use walk-forward evaluation. Fit preprocessing using only the data available at each training cutoff.
- Benchmark and results. Compare on the same dates with comparable costs and an appropriate exposure benchmark. Report net return, drawdown, trade count, and turnover. If you quote annualized metrics, describe how you computed them.
- Robustness. Disclose how many variants you tried. Check whether results depend on a narrow parameter setting, one market period, or a handful of trades.
- Reproducibility. Record the rule, dataset, date range, and parameters. Share code or pseudocode and enough detail to reproduce a few trades.
Paper trading and operations
Paper trading can check order flow and operational behavior. Actual fills depend on liquidity, queue position, and broker or venue behavior. Before relying on automation, test how it handles:
- Order changes. Track acknowledgments, partial fills, rejections, cancels, and timeouts. Query broker state before retrying an order whose outcome is unknown. Use a client order ID when the broker supports it.
- Startup and reconnects. Reconcile open orders and positions with the broker before resuming. Define what the system does when prices are stale, the feed disconnects, or the market is closed.
- Risk and monitoring. Set order-size and position limits. Log decisions, orders, and fills. Alert on errors and position mismatches. Test a manual stop and decide what it should do with open orders and positions.
- Hosting. Choose a local machine or hosted server based on uptime, network latency, and the broker gateway's requirements. Test restart recovery and secure API keys wherever the system runs.
Frequently asked questions
Do I need machine learning? Start with a simple baseline. If you try machine learning, test whether it improves out-of-sample results after costs. Keep feature construction, model selection, and evaluation in time order.
Why do my paper trades differ from my backtest? Compare a few orders end to end. Check data timestamps, session boundaries, order submission times, and fill assumptions. Verify that both systems use the same feed and price adjustments.
Where should I ask for debugging help? For a general language question, use the language's community or Stack Overflow. For a trading-system question here, include a minimal example, the expected outcome, and the actual output or order event.
Where can I ask about getting a job? Try r/financialcareers. Use r/algotrading for specific questions about research, data, and trading systems.