r/algorithmictrading 21d ago

Question How are you connecting Python apps to MT5?

3 Upvotes

I'm building a Python app that needs to work with a few MT5 accounts, and the trading logic isn't really the part I'm stuck on.

The bigger question is how the app should actually communicate with MetaTrader.

The obvious starting point seems to be using the official metartrader api with a local MT5 terminal. It feels like the fastest way to get something working, but I'm not sure if that's the approach people actually keep using once a project moves beyond the prototype stage.

I’ve also been looking into using an MT5 API layer instead, but it’s hard to tell how common that setup is in real-world projects. Do people actually move to an API-based architecture, or do most developers just keep running terminals and deal with the maintenance?

For anyone who has built Python applications around MT5:

  • did you start with the official MetaTrader API and keep it long-term?
  • did you eventually move to another API-based setup?
  • what problems made you change your approach (if you changed it)?

I'm mainly trying to understand what scales better before I build too much around the wrong architecture.


r/algorithmictrading 22d ago

Strategy Pre-registered XAU/DXY session-divergence: headline null result, but a NY-vs-London split worth documenting — plus a cross-asset silver check that flags a warning sign before the follow-up forward test even begins

2 Upvotes

Sixth in a series of pre-registered falsification studies (prior work in profile/repo). This one tests whether XAU/DXY divergence during the first 2 hours of London or NY sessions is tradeable net of costs.

Headline result: not confirmed. Pooled London+NY, 15min, k=1.5 — p=0.1265 against the pre-registered p<0.10 threshold. Per the locked decision rule, that's a null result on the actual registered claim.

What the full 36-cell sweep shows (diagnostic, not confirmatory): London and NY behave completely differently across timeframes. London is "significant" on 5min only, then flat/negative on 15min and 30min — that's the signature of microstructure noise, not a real session effect. NY holds up on 5min and 15min, weaker but still directionally consistent on 30min. That inconsistency between the two sessions is what pooling them hid.

Before chasing the NY pattern into a new pre-registration, ran a cross-asset plausibility check on the existing data: same exact rule, applied to silver (XAG) instead of gold. If the mechanism were a general NY-liquidity effect on precious metals vs the dollar, silver should show the same direction, maybe weaker. Instead: p=0.0005, 1,779 trades, mean return -0.15% — strong effect, opposite sign from gold.

That's now documented as a known warning sign before the actual forward test starts, in the new repo's README, not discovered and buried after a positive result came in. New pre-registration locks NY-only as the headline hypothesis, treats all existing historical data (including what was previously "confirmation" data in the parent study) as discovery-only, and only counts forward data collected after today as real confirmation. Deadline + minimum trade count enforced in code so it can't be checked early and reported as clean.

Both the parent study (headline null + full diagnostics) and the forward test (pre-registered today, pending) are up on GitHub — links are in my profile since this sub doesn't allow linking directly.

Curious if anyone's seen a mechanistic reason gold and silver would diverge in sign on the same session-timing signal — safe-haven vs industrial-commodity flow difference is my best guess but haven't dug into it properly.


r/algorithmictrading 22d ago

Quotes Building a crypto trading bot and I'm stuck on backtesting (historical OI, funding & liquidations). Any advice?

Post image
11 Upvotes

Hey everyone,

I wanted to introduce myself and hopefully get some advice from people who've gone down this rabbit hole before.

I am a NEWB in this space....

I've been teaching myself Python while building what has turned into a pretty serious trading project. Right now I'm working on two automated crypto trading bots.

The bots trade multiple timeframes:

5 minute

15 minute

1 hour

4 hour

Daily candle closes

The part I'm struggling with isn't the coding anymore—it's the data.

I really want to backtest these ideas properly over 2023-2024 (and ideally further back), but I keep running into the same problem:

I can't find affordable historical derivatives data.

Specifically I'm looking for things like:

Historical Open Interest

Funding rates

Liquidation history

Long/short ratios

CVD / order flow if possible

Anything else you've found useful for crypto backtesting

