OFFLINE USER GUIDE · v34.9

Binance Auto Trader
user manual

We have configured it so that even first-time installers can follow the instructions in order from connecting API to backtesting and starting actual trading. Everything you need is in this HTML file and it will open even without an internet connection.

WINDOWS · macOS · LINUXBINANCE USDⓈ-M FUTURESGUI API SETUP
read first

If this is your first time, just follow these steps

Binance Auto Trader categorizes market conditions in the Binance USDⓈ-M futures market, Trend Following class Mean Reversion Execute your strategy automatically. It is important not to start with actual trading immediately after turning on the program, but to follow the order below.

Investment Risk Guide: This program does not guarantee profits. Futures trading carries the risk of total loss of principal and forced position close. Backtest results do not guarantee future performance, and final trading responsibility rests with the user.

The fastest way to read this manual

Security principles: API Secret is like a password. Please do not send it to anyone or expose it to screen captures or logs. Automated trading does not require withdrawal permission.

Account linking

Sign up for Binance and set up API

1. Prepare a Binance account

at the top of the program Sign up for Binance Click the button to open the signup page. Complete account creation, identity verification, and USDⓈ-M Futures activation in order. If you already have an account, skip this step.

Futures trading availability: Trades for some products may be restricted depending on country/region and account status. If you are not allowed to trade, add them to Excluded Symbols.

2. Generate API Key on Binance

  1. 1
    Open API Management
    Go to the API management screen of your Binance account.
  2. 2
    Create new API
    Give it a friendly name and complete the security authentication.
  3. 3
    Key and secret storage
    A Secret can only be displayed once, immediately after creation, so keep it in a safe place.
  4. 4
    Permission settings
    It only enables reading and Futures trading permissions, but does not enable withdrawal permissions.

API permission check

PermissionRequired?Notes
Enable FuturesRequiredCheck on Binance API management page
Enable ReadingRequiredView balances and positions
Enable Spot & Margin TradingNot requiredRecommended to disable as it is for Spot trading
Enable WithdrawalsNever enableNo need for automated trading
IP restrictionsHighly recommendedAllow list registration when a 24-hour operating PC has a static IP

3. Enter API into the program

  1. 1
    at the top of the program API Settings Press the button.
  2. 2
    API Key and Secret Key Paste . Secret is masked on the screen.
  3. 3
    When you first practice Testnet Select and enter the testnet-specific key. The live trading key and testnet key are different.
  4. 4
    After saving, check the connection status and balance display in Account Dashboard.
Current version: v34.9. You do not need to create or edit the .env file manually. API credentials and the Testnet selection are saved from the API Settings window.
When error API occurs: Check for spaces before and after, incorrect Secret, Futures permissions, IP restrictions, and mixed use of Testnet/live trading keys.

10 minutes to start

First run order

Recommended starting value (conservative)

parametersRecommended valuereason
Decision TF15mFor direction/trend judgment. Determine EMA, ADX, Volume, Regime, RSI Exhaustion
Execute TF5mFor actual entry timing. Order only when a Donchian breakout occurs in the same direction as the decision.
Trailing TF5mIf set to shorter or equal to Decision/Execute TF, trailing responds quickly.
Leverage3 ~ 5If it exceeds 5 times, the risk of forced liquidation increases rapidly due to volatility.
Risk %0.25 ~ 0.5Only 0.25~0.5% of the balance is consumed by stopping one position. 0.25 recommended initially
Max Position %10 ~ 151 position notional cap. If it is too large, there is a risk of balance imbalance.
ATR Mult1.5 ~ 2.0If it is low, the stop loss is too narrow and frequent stop losses occur.
EMA Gap %Separation rate (%) of EMA20 and EMA60. LONG is allowed to enter Trend Following only when it is above the EMA Gap, and SHORT is only below the -EMA Gap. 0 disables the filter.Not used in Mean Reversion.
Trigger R1.0 ~ 1.5Activate trailing after achieving 1R profit — Minimize stop loss before entering profit zone
Regime activeNORMAL + TRENDInitial operating standards. The final value is determined by the results of a backtest performed by the user.
The recommended values ​​are only a starting point. Performance varies depending on market, period, commission, and slippage conditions. Do not use it for live trading, but be sure to verify it under the same conditions.


cache system

Cache Manager

The program uses Parquet-based candle cache. When running for the first time, the necessary candles are built in the background, and thereafter only newly closed candles are incrementally updated.

How it works

Metricexplanation
StatusInitial Build: No cache, first downloading matching 365
Updating: Existing cache present, adding new candle increments
Ready: Construction completed
Error: Network error, etc.
ProgressNumber of (symbols × intervals) processed / total. Example: 490 / 1058 (46%)
Cache HitThe manifest covers the number of reads directly from local files without calling API.
API DownloadThe number of downloads by calling the actual API without covering the manifest.
ErrorsNumber of download failure symbols. Displayed only when an error occurs. Skip that symbol and continue
Mode365-day initial download: First construction
background append: Periodic incremental update
4h volume cache: Pre-updated 4-hour bar for Dynamic TopN volume ranking
Next UpdateWhen the next automatic incremental update is due. After the update is complete, wait until the next closing bar of each interval.
Cache SizeLocal cache directory total size
Last SyncLast incremental update completion time
API key not required: Candle Cache construction is done through the Binance public endpoint (/fapi/v1/klines) is used. Even if the API key is not set, the cache will be built normally as long as you have an Internet connection.
Dynamic TopN 4h cache pre-build: Cache Manager is now required for Decision/Execute/Trailing TF as well as Dynamic TopN volume ranking. 4h Candlesticks are also built in advance and updated incrementally in the background. When Sweep is executed, Pass 1 is mostly processed as a local parquet/manifest read rather than a API download, and only the insufficient sections are downloaded to make up for it.
Detailed structure: The overall relationship between manifest, Candle Cache, market_data, and Indicator Cache isCache Structure SectionThis is explained in detail.
tap guide
Recent UI changes
  • Added Top N panel (shows current Top N symbols)
  • Currently owned Top N stocks are highlighted in bold blue letters.
  • Added Excluded Symbols panel (enter one symbol per line)
  • Excluded Symbols are applied equally to live trading, backtesting, validation, and walk-forward.
  • Improved Log/Top N/Cache Manager layout
  • OPEN status in Trade History shows both date and time

Trading tab

All settings for live automated trading are concentrated in this tab. Setting fields are disabled during automated trading.

default settings

parametersdefaultrangeexplanation
Top N Symbols3010~50 Top N stocks with 24h trading volume are selected for scanning. The bigger it is, the greater the opportunity for entry.·API load increases. The symbol universe automatically updates every 4 hours.
Market UniverseCRYPTOCRYPTO / TRADFI / ALL CRYPTO: Coin Futures Top N
TRADFI: Gold, stocks, ETF, etc. TRADFI futures Top N
ALL: Top N trading volume combining two markets
Decision TF15m1m~4h Candlestick timeframe for judging entry signals. The shorter the signal, the higher the signal frequency and the more noise. Only the completed candle (closed candle) is used for signal judgment.
Trailing TF5m1m~15m Timeframe for calculating Trailing Stop ATR. Trailing responds faster when set shorter than Decision TF.
Leverage51~20 Futures leverage multiple. Automatically set to the exchange upon entry. Both profits and losses are multiplied. 5x or less is strongly recommended.
Risk %1.00.1~5.0 Maximum amount lost when stop loss is activated in one position = Total balance × Risk%. If you do not specify a risk% for each regime, this value will be used as the default fallback.
Max Long Pos.51~20 Maximum number of LONG positions held simultaneously. When the limit is reached, entering a new LONG is skipped.
Max Short Pos.51~20 Maximum number of SHORT positions held simultaneously. Independent management with LONG.
Max Position %205~100 Notional limit for 1 position = Total balance × Max Position% × Leverage. Use the smaller of the Risk reference quantity and this upper limit.

3-TF Entry Engine

The Trend Following strategy uses a three-step timeframe structure that separates judgment and execution. The Decision TF authorizes direction, the Execute TF confirms the actual entry timing, and the Trailing TF manages position close after entry.

divisionroleUsage Metricsexample
Decision TFDetermination of trade direction and entry permissionEMA, ADX, Volume, Regime, RSI ExhaustionDetermine LONG/SHORT direction at 15m
Execute TFCheck live order timingDonchian High/Low BreakthroughEnter when there is a breakthrough in the same direction at 5m.
Trailing TFExit and trailing-stop management after entryATR Trailing, Exit ModeStop update based on 5m ATR
importance: The Mean Reversion strategy enters immediately when a signal occurs in the Decision TF and does not use the Execute TF. Only Trend Following uses the three-step structure of Decision→Execute→Trailing.
Avoid entry delays: Even if the Decision TF approves a direction, no order is placed unless the Execute TF confirms a breakout in the same direction. This structure is designed to combine the stability of a 15-minute bar with the fast timing of a 5-minute bar.

Regime Settings

Strategies and parameters are set independently for each regime (QUIET · NORMAL · TREND · PANIC). If checkbox OFF is checked, there will be no new entries in that regime.

Dual parameter fields: The meaning of the Vol/RSI, Trig/BB, and ADX fields changes depending on the selected Strategy. The UI label automatically switches to match Strategy.
parametersTrend FollowingMean Reversion
Strategy trend_following (breakout trend following) mean_reversion (mean reversion)
ADX
ADX Min / ADX Max
ADX Min: Minimum trend strength allowed for entry. If ADX < this value, entry is ignored. If it is low, the signal increases / false signal ↑ ADX Max: Maximum trend strength allowed for entry. ADX > Ignore entry if this value (block entry into trend market)
ATR Mult commonness. Stop Loss = Entry ATR × ATR Mult. If it is low, there will be frequent stop losses / if it is high, the loss will increase with one stop loss.
Vol Mult
/ RSI Entry
Vol Mult: Trading volume > Volume MA × Vol Mult. If it is low, the frequency of entry increases. RSI Entry: LONG: RSI ≤ this value / SHORT: RSI ≥ (100 − this value). If it is low, only extreme oversoldness is captured.
Trigger R
/ BB Sigma
Trigger R: Trailing activation distance = Stop loss × Trigger R. If it is low, trailing starts at the beginning of profit. BB Sigma: Bollinger Band Bandwidth multiple (σ). Basic 2.0. If it is low, the frequency of entry increases.
Risk % Position size adjustment by regime. If not entered, use the default Risk% setting.
Exit Mode Choose trailing/partial_tp/fast_exit (see comparison below) BB Mid / trailing / partial_tp / fast_exit selectable. BB Mid uses BB Middle at the time of entry as the target price, and the remaining modes use the same exit method as Trend Following.

