torchtrade icon indicating copy to clipboard operation
torchtrade copied to clipboard

Deduplicate the four futures exchange stacks (~2,000 LOC, 70-96% copy-paste) into the shared futures base

Open BY571 opened this issue 3 months ago • 24 comments

Measured identical lines after exchange-name substitution: okx vs bybit — env.py 253/278 (91%), env_sltp.py 321/339 (95%), base.py 216/224 (96%); binance vs bitget env_sltp.py 388/436 (89%). This is the pattern that produced the historical triple-SLTP-action-map bug, and this audit found three fresh instances of a fix landing on some exchanges but not others (lot size #271, full_done_spec #272, hedge-mode surface).

Plan (each step extends the structural-guard tests in `tests/envs/test_live_env_base.py` so re-forking fails CI):

  1. Fold the 4 per-exchange `base.py` files into `TorchTradeFuturesLiveEnv` via `OBSERVER_CLS`/`TRADER_CLS` class attributes — the pattern `futures_live_base.py` already proves (~600-700 LOC)
  2. Share `env.py` trade-path helpers: 4 byte-identical `_create_trade_info`, near-identical `_step`/`_execute_market_order`/`_handle_close_action`/`_execute_fractional_action`; per-exchange facts reduce to taker fee + lot-size rounding (~500 LOC)
  3. Share `env_sltp.py` incl. the 70-line config dataclass repeated 4x (~900 LOC)
  4. Consolidate 3 verbatim `_calculate_unrealized_pnl_pct` and 3 verbatim `_round_price` copies in the order executors
  5. Mirror in tests: route more per-exchange test files through the existing shared `tests/envs/base_exchange_tests.py` (okx test file is 392/506 lines identical to bybit's)

Also fold in the small ceremony cleanups: 20-alias `unit_to_timedelta` map in `core/live.py:127-153` (store TimeFrameUnit instead of str), redundant abstract re-declarations, defensive action-index cascades guarding `Categorical`-spec output.

BY571 avatar Aug 07 '26 14:08 BY571

Step 5 measured — it is much smaller than the line count suggests, and mostly already done

The issue cites "okx test file is 392/506 lines identical to bybit's". That is a line-level count; at the function level the overlap is far smaller. AST-comparing every function after normalising exchange names:

okx fns: 29   bybit fns: 35   identical-after-rename: 6
  mock_observer, mock_observations          <- fixtures
  test_step_emits_the_whole_done_family     <- ALREADY delegates to the shared harness
  test_action_spec, test_observation_spec, test_check_env_specs_passes

So of 6, two are fixtures, one already routes through assert_the_step_emits_the_whole_done_family, and the remaining three are 2–6 lines each:

def test_action_spec(self, env):
    assert env.action_spec.n == 5
    assert env.action_levels == [-1.0, -0.5, 0.0, 0.5, 1.0]

def test_check_env_specs_passes(self, env):
    with patch.object(type(env), "_wait_for_next_timestamp"):
        check_env_specs(env)

test_action_spec asserts venue-specific values, so sharing it means parameterising the expected numbers — which is the assertion, so the helper would carry nothing. test_check_env_specs_passes is genuinely identical but is two lines; routing it through a harness adds an import and an indirection to save one.

All four venues already use base_exchange_tests.py in three files each (BaseObservationClassTests, assert_a_direct_flip_does_not_age_the_new_position, assert_the_step_emits_the_whole_done_family), so the harness has already absorbed the parts where sharing pays.

Recommendation: drop step 5, or rescope it. The remaining duplication is short, venue-specific assertions where a shared helper costs more than it saves — CLAUDE.md's "creating helper functions for one-time operations" anti-pattern. The line-level 392/506 is mostly imports, fixtures with different mock payloads, and independently-worthwhile venue-specific tests that happen to share shape.

If the real concern behind step 5 is the test-depth gap (#289 notes vectorized SLTP has 10 tests vs scalar SLTP's 31), that is a coverage problem rather than a duplication one, and consolidating these three would not touch it.

Steps 1–3 (the base.py / env.py / env_sltp.py consolidations, ~2,000 LOC) are untouched and remain the substance of this issue. Step 4 landed in #378 and #380.

BY571 avatar Aug 18 '26 05:08 BY571

Step 2 measured properly: two exact 3-of-4 clone clusters remain, blocked on a binance question

PR #385 hoisted _create_trade_info (the one method identical across all four). But I had been reading the all-four intersection, which hid the real picture. Pairwise, comments stripped:

method bitget/bybit/okx binance
_execute_market_order byte-identical differs by one log-string char ({side} vs {side.capitalize()})
_handle_close_action byte-identical differs by 5 lines
_step bybit/okx differ by 4 binance ≡ bitget, zero differing code lines
_execute_fractional_action 15-27 differing lines genuinely per-venue

So two methods have an exact 3-venue clone cluster available to hoist today, and _step has an exact 2-venue one.

What blocks the 3-venue hoists is a correctness question, not a refactor one. binance's _handle_close_action:

  • reports side="CLOSE" where the other three report the real side, and
  • omits self.position.current_position = 0, which bitget/bybit/okx all carry.

The second is harmless duplication — core/live.py already sets it from sign(desired_action) — so the other three carry a redundant line. The first is not obviously harmless: side goes into the trade-info dict that _step returns, and a venue reporting "CLOSE" where its siblings report "BUY"/"SELL" is exactly the silent per-exchange divergence this issue exists to remove.

That needs deciding before the hoist, because folding it into a dedup would bury it: whichever version becomes shared, one venue's observable behaviour changes, and it should change deliberately. Is binance's side="CLOSE" intentional, or drift?

Once that is settled, _execute_market_order and _handle_close_action are a clean 3-venue hoist (binance keeping an override, or converging if the difference is drift), and _execute_fractional_action is the only one that genuinely justifies four implementations.

BY571 avatar Aug 18 '26 06:08 BY571

Where step 1-2 stand after #384/#385/#386/#387, and what the remaining clusters actually are

Re-measured on current main (AST identity per method, exchange names normalised). No 4-way exact clone remains in env.py. What is left:

__post_init__                   : bitget ~ bybit ~ okx   (3 of 4)
_calculate_fractional_position  : bybit ~ okx            (2 of 4)
_step                           : binance ~ bitget       (2 of 4)

The 3-way __post_init__ is not the win it looks like. The bodies hash identically only because the venue name normalises away — each imports its own normalize_<venue>_timeframe_config:

from torchtrade.envs.live.bybit.utils import normalize_bybit_timeframe_config

Sharing it means a common config base with the normaliser as a class attribute, across five dataclasses. That is a real structural change, not a hoist, and it is the same shape as the OBSERVER_CLS/TRADER_CLS fold the issue describes for the bases.

The two 2-way clusters are arguably not worth hoisting at all. Moving a method shared by 2 of 4 onto TorchTradeFuturesLiveEnv means the other two need overrides — two copies become one shared version plus two overrides, which is not obviously fewer places for a fix to land wrongly.

What was worth doing, and what it found

The 4-way hoists are done, and each surfaced a real divergence that the copies had been hiding:

  • _handle_close_action (#386): binance reported side="CLOSE" where the other three reported the real order side, and omitted a current_position = 0 that turned out to matter — on a direction switch whose close succeeds and open fails, binance reported a long against an exchange holding nothing (invariant 2).
  • _execute_market_order (#387): binance built uppercase order sides; the executor upper-cases anyway, so the venue never saw it, but trade_info["side"] was mixed-case across exchanges.
  • get_account_state / get_market_data_keys (#384): hoisted to TorchTradeLiveEnv so all five venues share them, not four.

That pattern is the argument for finishing the remaining work when there is room to do it properly: the collapse is cheap, the divergence it exposes is the finding, and each of these needed a review round to get right.

Still open under this issue

  • The OBSERVER_CLS/TRADER_CLS fold of the four base.py files (~600 LOC).
  • env_sltp.py, including the 70-line config repeated 4× (~900 LOC) — the __post_init__ cluster above is part of this.
  • Step 5 (test consolidation) measured as ~90% already done; recommended for dropping or rescoping.

BY571 avatar Aug 18 '26 08:08 BY571

Step 3 measured: the SLTP config is the strongest dedup case in this issue

AST comparison of the four env_sltp.py config dataclasses (field name + type annotation):

binance: 23 fields   bitget: 25   bybit: 24   okx: 24
identical across all 4: 20
venue-specific:
  binance: margin_type, time_frames*, execute_on*
  bitget : margin_mode, position_mode, product_type, time_frames*, execute_on*
  bybit  : margin_mode, position_mode, time_frames*, execute_on*
  okx    : margin_mode, position_mode, time_frames*, execute_on*
        (* differ only in DEFAULT VALUE -- "1Hour" vs "1h" etc. -- not in type)

So ~80 field declarations across four files collapse to 20 in a shared base plus 3-5 overrides each. Every field has a default, so dataclass inheritance works without the non-default-after-default problem.

This is the highest-value remaining piece of #288 and the most mechanical. It is also the one place where the "70-line config repeated 4x" figure in the issue is accurate rather than inflated — unlike the line-level counts for base.py (claimed 96%, measured 2 identical methods) and step 5 (claimed 392/506 lines, measured ~90% already shared).

Two things to watch when doing it, both learned the hard way in this issue's earlier slices:

  1. margin_type (binance) vs margin_mode (the other three) is a genuine naming divergence the issue calls out separately. Folding the configs together forces a choice, and whichever name wins changes one venue's public API. That decision should be made explicitly and first — the same sequencing that mattered in #386 and #387, where collapsing first would have buried a behaviour change inside a refactor.
  2. The __post_init__ bodies hash identically across bitget/bybit/okx only because each imports its own normalize_<venue>_timeframe_config. A shared base needs that as a class attribute, not an inlined import.

Issue status after this sweep

Merged for #288: step 4 (#378, #380), the ceremony cleanups (#379), get_account_state/get_market_data_keys (#384), _create_trade_info (#385), _handle_close_action + the binance side="CLOSE" divergence (#386), _execute_market_order + the binance uppercase-side divergence (#387).

Remaining: this config extraction, the OBSERVER_CLS/TRADER_CLS fold of the four base.py files, and the binance observation class (#289's last item, 8 methods its siblings inherit). Step 5 measured as ~90% already done and recommended for dropping.

BY571 avatar Aug 18 '26 08:08 BY571

Adding a sixth item, measured while fixing #400 — this one is alpaca vs the shared futures base, so it sits outside the four-futures-stack scope above but is the same failure mode and arguably the highest-value single deletion left.

AlpacaObservationClass.get_observations (torchtrade/envs/live/alpaca/observation.py, ~66 lines) and BaseFuturesObservationClass.get_observations (torchtrade/envs/live/shared/futures_base_obs.py, ~70 lines) have converged to the same function. Diffing the two bodies, the only substantive differences are:

  • self.timeframes vs self.time_frames (the public kwarg name — this is the actual blocker)
  • _fetch_single_timeframe(timeframe) vs (timeframe, limit=window_size + 50)
  • module-level _timestamps_of(df, 'timestamp') vs self._timestamps_of(df, self._get_timestamp_column())

Everything else — the length check, the stale-bar refusal, the base_features slice, the windowing — is character-identical. _timestamps_of is itself a second copy (observation.py:10-24 vs futures_base_obs.py:186-204: same three branches, same KeyError).

Why it earns a place on this list: the last three live-observation fixes were each pasted into both copies — #395 (row alignment), #397/#399 (stale bar, non-finite rows), #400 (short observation). That is the exact "a fix lands on some and not others" pattern this issue exists to end, and it has now recurred three times in a row on this one function.

Worth roughly -83 lines from alpaca/observation.py. The base's seven abstract hooks contain nothing futures-specific, so the mechanics are straightforward; the cost is the public timeframes= vs time_frames= kwarg rename, which is a breaking change for user code and needs a deliberate call.

Evidence it is not hypothetical: alpaca's copy of the #397 dropna had zero test coverage until #400 added a shared-base test — deleting it failed no tests at all.

BY571 avatar Aug 19 '26 12:08 BY571

Slice 1 done (#404). The alpaca/futures observation fold, measured:

module
shared/base_obs.py (new) the window pipeline, venue-agnostic 299
shared/futures_base_obs.py kline hooks only 361 → 97
alpaca/observation.py date-range fetch + MultiIndex undo 321 → 109

get_observations now exists in exactly one place for all five venues. Net +515/−558.

What slice 2 should know

The boundary was measured, not guessed. Of the seven abstract hooks on the futures base, the window logic calls only three (_create_client, _validate_timeframe, _get_timestamp_column). Use the same method for the next slice — hoist what the shared code actually calls, not what looks shared.

_get_default_lookback is unreachable and is slice 2's headline. A reviewer planted raise AssertionError at its sole call site (limit = self._get_default_lookback() in the kline fetch) and ran the full suite: 3998 passed. get_observations always passes limit=window_size + 50, and the only argument-free call is alpaca's own override. It is an abstract hook implemented four times that nothing reaches — roughly −14 lines across 5 files.

Also left for slice 2:

  • bitget/observation.py:161 still carries a ~56-line __main__ block. Alpaca's equivalent (74 lines, made live network calls needing real credentials) was deleted in #404.
  • shared/__init__.py does not export BaseObservationClass.
  • The margin_type: MarginType (binance) vs margin_mode: MarginMode (bitget/bybit/okx) rename, deferred here from #289. MarginType lives in core/common_types.py but serves binance alone; MarginMode is redefined three times locally with venue-specific values ('ISOLATED' vs 'isolated' — API strings that must stay different). A three-way dedup plus a breaking rename across 79 references.

Two guards now protect the fold, and they are not redundant

Verified by mutation: re-forking _fetch_single_timeframe on binance passes base_exchange_tests.py's guard (that method is abstract at the BaseObservationClass level, so it is excluded from the protected set) and fails binance's MRO guard. They cover different layers. Both are name-based and never read a body — a venue reimplementing the pipeline inside an exempted override would pass, which the docstring now says.

One thing worth carrying forward: df.copy() in _normalise_frame turned out to be load-bearing. Preprocessing drops rows inplace=True, and the #399 stale-bar check compares the processed frame against the fetched one — share a single object and the comparison can never differ, so a stale bar reaches the policy. Returning df instead passed all 3999 tests before a guard was added. Any future hoist that moves frames between these two stages needs the same check.

BY571 avatar Aug 20 '26 08:08 BY571

Slices 1–4 merged (#404, #405, #406, #407). Measured state of the original plan:

plan step state
3 — share env_sltp.py's 70-line config dataclass ×4 done — BaseFuturesSLTPConfig (#391)
4 — consolidate verbatim _calculate_unrealized_pnl_pct ×3, _round_price ×3 done — _calculate_unrealized_pnl_pct now has 1 definition, _round_price 2
— (not in the plan) get_observations ×2 done — #404, one implementation for all five venues, −111
— (not in the plan) PositionStatus ×5 done — #406, identity-guarded, −77
— (not in the plan) __main__ demo blocks ×12 done — #407, −578
1 — fold the four base.py into the shared base blocked on a design call, see below
2 — share env.py trade-path helpers open
5 — mirror in tests partially — the shared guards land in base_exchange_tests.py and test_executor_helpers_288.py

Step 1 is not the same kind of duplication as slices 1–4

Measured similarity of base.py after normalising venue names:

binance vs bitget   91.2%      binance vs bybit   77.3%
bybit   vs okx      83.2%      binance vs okx     66.2%
bitget  vs bybit    75.7%      bitget  vs okx     65.2%

High, but the residue is meaningful, not cosmetic. The __init__ signatures genuinely differ: okx and bitget take a passphrase; binance and bybit do not. Folding them means one of:

  • **credentials — loses the explicit, typed signature that makes a wrong keyword fail at the call site;
  • an optional passphrase on the shared base — which gives binance and bybit a parameter they ignore. That is precisely the dead-parameter defect #289 removed (position_side, four unreachable branches), and re-creating it to save ~200 lines is a bad trade.

Slices 1–4 were all cases where the copies were byte-identical or differed only in an annotation. This one isn't, so it needs a decision rather than a mechanical fold — the same shape as #279's action-space call and #289's hedge-surface call.

Suggested framing for whoever picks it up: the question is not "can these be folded" but "should credential shape be part of the shared constructor at all". A CREDENTIAL_FIELDS class attribute, or venue-owned __init__ calling a shared _init_common(), both keep the explicit signature. Worth deciding before writing code.

Where the sweep got to

Suite 3826 → 4020 while the package shrank by roughly 900 lines across the five merged PRs. Every fold is guarded structurally — a re-fork fails a test by name — because the recurring lesson was that a re-declared copy passes every behavioural test on the day it is written.

BY571 avatar Aug 20 '26 18:08 BY571

Slice 2 (PR #408) found three copies of the same defect outside its scope. Recording them here rather than opening issues, since they belong to this dedup effort.

Slice 2's subject: the policy's action index was validated ten different ways across five live venues. action_levels[-1] wraps a list, so a negative index silently opened a full LONG on binance/bitget/alpaca; bybit/okx clamped instead; on the SLTP side bybit/okx carried a byte-identical copy of that clamp while alpaca/binance/bitget let a bare KeyError escape mid-step. All ten now share one validator that raises.

The same shape survives in three places the live base class cannot reach:

  1. torchtrade/envs/offline/sequential.py:549 — self.action_levels[action_idx], raw, on a list. Identical negative-wrap. This is the highest-priority instance: CLAUDE.md ranks offline correctness above everything, since these envs train the policies. Not a reuse fix — offline inherits TorchTradeOfflineEnv, so either the validator hoists to a common ancestor or offline gets its own.

  2. torchtrade/envs/live/polymarket/env.py:295 — int(td.get("action").item()) then if action_idx == 1 else no_price, so any malformed index silently becomes a NO bet. PolymarketBetEnv inherits EnvBase directly, not TorchTradeLiveEnv, which is worth noting on its own: it is outside every shared guarantee this issue has been consolidating, so "parity across live envs" currently means five of six.

  3. torchtrade/actor/parsers.py:23 — extract_action falls back to index 0 on a missing or out-of-range <answer> tag. Verified by execution:

    futures levels=[-1.0, 0.0, 1.0] -> idx 0 => -1.0   MAXIMUM SHORT
    spot    levels=[ 0.0, 0.5, 1.0] -> idx 0 =>  0.0   flat, fine
    

    The docstring says "a trading agent must always emit a valid action", which reads as though the fallback is neutral. It is only neutral on spot. Not mechanical to fix: the neutral index differs across spot, futures and the SLTP action map, so it needs a decision about what "hold" means per action space.

(1) and (3) are money-path. (2) is arguably the more interesting structural finding for this issue, since polymarket sitting outside TorchTradeLiveEnv means it silently misses the dust rule, the exchange-truth sync and the bankruptcy rule as well — worth deciding deliberately rather than by omission.

BY571 avatar Aug 20 '26 19:08 BY571

Slice 1 is in review as #410 (net −109; the four base.py files 524 → 246). Recording a follow-up slice that came out of its review, per @CharlieHelps:

every orchestration path that normal tests bypass through dependency injection needs one network-free characterization test at the real production seam

Track the broader convention as a focused follow-up linked to #288 rather than burying it in the general test-consolidation slice; the failure mode is path reachability, not test deduplication.

Why it earned a slice of its own. #410 shipped a live-money regression — okx's observer was handed the trader's Trade.TradeAPI, which has no get_candlesticks, so the env could not fetch a single observation — and nothing in the suite could have caught it: 83 of 85 env constructions inject an observer, and the 2 that don't need live credentials and skip. _init_trading_clients was structurally unreachable.

Two of my own attempts to prove equivalence also measured the wrong thing:

  1. A probe that patched one class at a time, so on the trader-first venues the trader constructor threw before the observer was reached. It recorded "observer": "ERR ValueError" on both sides; I diffed two identical error strings and reported "identical kwargs".
  2. A test that called _observer_kwargs() directly and never ran _init_trading_clients. Against three wiring regressions it caught 0 of 3.

So the slice is: find every shared orchestration seam that DI hides, and give each one characterization coverage. Candidates beyond _init_trading_clients: _finish_futures_init, the SLTP _execute_trade_if_needed dispatch, and the observer/executor construction in the alpaca and polymarket stacks.

The generalisable lesson, which is why this is not just "add tests": the reliable question is not does my check touch the right code but what mutation of the changed code does this check kill? All three failures above are invisible to the first question and obvious to the second.

BY571 avatar Aug 25 '26 11:08 BY571

Slice 3 merged (#412) — and the remaining scope, measured

_step for the four plain futures envs is folded onto TorchTradeFuturesLiveEnv, and the record-then-score tail is folded onto TorchTradeLiveEnv._record_and_score — the latter reaches all ten live envs, alpaca included. Production net −191 lines. Suite 4334, 0 failed.

Two bugs fell out of the fold that the duplication had been hiding:

  • logger.warning(..., self.symbol) where these envs have no symbol attribute — so the graceful-degradation path raised AttributeError instead of degrading, in all four copies.
  • Alpaca's two copies of the reward tail were unpinned: zeroing the reward, dropping the overwrite, or scoring before recording each survived the whole suite. Closed by construction — there is no alpaca tail left to mutate.

Corrected status of the original slice list

Two items in this issue's plan were already done before I started, and the estimates misled me twice — so here is what is actually left, measured rather than estimated:

target copies lines pairwise similarity
_calculate_fractional_position 4 217 54–100%
__post_init__ (config) 4 56 54–98%
_execute_trade_if_needed 4 53 60–100%

The 100% upper bound in each row is the finding: at least one pair is byte-identical, so each of these splits into a fold-now cluster and a genuinely-different remainder. The 54–60% lower bounds are real venue differences (lot-size spellings, margin/position-mode APIs), not laziness — folding those under one signature is how you get a parameter nobody sets.

order_executor.py (2152 lines) is not in scope: measured at 47% similar at best. Different exchange APIs, not duplication.

Test side, which is the larger half

tests/envs/binance  3195 lines
tests/envs/bitget   2779
tests/envs/bybit    2748
tests/envs/okx      1850

okx's tests were 392/506 lines identical to bybit's when I checked during slice 1. This is the biggest remaining win and the lowest risk, but it needs the lesson from #412's review rounds applied deliberately: consolidating per-venue tests into one shared body removes the venue axis, and that is only safe where the venues differ in code. It is not safe where they differ in data — collapsing the action-level test to one venue made a whole class of mutation unobservable, because binance ships [-1, 0, 1] and the others [-1, -0.5, 0, 0.5, 1].

Recommended next slice

_calculate_fractional_position — largest, and the sizing math is money-moving, so it is where a silent divergence costs most.

BY571 avatar Aug 26 '26 11:08 BY571

Live min-notional gaps, found while folding the sizing (#413)

Not caused by #413 and deliberately not fixed there — recording so they are tracked rather than lost in a PR thread. Surfaced by @CharlieHelps while reviewing the fold; the comparison across all four venues is what made them visible, which is itself an argument for the deduplication.

1. binance revalidates min-notional on the wrong quantity. A direction switch validates min-notional on the rounded delta, then closes and opens abs(target_qty). The rounded target can sit below MIN_NOTIONAL while the larger switch delta passes. Concretely: price 99.99, minimum 100, raw target 1.0002 floors to 1.0 (notional 99.99, below the minimum) while a 1.01 delta passes the check. The opening quantity is what the exchange sees, and it is not the quantity that was validated.

2. binance SLTP has no min-notional guard at all. Separate execution path; it submits fractional quantities and its executor enforces only quantity constraints.

3. bitget and bybit never read their exchanges' minimum-notional fields. Both consume min-qty and step but ignore minTradeUSDT (bitget) and lotSizeFilter.minNotionalValue (bybit). No equivalent concrete omission found for OKX derivatives, where minSz/lotSz are the binding constraints.

The shape is the same in all three: an order that the env believes it placed and the venue rejected. That is invariant 2 inverted — the cache says a position exists when the account is flat — and this repo has already paid for that failure class twice.

Also outstanding on the sizing

_calculate_fractional_position is folded for the four PLAIN futures envs. Each <venue>/env_sltp.py still inlines the same arithmetic — balance * 0.98, the isfinite guard, calculate_fractional_position(...) — and sources its fee from trader.transaction_fee falling back to the module-level TAKER_FEE. So four of eight copies remain, and each venue now has two mechanisms for "this venue's taker fee". The class attribute added in #413 sits on <venue>/base.py, which the SLTP classes DO inherit, so the SLTP fold can read self.TAKER_FEE when it happens.

BY571 avatar Aug 26 '26 13:08 BY571

Tracked here as follow-up scope for #288. I won’t widen #413 for these pre-existing min-notional gaps or the remaining SLTP fold.

charliecreates avatar Aug 26 '26 13:08 charliecreates

One more pre-existing gap, found while folding the sizing (#413)

binance/env.py, in _execute_fractional_action:

delta = self.trader.round_quantity(abs(delta)) * sign

Replacing that whole line with delta = delta passes all 3,168 tests. The line is byte-identical on main and dates to #352 (which fixed #271): that PR pinned the target rounding and left the delta rounding unpinned. The consequence is an un-lot-rounded quantity sent to the venue — the same class of rejection as the min-notional items above.

Not caused by #413 and out of scope there.

Also recorded, for whoever takes the SLTP slice

_calculate_fractional_position is now folded for the four plain futures envs, but four of eight copies remain: each <venue>/env_sltp.py still inlines balance * 0.98, the isfinite guard, and its own calculate_fractional_position(...) call. Two specifics worth carrying into that work:

  • The SLTP path sources its fee from getattr(self.trader, "transaction_fee", None) falling back to the module-level TAKER_FEE, with only a logger.warning on an unusable value — a silent degrade on a money path, and the fallback branch has no test in either direction.
  • The TAKER_FEE class attribute #413 added sits on <venue>/base.py, which the SLTP classes do inherit, so the SLTP fold can read self.TAKER_FEE without further plumbing.

The plain fold's own evidence is committed as _GOLDEN_SIZINGS — eight pre-fold (size, notional) pairs across four venues at 1x and 125x. The SLTP fold should produce its counterpart; there is currently no value-level pin on SLTP sizing output at all.

BY571 avatar Aug 26 '26 16:08 BY571

Live-money bugs split out to #414

The four order-size validation gaps found while folding (binance revalidating min-notional on the rounded delta, binance SLTP having no min-notional guard, bitget/bybit ignoring their exchanges' minimum-notional fields, and binance's unpinned delta lot-rounding) are now #414. They are defects the comparison surfaced, not deduplication work, and keeping them here would stop this issue ever closing.

What remains for #288, measured on main at 3b45c61

target copies lines pairwise similarity note
_execute_trade_if_needed (env_sltp) 4 748 45–95% contains the still-inlined sizing
__post_init__ (config) 4 56 54–98%
_execute_trade_if_needed (env) 4 53 60–100% bybit/okx byte-identical
venue test dirs 4 10,572 — okx was 392/506 identical to bybit's

_execute_fractional_action is NOT on this list, deliberately. 4 copies, 180 lines, but 18–49% pairwise — that is four genuinely different exchange APIs, not duplication. Folding it would mean inventing parameters to paper over real differences, which is how a config field nobody sets gets born. Recording it here so it does not get re-proposed on a line count.

Same for order_executor.py (2,152 lines, 47% at best), already excluded.

Done so far

  • #410 four base.py → shared base
  • #411 SLTP _step/_reset → SLTPMixin
  • #412 plain _step → TorchTradeFuturesLiveEnv, plus the record-then-score tail onto TorchTradeLiveEnv._record_and_score (all ten live envs, alpaca included)
  • #413 _calculate_fractional_position → shared, with TAKER_FEE lifted to a per-venue class attribute

Cumulative production: roughly −650 lines.

Next: the SLTP _execute_trade_if_needed

Largest remaining, and it holds the sizing arithmetic #413 deliberately left inlined. Two things already in place for it:

  • the TAKER_FEE class attribute sits on <venue>/base.py, which the SLTP classes do inherit, so the fold can read self.TAKER_FEE with no further plumbing;
  • _GOLDEN_SIZINGS is the shape its evidence should take — there is currently no value-level pin on SLTP sizing output at all, and the SLTP fee's trader.transaction_fee fallback degrades silently with only a logger.warning.

BY571 avatar Aug 27 '26 06:08 BY571

Scope, re-measured (2026-08-27)

After #410–#413, #415 and #417, roughly 900 production lines are gone. Recording what is actually left, because two numbers in the original issue are wrong in ways that would misdirect whoever picks this up.

Production side, remaining

target copies lines similarity
__post_init__ 4 56 54–98%
plain _execute_trade_if_needed 4 53 60–100% (bybit/okx identical)

_execute_fractional_action is not on this list. It measures 18–49% similar — four genuinely different exchange APIs, not duplication. Deliberately excluded; it keeps getting re-proposed.

Test side — the "10,572 duplicated lines" figure is roughly 2× too high

104 same-named test_* functions across ≥2 of {binance, bitget, bybit, okx}; 27 in all four. But the 4,086-line figure was computed on best-pair similarity. Foldability is governed by the worst pair:

threshold best-pair names min-pair names min-pair lines
≥0.99 41 22 1,162
≥0.90 57 35 1,891

Costed properly — each fold as a shared base (~6 lines) plus a per-venue hook (~9–10) — 8 of 14 class-groups come out net positive: parametrizing costs more than the body saves. Only 5 pay for themselves.

Defensible total: −1,300 to −1,700 lines (12–16%), not the ~3,000 the raw claim implies.

The saving is in the fixtures, not the test bodies

The claim counted only test_* functions. Those four directories also hold 113 non-test defs totalling 2,406 lines, ~1,588 of them in classes present in ≥2 venues. That is worth about −600 and nobody has been looking at it.

Best single cluster to start with: the 8 TestWithReplayData classes — 675 lines collapse to ~103 plus a 24-line shared replay_df fixture. −548 on its own, and clean: all four venues expose exactly one *FuturesTorchTradingEnv / *FuturesSLTPTorchTradingEnv and all four configs accept demo.

Two traps in the byte-identical set

  • test_bankruptcy_termination is byte-identical across all four venues and steps torch.tensor(2). binance builds its levels via build_default_action_levels(allow_short=True) → [-1, 0, 1], so index 2 is a full long. bitget/bybit/okx hardcode [-1, -0.5, 0, 0.5, 1], where index 2 is flat. The same bytes test two different behaviours. Fold it naively and one disappears silently.
  • test_fractional_converts_balance_to_quantity reads 99% but is min-pair 0.38. bybit's copy carries an extra assertion on the accepted branch of the fee guard that no other test covers — every other SLTP test passes a bare MagicMock trader, which the guard rejects, so they all assert the fallback instead.

The blocker for any 4-way fold

_execute_trade_if_needed has forked signatures: binance/bitget take (action_tuple) and price the bracket off their own candle; bybit/okx take (action_tuple, *, current_price) because #295 moved the mark read out of the trade path. A shared test body calling with current_price= raises TypeError on two venues; one omitting it changes what the other two assert.

Fold within each pair first. #417 did exactly that on the production side for binance+bitget — and the fold is what surfaced a live bug (include_close_action silently no-opped on those two venues).

BY571 avatar Aug 27 '26 10:08 BY571

Slice done: the four plain configs (#425, merged b612fe8c)

Closes two rows from the 2026-08-27 table: __post_init__ (4 copies, 56 lines) and the TestWithReplayData cluster flagged as the best test-side starting point. Production −105, tests −172, net −277, suite 4700 passed.

The fold surfaced one live divergence, as folds here keep doing: binance derived action_levels from build_default_action_levels while bitget/bybit/okx hard-coded a five-level list, so the same unset config produced a 3-action space on one venue and 5 on the other three. action_spec.n is what a checkpoint binds to, so a policy could not move between venues it was supposed to be portable across. Unified to [-1, 0, 1] — breaking for the three venues' existing checkpoints, and the default is still only a default.

Also caught in review, each now pinned by a mutation-verified test: an okx margin_mode default that flipped ISOLATED → CROSS during the fold and passed 4671 tests; ten hardcoded action indices that meant the opposite of their name under the new default (including all four test_step_hold_actions, the only per-venue coverage of the flat route); and _normalize_timeframes, the one token the fold created that nothing checked — cross-wiring two venues' parsers passes all 3678 env tests.


The last production row is not duplication. It is a semantic fork.

_execute_trade_if_needed (plain, 4 copies, 53 lines, listed at 60–100% with bybit/okx byte-identical). The similarity metric is right and the conclusion it invites is wrong:

binance / bitget / alpaca bybit / okx
guard desired_action == current_action_level → skip none; recompute target at the new price, skip only if abs(delta) < min_qty
repeated action, price moved hold rebalance

futures_live_base.py:955 already records the split — "Load-bearing for binance and bitget … Inert for bybit and okx, which take the threaded qty and never read the field" — so _sync_action_level_after_reset runs on all four to protect a guard two of them do not have.

The tiebreaker is the offline env, which is what the policy actually trains in. offline/sequential.py:697:

# If action hasn't changed and we already have a position, just hold
if action_value == self._prev_action_value and self.position.position_size != 0:
    return {"executed": False, ...}

Offline holds. So bybit and okx are the outliers, not the majority.

Measured, not argued

Same action (full long) every step, price walking 100 → 110, venue reporting back exactly what the env submitted (otherwise _sync_position_from_exchange releases the guard on all four — invariant 2 — and the difference vanishes under test):

venue     |   100    101    103    106    110 | re-trades after the open
binance   | TRADE   .     .     .     .       | 0/4
bitget    | TRADE   .     .     .     .       | 0/4
bybit     | TRADE TRADE TRADE TRADE TRADE     | 4/4
okx       | TRADE TRADE TRADE TRADE TRADE     | 4/4

The extra trades are resizes, not round-trips — $946.77 of extra notional against a $9,794.60 position over that 10% move, ≈$0.52 in taker fees at 0.055%. Small per move; the cost is that it recurs on every drift, and that the policy's learned "hold" silently means "rebalance" on two of four venues. That is the offline/live parity this repo lists as a reason the deduplication is worth doing at all.

Next slice

Fold the four into the shared base with the guard, which is simultaneously the dedup (−53) and the fix (bybit/okx stop re-trading), and lets the futures_live_base.py caveat go. It is a behaviour change on two live venues, so it gets its own PR and its own value-level evidence rather than riding along in a refactor.

BY571 avatar Sep 02 '26 11:09 BY571

Slice done: the plain trade gate (#426, merged 32ca8cce)

Closes the last production row of the 2026-08-27 table — and it was not duplication. _execute_trade_if_needed was 4 copies at 60–100% similarity with bybit/okx byte-identical, and those four copies implemented two different behaviours. Pairwise similarity cannot see which half is correct; the tiebreaker was offline/sequential.py, which holds on a repeated action and is the env the policy trains in. bybit and okx were the outliers, re-trading on every price move — ~$947 of resize notional per 10% move against a ~$9,795 position, at fees the training reward never charged.

Production −46, tests −170, net −216. Suite 4722 passed.

Production side of this issue is now empty

target status
__post_init__ (4 copies, 56 lines) done, #425
plain _execute_trade_if_needed (4 copies, 53 lines) done, #426
_execute_fractional_action excluded, 18–49% pairwise — four genuinely different exchange APIs
order_executor.py excluded, 47% at best

What is left, measured

Tests. The TestWithReplayData cluster (−548) and the seven replay_df copies went in #425; #426 took another −170. The 2026-08-27 estimate of −1,300 to −1,700 total still looks right, and the remaining win is where it said: the 113 non-test defs totalling 2,406 lines across the four venue directories, ~1,588 of them in classes present in ≥2 venues. Worth about −600, still unexamined.

SLTP _execute_trade_if_needed (4 copies, 748 lines, 45–95%) remains the largest single item, and it still holds the sizing arithmetic #413 left inlined. The forked-signature blocker recorded above still applies: binance/bitget take (action_tuple), bybit/okx take (action_tuple, *, current_price). Fold within each pair first.

New follow-up, deferred deliberately by @CharlieHelps

_execute_trade_if_needed was the only @abstractmethod on TorchTradeFuturesLiveEnv, so giving it a shared body left the five intermediate bases (TorchTradeFuturesLiveEnv + the four *BaseTorchTradingEnv) instantiable. BinanceBaseTorchTradingEnv() now constructs into a half-built env and fails later on action_spec with IndexError, where it previously failed fast with TypeError.

Declaring _execute_fractional_action abstract instead does not work — the four SLTP envs share this base and trade brackets, so it makes them abstract and drops the discovered-env list from 10 to 6. The cheap fix is to hoist the 4x-duplicated self.action_spec = Categorical(len(self.action_levels)) into the shared base, which restores fail-fast and continues the dedup theme. No production path instantiates those bases today, and both test-discovery sites were updated to key on the venue module.

Two pre-existing holes this work measured but did not fix

  • The forwarded price is unpinned by size anywhere but the new gate test. Corrupting the price _execute_trade_if_needed hands to sizing doubles the quantity every venue sends and passed 4718 tests; the same corruption survives on main's four separate forwarders. #426 pins it at the gate, but nothing pins the SLTP equivalent.
  • test_reentry_after_external_close_starts_a_fresh_holding_time (all five venues) asserts only that holding_time resets, which is equally true when the guard stays stuck and the account stays flat. #426 added end-to-end coverage on the plain path; the SLTP path still has none.

BY571 avatar Sep 02 '26 13:09 BY571

Correction to my previous comment

I wrote that the SLTP _execute_trade_if_needed (4 copies, 748 lines) "remains the largest single item." It does not — it is already done. I restated the 2026-08-27 table without re-measuring it against main, which is the same defect the last two PRs kept catching in my own prose.

Measured now: grep -rn "def _execute_trade_if_needed" torchtrade/ returns six definitions, and none of them is in a futures env_sltp.py. All four SLTP venues resolve it to SLTPMixin (torchtrade/envs/utils/sltp_mixin.py:252), pinned by ("SLTPMixin", "_execute_trade_if_needed") in _SHARED_METHOD_OWNERSHIP.

What is actually left in the four futures env_sltp.py files:

binance  106 lines | __init__(45)
bitget   112 lines | __init__(47)
bybit     79 lines | __init__(28)
okx       90 lines | __init__(29), _resolve_bracket_quantity(9)

okx's _resolve_bracket_quantity is the documented sub-minimum-refusal exemption from #414, already guarded to delegate via super(). So the production side of this issue is empty, not "empty except the SLTP row."

The one production item I had not measured

The eight __init__ bodies are the last duplication, and they show the familiar pair structure rather than a clean four-way fold:

SLTP plain
binance/bitget 94% 93%
bybit/okx 97% 95%
across the pairs 32–37% 49–58%
total 149 lines 101 lines

Same shape as the _execute_trade_if_needed signature fork recorded above, and the same prescription: fold within each pair first, which is what #417 did on the production side and what surfaced a real bug (include_close_action silently no-opping on two venues). Optimistically ~−80 across both families; the cross-pair halves are genuine venue differences and folding them would invent parameters nobody sets.

So the remaining scope is:

  1. Test fixtures — the larger half, and still the one nobody has looked at. Measured today: 9,935 lines across the four venue dirs, of which 145 non-test defs total 2,443 lines; 27 fixture names recur in ≥2 venues across 126 occurrences (env x18, mock_observations x12, status x10, mock_observer x8, env_config x8, mock_trader x7, env_with_mocks x7, order_executor x6). The −600 estimate still looks right.
  2. The eight __init__ bodies, pairwise (~−80).
  3. The deferred follow-up from #426: hoist the 4x-duplicated action_spec assignment into TorchTradeFuturesLiveEnv to restore fail-fast construction on the intermediate bases.

Test-side items 1 and 2 are what would close this issue.

BY571 avatar Sep 02 '26 13:09 BY571

Captured. I’m treating this as a status update rather than starting another slice: the action_spec hoist remains a narrowly scoped #288 follow-up, and the SLTP coverage gaps remain separate until explicitly picked up.

One thing to re-measure before the next slice: current main appears to have a single shared SLTPMixin._execute_trade_if_needed, so the four-copy SLTP count may now be stale.

charliecreates avatar Sep 02 '26 13:09 charliecreates

Three unpinned sizing guards, found by the fixture-fold's mutation sweep (#427)

Recording rather than fixing — they are pre-existing on main and not what #427 is for. Found because consolidating the fixtures made a 36-mutation sweep across both trees cheap to run.

Each of these is a refusal guard on a real money path, and deleting it fails zero tests in all of tests/envs:

site guard
torchtrade/envs/live/bybit/env.py:85 if abs(delta_qty) < min_qty:
torchtrade/envs/live/okx/env.py:81 if abs(delta_qty) < lot_size["min_qty"]:
torchtrade/envs/live/okx/env_sltp.py:87 the quantity < min_qty half of _resolve_bracket_quantity's refusal

Their siblings are well covered — target_tol mutations fail 9 tests each on bybit and okx, and the shared _refuse_below_venue_minimums fails 12 — which makes the omission look accidental rather than deliberate. Same shape as the #414 gaps: an order the env believes it placed and the venue rejected, which is invariant 2 inverted.

Also measured, and also pre-existing

  • a_position_status's five defaults are unobservable. Mutating notional, entry, mark, leverage, liquidation or margin_mode fails 0 tests. Verified apples-to-apples: the eight inlined PositionStatus(...) blocks #427 replaced carry byte-identical literals, and mutating those on main also fails 0. The fold concentrated the deadness into one visible place rather than creating it. Worth knowing before someone writes a test that reads account_state[4] and assumes leverage=5 means something.
  • bybit's and okx's conftest fixed OHLC bar is decorative — mutating the close changes nothing on either tree. Where the bar is load-bearing (binance/bitget SLTP) mutating it fails 5 and 4 tests respectively, so this is specific to those two conftest fixtures.
  • okx's non-default notional=qty*50000.0 / liquidation=40000.0 at okx/test_torch_env_futures.py are likewise unpinned on both trees.

BY571 avatar Sep 02 '26 15:09 BY571