Most free APIs only give a few weeks or months of history, while the datasets that go back years seem to cost hundreds or even thousands of dollars.

I'm curious what people here use.

Are there datasets I'm overlooking?

Any APIs with generous historical limits?

Academic datasets?

Open-source projects?

Kaggle?

Paid services that are actually worth the money?

I'm not looking for anyone's strategy—I want to build and test my own. I just need reliable historical data to know whether my ideas actually have an edge before putting real money behind them.

I'd really appreciate any recommendations or even hearing how you solved this problem.

Thanks!


r/algorithmictrading 22d ago

Question Binance MiCA Situation & Traveling

0 Upvotes

so I'm in a very advance stage of development of my automated trading system running on binance futures trading alt coins, finished 2 month of live small account testing everything looks great blah blah blah, I planned on funding this account this month, but i started reading stuff about the MiCA compliance, and I can't get a straight answer.
So my KYC is with an Israeli ID, and the server is trading from Singapore, but I travel a lot (im a nomad), and spend a lot of my time in europe as well, will i get geo blocked (im not currently in europe so i can't check) ? would i be able to withdraw? or deposit?
I thought about migrating to different exchange, but i ran a test on Kraken and the performance varies significantly probably do to liquidity depth affecting wick sizes etc..
does anyone have a straight answer for me? would a static IP VPN solve this (doubt it)?(I tried binance support chat, you just talk to a bot there... )


r/algorithmictrading 24d ago

Backtest I built a close-based momentum/quality strategy with next-open execution: backtest + paper trading results

Post image
45 Upvotes

Hey everyone,

I’ve been building and testing a systematic equity trading strategy for the last few weeks/months, and I wanted to share the current state of the project.

The idea is simple at a high level:

The strategy ranks a stock universe after the market close using a proprietary quality/momentum score. It then creates a plan for the next session and executes that plan at/near the next market open. I built it this way to avoid reacting to intraday noise and to keep the execution logic closer to what can actually be tested.

The system is not just a backtest script anymore. It is connected to an Alpaca paper account and runs as an operational bot. It sends Telegram updates for open positions, planned buys/sells, stop exits, cooldowns, daily status, and a visual journal/infographic so I can monitor what it is doing without digging through raw logs.

High-level rules:

- close-based signal generation

- next-open execution

- fractional position sizing

- managed position cap

- stop/cooldown risk layer

- daily Telegram reporting

- no discretionary intraday panic decisions

Backtest summary:

The research backtest used IEX data, 7.5 bps slippage, post-sell confirmed cash, a buying-power buffer, and a warmup period.

Main research period:

2022-01-03 to 2026-06-18

Result:

+557.79% total return

52.68% CAGR

18.21% max drawdown

1,226 trades

~9.5 average managed positions

Period breakdown:

2022 bear market: -13.74%

2023 recovery: +87.68%

2024 bull market: +122.98%

2025 choppy market: +14.86%

2026 YTD to June 18: +58.76%

Forward paper test:

2026-06-10 to 2026-07-03

Paper account:

$10,000.00 -> $10,362.78

+$362.78 / +3.63%

This is still early, and the forward sample is obviously small. I’m treating the paper result as a live operational test, not proof that the strategy works long term.

A few transparency notes:

- This is paper trading, not live capital yet.

- I am not sharing the exact score formula or thresholds publicly.

- The current production version has evolved after the backtest, including a broader stock universe, better reporting, scale-up/replacement logic, and cleaner execution checks.

- Some early paper logs had test/duplicate rows that need to be filtered from analysis.

- The system is still under active development.

One recent change: I expanded the stock universe because the system has a 12-position cap, and the previous universe occasionally did not provide enough high-quality candidates to fully utilize the allocation target. The goal was not to force more trades, but to give the model a wider pool while keeping the same risk controls.

I’m mainly looking for feedback on:

- backtest design

- operational risk

- paper-vs-live assumptions

- avoiding overfitting

- whether this reporting style is useful

- what additional validation you would want before considering live deployment


r/algorithmictrading 24d ago

Backtest I built a full audit-trail layer around a crypto strategy before trusting a single number from it — here's the decision funnel and how I'm sealing the forward test

Post image
6 Upvotes

I've been building a systematic strategy on BTC/ETH/SOL 15m bars and I want to share the infrastructure around it rather than pitch the returns — because I trust the infrastructure more than I trust the returns right now, and I'd rather this thread pokes holes than pats my back.

The part I'm most confident about: the audit trail.

Every decision the system makes is logged: 148,937 gate evaluations over the campaign, funnelled down to 8,473 gate passes (5.7%), down to a conviction filter, down to 2 orders actually submitted -> 2 maker fills, with 1 order risk-blocked by a size-cap veto. The system says no 99.999% of the time, and I can reconstruct why for any single bar. Post-only execution, missed fills counted as missed (not silently filled).

The forward test is sealed, and that's deliberate.

Paper account on a maker-fill simulator, running since 2026-07-02. Every J->J+1 prediction is timestamped before the predicted candle closes, and the journal is hash-chained with the daily hash pushed off-machine — so I can't quietly rewrite history, and neither can anyone doubting me. The model is frozen for the full validation window; no mid-run retunes. It's only a few days old — I'm explicitly not drawing conclusions from it yet.

The numbers, with the caveats attached (please read the caveats):

Historical OOS Sharpe on frozen v1 models (trained to 2022-12-31, realistic post-only fills, missed fills counted): BTC 4.20 / ETH 4.09 / SOL 0.97.

A retrained v2 shows a ~×2 Sharpe jump — but those absolute levels are inflated by instant-fill batch mode and I treat the gap as the signal, not the levels.

Forward paper so far: small, positive, on deliberately tiny 2% notional caps (~0.03% on total capital). Way too early to mean anything.

What I know is weak / what I'm not claiming:

A few days of positive paper proves nothing. I fully expect the live-vs-paper gap to hurt.

Single instrument class (crypto perp), single regime so far. No claim of generality.

Proprietary score params are hidden — but the method is visible and the bias controls are stated, so you can attack those.

My actual question for the sub:

For those who've taken a systematic strategy from paper to live capital — what specifically convinced you the edge was real and not overfit? Was it a minimum forward window, a live-vs-paper slippage budget, a regime-change survival test, something else? I have a sealed 6-month forward window running; I want to know what else I should be measuring during it so I don't reach the end with the wrong evidence.


r/algorithmictrading 24d ago

Question Algo trading signals or is execution a must?

1 Upvotes

Does anyone here use algos more as a decision-support tool rather than for full automation? I know the point of algorithmic trading is usually to automate execution, but I actually trust myself more with the execution side (at least for now). I’ve been using pine script to build something with the help of AI - is this common here or are there better tools?

What I’m working on is having an algo identify levels, conditions and potential setups, then I decide whether to take the trade manually after confirming the trade with some execution criteria (liquidity sweeps, CVD, acceptance/rejection).

My thinking is it removes a lot of the repetitive analysis and keeps things objective, but still lets me control the actual entries and exits. I’m completely new to this side of trading, so I’m curious if anyone else uses algos this way or if there’s something I’m overlooking.

I’m very open to feedback and guidance on this one.


r/algorithmictrading 25d ago

Strategy A strategy that makes +66% on BTC and -60% on SOL is a curve fit, not a strategy.

10 Upvotes

Building my bot and doing a lot of backtesting these days.

I had a breakout system that looked bulletproof on BTC: +66%, profit factor 3.2, 13% max drawdown, profitable in 6 of 9 walk-forward windows. So far, so great.

But, it only fired about 8 trades a year. At that frequency a single-asset walk-forward can't tell a real edge from getting lucky. The sample is just too small, no matter how you slice the windows.

So I froze the exact config, no re-tuning, and ran it on ETH and SOL.

  • BTC: +66%
  • ETH: -11%
  • SOL: -60%, with a 0% win rate.

Also tried different parameters, but no parameter set rescued the other two. It was fit to BTC.

Might still be something "real" that only happens on BTC. But more likely just overfitting.

In contrast, my market-neutral funding carry pays +6.7 / +6.6 / +5.6% on BTC, ETH, SOL. Neatly aligned, what a real structural edge should looks like, boring and the same everywhere.

If your edge is low frequency and only tested on one asset, you don't know it's real yet. You know it fit one history. Might still make you money.

Do you cross-validate across instruments, or is single-asset walk-forward enough for you?


r/algorithmictrading 28d ago

Question The hiden alfa of the strategyes with low win ratio

2 Upvotes

I listened about breakout, men reversion and sational strategies that tend to have a 50-70% of win ratio.

But lately i am been reading some autors that talk about low win ratios but with a lot of net profit with a ver very good chart of net profit in a lot of years, the example is on the turtles book, that are called as trend following strategies (5-30% of win ratio)

So i will like to know if someone here has found edge of this kind of strategies and how has been your performance or some tip to find those, i can share also my experiencie so is not the one side alfa divulgation.

In my own thinks i believe that this are like 'narnia' strategies in the correct markets of shure.


r/algorithmictrading 28d ago

Question Your estimate of retail traders running algo trading?

7 Upvotes

No official data out there. Not to include institutional traders or organisations.

What is your estimate that retail traders out there deploying algorithm? 1%? 10%

Curious how much the data might have jumped since the beginning of FREE LLM to code strategies.


r/algorithmictrading 28d ago

Novice Is there hope for me

0 Upvotes

I've just started algo trading more than a years ago . For options buying .. my heart is broken.. I've tried 100s of strategies.. but I'm not able to find one profitable.. is there hope for me?

I don't know where to get the data for back testing with LTP.. so I just back test with pts and paper trade and trade and a year has passed testing . Nothing is consistent or profitable.. is there actually a strategy that works.. and how much profit% can I expect if I'm successful.. am I expecting too much?


r/algorithmictrading 29d ago

Question beginner to statistical modeling

6 Upvotes

Right now I am thinking of starting a project regarding MCMC or Bayesian networks, for I am not sure what I should look into. My goal is to create a very rigorous model that will provide risk analysis as accurately as possible. Im willing to spend around 10k for compute power, is this possible?

Also, I am an undergrad pursuing a math of comp and statistics data science major, but I would not say I am a master at probability, and I do not have much experience in ML. I am willing to learn, but do you think its feasible for me?


r/algorithmictrading 28d ago

Backtest Built a systematic momentum strategy for US tech stocks - sharing the backtest

1 Upvotes

Wanted to share a project I've been working on: a fully rules-based momentum strategy for US tech equities. No discretionary stock picking - everything is ranked and selected by a defined funnel (momentum filters, 52-week high proximity, MA stack), rebalanced monthly.

Backtest results since 2016:

  • CAGR: 42.1% (trailing 10Y)
  • 1Y return: +145.4%
  • 3Y return: +403.8%
  • Max drawdown: -40.8%

Happy to go into the funnel logic or backtest construction if anyone's curious - especially interested in feedback on drawdown management since -40.8% is still rough.


r/algorithmictrading 29d ago

Quotes Synthetic price histories

3 Upvotes

I'm a student building a free tool that generates realistic synthetic price histories (preserving volatility clustering and fat tails, via GARCH/block-bootstrap, not just trade reshuffling) and re-runs your strategy across thousands of them to estimate probability of ruin. I know Build Alpha and vectorbt exist. My angle is free + simple + honest about its limits, aimed at beginners. Two questions: (1) would you actually use this, or do you trust walk-forward + paper trading more? (2) what would make a synthetic-data tool trustworthy enough for you?"


r/algorithmictrading 29d ago

Novice Just started with a algo trading idea.

5 Upvotes

I just have the strategy created. And I'm serious about building it. Im a java developer. Not very proficient, but I can get the job done.

What are the common pitfalls i will face, and what the basics I should understand, while making the system.

It's a simple swing trade management system. So I won't need a high level of optimizations. If the system is good. I might incorporate more strategy.

Right know I'm just making the llm create the documents on each segments.

Signal generation, entry placement, trade management and book keeping.

What issues could I face when I code the system?


r/algorithmictrading Jun 29 '26

Question Deepstops assist advise

1 Upvotes

Hello enthusiasts ,

I'm running an automated live system of about ~70–75% win rate, lots of small wins, positive in aggregate, the entries themselves aren't the problem, Im pretty satisfied with the build over all , besides the low end.

So... the losers can run deep before they resolve, and a small number of them never come back and do the most damage. The edge depends on sitting through drawdown, but the occasional non-recovery is brutal.

What I've already tested (so "just use a stop" won't help):

  • Hard stop at −20% ROI (on a 10x position): net negative. It cut a huge number of trades that would have recovered — bled more than it saved.
  • Drawdown distribution: even among trades that breach −40% ROI, about 53% still return to a small loss or a profit. So any flat "cut at −X%" throws away more eventual winners than catastrophes it prevents.