Exit Mode Comparison

Exit ModemovementcharacteristicRecommended regime
trailing Close only with stop loss or trailing stop. No separate TP Long-term tracking of strong trends is possible. Risk of return of profits in case of sideways movement NORMAL, TREND
partial_tp When the 1R goal is reached, 50% partial close → Trailing of the remaining 50% continues. RSI 50% position close in advance even when overbought/oversold Certain profits + additional profits if the trend continues. balanced NORMAL
fast_exit Close the entire amount as soon as the 1R goal is reached. No trailing Quick confirmation of profits in areas of rapid change. Big trends can be missed PANIC
BB Mid Mean Reversion only. When the BB middle band (SMA20) is reached, all profits are lost. Mean reversion goal achieved and closed. Set target to BB Mid at entry point QUIET (recommended)

CI Filter (optional)

Use Choppiness Index (CI) to block trend following entry in sideways movements. Does not apply to Mean Reversion strategies.

settingexplanation
CI Filter ONCI < 61.8 condition added. TF entry is blocked at CI ≥ 61.8 (sideways section)
PeriodCI calculation lookback period (number of bars). Default value 14. The shorter it is, the faster the response and the higher the noise. The longer it is, the more stable it is and the delay in entering the trend.

Server Stop (Server-side STOP_MARKET)

When entering a position, the Binance server Order STOP_MARKET automatically registers. Even in situations where the bot process is down or the network is down, the exchange will execute the stop loss on your behalf.

Double safety net: The local stop monitor (inside the bot) and the server STOP_MARKET order operate simultaneously. If the bot is running normally, the local monitor clears it first and cancels the server stop. If the bot is offline, server stop works alone.
movementexplanation
Register upon entrySTOP_MARKET order is automatically registered on Binance immediately after position opening. workingType=MARK_PRICE Use — Prevent unreasonable position close with Last Price spikes
Updated when moving to trailingEach time the trailing stop moves, cancel the existing order and re-register at the new price. Server stop prices are always synchronized with the latest trailing stop
Cancellation upon local position closeWhen the bot closes a position (STOP, TRAILING_TAKE, TIME_EXIT, etc.), the server stop order is also canceled. No orphan orders left after position close
Cancellation during Emergency CloseWhen you click the [Emergency Close All] button, the server stop for each position is canceled first and then the position is closed at market.
Cancellation when an external close is detectedIf the position disappears without the bot's knowledge (manual close, etc.), the server stop is automatically canceled in the next monitor cycle.
Restore after restartSaved on restart server_stop_order_id If there is no server stop, automatic re-registration (repair path)
reduceOnly protection: STOP_MARKET order is reduceOnly=true It is registered as . Even if the server stop quantity after partial close is greater than the actual remaining amount, excess positions will not be opened because Binance will close only the remaining amount.
best-effort behavior: Even if server stop registration fails, bot operation does not stop. [SERVER STOP ERROR] A log is recorded and the local stop monitor continues to operate. However, if the bot is offline and there is no server stop, stop loss will not be executed.

Suspension/Emergency Position Close

buttonmovementcaution
StopNew entry halted. Existing positions continue to be automatically managedSafe exit possible while maintaining position
Emergency Close AllFirst cancel the server STOP_MARKET order for each position, then immediately close all positions on the exchange at market price reduce-onlySlippage may occur in volatility sections

How to use the screen

Trading screen panel

During live trading, you will check the status panel more often than the settings. You can quickly determine the current program status by learning just the four areas below.

panelwhat does it showconfirmation point
Account DashboardBalance, P&L, number of positions, connection statusImmediately after connecting API, first check if the balance is correct.
Open PositionsCurrent direction, entry price, current price, Stop, PnLComparison of quantity and direction with the actual position of the exchange
Current Top NScanned stocks based on current 24-hour trading volume and last update timeOwned stocks are highlighted in bold blue letters. List updated every 4 hours
LogUniverse update, signal, order, stop, position close, errorDon't just look at ERROR, check the previous SIGNAL/OPEN flow chart as well.
API MonitorREST call, WebSocket, User Data Stream statusCall spike, WS SILENT, check for repeat reconnection

Excluded Symbols

Enter the symbols you want to exclude from automated trading, one per line. yes: BTCUSDT. The saved list applies not only to live trading but also to sweep, validation, and walk-forward.

TRADFI stocks restricted for trading in Korea: Please add items that cannot be ordered from your account to the exclusion list in advance. Trade availability may vary depending on user account and region.

Start · Stop · Emergency Close

buttonmovementWhen to use
Start Auto TradeStart new signal search and position management with set valuesAfter checking all settings, API, and balance,
StopStop new entries and continue to manage existing positionsWhen safely stopping a program or preventing new entry
Emergency Close AllAfter canceling the server stop, all positions are closed at market price.Only in emergency situations where normal stopping is difficult

How to use the screen

Trade History

It shows entry, position close, and realized profit and loss based on the trades managed by the program and Binance conclusion history. When you run the program again, it will load the last three days of Binance trades to supplement your history.

MetricexplanationHow to check
OPENCurrently open trades. Open Time displays date and time togetherOpen Positions and Symbol/Direction Contrast
CLOSEDTrade confirmed to be closedCheck Exit Reason and Fill Price
Realized PnLRealized profit and loss based on Binance conclusionMay differ from simple price difference calculation due to fees and multiple partial trades
SERVER STOPClosed with STOP_MARKET order on Binance serversSynchronizes after restart even if the program was signed while it was turned off
Exit ReasonSTOP, TRAILING_TAKE, TIME_EXIT, FAST_EXIT, etc.When analyzing strategy results, separate performance by reason and check
When the numbers are different from Binance: Trade History can be updated after synchronizing the most recent execution. If they do not match immediately, please wait for a while and recheck, and the final settlement standard is Binance's Futures Trade History.

tap guide

Backtest Sweep Tab

Batch test multiple parameter combinations to explore optimal parameters for each regime. Sweep is the step of testing each regime independently to find candidate settings, and verification of actual time-base adaptive performance is performed in the Validation tab.

Sweep method

Independent Cartesian Products by Regime: Parameters within each regime are tested in all combinations (multiplications) and summed across regimes.

Example: QUIET (3 combinations) + NORMAL (12 combinations) + TREND (6 combinations) =Total 21 times Run (21 = 3 + 12 + 6)
What the sweep results mean: Sweep Test independently separates QUIET / NORMAL / TREND / PANIC to find optimal parameters. So the Sweep tab has Adaptive Regime Best Settings and Regime Best Top 10 Ranking only displays. Adaptive Combined performance that reflects actual Top N and time axis regime conversion can be checked in the Validation tab.

Enter parameter list

If you enter multiple values ​​separated by commas (,) in each parameter field, they will be tested as the Cartesian Product of that regime.

# Example: NORMAL regime
ADX Min:  20, 25, 30
ATR Mult: 1.5, 2.0
Vol Mult: 1.2
Trigger R: 1.0, 1.5
Risk %:   0.5

# NORMAL Number of combinations: 3 × 2 × 1 × 2 × 1 = 12
Exit Mode Note: In Backtest Sweep / Validation / Walk-forward, Exit Mode is not subject to sweep. Test by fixing one Exit Mode selected by the user. To compare different Exit Modes, change only the Exit Mode and run again.

Sweep setup parameters

parametersexplanation
Days / Date RangeBacktest period. Recent Days (last N days) or date range can be specified directly
Top NNumber of stocks to use for backtesting. The more there are, the more statistical reliability and time increases.
Decision TF / Execute TF / Trailing TFA three-step timeframe to use for backtesting. Same as actual trading, Decision is used to determine direction, Execute is used for entry timing, and Trailing is used for position close management.
Leverage / WalletBacktest leverage/virtual initial balance (USDT)
Market UniverseCRYPTO / TRADFI / ALL. Determine what to backtest scan
Regime checkboxWhether to include the regime in the sweep

Sweep Combos Card

This card appears on the right side of the Settings box. Based on the current input value, the number of combinations for each regime, the total, and the estimated time required are calculated in real time.

Estimated time formula: Based on total number of combinations × 0.04 seconds × Top N × (Days / 30). Varies depending on actual network environment.
Displayed items: In the Sweep tab Adaptive Combined Result and Daily PnL Charts does not display . Since the purpose of Sweep is not to verify performance but to explore candidate settings for each regime, actual Adaptive performance and daily profit and loss charts are checked in Validation.

Interpretation of results

characteristicmeaningstandard
PF (Profit Factor)Total Profit / Total Loss1.3 or higher is excellent, less than 1.0 is lossable.
Net PnLNet profit (including commissions)Must be a positive number to be valid
Win RateProfit Trade Ratio (%)Standards vary for each strategy. Interpretation with PF
MDDMaximum Drawdown — Maximum drawdown. USDT absolute value class % from high point displayed together.
Example: -234.50 (12.34%)
The lower the better. Caution if % exceeds 20%
TradesTotal number of tradesLess than 10 times, statistical reliability is low (INSUFFICIENT)
ScorePF×0.45 + Net PnL×0.30 + Trades×0.25 Normalized composite scoreBased on top 10 rankings within the regime

Apply Regime Best