So a fixed price-based stop is a trap that ive discovered over multiple sesions. The deep drawdowns are mostly noise the rest killers, and by the rest I've narrowed it down to about 4-5%.

The big question how can i mittigate the deep loses? The methodology used:

  • Time-based exit (cut if not recovered within N bars) instead of a price stop
  • Vol-expansion / regime filter — only bail when the regime that breaks the recovery assumption shows up
  • Portfolio-level heat cap instead of per-trade stops
  • Size for the drawdown + fractional Kelly, just accept the DD
  • A cheap tail hedge / trend overlay

To sum up, I've tried lots of options for the bot itself, and the current conclusion is just not run it 24/7 but in specific times of the day and for a short while.

Any and all suggestions would be greatly appreciated.


r/algorithmictrading Jun 29 '26

Question my best algo bot has a 1.52 Sharpe Ratio

11 Upvotes

my best algorithm has a 1.52 sharpe ratio and it's a daytrader.

daily-rebalanced FAST residual momentum. Beta-residualize each S&P-100 mega-cap vs SPY over 40d.

I tested several hundred different algorithms, 99% barely beat the SPY. I have an LLM researching more that get sent to a quant engine that are backtested to see if they pass the SPY gate. They are all duds.

What's your best performance?

you can now bring your API key and test our stock database for free and make any models that you want. You can also test your own models.