After completing the sweep, click the [Apply Regime Best #1] button and the optimal parameters for each regime will be automatically applied to Regime Settings in the Trading tab.

Apply Regime Best #1 copies Strategy, ADX, EMA Gap, ATR, Volume/RSI, Trigger/BB, Risk, and Exit Mode to the Trading tab.
caution: Please make a separate Notes of your current Trading tab settings before applying them. There is no revert function after overwriting.

tap guide

Backtest Validation Tab

The best settings for each regime selected through sweep are verified using an adaptive method on the actual time axis. By reflecting Top N application, regime conversion, position limits, and profit and loss curve together, we confirm results that are close to actual operation.

Sweep vs Validation Comparison

MetricSweepValidation
purposeSearch for optimal parameters by regimeVerification of actual adaptive performance of selected settings
Calculation methodTest each regime independently and separatelyIntegrated execution reflecting Top N and time axis regime conversion
inputParameter list (comma separated)Single parameter value or Sweep Best applied value
resultAdaptive Regime Best Settings + Regime Best Top 10 RankingAdaptive Regime Best Settings + Adaptive Combined Result + Daily PnL Charts
useinitial navigationFinal confirmation and overfitting verification
Meaning of validation results: Validation is not a simple summation estimate of the sweep. This is the Adaptive Combined result calculated by playing the selected Best Settings in actual chronological order. Since the Dynamic Top N and Regime at that time are applied together, the results and figures of Sweep's independent regime may differ.
Recommended verification procedure:
1. Select optimal parameters in sweep
2. Re-verification in another period (Out-of-Sample) with validation
3. If PF ≥ 1.2 or higher in both periods, consider actual operation
Displayed items: In the Validation tab Regime Best Top 10 Ranking does not display . Validation is a verification step, not a candidate search, so it is checked based on the actual Adaptive Combined Result and Daily PnL Charts.

tap guide

Walk-forward tab

Entered in the Validation tab single setpoint By repeatedly applying to multiple time intervals, we check how similar the in-sample (IS) performance remains in the out-of-sample (OOS). Walk-forward is not a function of finding profitable settings, but of the settings you have already chosen. Time base generalization stability This is a function to check.

Sweep·Validation·Walk-forward comparison

functionpurposesettings source
SweepExploring candidate settings in multiple combinationsParameter list in Sweep tab
ValidationVerification of absolute performance of a single selected configurationCurrent settings in the Validation tab
Walk-forwardVerification of IS/OOS performance similarity and stability of identical settingsValidation settings snapshot at execution time
importance: It is not necessary to turn the sweep before running walk-forward. The moment you press the Run button, the Validation tab's Top N, period-related common values, Market, TF, leverage, position limit, active Regime, Strategy·ADX·ATR·Volume/RSI·Trigger/BB·Risk·Exit Mode, and filter settings for each regime are copied once and applied equally to all Windows.

How it works

Sliding Window Structure:
The entire period is divided by the specified number of windows, and the front part of each window is used as IS, and the back part is used as OOS. Calculate IS and OOS with the same validation settings, then compare the similarity of the two results.
# Fix once at run time
Validation Settings Snapshot→ Commonly applied to all Windows W1→ IS calculation + OOS calculation → PF Similarity evaluation W2→ IS calculation + OOS calculation → PF Similarity evaluation W3→ IS calculation + OOS calculation → PF Similarity evaluation
Change settings while running: Even if you change the Validation UI value after walk-forward starts, it will not be reflected in the current execution. The new settings will be used from the next launch.

Setting method

① Validation tab — Prepare a single setting to be validated

Enter the settings you want to validate in the Validation tab. You can apply the Sweep results, or use the settings entered directly by the user.

② Walk-forward tab — Period/Window settings

MetricexplanationRecommended value
Start date / End dateEntire analysis periodSet long enough to cover multiple market phases
Number of windowsDecide how many sliding sections the entire period will be divided into4 to 6
IS rate (%)The proportion of IS in each window. The rest is OOSAround 70%

Result Table Columns

columnmeaninganalysis
IS Trade / OOS TradeNumber of trades in each sectionIf the number of trades is too small, the reliability of PF/WR comparison is low.
IS PF / OOS PFProfit Factor for each sectionAbsolute profitability is interpreted together with validation results
OOS MDDOOS USDT·% display of maximum dropCheck the downside risks arising from OOS
IS WR / OOS WRWin rate for each sectionUsed with PF
WR ΔOOS WR − IS WRThe closer it is to 0, the more stable the win rate is.
Trade RatioOOS number of trades ÷ number of IS tradesBecause the period length is different, it is for reference only for changes in signal density rather than for independent evaluation.
PF Similaritymin(OOS PF ÷ IS PF, IS PF ÷ OOS PF) × 100The closer it is to 100%, the more similar IS and OOS PF are. Even if OOS gets better, it does not exceed 100%
Generalization assessmentAutomatic rating based on PF SimilarityIS/OOS similarity assessment, not absolute profitability
Validation SettingsSnapshot of settings fixed for this runUsed to reproduce results under what conditions

Generalization evaluation criteria

ratingPF Similaritymeaning
ExcellentMore than 90%IS and OOS performance are very similar
GoodMore than 75%Good generalization stability
FairMore than 60%Additional confirmation is required as there are differences.
WeakMore than 40%IS/OOS performance deviation is large
Poorless than 40%Very large performance instability across time intervals
Reasons for using symmetric calculations: For example, if IS PF=1.0 and OOS PF=1.6, simple OOS/IS is 160%, but the two performances cannot be considered similar. PF Similarity is calculated to be approximately 62.5%, which correctly reflects the performance gap.

last summary window

Metricexplanation
Average PF SimilarityAverage similarity of all windows
Lowest PF SimilarityThe most unstable window similarity
OOS PF ≥ 1.0 WindowNumber of windows for which OOS had the beneficial interest. Separate reference from generalization score
Generalization RiskRisk that combines the similarity and lowest section of the entire window. lowness / middle / height Show color with
Interpretation principles: Validation determines “whether this setting makes money well,” and walk-forward determines “whether it works similarly even when the period changes.” You must pass both results together to be considered a candidate for the actual exam.

Recommended Use Procedure

run-time

Sweep removal by window: A single validation setting is applied once each to IS and OOS without re-searching for parameter combinations in each window. Therefore, the amount of execution is approximately Number of windows × 2 times, and is much faster than previous window-specific optimization methods.

Live trading conversion

Final check before live trading begins

If any of the items below are not confirmed, postpone starting actual trading.

First live trading principles: Start with a small amount that will not affect operations even if you lose, and increase the size after checking order, commission, slippage, and profit/loss synchronization in at least dozens of live trading.

strategy principles

Market Regime Classification

At each closing time ATR% Calculate (= ATR ÷ current price × 100) and classify it into 4 regimes. Strategy and parameters are automatically switched depending on the regime.

QUIET
ATR% < 2
Mean Reversion
Exit: BB Mid
NORMAL
2 ≤ ATR% < 4
Trend Following
Exit: trailing / partial_tp
TREND
4 ≤ ATR% < 8
Trend Following
Exit: trailing
PANIC
ATR% ≥ 8
Trend Following
Exit: fast_exit
Frequency of regime changes: Regimes are reclassified at each bar close. The regime at the time of entry determines the position close strategy for the position, and even if the regime changes during holding, the position close logic of the existing position does not change.

Parameter tuning guide for each regime

regimeATR MultReasons for recommendation
QUIET1.0 ~ 1.5Because it is a low-volatility zone, MR risk is limited with narrow stop losses.
NORMAL1.5 ~ 2.0Balance settings. Suitable for use with partial_tp
TREND2.0 ~ 2.5Prevent early stop loss by widening stop loss in strong trends
PANIC2.0 ~ 3.0Extreme volatility. However, since it is a fast_exit, there are many cases where the actual stop loss is not reached.

Strategy Details

Trend Following Strategy

Used in the NORMAL · TREND · PANIC regime. EMA cross + Donchian breakout + surge in trading volume + ADX filter Enter when all four conditions are met.

Usage Metrics

characteristicCalculation methodrole
EMA 20 / 60Exponential moving average, period 20·60Determination of trend direction. EMA20 > EMA60 = Uptrend
ATRSMA method, period 14 (not Wilder RMA)Stop loss, trailing distance, Regime ATR% calculation
ADXSMA method, period 14Trend strength filter. Entry must be ADX ≥ ADX Min
Donchian ChannelHighest/lowest price of the last 20 barsBreakout signal. Closing price > Previous candle Donchian High → LONG
Volume MA20-period simple moving averageVolume surge filter. Volume > MA × Vol Mult
RSIWilder RSI, period 14partial_tp mode secondary exit signal (overbought/oversold)
CIChoppiness Index, period 14 (default)Optional. Blocks sideways entry when adding CI < 61.8 condition
ATR·ADX Accuracy: It uses the SMA method rather than the standard Wilder method. ADX numbers may differ from external charts such as TradingView, but internal consistency is maintained as both live and backtest use the same formula.

Entry conditions (4+1)

conditionEnter LONGEnter SHORT
① Trend directionEMA20 > EMA60EMA20 < EMA60
② Trend strengthADX ≥ ADX MinADX ≥ ADX Min
③ Rapid increase in trading volumeVolume > Volume MA × Vol MulVolume > Volume MA × Vol Mul
④ Price breakthroughWanjeongbong closing price > Ijeonbong Donchian HighDongwanbong closing price < previous peak Donchian Low
⑤ CI filter(select)Added when CI Filter is ON: CI < 61.8

Trailing stop mechanism

stop loss= Entry ATR × ATR Mult
Trailing active distance= Stop Loss × Trigger R
Trailing active conditions= Price movement ≥ trailing active distance
Trailing Stop Renewal= Highest price (LONG) − Stop Loss

Trailing TF When the bar standard ATR changes, the trailing distance is also dynamically updated.

Time Exit

After opening a position 72 hours After this period, compulsory position close will occur. It is a safety net that protects against cases where mean reversion fails over a long period of time.


Strategy Details

Mean Reversion Strategy

Used in the QUIET regime (ATR% < 2, low volatility sideways). Entry occurs when all three conditions are met: Bollinger Band Breakout + RSI Oversold/Overbought + ADX Max Filter, and returns to the BB middle band (SMA20).

Usage Metrics

characteristicCalculation methodrole
Bollinger Bands20 bars SMA ± BB Sigma × σEntry boundary: exit from the lower band (LONG) / exit from the upper band (SHORT). The middle band (SMA20) is the profit target.
RSIWilder RSI, period 14Oversold/overbought confirmation. RSI ≤ RSI Entry → LONG / RSI ≥ (100 − RSI Entry) → SHORT
ATRSMA method, period 14Stop loss. Stop Loss = Entry Price ± ATR × ATR Mult
ADXSMA method, period 14Upper limit filter for checking sideways movements. ADX ≤ ADX must be Max to enter

Entry conditions (all 3)

conditionLONG (oversold rebound)SHORT (overbought and reversal)
① ADX sideways movement confirmedADX ≤ ADX MaxADX ≤ ADX Max
② RSI oversold/overboughtRSI ≤ RSI EntryRSI ≥ (100 − RSI Entry)
③ BB band departureClosing Price < BB Lower (= SMA20 − BB Sigma × σ)Closing price > BB Upper (= SMA20 + BB Sigma × σ)
Without CI filter: MR strategy ignores CI Filter. This is because CI < 61.8 (trend section judgment) does not meet the MR entry conditions. ADX Max does the same.

Exit logic

Profit conditions (LONG) Current price ≥ entry point BB Mid (SMA20)
Profit conditions (SHORT) Current price ≤ entry point BB Mid (SMA20)
stop loss condition Current price ≤ Entry price − ATR × ATR Mult (LONG)
Time Exit Forced position close if position is held for more than 72 hours
BB Mid Target Lock: The profit target is fixed at BB Mid at the time of entry. Even if the actual BB Mid moves while the position is held, the target does not change. If held for a long period of time, it may be closed with a 72h Time Exit before the target is reached.

position close strategy

Position Close priority

In the position monitoring loop, position close conditions are checked in the following order:

priorityposition close conditionscorresponding strategy
1fast_exit: Close the entire amount when the 1R goal is reachedTF PANIC
2partial_tp: 50% partial close when 1R is reached or RSI is overbought/oversoldTF NORMAL
3When BB Mid is reached, all profits are lost.MR QUIET
4Time Exit: Retention exceeds 72 hoursstrategy common
5Stop/Trailing Stop: Price reaches stop loss (local monitor)strategy common
Secondary protectionServer STOP_MARKET: Binance server runs directly when the bot is offline. Automatic cancellation during local position close to avoid overlapping with local position closestrategy common

Risk Management

position sizing

Quantity is calculated based on two criteria and the smaller value is used as the final quantity.

stop loss = Entry ATR × ATR Mult
Risk standard quantity= (Total Balance × Risk%) ÷ Stop Loss
Quantity based on Cap = (Total Balance × Max Position% × Leverage) ÷ Current Price
final quantity = min (Risk-based quantity, Cap-based quantity)
Conditions for skipping orders (safeguards):
• If the final quantity is less than the minQty of the exchange
• When the required margin exceeds 95% of the available balance
• If the same symbol already exists in a local position or on an exchange.

Calculation example

# Settings: Balance=1000 USDT, Risk%=0.5, ATR=50, ATR Mult=2.0
# Leverage=5, Max Position%=15, current price=2000 USDT

stop loss          = 50 × 2.0 = 100 USDT
Risk standard quantity  = (1000 × 0.5%) ÷ 100 = 0.05 units
Quantity based on Cap   = (1000 × 15% × 5) ÷ 2000 = 0.375
final quantity       = min(0.05, 0.375) = 0.05 units
# → Notional 0.05 × 2000 = 100 USDT / Margin = 100 ÷ 5 = 20 USDT

operate

WebSocket & API Structure

PriceWebSocketManager

This is a mark-price WebSocket that only subscribes to currently held positions. Automatically resynchronizes subscriptions when you change positions.

Metricdetail
Backend prioritywebsockets (async) → websocket-client (fallback)
Subscription methodActive-position only: Subscribe to bookTicker/markPrice only for stocks you own
SSLcert_reqs=NONE (Response to certificate issues in some environments)
reconnectWhen changing the subscription type, the existing connection is terminated → automatically reconnected to the new URL
price max_ageWS prices that have elapsed for more than 10 seconds are invalidated → REST fallback

UserDataWebSocketManager (UDS)

Receive account events (position changes, order execution) in real time with the Binance User Data Stream.

Metricdetail
purposeREST Real-time detection of position changes without polling
Listen KeyAutomatic issuance + keepalive renewal every 30 minutes
max_ageIf there is no UDS event for more than 300 seconds, REST safety sync is performed.

REST Fallback

If the WS connects but there is no payload for more than 5 seconds, DashboardThread takes a full price snapshot as REST. GLOBAL_PRICE_CACHE Supplements .

When WS is “Connected” but the price is not updated: API monitorWS Msg/minIf this is 0, the WS is only connected and no payload is received. Since the REST fallback operates automatically, there is no problem with the function. pip install websockets Check out .

operate

API Monitor

You can check the call status of API in real time in the API Monitor panel at the top of the Trading tab.

characteristicDisplay value exampleDescription and normal criteria
Health 🟢 Healthy
🟡 Warning
🔴 Critical
Comprehensive data reception status. Healthy= WS LIVE + price cache 90% or more + fallback 5 times or less. Warning= Partially normal. Critical= Unable to receive price
Data Source LIVE / MIXED
/ REST / OFFLINE
Pricing and account data source. LIVE= WS+UDS are all normal. MIXED= Mixed use of some REST. REST= Only REST without WS. OFFLINE= No data received
Price WS 🟢 LIVE
🟡 Connected(No Data)
🔴 Disconnected
Price WebSocket status. LIVE= Payload received within 5 seconds + cache over 80%. Connected(No Data)= Connected but payload not received → REST fallback in operation
UDS 🟢 LIVE
● Connected
● Reconnecting
User Data Stream status. LIVE= Connect + Receive event within 300 seconds. Connected= Connected but no event (normal when there is no trade). Reconnecting= Reconnecting
Price Cache 28 / 30 (93%) Number of stocks with current prices cached / Total number of stocks scanned (ratio). Anything over 90% is normal. If it is low, WS subscription is missing or REST fallback is insufficient.
Last Price 1.2 sec
waiting
Price Cache Time elapsed since last update (including WS or REST fallback). Normal within 10 seconds. waiting= No price received yet
Last UDS 42.3 sec
no event yet
waiting
UDS (User Data Stream) Time elapsed since the last account event was received. It can get old without a trade — 300 decision within LIVE seconds. no event yet= Connected, but no events yet (normal). waiting= UDS not connected
REST/min 45 (1.9%) Number of calls to REST API in the last minute (ratio compared to Binance per minute limit of 2, 400). Beware of excessive calls when exceeding 10%
WS Msg/min 120 Number of price WS payloads received in the last minute. If 0, only WS connection is established and data is not received → REST fallback is in operation. Increases in proportion to the number of stocks held
REST Fallback/min 0 / 3 Number of times REST price was used instead of WS in the last minute. Normally 0 when WS LIVE, increases when WS is temporarily delayed. The value is automatically updated based on the last minute. Health is judged comprehensively not only by this value but also by Price WS, Cache Fill, and Price Age.
Reconnects 2 Cumulative number of WS reconnections. A small amount is normal (network is temporarily disconnected). If it continues to increase at a rapid rate, check the endpoint and firewall.
Last REST Sync 38 sec
-
Elapsed time since the last REST safety sync (full position collation). UDS Automatically performed when the event gap becomes long. -= No sync yet
WS Version 1.8.0 Installed websocket-client version. Recommended version is 1.8.0. If there is a mismatch, output VERSION WARNING to the startup log.

operate

Troubleshooting

When there is no entry signal at all

causeCheck/Resolve
Regime checkbox OFFCheck whether the checkbox for the relevant regime (NORMAL/TREND, etc.) is ON.
ADX Min is too highIf ADX is above 30, the signal may be rare. Search for optimal values ​​with Sweep
Vol Mult too highTrading volume explosion conditions are too strict. 1.2~1.5 range recommended
CI Filter transient blockingCheck signal occurrence after CI Filter OFF. In sideways markets, CI can always be high
Reach Max PositionsIf the existing position has reached the Max Long/Short limit, new entry is skipped.
Top N too fewIf there are too few stocks to scan, the chances of meeting the conditions are low. Increase Top N or switch TRADFI

WS connection issues

symptomssolve
Price WS: SILENTpip install websockets After restart. Without the websockets package, the websocket-client fallback causes payload not to be received in some environments.
Frequent reconnections occurCheck network stability and check if the Testnet/live trading selection in the API settings window matches the key.
UDS not connectedIn the API settings window, check whether to save the key, Enable Futures permission, and IP restrictions.

Position related

symptomssolve
[POSITION UNMANAGED] logThere is no stop information in the position state file (state/open_positions.json). The position needs to be restored by manual close or restart
Position disappears after restartCheck if open_positions.json exists in the state/ folder. Manual comparison with exchange status when file is damaged
Order omitted due to quantity calculation errorInsufficient balance or less than minQty for price. Increase balance or adjust leverage/Risk%
Attempts to repeatedly enter the same stockNormal operation. Stocks already owned are automatically skipped.
[SERVER STOP ERROR] Repeat outputBinance STOP_MARKET registration failed due to error API. The local stop monitor continues to operate. Check whether API Key has Enable Futures permission. In case of network problem, automatic retry in the next cycle
Position Close recorded as SERVER_STOP_FILLEDNormal operation with Binance server stop while bot is offline. Automatically detects and records in the next monitor cycle after restart
Old STOP orders remain on BinanceCould be a previously created or orphaned stop order left behind by a crash. Recommended manual cancellation and bot restart in Binance app/web

Backtesting is slow

Parallel downloads are limited to workers=2. This is an intentionally restricted setting due to past IP ban cases. Reduce the Top N and duration, or if you already have a downloaded cache, it will be faster on rerun.

Disable Apply Regime Best button

If the button is disabled even after the sweep is completed, backtest_results/parameter_sweep_summary.csv The file does not exist. Check the log to see if the sweep was completed normally.

Live trade conversion: After selecting the live trading mode and live trading key in the API settings window,Live trading final checklistCheck them all out.

reference

Log interpretation

The format and meaning of messages displayed in the Log window are organized in chronological order. In the message {} Parts are replaced with actual values.

① At startup (Startup)

log messageMeaning/Action
Strategy : universe=ALL, top_n=30, entry=15m, trailing=5m, ... Output a summary of settings at startup. Verify that parameters are applied as intended
BASE_URL=https://fapi.binance.com Check mainnet connection. If it is testnet testnet.binancefuture.com mark
Server time synced. offset={n} ms Time synchronization with Binance server completed. If the offset is more than 1,000ms, beware of server time discrepancy.
API KEY / SECRET KEY missing in .env error. No API information saved. Enter and save the Key and Secret in the API settings button at the top of the program.
[WS] Price websocket enabled: active-position bookTicker + REST fallback Pricing WebSocket normal start. Subscribe to only the positions held and REST is waiting
[UDS] User data stream enabled (REST safety sync kept) Starting an account event stream. Real-time reception of closing and position changes
[WS VERSION WARNING] websocket-client 1.9.x may not receive... Warning: websocket-client version is different from recommended (1.8.0). pip install websocket-client==1.8.0 After restart
Symbol universe refresh: 4h fixed Notice that the scanned item universe is automatically updated every 4 hours.
Position restore: supervised=3, exchange-only=1 Result of position restoration upon restart. supervised = number of self-managed restores, exchange-only = number of positions on exchange only, without state file
WARNING: Some existing exchange positions have no saved SL/TP... caution. Position without status file → Automatic stop loss management not possible. Manual Close or Emergency Close Required

② Entry signal (Signal)

log messageMeaning/Action
SIGNAL BTCUSDT LONG / trend_following / REGIME=TREND ATR%=5.21 SET=STRATEGY=trend_following,ADX_MIN25.0,VOL1.5,TRIG1.0,ATR_TRAIL2.0,RISK0.50% Entry signal detection. Check the combination of items, direction, strategy, regime, ATR%, and parameters. Then proceed with position sizing.
BTCUSDT sizing: balance=1000.0, available=850.0, risk=5.0000(0.50%), stop_atr_mult=2.00, notional=240.0000, required_margin≈48.0000 Quantity calculation details. risk=maximum loss amount of position, notional=notional amount of position, required_margin=required margin
BTCUSDT skipped: required_margin=820.0, available=850.0 The order is skipped because the margin exceeds 95% of the available balance. Insufficient balance or need to adjust leverage/risk%
BTCUSDT already in local positions Stocks you already own. Prevent duplicate entries — normal operation
BTCUSDT already exists on exchange There is a position in the same stock on the exchange. Prevent duplicate entries — normal operation
BTCUSDT adjusted qty below minQty The calculated quantity is less than the minimum order quantity. Need to increase balance or adjust Risk%/Leverage

③ Position opening (Open)

log messageMeaning/Action
OPEN BTCUSDT LONG qty=0.050 entry=42000.000000 SL=41520.000000 TRAIL_TRIGGER=42480.000000 TRAIL_DIST=480.000000 TRAIL_TF=5m TRIGGER_R=1.0 ATR_MULT=2.0 RISK=0.50% STRATEGY=trend_following REGIME=TREND ATR%=5.21 Order completion log.
SL= stop loss /TRAIL_TRIGGER= Trailing activation price /TRAIL_DIST= Trailing gap
OPEN ETHUSDT SHORT qty=0.200 ... STRATEGY=mean_reversion REGIME=QUIET ATR%=1.43 Enter the MR strategy. TRAIL_TRIGGER is set as BB Mid position close target price

④ Position monitoring (Monitor)

log messageMeaning/Action
TRAILING ON BTCUSDT LONG trigger=42480.000000 Activate trailing stop. The price reached TRAIL_TRIGGER. Then start tracking the highest price
TRAIL UPDATE BTCUSDT LONG SL=42200.000000 high=42680.000000 Trailing stop loss has been updated upward. high=highest price to date, SL=updated stop loss price
TRAIL UPDATE BTCUSDT SHORT SL=41800.000000 low=41600.000000 SHORT Trailing. low=lowest price, SL=updated stop loss (upward direction)
RSI EXIT SIGNAL BTCUSDT LONG RSI=74.2 RSI overbought → triggers 50% partial close in partial_tp mode. Afterwards, logs PARTIAL and CLOSE follow.
[POSITION UNMANAGED] BTCUSDT: stop/ATR state is missing... caution. Automatic management is not possible as there is no stop loss status information for the position. Manual position close or state file recovery and restart
[POSITION SYNC] REST safety sync OK (3 open exchange positions); next in 60s Successfully synchronized position status with exchange. Performed periodically when UDS event is blank.
[SERVER STOP] BTCUSDT LONG stop=41520.000000 orderId=12345678 STOP_MARKET order registration completed on Binance. Stop loss will be executed at that price even when the bot is offline
[SERVER STOP CANCEL] BTCUSDT orderId=12345678 TRAILING_TAKE Server stop Order cancellation completed. Removed orphaned orders since they were successfully closed locally. Display the reason for position close in the reason field
[SERVER STOP WARN] BTCUSDT cancel failed: {e} Warning: Server stop cancellation failure — if the order has already been placed or the order ID has expired. Generally negligible due to low probability of local position close and duplicate close
[SERVER STOP ERROR] BTCUSDT: {e} error. STOP_MARKET Order registration failed. The local stop monitor continues to operate, but there is no server loss when the bot is offline. API Check permission/network
MANUAL CLOSE DETECTED BTCUSDT LONG PnL=+32.5000 USDT Positions are manually closed outside the program (app/web). Automatic removal from local state
Universe added: XRPUSDT, SOLUSDT Newly added items when the 4-hour universe is updated
Universe removed: DOGEUSDT Stocks excluded from scanning due to falling trading volume rankings

⑤ Close

All exit logs are reason Separate causes by fields.

log messagemeaning
CLOSE BTCUSDT LONG reason=STOP price=41520.000000 PnL=-5.0000 USDT Position Close of stop loss. The price reaches the initial stop loss (SL). In case of stop loss before trailing is activated
CLOSE BTCUSDT LONG reason=TRAILING_TAKE price=42200.000000 PnL=+35.0000 USDT Trailing stop profit. Trailing stop loss is reached by falling by trail_distance compared to the highest price. Position Close from beneficial interest
CLOSE ETHUSDT SHORT reason=MEAN_REVERSION_TAKE price=2050.000000 PnL=+18.0000 USDT MR Ikjeol. The price reaches BB Mid at the entry point. Mean Reversion Goal Achieved
CLOSE SOLUSDT LONG reason=TIME_EXIT price=98.500000 PnL=-2.0000 USDT Forced position close beyond 72 hours. Position held for more than 72 hours. Position Close regardless of profit or loss
CLOSE XRPUSDT SHORT reason=fast_exit price=0.620000 PnL=+8.0000 USDT Quick profit. In fast_exit mode, the entire amount is closed as soon as the 1R goal is reached.
SERVER_STOP_FILLED BTCUSDT LONG PnL=-5.2000 USDT Server stop concluded. While the bot was offline, Binance's STOP_MARKET order was filled, liquidating the position. Detected and recorded in the next monitor cycle after restarting the bot
PARTIAL CLOSE BTCUSDT LONG reason=RSI_EXIT qty=0.025 price=43100.000000 PnL=+27.5000 USDT remaining=0.025 RSI overbought/oversold 50% closed first. Half position close with RSI signal in partial_tp mode. remaining=quantity remaining
PARTIAL CLOSE BTCUSDT LONG reason=partial_tp qty=0.025 price=42480.000000 PnL=+12.0000 USDT remaining=0.025 1R goal reached 50% partial close. Half position close when 1R (stop loss) is achieved in partial_tp mode
{symbol} close skipped: invalid qty Failed to calculate position close quantity → Skip position close. Exchange minQty or less or position quantity error

⑥ Warning & Error

log messageMeaning/Action
[WS WARN] active price symbol sync failed: {e} WS subscription item update failed. Automatic retry in the next cycle. Check network on repeat
[DASHBOARD] REST fallback standby activated for stale WS price cache WS price is old → converted to REST. Automatically occurs when WS is in SILENT state. Normal operation or WS check recommended
[TRAIL INDICATOR ERROR] BTCUSDT: {e} Error calculating trailing ATR. Candle data reception may fail. The bar remains the previous ATR
[PARTIAL CLOSE ERROR] BTCUSDT: {e} 50% partial close order failed. All positions are maintained. Network error or exchange error
[POSITION SYNC ERROR] {e} REST safety sync failed. Retry next cycle. Check API Key permission or network when repeating.
[SCAN ERROR] BTCUSDT: {e} Error while scanning the item. Skip stock, retry in next loop. Check detailed error information when repeating
[UNIVERSE REFRESH ERROR] keep previous symbols: {e} Universe update failure → Previous items maintained. Network or API error
[FATAL] {e} Auto trading thread fatal error. Force ending loop. A restart is required after determining the cause through the log contents.
Auto trader stopped Normally terminated with the Stop button. Maintain existing positions (stop automatic management)

⑦ Backtest log (Backtest)

log messagemeaning
Backtest started. Downloading public Binance Futures kline data... Start backtesting. Downloading candle data
[DATA 5/30] BTCUSDT Data download progress. 5th download out of 30 items
[BACKTEST DATA ERROR] XYZUSDT: {e} Download of relevant item data failed. Skip this item. Delisting, symbol change, etc.
[TREND SWEEP 3/12] ADX25.0_VOL1.5_TRIG1.0_ATR2.0_RISK0.50 TREND Regime Sweep progress. Running 3rd out of 12 combinations. Parameter combination display
Stop Backtest requested. User requests to stop backtesting. Exit after completion of current combination

Example of normal entry to position close log flow

# ① Signal detection
SIGNAL BTCUSDT LONG / trend_following / REGIME=TREND ATR%=5.21 SET=...
# ② Quantity calculation
BTCUSDT sizing: balance=1000.0, available=850.0, risk=5.0000(0.50%), ...
# ③ Entry and conclusion
OPEN BTCUSDT LONG qty=0.050 entry=42000.000000 SL=41520.000000 TRAIL_TRIGGER=42480.000000 ...
# ④ Server stop registration
[SERVER STOP] BTCUSDT LONG stop=41520.000000 orderId=12345678
# ⑤ WS subscription renewal
[WS] Active price stream symbols=3 reason=position_open
# ⑥ Activate trailing
TRAILING ON BTCUSDT LONG trigger=42480.000000
# ⑦ Stop loss update + server stop update (repeat)
TRAIL UPDATE BTCUSDT LONG SL=42200.000000 high=42680.000000
[SERVER STOP] BTCUSDT LONG stop=42200.000000 orderId=12345679
TRAIL UPDATE BTCUSDT LONG SL=42400.000000 high=42880.000000
[SERVER STOP] BTCUSDT LONG stop=42400.000000 orderId=12345680
# ⑧ Position Close + Server stop cancellation
CLOSE BTCUSDT LONG reason=TRAILING_TAKE price=42400.000000 PnL=+20.0000 USDT
[SERVER STOP CANCEL] BTCUSDT orderId=12345680 TRAILING_TAKE

reference

glossary of terms

All terms that appear in the program UI and log are organized in alphabetical order.

Technical Indicators

terminologyDescription and Examples
ATR
Average True Range
Average Amplitude — The standard unit of volatility. The simple average (SMA) of the High-Low range of 14 bars. Used to determine stop loss, position size, and regime.
Example: 15-minute bar BTCUSDT ATR = 120 USDT → Average 120 USDT movement in one bar
ATR%
ATR Percent
The ratio of ATR divided by the current price. Regime classification criteria. ATR% = ATR ÷ Current price × 100
Example: ATR = 120, price = 60,000 → ATR% = 0.2% (QUIET), ATR = 2,400 → ATR% = 4% (TREND)
ADX
Average Directional Index
Trend strength indicator (0~100). Measures only the strength of the trend itself, without direction. If it is above 25, it is generally judged that there is a trend. This program uses the SMA method instead of Wilder RMA.
Example: ADX = 15 → weak trend (sideways), ADX = 35 → strong trend in progress
EMA
Exponential Moving Average
Exponential Moving Average — Higher weighting on recent bars. If EMA20 (short-term) is above EMA60 (long-term), it is judged to be an upward trend, and if it is below, it is a downward trend.
Example: EMA20 = 42,500 / EMA60 = 41,800 → EMA20 > EMA60 → LONG Allow directions
RSI
Relative Strength Index
Overbought/oversold indicator (0~100). Wilder RSI 14-period calculation. Below 30 = oversold, above 70 = overbought. Used for MR entry filter and partial_tp secondary exit.
Example: RSI = 22, RSI Entry = 30 → RSI ≤ 30 met → MR LONG one entry condition passed
BB
Bollinger Bands
Moving average ± standard deviation band. SMA20 ± BB Sigma × σ (standard deviation). MR entry signal when leaving the top/bottom. The middle band (SMA20) is the MR profit target.
Example: SMA20 = 41,000 / σ = 800 / Sigma = 2.0 → Upper = 42,600, Lower = 39,400, Mid = 41,000
Donchian Channel The highest/lowest price channel of recent N peak. Based on 20 bags. The closing price broke through the upper channel → LONG, and broke through the lower channel → SHORT. Conditions for entry into TF strategy.
Example: Highest price of the last 20 bars = 43,100, current bar closing price = 43,250 → Break through the top of Donchian → Condition met
CI
Choppiness Index
Sideways/trend indicator (1~100). Higher values ​​indicate choppiness, lower values ​​indicate trend. If it is above 61.8, it is judged as a sideways trend and TF entry is blocked. Applies only when CI Filter is ON.
Example: CI = 68 → sideways section → If CI Filter is ON, TF entry is skipped
Volume MA Volume moving average (20-week SMA). Among the TF entry conditions, a rapid increase in trading volume filter. To enter, the current bar trading volume must be > Volume MA × Vol Mul.
Example: Volume MA = 500 BTC / Vol Mult = 1.5 → 750 The trading volume must be over BTC to meet the condition.

Setting parameters (Parameters)

terminologyDescription and Examples
Decision TF Candlestick timeframe for judging entry signals. Only closed candles are used for signals. The shorter the signal frequency ↑ the noise ↑.
Example: 15m → Check signal with completion bar every 15 minutes
Trailing TF Timeframe for calculating Trailing Stop ATR. Trailing will respond quickly if set shorter than Decision TF.
Example: Decision TF = 15m / Execute TF = 5m / Trailing TF = 5m → Stop loss update with 5-minute bar ATR
ATR Mult ATR multiple — determines stop loss. Stop Loss = Entry ATR × ATR Mult. If it is low, the stop loss will be narrow (frequent stop loss), if it is high, the stop loss will be wide (large losses at once).
Example: ATR = 120, ATR Mult = 2.0 → Stop loss = 240 USDT (entry price ± 240)
Trigger R (TF) Trailing activation distance multiplier. Trailing begins only when the price moves to the advantage of Trigger R When it is low, fast trailing is active.
Example: Stop Loss = 240, Trigger R = 1.5 → Start trailing when profits exceed 360 USDT
BB Sigma (MR) Bollinger Band standard deviation multiple. The higher it is, the wider the band width is, reducing the frequency of entry. Default 2.0.
Example: Sigma = 2.0 → SMA20 ± 2σ / Sigma = 1.5 → Narrower band, higher entry opportunities.
Vol Mult
/ RSI Entry
Dual parameters with different meaning depending on the strategy.
• TF: Vol Mult — Volume surge multiplier (Volume > MA × Vol Mult)
• MR: RSI Entry — Oversold/Overbought baseline (LONG: RSI ≤ this value)
Example: TF Vol Mult = 1.5 / MR RSI Entry = 30
ADX Min
/ ADX Max
Dual parameters with different meaning depending on the strategy.
• TF ADX Min: Lower limit of trend strength. ADX < If this value does not enter
• MR ADX Max: Upper limit of trend strength. ADX > Do not enter at this value (trend market blocking)
Example: TF ADX Min = 25 / MR ADX Max = 20
Risk % Maximum allowable loss percentage per position. Calculate the quantity so that only Risk% of the balance is lost when one position is stopped.
Example: Balance 1,000 USDT / Risk% = 0.5% → Maximum loss for one position 5 USDT
Max Position % 1 position notional upper limit ratio. Balance × Max Position% × Leverage is the maximum order possible. Use a smaller value compared to the risk standard quantity.
Example: Balance 1,000 / Max Position% = 15% / Leverage 5 → Notional upper limit = 750 USDT
Leverage Futures leverage multiple. Position size multiple over margin. Both profits and losses are multiplied by multiples. Automatically set to the exchange upon entry.
Example: 5x leverage / margin 100 USDT → Notional 500 USDT positions available
Top N The top N stocks with 24-hour trading volume are selected for scanning. Automatically renews every 4 hours. The more, the greater the opportunity·API load increases.
Example: Top N = 30 → Scan entry signals only for USDT futures items ranked 1st to 30th by trading volume

Strategy & Regime

terminologyDescription and Examples
Regime Market status classification. Classified into 4 levels QUIET / NORMAL / TREND / PANIC by ATR%. Strategies and parameters are automatically switched depending on the regime.
Example: ATR% = 5.2% → TREND regime → Apply TF strategy
Trend Following (TF) Trend following strategy. A strategy to follow the trend by entering the breakout point where the up/down trend begins. Used in the NORMAL·TREND·PANIC regime.
Key point: Breakout entry → Follow the trend until the end with a trailing stop
Mean Reversion (MR) Mean reversion strategy. A strategy that enters when the price deviates significantly from the average (BB middle band) and hopes to return to the average. Used in the QUIET regime.
Key point: Breakout below BB + Oversold (RSI) → Entry into LONG → Profit when BB Mid returns
Closed Candle Completed rods — excluding rods that are still in progress. When judging signals in live trading, only the previous completed bar is used, excluding the currently in progress bar (incomplete).
Reason: The price of the ongoing bar keeps changing, so the signal changes frequently → Prevents false signals

Position Close and Risk (Exit & Risk)

terminologyDescription and Examples
Stop Loss Stop loss. Calculated upon entry. Entry price ± ATR × ATR Mult. Automatic position close when the price reaches this point.
Example: LONG entry price 42,000 / stop loss 240 → stop loss = 41,760
Trailing Stop Moving Stop Loss — Follow the stop loss price at the profit zone. Activated after reaching Trigger R. Highest price (LONG) - Stop loss is updated with stop loss. Follow the trend further while protecting your profits.
Example: Highest price 43,200 / Stop loss 240 → Trailing stop = 42,960 (Stop loss updated)
partial_tp Partial profit mode. When 1R (profit equivalent to stop loss) is achieved, 50% of the position is closed first and the remaining 50% continues trailing.
Example: Stop loss 240 → Profit 240 USDT Position Close of half, trailing the rest
fast_exit Fast full-capacity mode. Close the entire amount as soon as the 1R goal is achieved. Confirm profit without following the trend further.
Mainly used in the PANIC (sudden change) regime — Prioritizes quick profit confirmation over large trends
BB Mid (Exit) MR-only wing mode. Set the target price as the mid-BB band (SMA20) at the time of entry. When the price reaches that level, the entire amount is profited. Even if the actual BB Mid moves while held, the target price is fixed.
Example: Upon entry, BB Mid = 41,000 → When the price reaches 41,000, all LONG is closed.
Time Exit Forced position close over time. After 72 hours from opening a position, it is closed at the market price regardless of strategy or profit.
Purpose: To prevent situations where capital is tied up due to long-term failure of MR
Emergency Close Emergency full position close button. Immediate position close of all futures positions on the exchange at market price (Reduce-only). For manual intervention in situations of sudden drops or surges.
Caution: Slippage may occur. Additional losses are possible when profits and losses have already occurred.
Reduce-only Position Close-only order flag. Orders with this flag set are executed only in the direction of reducing the position, not increasing it. Prevents accidental opening of opposing positions.
Emergency Close, next-day order, automatically applied to server STOP_MARKET
STOP_MARKET
Server Stop
Stop loss order registered on Binance servers. When the specified price is reached, the exchange automatically closes at the market price. workingType=MARK_PRICE Use to prevent unreasonable closing due to Last Price spike. reduceOnly=true Therefore, only the remaining position is closed.
Double safety net with stop loss running even when the bot is offline. Automatically canceled upon local position close
Notional Position nominal amount. Quantity × current price. Actual position size, not margin.
Example: 0.05 BTC
Mark Price Position Close standard price. Fair prices provided by Binance. It may be different from the general trade price (Last Price). This program determines stop loss based on Mark Price.
Reason: Last Price has temporary spikes, preventing unreasonable position close with Mark Price.
Position Close Forced position close (roll).) If the margin falls below the maintenance margin, the exchange is forced to close the position. This program's stop loss is preemptively closed before forced position close occurs.
Prevention: Lower leverage and limit Max Position% to reduce position close risk