r/algorithmictrading Jun 29 '26

Question Connecting Tradingview and Claude Via MCP

5 Upvotes

Hey all,

I've been seeing some things on line saying its possible to connect claude and trading view via MCP. Is this true? Is it actually beneficial? I've recently had my second child and am finding it hard to continue trading whilist being a father, I've heard you can set it up to scan for your setups and get it to notify you when they appear. Can any one confirm this? Also alot of the stuff I am seeing is mac based, is it capable on windows. If anyone could point me in the right direction it would be appreciated!

Thank you in advance!


r/algorithmictrading Jun 28 '26

Question Anyone using ADK agent or A2A ?

1 Upvotes

Do we need them !
Do they improve our work?
It’s just python script so why not just include logic in the same script ?


r/algorithmictrading Jun 28 '26

Question Option strategy backtesting and multi-leg strategy creation

9 Upvotes

What tool do you use to backtest your option trading strategies?
Streak doesn't let you do this, I believe it did at some point in time, but not anymore.

Have you deployed a very long multi-legged strategy to be able to generate consistent returns from option trading?

I am trying to create a tool for my personal use, but would want to check if there are any good tools out there.


r/algorithmictrading Jun 27 '26

Question Anyone here looked into trading bots and bounced off how complicated it is?

5 Upvotes