Backtest Performance Metrics

terminologyDescription and Examples
PF
Profit Factor
Profitability ratio = total profit ÷ total loss. 1.0 = break even, less than 1.0 = loss, 1.3 or more is excellent.
Example: Total profit 1,300 USDT / Total loss 1,000 USDT → PF = 1.3
MDD
Max Drawdown
Maximum drop — USDT Absolute value and % of high point displayed together. The lower the better. Be careful when exceeding 20%.
Example: High balance 1,200 USDT → Low balance 900 USDT → MDD =-300.00 (25.00%)
% calculation criteria: Not the entire high point, but the previous high point (running peak) at the time of occurrence of MDD Contrast.
For example, even if a higher high was formed after MDD, it does not affect the % calculation — because the “actual drop rate at the time” is meaningful.
Win Rate Profit Trade Ratio. The percentage of total trades that ended in profit. It is meaningful only when viewed together with PF. Even if the win rate is low, if the PF is high, the structure is large profit and small loss.
Example: Win Rate 40% + PF 2.0 → Structure to win by quality (trend following model)
Net PnL Net Profit and Loss — Final profit or loss including fees. A positive number is a valid strategy.
Example: Total trading profit +800 USDT / Total loss -600 USDT / Fee -50 USDT → Net PnL = +150 USDT
Score Sweep ranking overall score. Normalized PF × 0.45 + Net PnL × 0.30 + Trades × 0.25. Criteria for selecting the top 10 within the regime.
If the number of trades is too small, the score may be low even if the PF is high.
INSUFFICIENT Insufficient number of trades. As a result of the backtest, if the number of trades is less than 10, the statistical reliability is low and this indicator is warned.
Solution: Increase period, increase Top N, or relax parameters
Cartesian Product Product of all combinations. If you enter 3 values ​​for parameter A and 2 values ​​for parameter B, all 3 × 2 = 6 combinations will be tested.
Example: ADX [20,25,30] × ATR Mult [1.5,2.0] = 6 combination sweeps
Out-of-Sample Validation period not used for optimization. Re-verify the parameters found in sweep through validation in another period (OOS) to check for overfitting.
Example: Sweep period 2025.01~03 → Validation OOS with validation period 2025.04~06

Infrastructure and API (Infrastructure)

terminologyDescription and Examples
WebSocket (WS) Real-time two-way connection protocol. Like REST, the server pushes data without making a request every time. Used to receive real-time prices.
Advantages: Compared to REST, API significantly reduces the number of calls and reduces latency.
REST API Request-response method HTTP API. Data is received only when requested by the client. Used for order execution, balance lookup, and candle data download.
When WS is broken, REST automatically acts as a price fallback
UDS
User Data Stream
WebSocket dedicated to account events. Receive account-related events in real time, such as closing, position change, and balance change. A Listen Key is required and automatically renews every 30 minutes (keepalive).
Advantage: REST position status can be updated immediately upon execution without polling
Listen Key UDS authentication token. One-time key required when subscribing to User Data Stream. Valid for 60 minutes, renewed with keepalive requests every 30 minutes.
When it expires, the UDS connection is disconnected, so the program automatically maintains keepalive
bookTicker Real-time priority quote stream. Immediately sent whenever the highest priority buy/sell price changes. Pricing WebSocket's subscription channel.
This program only subscribes to the bookTicker of the held position items (active-position only)
REST Fallback/min Auxiliary means of querying prices with REST instead of WS. Automatically switches when WS is connected but no data comes. This can be checked with the REST Fallback counter on the API monitor.
0 in normal WS state, increases in WS SILENT state
Testnet Binance Test Environment. A simulated trading environment where no real funds are exchanged. Select API in the settings window, and the testnet API key needs to be issued separately from the live trading.
It is recommended that you first verify it on Testnet before switching to live tradings.
USDT-M Futures USDT based perpetual futures. Binance USDⓈ-M perpetual futures market. Both margin and profit/loss are settled as USDT. What this program deals with.
Different from Coin-M (COIN-M) futures — this program does not support COIN-M
state/ folder Position state persistence storage. Saved with atomic write and automatically restored upon restart.
open_positions.json— Position information such as entry price, stop loss price, strategy, etc. server_stop_order_id·server_stop_price·server_stop_status Fields are also saved and the server stop state is restored after restart.
reentry_cooldowns.json— Re-entry blocking cooldown after a position closes. The cooldown is maintained even after restarting, preventing immediate re-entry into the same symbol immediately after a position closes. When restoring [REENTRY] Cooldown Restore: ['BTCUSDT'] (up to N seconds until expiration) log output
If the file is damaged, position and cooldown cannot be restored — regular backups are recommended.