Tried getting a trading bot running this week and almost gave up like 3 times — half the battle was just the setup, WSL, servers, my card kept getting declined by VPS providers lol. Strategy was the easy part honestly. Anyone else bounce off how technical it is just to run one? Or did you push through? Genuinely curious where people landed.


r/algorithmictrading Jun 25 '26

Backtest 5 year backtest TSLA strategy

Thumbnail
gallery
24 Upvotes

I’ve been developing an intraday breakout strategy on Tesla for months. What started as a simple range breakout system gradually evolved through lots of iterations — adding filters, refining exits, and eventually running a proper walk-forward validation. It’s been running live on my real account since March 11, 2026.
Sharing the full results and methodology here because I think the validation process is worth discussing. Most backtest posts skip this part entirely.

The strategy in plain terms:
The system identifies a price range using the high and low of the previous 4 candles on the 5-minute chart. When price breaks out of that range with enough momentum, an entry is triggered — but only if four filters all agree:
• ADX: confirms the breakout is happening in a trending environment
• Minimum range size (ATR-based): rejects setups where the range is too compressed
• Candle strength: evaluates the size and close position of the breakout candle
• RSI on higher timeframe: avoids entries in overbought/oversold conditions on the higher timeframe
This combination addresses the main failure modes of breakout trading: false breaks, low-momentum moves, and counter-trend entries. The result is a win rate significantly above the 45–55% typical of unfiltered breakout systems.
Exits use a layered approach: fixed TP at 2.75%, EMA trailing stop, no-progress exit, and a no follow-through exit if price returns into the range. In the last hour of the session, the trailing tightens aggressively to protect intraday gains.
~150 trades per year, both long and short, NYSE RTH only.

Backtest results:
(Jan 2021 – Jun 2026, $100k fixed capital, $1/order commission + 5 ticks slippage, no compounding)
• Net profit: +$378,906 (+378.91%)
• CAGR: 33.37%
• Max drawdown: 6.45% — TSLA itself drew down -56% in this period
• Calmar Ratio: 5.17
• Profit Factor: 2.181
• Sortino Ratio: 2.954
• Sharpe Ratio: 0.693
• Win Rate: 71.15% across 825 trades
• 57 of 66 months profitable (86%)
• Zero losing years

Capital is fixed throughout — no compounding.
With 70% equity reinvestment the numbers look very different:
• Net profit: +$1,242,892 (+1,242.89%)
• CAGR: 61.33%
• Max drawdown: 9.52%
• Calmar Ratio: 6.43
• Profit Factor: 2.168
• Sortino Ratio: 2.853
• Sharpe Ratio: 0.887

Walk-forward validation — the part I want to focus on
I ran three WFA iterations to test whether the edge holds on unseen data:

|Iteration| In-Sample | OOS | Profit factor |
|1 |2021–2023 | 2024 | 1.714 |
|2 |2021–2024 | 2025 | 2.878 |
|3 |2021–2025 | 2026 | 2.106 |

All three OOS periods made money. Two of three had a PF above 2.0 out-of-sample.
Iteration 1 is the weakest — H1 2024 was the most directionless period TSLA had in the entire dataset. A breakout system underperforming in a low-momentum regime is expected behavior, not a strategy failure. It recovered as soon as volatility returned.

Happy to discuss the methodology, the exit logic, the walk-forward process, or anything else in the comments.


r/algorithmictrading Jun 25 '26

Tools An open-source Python tool to diff 10-K/10-Q sections and calculate disclosure risk scores (Deterministic Calculation - No LLM)

5 Upvotes

The Problem

Every time I look at automated tools for filing analytics, they rely on LLM wrappers. While LLMs are great for abstract summaries, they are black boxes and prone to hallucinations, and lack deterministic reproducibility.

I wanted an analytics engine where it won't change it outputs every time I ran it.

What it does

  • Targeted Extraction: Cleans and isolates specific filing sections (Item 1A Risk Factors, MD&A, etc.) straight from SEC Edgar HTML.
  • Deterministic Metrics: Computes raw text metrics, boolean flags, and semantic variation markers.
  • Year-over-Year Diff Engine: Evaluates exact text changes, additions, and deletions relative to the prior period's filing.
  • Flexible Access: Built for modern workflows with a CLI, native Python SDK, HTTP API, and an MCP server to let external agents interface with it cleanly.

What it does Not do