internal structure

overall architecture

Separate Sweep / Validation roles: Sweep is an independent optimization for each regime, and Validation plays the selected regime best settings in an adaptive manner according to the Top N and time axis regime transitions.

The program operates divided into GUI, data collection, cache, backtest engine, live trading engine, and order execution layer. The core goal is to keep the stock selection, indicator calculation, entry/position close logic of real trading and backtesting as the same as possible, while improving the repeat execution speed with cache.

architecture diagram

PySide6 GUI
  │
  ├─ Trading Tab
  │    ├─ AutoTradeThread
  │    ├─ Price WebSocket
  │    ├─ User Data Stream
  │    └─ Order / Position Manager
  │
  ├─ Backtest Sweep
  │    └─ BacktestThread
  │
  ├─ Backtest Validation
  │    └─ BacktestThread
  │
  └─ Walk-forward
       └─ WalkForwardThread

Binance REST / WebSocket
  │
  ├─ Public Market Data
  │    └─ Candle Cache
  │         └─ Historical Build
  │              └─ Indicator Cache
  │                   └─ market_data Memory Cache
  │                        └─ Backtest / Validation / Walk-forward
  │
  └─ Private Account Data
       ├─ UserDataStream
       ├─ Position State Store
       └─ Order Engine

main components

componentroleNotes
GUITrading, sweep, validation, walk-forward settings and result displayBased on PySide6
AutoTradeThreadReal-time entry scanning, position management, and position close processingLive trading engine
BacktestThreadRun sweep and validation backtestsUse the same strategy conditions as actual trading logic
WalkForwardThreadRepeat IS optimization and OOS verificationFor verification of over-optimization
Candle CacheStore and reuse candle data locallyIncremental updates after initial deployment
Historical BuildCreate internal market_data structure by reading cache candlesOHLCV DataFrame creation steps
Indicator CacheReuse calculation results such as EMA, ATR, ADX, RSI, CI, etc.Improved speed of iterative backtesting
Memory CacheStore market_data with the same data conditions in memoryReuse even when changing strategy parameters
Core principles: Even if the strategy parameters change, the candle data itself does not change. Therefore, Historical Build can be reused even if the ADX, ATR Mult, Volume Mult, Trigger R, Risk %, Exit Mode, and Regime settings change.