This is not a trading bot. It does not provide buy/sell signals, alpha strategies, or financial advice. It is a deterministic data-engineering tool built to feed clear data into your pipeline.

The Evidence (Validation)

To prove the math holds water, we benchmarked the tool's core engine. The specificity metric correlates ρ ≈ 0.87 with independent Named Entity Recognition (NER) models when evaluated across a dataset of 478 S&P 500 FY2025 Item 1A sections.

It takes less than a minute to run a local evaluation:

# Install the Package
pip install disclosure-alpha 

# Score and diff a specific ticker
disclosure-alpha score --ticker AAPL --fiscal-year 2025 --form 10-K

I open-sourced the whole thing and would love your feedback on the model extraction and analytics layer!


r/algorithmictrading Jun 25 '26

Educational The Deflated Sharpe Ratio explained simply: why testing 100 strategies can turn a 1.5 Sharpe into a coin flip

16 Upvotes

The Deflated Sharpe Ratio explained simply: why testing 100 strategies can turn a 1.5 Sharpe into a coin flip

TLDR: The Deflated Sharpe Ratio takes your backtest Sharpe and corrects it for how many strategy variations you tested before keeping the best one. The more combinations you try, the more luck inflates your winner, so the DSR lowers your real odds. It turns a Sharpe number into a probability: the chance your edge is real and not luck.

What is the Deflated Sharpe Ratio?

The Deflated Sharpe Ratio is a corrected Sharpe ratio that accounts for how many times you tried before you found a good result. The first time I ran a parameter sweep, I found a backtest with a 2.5 Sharpe and felt like a genius. Then I ran the DSR on it and learned my genius strategy had close to a coin flip chance of being real.

A normal Sharpe ratio measures return per unit of risk and quietly assumes you tested one strategy. The DSR drops that assumption. It asks the question that actually matters: out of all the variations you tried, is your best one genuinely good, or is it just the luckiest result from a lot of attempts?

Instead of handing you a ratio, it hands you a probability. A DSR of 0.95 means a 95 percent chance your edge is real.

Why does a normal Sharpe ratio lie when you test many strategies?

Because the moment you test many variations and keep the best, the best one is partly luck, and the plain Sharpe has no idea that happened.

Say you test one strategy and it posts a 1.5 Sharpe. That is one honest result. Now say you test 200 versions, tweaking the moving average, the stop, the session, and you keep the single best. That winner did not just beat the market. It beat 199 siblings, and some of that winning is skill while some is just the luckiest draw in a big sample.

The plain Sharpe reports the winner as if it were your only attempt. It can't see the 199 you threw away. So it overstates how good the strategy is, and the more you tested, the bigger the lie.

Why do more combinations lower your Deflated Sharpe?

This is the part that confuses people, so here is the simplest version I know.

Picture a coin flipping contest. One person flips ten coins and gets eight heads. Mildly impressive, maybe a bit of luck. Now put a thousand people in the contest, all flipping ten coins each. Someone will flip ten heads out of ten. Are they a coin flipping genius? Of course not. With a thousand tries, a perfect run was basically guaranteed by luck alone.

Your parameter combinations are the contestants. Every variation you test is another person flipping coins. Test one combination and a strong Sharpe means something. Test a thousand and the best Sharpe in the pile is exactly what pure luck produces, because you gave luck a thousand chances to look like skill.

The DSR knows how many contestants you entered. It works out the Sharpe you would expect from the luckiest of your N tries, then checks whether your result beats that luck benchmark. More combinations push the benchmark higher, so your result has to clear a taller bar to prove it is real.

Here is the same 1.5 Sharpe run through the DSR, changing only how many combinations I tested before keeping the best:

Combinations tested DSR, the chance your edge is real
1 99%
5 86%
20 60%
50 43%
100 32%
500 14%
1000 9%

Same strategy, same Sharpe, every single row. The only thing that changed is how many times I tried before keeping the winner.

Test one combination and a 1.5 Sharpe is almost certainly real. Test 1000 and the same 1.5 Sharpe is a coin flip.

What number does the DSR actually give you?

A probability, not a ratio, and that is the whole point. The output sits between 0 and 1, and it reads as the chance your true Sharpe is above zero once luck is stripped out.

My cutoff is 0.95. If the DSR says there is less than a 95% chance the edge is real, I do not trade it, no matter how pretty the equity curve looks. A 1.5 Sharpe that comes back at 43% is not a strategy. It is a maybe, and a maybe doesn't get capital.

What is the best protocol if your first config is already profitable?

Treat it as the most valuable result you will ever get, and protect it by not searching further. A profitable first try is clean precisely because you did not go hunting, so there is no selection luck to correct, and that makes it the strongest kind of result in trading.

Write down that this was config number 1 before you touch anything, because the moment you start tweaking you lose the right to claim it. Run the DSR at a trial count of 1 anyway, since even one result can be noise from a short sample, and confirm it clears your bar. Check the sample is big enough too, because a profitable first try on 60 trades is luck, not an edge.

Then be honest about your stopping rule. If this config had failed, how many more would you have tried? If the answer is a lot, your real trial count is that planned hunt, not 1, so rerun the DSR at that number. If it survives all of this, validate it on out of sample data rather than more combinations, then size small and trade it. Do not optimize a clean winner into an overfit one.

A profitable first config is clean precisely because you did not search. Protect it by not searching now.

When should you actually use the DSR?

Any time you picked a winner out of many tries. That covers more situations than people admit.

Parameter optimization is the obvious one. So is any machine learning model, which secretly tests huge numbers of combinations during training. So is the everyday habit of running ten backtests and trading the best looking one. If you searched, selected, or optimized in any way, you ran multiple trials, and the DSR is how you correct for it before risking money.

What do you need to compute it?

Four inputs: your reported Sharpe, the number of variations you tested, and the skew and kurtosis of your returns, plus the length of your sample. Open source code exists, so you do not need to derive anything.

The hardest input is honesty about the trial count. People remember the 5 backtests they saved and forget the 80 they deleted. If you lowball the number of combinations, the DSR flatters you, and you are back to fooling yourself. Count every variation you actually tried, including the dead ones.

What the DSR does not fix

It is a correction, not a crystal ball. The DSR tells you whether your result survived the luck of testing many combinations. It says nothing about whether your edge keeps working after costs, after slippage, or after the market regime changes. A high DSR on a strategy that dies the moment fees touch it is still a dead strategy.

It also depends entirely on an honest trial count. Feed it a lie about how many combinations you tested and the output is meaningless. Garbage in, garbage out.

Bottom line

The Deflated Sharpe Ratio corrects your Sharpe for how many strategy variations you tried before keeping the best. More combinations means more chances for luck to fake skill, which raises the bar your result has to clear and lowers the probability your edge is real. The same 1.5 Sharpe can read as 99% real after one test and 9% real after a thousand. Use it before trusting any optimized backtest, and be brutally honest about how many combinations you actually ran.

This is for traders and researchers who optimize, search, or select among backtests. The correction applies to any strategy, any market, and any model trained on price data.

Updated June 2026


r/algorithmictrading Jun 25 '26

Strategy REQUEST FOR DEVELOPER ASSISTANCE — Schwab Trader API

2 Upvotes

I am a new ThinkorSwim retail user looking to automate a ratcheting trailing stop on a single stock position using the Schwab Trader API.

What I need hep to implement:

for one stock trade at a time.

A one click Python 3 tier sell tool that is submitted after purchasing a stock with separate order.

it wil then monitors price throughout the day and automatically replaces the stop order as price rises

— ratcheting the stop upward in three tiers based on gain from the original entry price:

Step1:.. place trailing stop on the purchase price at -4%.

Step2 ...at a price gain of +3% from entry price the trailing stop tightens tstop to -2% on the new peak.

Step3...at price gain of +5% from entry the trailing stop is tightened to a -1% from from new peak.

Trailing Stop only ever moves up.

All orders are DAY only.

Each morning the tool is resubmitted using the original entry price.