data flow

data flow

Separate Sweep / Validation roles: Sweep is an independent optimization for each regime, and Validation plays the selected regime best settings in an adaptive manner according to the Top N and time axis regime transitions.

Data comes from REST and WebSocket, passes through cache and memory structures, and is then delivered to the strategy engine. Real trading and backtesting differ only in the timing of execution, and are designed to use the same indicators and conditions as much as possible.

Live trading data flow

Price WebSocket
      │
      ▼
Global Price Cache
      │
      ▼
Position Monitor / Trailing Stop
      │
      ▼
Order Engine
      │
      ▼
Binance Futures

User Data Stream
      │
      ▼
Balance / Position / Order Event
      │
      ▼
Dashboard / Position State Store

Backtest data flow

Binance REST or Local Candle Cache
      │
      ▼
OHLCV DataFrame
      │
      ▼
Historical Build
      │
      ▼
Indicator Cache
      │
      ▼
market_data
      │
      ▼
Dynamic Top N Universe
      │
      ▼
Strategy Signal
      │
      ▼
Virtual Position/Exit Simulation
      │
      ▼
PnL / MDD / PF / Trade Log

Where data is used

dataWhere to useexplanation
OHLCVBacktest / Validation / Walk-forwardUsed for candle-based indicator calculations and entry/exit simulations
quote_volumeDynamic Top NCalculate past 24-hour trading volume ranking every 4 hours
WebSocket PriceTradingReal-time trailing stop, current price display, position monitoring
User Data EventTrading / DashboardReal-time reflection of trades, position changes, and balance changes
Trade CSVAnalysis/VerificationAnalysis of live trading results and use as future AI analysis data

cache structure

cache structure

Cathy is Disk files (retained across restarts) class Memory during execution (maintained for one backtest) It consists of: Each layer divides roles to minimize API calls and disk I/O.

Cache hierarchy

── Disk (remains after restart) ──────────────────────────────

1. manifest.json candle_cache/manifest.json
   first/last open_time index by symbol (65KB level)
   Used to immediately determine cache freshness without calling API

2. Candle Cache (parquet) candle_cache/{SYMBOL}/{interval}.parquet
   Actual OHLCV candle data (100~200KB per symbol)
   CacheUpdateThread only incrementally adds new candles every 5 minutes

── Memory (maintained while running one backtest) ──────────────────────────

3. manifest_cache Load entire manifest.json when backtest starts
   O(1) freshness check for each symbol → Determine whether to skip API
   Only memory is updated during download, saved once to disk when pass ends

4. market_data {symbol: {entry/execute/trailing: DataFrame}}
   Keep parquet read results in memory
   Reuse when parameter combination changes within the same execution (when TF and period are the same)

5. Indicator Cache {symbol: DataFrame with EMA/ADX/ATR/RSI/CI}
   _precompute_indicators() result
   Shared by all parameter combinations within the same run

market_data reuse conditions

When changing parameter combinations within the same backtest run, whether or not OHLCV data (market_data) can be reused is determined according to the conditions below.

Changed Itemsmarket_data reuseexplanation
ADXSharedOnly the strategy conditions change and the OHLCV data is the same
ATR MultSharedOnly the stop loss calculation value has changed.
Volume MultSharedOnly the entry filter threshold has changed.
Trigger RSharedOnly the criteria for trailing activation have changed.
Risk %SharedOnly the position quantity calculation has changed.
Exit ModeSharedOnly the Exit logic has changed.
Regime ON/OFFSharedOnly changes whether signal is used or not
Top NSharedDynamic Top N list is recalculated but OHLCV is the same
Market UniverserebuildCRYPTO/TRADFI/ALL Universe has changed
Decision TFrebuildThe entry judgment candle itself changes.
Execute TFrebuildActual entry timing candle is different
Trailing TFrebuildATR Trailing calculation candle has changed
periodrebuildRequired candle range varies
Run a new backtestrebuildMemory cache is not shared between executions. However, candle files (parquet) are reused.
reference: When you run a new backtest, market_data is always constructed from scratch. However, if the Candle Cache (parquet) is already built and the manifest confirms freshness, it is completed quickly by just reading SSD without calling API.

Stock selection

Dynamic Top N Algorithm

Dynamic Top N is a function to reduce the difference in stock selection between actual trading and backtesting. Rather than using a fixed Top N list for the entire period, the Top N is re-selected every 4 hours based on trading volume over the past 24 hours.

basic concepts

Every 4 hours:
  1. Sum of quote_volume for the previous 24 hours for each item
  2. Sort by trading volume in descending order
  3. Designate the top N as the active Universe for that 4-hour period.
  4. Continue to manage existing positions
  5. New entries are limited to stocks included in the Top N at the time.

Why Prepare Full Universe Data?

In long-term backtesting, it is impossible to know in advance which stock will enter the Top N due to a surge in trading volume at a specific point in time. Therefore, to maintain the accuracy of Dynamic Top N, the Top N for each 4-hour bucket must be calculated based on the volume data of the entire universe.

2-pass download and ever-active

Only 4h candles are used to calculate trading volume rankings, and strategy TFs (15m/5m, etc.) are downloaded only for symbols that have entered Top N at least once (ever-active). Since the 4h candle is built in advance by the Cache Manager in the background, when running Sweep, Pass 1 mostly performs only cache reads. This drastically reduces the strategic TF download range from full Universe (~500 units) to ever-active (~100 units).

Pass 1: Entire Universe (~500 pieces) × 4h candles
        → 4h cache is pre-built in the background at startup
        → When running Sweep, only parquet is read in the manifest fresh section without API.
        → Dynamic Top N calculation based on 4h vol_data
        → ever_active = Set of symbols included in Top N in any one bucket

Pass 2: ever_active (~100) × Decision / Execute / Trailing TF
        → Configure market_data to be used for actual strategy simulation

※ If ever_active is empty (Pass 1 failure, etc.), "[WARN] Dynamic TopN empty; fallback to static TopN"
  Automatically switches to Static Top N with logs.
Behavior of the section before the first bucket: Since there is no trading volume data in the section immediately after the start of the backtest and before the first 4h bucket is created, entry of all stocks is blocked. It is a conservative design to maintain the accuracy of Dynamic Top N, and even if signals in this section occur, they do not lead to live trading.
Why calculate trading volume with 4h candles? Dynamic Top N updates Universe with 4h buckets. Since the close_time of the 4h candle exactly matches the 4h bucket boundary, there is no 24h rolling window aggregation error. 1d candles close at midnight at UTC, so there is a ±8h discrepancy with the bucket, and 15m candles have no real benefit as the data amount increases by 16 times.
methodmeritdisadvantageaccuracy
Static Top NspeedLack of reflection of changes in trading volume within the periodMay differ from live trading
Dynamic Top NSimilar to the update method for real-time trade itemsIncreased data preparation volume over long periods of timeheight

Behavior when changing Top N

If you change the Top N value from 50 to 100, the OHLCV data will be reused, and only the active stock list for each 4-hour bucket will be recalculated. Therefore, Historical Build can be reused if the Market, Period, and Timeframe are the same.

core: Top N is a filter that determines the universe you can enter, not the data loading range. Dynamic Top N calculates the Top N at each point in time based on the entire universe data.

backtest engine

How the backtest engine works

Separate Sweep / Validation roles: Sweep is an independent optimization for each regime, and Validation plays the selected regime best settings in an adaptive manner according to the Top N and time axis regime transitions.

The backtest engine operates in the following order: data preparation, indicator calculation, Dynamic Top N generation, signal search, virtual execution, position management, and result aggregation.

execution order

Sweep / Validation / Walk-forward difference

modepurposedata downloadParameter execution
SweepSearch for optimal parameters by regime2-pass (4h all + 3TF ever-active)All combination grid search, compare results in table
ValidationDetailed verification of single parameter combinationsSame 2-passRun once, output detailed results for each regime
Walk-forwardIS/OOS similarity verification of single validation setting × N windowSame 2-pass (once for the entire period)When running, fix the validation settings and apply the same to IS·OOS of each window. Data is reused by all windows

fastening model

Backtesting creates virtual positions without placing live orders. We calculate results close to live trading by reflecting fees and slippage.

Metricreflection method
chargeFee rates applied to entry and exit respectively
SleepyConservative reflection of entry/exit prices in bps units
leverageReflected in notional calculation and Max Position limit
Risk %Calculate position quantity based on stop loss
Simultaneous position limitsMax Long / Max Short number limit applied
Simultaneous SL/TP touch within the same rodWhen the high price touches TP and the low price touches SL at the same time on the same candle. SL priority processing. Since the tightening order within the rod cannot be known with just OHLC, a conservative assumption is applied. Results may be slightly lower compared to live trading

Performance Optimization

Performance Optimization

Backtest speed is Download API → Read SSD (parquet) → Calculate indicator → Execute strategy combination They are divided in order. It is a structure that minimizes each step with cache and skip logic.

Speed ​​by execution situation

situationmain taskspeed characteristics
First run (no cache)Download full Universe candle API + save parquetTakes longest (moisture)
Backtest after building the cacheCheck manifest → API 0 times → Read parquet → Calculate indicatorSSD read only (~10 seconds)
Change parameters within the same runReuse market_data + Indicator Cache, re-evaluate only strategy conditionsFastest (in seconds)
TF/Period/Market Changeparquet reread + market_data reconstructionRead SSD (~10 seconds)
Backtest after restarting the programCheck manifest → API 0 times → Read parquet (if there is cache)SSD read only

List of optimization techniques

techniqueseffect
CacheUpdateThread every 5 minutesCache is always kept fresh before running backtests
manifest preloadLoad manifest once when starting backtest → O(1) freshness check for each symbol
Manifest-based API skipWhen refreshing the cache, API is called 0 times, and only parquet is read (Pass 1 × 500 times saved)
2-pass downloadThe entire universe is only once for 4h, and the strategy TF is ever-active (~100)
manifest batch saveSave by symbol → Batch save up to 2 times when pass ends
Temporary file organization episode 1Clean up the .tmp file only once at the start of the backtest (prevent repeated calls)
Indicator CacheCalculate EMA/ATR/ADX/RSI/CI once per symbol, shared by all parameter combinations
Sweep worker-side metric calculationOnly OHLCV sends process boundaries → Each worker calculates independently when initialized. Reduces pickle transmission by not copying a large DataFrame containing indicator columns N times.
Dynamic Top N Recalculation SeparationWhen Top N changes, OHLCV is reused and only the active Universe is recalculated.

Key log interpretation

[Pass 1/2] Download 4h Candles for Volume Ranking: N Symbols
  → Start reading the entire Universe × 4h candle
  zXQPH0000QXZ 0 times if → manifest fresh, only read parquet

[Pass 2/2] Download ever-active N symbol strategy TF
  Read only the symbols in the TopN → at least once Strategy TF

VOL N/M     → {sym} Pass 1 Status
STRAT N/M {sym}   → Pass 2 Progress Status

[WF-VOL N/M]/[WF-STRAT N/M]
  → Walk-forward 2-pass progress status
Recommended usage: You can maximize the reuse of Indicator Cache and market_data by setting the backtest period and Timeframe first, then replacing only the ADX/Volume/Trigger/Risk values with iterative validation. Changing the TF or duration will require a parquet reread, but the API call will not occur (when the cache is fresh).