Pine Script®策略
指標和策略
Heston Multi-Slot PeriodicityHESTON INTRADAY PERIODICITY STRATEGY
ACADEMIC BASIS:
Based on research by Heston, Korajczyk & Sadka (Journal of Finance, 2010).
Finding: "Stock returns in a specific half-hour window show continuation at the SAME time window the next day, persisting for 40+ trading days."
CORE CONCEPT:
If NQ went UP during 10:00-10:30 AM yesterday → likely goes UP during 10:00-10:30 AM today
If NQ went DOWN during 10:00-10:30 AM yesterday → likely goes DOWN during 10:00-10:30 AM today
WHY IT WORKS:
- Institutional VWAP trading (Volume Weighted Average Price algorithms)
- Index rebalancing flows occur at predictable times
- Market-on-close orders create patterns
- Institutions CAUSE the pattern but can't arbitrage it (position size, slippage, mandate restrictions)
STRATEGY RULES:
1. Track yesterday's return in 6 specific half-hour slots
2. At start of each slot today, if yesterday was UP → GO LONG
3. Exit: 30pt stop loss, 90pt target (3:1 R:R), or slot end (whichever first)
4. Longs only (proven 60%+ win rate vs shorts 50%)
TIME SLOTS:
S1: 9:30-10:00 AM (opening flows)
S2: 10:00-10:30 AM (post-open institutional)
S3: 11:00-11:30 AM (mid-morning)
S4: 1:00-1:30 PM (post-lunch)
S5: 2:00-2:30 PM (afternoon rebalancing)
S6: 3:00-3:30 PM (approaching close)
BACKTEST PERFORMANCE (5 months):
- Win Rate: 60.36%
- Profit Factor: 2.537
- Total Trades: 338
- Avg Win: $241 vs Avg Loss: $148 (1.6:1)
- Max Drawdown: $1,240 (0.12%)
EXECUTION:
- 3-6 setups per day
- Fully mechanical (no discretion)
- Scalable to multiple accounts
- Works on NQ futures (NASDAQ 100)
ACADEMIC REFERENCE:
Heston, S.L., Korajczyk, R.A., Sadka, R. (2010). "Intraday Patterns in the Cross-Section of Stock Returns." Journal of Finance, 65(4), 1369-1407.
Pine Script®策略
Swing Strategy Feature Set E [theEccentricTrader]█ OVERVIEW
This swing strategy is part of a broader research and exploration framework designed to encourage users to experiment with a variety of technical concepts and evaluate the comparative effectiveness of different strategy configurations. For example, users can first configure a core strategy as a benchmark, then iteratively test a range of feature configurations as additional entry conditions and compare their performance against one another and against the core strategy.
Feature Set E includes concepts beginning with the letter "E" and forms part of a larger swing strategy suite that covers a wide range of technical concepts. The objective of the suite is not curve-fitting, but rather structured experimentation, exploration and statistical validation (or invalidation) of technical concepts.
Concepts exclusive to the feature set are as follows:
Ease of Movement
█ OPERATIONAL
Initial Capital
The initial capital is defined as a monetary value denominated in a given base currency.
The default initial capital is set to 100,000.
The default base currency is set to the selected symbol's default base currency.
Users can adjust the initial capital and select an alternative base currency via strategy Settings/Properties.
Risk as Percentage of Equity
The equity is defined as the sum of initial capital, net profit and open profit.
The risk is defined as a percentage of equity per-trade. As a result, net profit outcomes are subject to compounding effects over time.
The default risk is set to 1% of equity.
Users can adjust the strategy's per-trade risk via strategy Settings/Inputs/STRATEGY.
For further information on how the risk is applied in practice, refer to the position sizing section below.
Unit of Value
The unit of value is defined as a decimal precision factor that converts user-defined point or pip distances into actual price units used by the selected symbol.
Different symbols express price movement using different conventions. For example, some symbols are quoted directly in whole price points, while others use pips or fractional point increments. The unit of value provides a normalisation layer that allows all distance-based logic in the strategy to operate consistently across symbols.
Examples:
A unit of value of 1 corresponds to a price increment of 1.0.
A unit of value of 10 corresponds to a price increment of 0.1.
A unit of value of 100 corresponds to a price increment of 0.01.
A unit of value of 1000 corresponds to a price increment of 0.001.
A unit of value of 10000 corresponds to a price increment of 0.0001.
Users should consult their broker’s published symbol specifications to confirm how price movement is defined for the symbols they intend to backtest. Incorrect configuration of the unit of value may result in misaligned stop distances, targets and/or risk calculations.
The default unit of value is set to 1.
Users can adjust the unit of value via strategy Settings/Inputs/STRATEGY.
Stop Buffer
The stop buffer is defined as the number of points or pips beyond a stop loss level required for the level to be considered clearly breached.
The default stop buffer is set to 0 points/pips.
Users can adjust the stop buffer via strategy Settings/Inputs/STRATEGY.
Risk Range
The risk range is defined as the difference between the entry price and the stop loss price (inclusive of the stop buffer) for any given trade.
Position Sizing
Position sizing determines the quantity of contracts, shares or units opened for each trade based on the user-defined risk and the selected symbol’s pricing structure.
"syminfo.pointvalue" is a built-in Pine Script variable that defines the number of underlying units contained within a single contract for any given symbol, and is critical for accurate position size calculations.
The position size is calculated as follows:
The risk range is multiplied by the syminfo.pointvalue to convert the price movement into its monetary equivalent.
The user-defined risk amount (expressed as a percentage of equity) is divided by this monetary risk per unit to determine the position size.
This ensures that each trade risks a consistent proportion of account equity regardless of point or pip based quoting conventions, symbol price scale or contract specifications.
While the strategy targets a fixed percentage of equity risk per-trade, the exact risk applied cannot always be matched precisely due to symbol-specific constraints such as contract sizing and margin requirements. In these cases, the strategy opens the largest permissible position that does not violate operational constraints, resulting in a realised risk that is as close as possible to the user-defined risk without exceeding it.
For further information on the syminfo.pointvalue variable, please refer to:
www.tradingview.com
Margin
The margin is defined as the minimum percentage of a position’s notional value that must be covered by the strategy’s available equity in order for TradingView's strategy tester to simulate opening and maintaining that position. For example, a margin setting of 25% means the simulated account must hold equity equal to at least 25% of the position’s notional value in order to enter or maintain that trade, the remaining 75% is considered provided by the simulated broker.
A lower margin percentage allows the account to open larger positions relative to its equity, because the required equity portion is smaller. Conversely, a higher margin percentage demands more of the account's equity be committed to any given position.
When the account’s equity falls below the required margin, the strategy tester emulates a margin call event, in which the broker emulator forcibly closes or reduces positions so that remaining positions no longer exceed available equity relative to the margin requirement. This behaviour is documented as part of TradingView’s margin/leverage feature for strategies.
Margin settings in a strategy are used solely for simulation purposes and do not automatically match any broker’s real-world margin requirements (which can vary by broker, asset class and symbol). Users should consult their broker’s published specifications for further details.
The default margin is set to 25% for both long and short positions.
Users can adjust the margin for long and short positions independently via strategy Settings/Properties/MARGIN.
For further information on the strategy tester's margin functionality, please refer to:
www.tradingview.com
www.tradingview.com
Pyramiding
The pyramiding count is defined as the maximum number of open positions permitted at any one time. TradingView's strategy tester does not facilitate hedging, as such, long entries will close any open short positions and short entries will close any open long positions.
The default pyramiding count is set to 100.
Users can adjust the pyramiding count via strategy Settings/Properties.
For further information on TradingView's strategy tester and broker emulator, please refer to:
www.tradingview.com
Spread
The spread is defined as the difference between a given symbol's bid (buy) price and ask (sell) price.
Typical spreads vary by broker and symbol. Some brokers offer fixed spreads on certain symbols, while others offer variable spreads that fluctuate with market conditions. Users should consult their broker's published specifications for further details.
Commission
The commission is defined as a transaction cost applied by a broker and may be expressed as a percentage of position size, a per-contract fee or a fixed fee per-transaction.
Commission structures vary by broker and symbol. Some brokers charge no explicit commission and instead generate revenue through the spread or other indirect sources, while others will typically apply one of the three aforementioned commission types, depending on the product offered. Users should consult their broker's published specifications for further details.
The default commission is set to 0.005% of position size.
Users can select and adjust the commission type via strategy Settings/Properties/COST SIMULATION.
█ CORE STRATEGY
Green and Red Candles
A green candle is defined as a candle that closes at or above its open price and a red candle is defined as a candle that closes below its open price.
Swing Highs and Swing Lows
A swing high is defined as a green candle, or a series of consecutive green candles, followed by a single red candle that completes the swing and forms the peak.
A swing low is defined as a red candle, or a series of consecutive red candles, followed by a single green candle that completes the swing and forms the trough.
Peak and Trough Prices
The peak price of a complete swing high is either the high of the red candle that completes the swing high or the high of the preceding green candle, depending on which is higher.
The trough price of a complete swing low is either the low of the green candle that completes the swing low or the low of the preceding red candle, depending on which is lower.
Fixed Reward-to-Risk
Fixed reward-to-risk is defined as a user-defined reward multiple for a given unit of risk.
Variable Reward-to-Risk
Variable reward-to-risk is defined as a path-dependent reward multiple for a given unit of risk.
Swing High Swing Low (SHSL) Strategy
The SHSL strategy uses swing lows for core long entry conditions and swing highs for core short entry conditions. The strategy is designed for standard OHLC candlestick charts only and will not behave as intended on other chart types.
All entries are processed at candle close and use the candle close price for the entry price.
Long stop losses are anchored to the most recent trough and short stop losses are anchored to the most recent peak.
Users can choose between long-only and short-only configurations, or alternatively simulate trades in both directions (long-short). However, when the "Both" option is selected, long entries will close any open short positions and short entries will close any open long positions (as mentioned in the pyramiding sub-section above). This can and will result in variable reward-to-risk outcomes.
The default direction is set to "Long" for a long-only configuration.
The default exit type is set to "Target" for a fixed reward-to-risk configuration.
Long targets are determined by adding a user-defined multiple of the risk range to the entry price and short targets are determined by subtracting a user-defined multiple of the risk range from the entry price.
Even when using a fixed reward-to-risk configuration, realised reward-to-risk outcomes may vary due to market gaps, particularly when positions are held across session boundaries or market closures. Gaps can cause stop losses or exits to be executed at prices materially different from those implied by the strategy’s static distance calculations. Users who wish to minimise gap-related variability may consider applying the close at end of session filter (see core filters section below), accepting that this introduces its own form of reward-to-risk variability.
The default reward-to-risk is set to 1.
Users can adjust strategy parameters via strategy Settings/Inputs/STRATEGY. Selecting a non-target exit type removes profit targets and renders the reward-to-risk input inactive.
Trailing Stop Loss
A trailing stop loss is defined as an exit type that dynamically moves a stop loss level in a favourable direction when a predefined condition is met. For example, a predefined point move or the formation of a higher trough or lower peak.
Risk Range Trailing Stop Loss
The risk range trailing stop loss is defined as a trailing stop mechanism that activates once price has moved favourably by one full risk range. Upon activation, the stop loss is moved to breakeven and subsequently trails favourable price movement by the risk range into profit.
Users can apply this exit type by selecting "Trail" via strategy Settings/Inputs/STRATEGY.
Trend Trailing Stop Loss
The trend trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher troughs (for longs) or lower peaks (for shorts).
Users can apply this exit type by selecting "Trend Trail" via strategy Settings/Inputs/STRATEGY.
Candle Trailing Stop Loss
The candle trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher candle lows (for longs) or lower candle highs (for shorts).
Users can apply this exit type by selecting "Candle Trail" via strategy Settings/Inputs/STRATEGY.
Opposing Candle Colour Close
The opposing candle colour close exit type is defined as an exit condition that closes any long positions when a new red candle forms and closes any short positions when a new green candle forms.
Users can apply this exit type by selecting "Opposing Candle" via strategy Settings/Inputs/STRATEGY.
█ CORE FILTERS
Minimum Risk Range Filter
The minimum risk range filter is defined as an entry filter that invalidates trade signals with a risk range below a user-defined threshold.
The default minimum risk range is set to 4 points/pips.
Users can adjust the minimum risk range via strategy Settings/Inputs/RISK RANGE FILTER.
It is recommended that users set the minimum risk range at least 1–2 points/pips above the selected symbol’s spread to invalidate trades that would be completely impractical under realistic trading conditions.
Time Zone
The time zone is defined using either an IANA region identifier (e.g. Europe/London, America/New_York) or a fixed UTC/GMT offset (e.g. UTC+1, GMT-05:30). Fixed offsets do not account for daylight saving time.
The default time zone is set to Europe/London.
Users can change the time zone via strategy Settings/Inputs/TIME ZONE.
For further information on time zone configuration, please refer to:
data.iana.org
en.wikipedia.org
Session Filter
The session filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined intraday trading session, with session start and end times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, session boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered or held beyond the intended session end, users should configure the session end time at least one full timeframe period earlier than the desired practical session close. For example, on a 5-minute chart with a desired session end at 22:00, the session should typically be configured to end at 21:55. This ensures that no new trades are taken at the final session close and that any session-dependent exit logic is applied before the session ends in practice.
When using custom or non-standard timeframes where the desired session end does not align cleanly with candle boundaries, it is recommended that users set the session end two full timeframe periods earlier than the desired session end. This provides an additional safety buffer, ensuring the strategy avoids taking trades near the session boundary.
By default, the session filter is set to false and the default session is set to "2300-2155".
Users can apply the session filter and adjust session boundaries via strategy Settings/Inputs/SESSION FILTER.
Close At End of Session Filter
The close at end of session filter is defined as an exit filter that closes all open positions when the active trading session ends, provided that the session filter is appropriately configured and applied.
When enabled, the strategy monitors the session filter state and detects the transition from an active session to an inactive session. All open trades are closed on the first candle that falls outside the defined session window. This ensures that no positions are carried beyond the user-defined trading session.
The close at end of session filter operates independently of entry conditions and other exit types. When enabled, it will force the closure of all open positions at session end regardless of the selected exit configuration.
Enabling the close at end of session filter can result in variable reward-to-risk outcomes. Because positions are forcibly closed at session end regardless of stop loss or target placement, exits may occur at prices that differ from those implied by the fixed reward-to-risk configuration. This behaviour is intentional and reflects a design trade-off between enforcing strict session boundaries and allowing trades to reach their predefined directional objectives, regardless of how severely distorted the realised reward-to-risk outcomes could be in the event of price gaps.
By default, the close at end of session filter is set to false.
Users can apply the close at end of session filter via strategy Settings/Inputs/CLOSE AT END OF SESSION FILTER.
Users should also ensure that the session filter is applied and that session boundaries are configured appropriately with respect to candle timestamp behaviour, as described in the session filter section above.
Sample Period Filter
The sample period filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined date-time range, with start and end date-times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, sample period boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered beyond the intended sample period end, users should configure the sample period end date-time at least one full timeframe period earlier than the desired practical sample period end date-time. For example, on a 5-minute chart with a desired end date-time of 01/01/2026 22:00, the end date-time should typically be configured to 01/01/2026 21:55.
The default sample period start and end date-times are set to 01/01/1900 00:00 and 01/01/3000 00:00, respectively.
Users can adjust the sample period via strategy Settings/Inputs/SAMPLE PERIOD FILTER.
█ GENERIC FILTERS
Generic Filter Behaviour
Unless otherwise stated:
"None" inputs return true.
Filters return true only when their selected condition is satisfied.
Minimum Percentage Change Positive-Flat/Negative Filter
The minimum percentage change filter is an entry filter that measures the relative change of a time-series value over a configurable historical window and applies a directional threshold condition, invalidating trade signals that do not meet the directional threshold criteria.
The filter compares the current value to its value n bars ago and computes the percentage difference. A signal returns true only if this percentage change satisfies both:
The selected directional requirement.
The user-defined minimum percentage change magnitude.
"Positive-Flat" direction logic:
Accepts values that have increased or remained unchanged, provided the percentage change is greater than or equal to the minimum threshold.
"Negative" direction logic:
Accepts values that have decreased, provided the magnitude of the decrease meets or exceeds the minimum threshold.
When the minimum threshold is set to 0%, the filter behaves as a pure directional check:
"Positive-Flat" accepts ≥ 0% changes.
"Negative" accepts < 0% changes only.
Basic and Multi-Part Trend Filters
Basic and multi-part trend filters are defined as entry filters that evaluate changes in time-series values from one period to the next and invalidate trade signals that do not satisfy a user-defined trend condition.
Basic trends operate independently of prior trend state, whereas multi-part trends are defined by the presence or absence of preceding trend sequences. The multi-part trend states are distinguished numerically and the conditions are bound to a user-defined trend count.
"Basic Uptrend" returns true when a time-series value is greater than the preceding value. For example, a basic volume uptrend filter returns true if the most recent candle's volume is greater than the preceding candle's volume.
"Basic Downtrend" returns true when a time-series value is less than the preceding value. For example, a basic volume downtrend filter returns true if the most recent candle's volume is less than the preceding candle's volume.
"Uptrend" returns true while a multi-part uptrend state is valid. The uptrend state begins when a new basic uptrend forms following a basic downtrend and remains valid until a new basic downtrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part uptrend conditions will return true.
"Downtrend" returns true while a multi-part downtrend state is valid. The downtrend state begins when a new basic downtrend forms following a basic uptrend and remains valid until a new basic uptrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part downtrend conditions will return true.
█ FEATURE SET E SPECIFIC FILTERS
All feature set specific indicators use the same calculations as the built-in TradingView indicators unless otherwise stated in the relevant filter sub-section. While users do not need to apply the indicators for the strategy to function, they can of course apply the relevant indicators as visual aids if they so desire.
For further information on how to apply built-in TradingView indicators, please refer to:
www.tradingview.com
Ease of Movement (EOM) Filters
The default EOM inputs are as follows:
Length is set to 14.
Divisor is set to 10000.
Users can adjust the EOM inputs via strategy Settings/Inputs/Ease of Movement (EOM).
The EOM above-equal/below zero filter is defined as an entry filter that evaluates the EOM value relative to the zero line and invalidates trade signals that do not satisfy a user-defined directional condition.
The default EOM above-equal/below zero filter mode is set to "None".
The EOM minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The EOM trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the EOM filters and adjust filter parameters via strategy Settings/Inputs/EOM FILTERS.
█ ALERTS
Users can set alerts for any given strategy configuration via the alerts dialogue box.
Users must first ensure that the correct condition (the strategy title) is selected from the first drop-down list in the alert dialogue box's condition field.
Default alert messages have been configured for both entries and exits so that users can more effectively distinguish between long and short entries and exits while using long-short configurations.
To get alerts for both entries and exits the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "Order fills only". When using "Order fills only" with long-short configurations, it is recommended that users define their alert via the alert name field and use only the default {{strategy.order.alert_message}} call in the alert message field.
Alert conditions generated by "Order fills only" are evaluated after entry conditions have been satisfied and operational constraints (risk, position size and margin requirements) have been applied. As such, trade signals that would result in position sizes exceeding the simulated account's margin constraints will not generate alerts.
To get alerts for entries only the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "alert() function calls only".
The default alert messages generated by "Order fills only" are as follows:
"long entry".
"long exit".
"short entry".
"short exit".
The default alert messages generated by "alert() function calls only" are as follows:
"long entry".
"short entry".
Alert conditions generated by "alert() function calls only" are operational-constraint-agnostic and will generate alerts whenever entry conditions are satisfied, regardless of the simulated account's margin constraints.
For further information on setting and managing alerts, please refer to:
www.tradingview.com
www.tradingview.com
www.tradingview.com
█ LIMITATIONS AND CONSIDERATIONS
Backtesting
Backtest results should always be interpreted cautiously. Strategy performance can vary significantly across time periods and sample sets. While strong historical performance does not guarantee future results, poor historical performance reliably indicates a weak strategy when sample sizes are statistically meaningful.
Statistical Significance and Path-Dependent Outcomes (Overfitting)
In statistical practice, sample sizes of 100 observations are sometimes cited as a rough lower bound for certain forms of basic significance testing. In the context of trading strategy evaluation, such sample sizes are rarely sufficient to produce results that are meaningfully reliable or replicable. Based on practical experience, sample sizes closer to 1,000 observations or more are generally required before performance characteristics begin to stabilise. As a general rule, larger sample sizes increase the reliability and replicability of observed results.
Path dependence refers to situations in which outcomes are determined not only by initial conditions, but by the specific and unique sequence of price movements over a given time period.
Even with large sample sizes, favourable net profit outcomes should be interpreted with caution when they are primarily driven by either variable reward-to-risk configurations or fixed reward-to-risk configurations that employ unrealistically high reward multiples. In both cases, performance is often strongly influenced by path-dependent effects, making such outcomes less reliable and less replicable.
Fixed reward-to-risk configurations are generally less susceptible to path dependence when the reward multiple is kept within reasonable bounds. However, empirical studies and practitioner research suggest that reward multiples above approximately 3:1 increasingly exhibit the same path-dependent characteristics observed in variable reward-to-risk strategies.
Bar Magnifier
Due to the limitations of OHLC data, intra-bar price movement cannot be precisely determined.
When both stop loss and target levels are reached within the same candle, assumptions are made by the strategy tester.
Pine Script's bar magnifier partially mitigates this limitation by evaluating lower-timeframe data. However, this feature is available only to TradingView Premium users and remains inherently limited.
For further information on the bar magnifier functionality, please refer to:
www.tradingview.com
www.tradingview.com
TradingView Premium users can enable bar magnifier via strategy Settings/Properties/FILL ORDERS.
Processing Orders at Candle Close
Backtests cannot accurately account for slippage between signal generation and trade execution.
A practical mitigation is to use fixed-distance stop losses and targets rather than absolute price levels, a feature supported by many brokers and APIs.
Empirical Probabilities
Empirical probabilities are derived directly from observed outcomes rather than from theoretical models or assumed distributions. In the context of trading, they are calculated by measuring the relative frequency of events (such as wins and losses) across a large sample of historical trades.
Unlike conditional or model-based probabilities, empirical probabilities make no assumptions. Their validity relies primarily on sample size and the consistency of the rules used to generate observations, making them particularly relevant for trading systems evaluated under the law of large numbers.
Empirical probabilities are most useful for comparative analysis, such as assessing how different configurations, filters or exit mechanisms alter the statistical behaviour of a strategy under identical conditions. They are not intended to represent true predictive probabilities or to imply stable future performance.
To study empirical probabilities for comparative purposes, it is recommended that users set commission and both long and short margin values to 0% in order to maximise sample size. However, users should not interpret any resulting profits as realistic. Setting commission and margin (in particular) to 0% produces highly distorted outcomes that are not representative of realistic live trading conditions.
█ DISCLAIMER
This Pine Script strategy is provided for educational purposes only and does not constitute financial advice in any form.
Pine Script®策略
Swing Strategy Feature Set D [theEccentricTrader]█ OVERVIEW
This swing strategy is part of a broader research and exploration framework designed to encourage users to experiment with a variety of technical concepts and evaluate the comparative effectiveness of different strategy configurations. For example, users can first configure a core strategy as a benchmark, then iteratively test a range of feature configurations as additional entry conditions and compare their performance against one another and against the core strategy.
Feature Set D includes concepts beginning with the letter "D" and forms part of a larger swing strategy suite that covers a wide range of technical concepts. The objective of the suite is not curve-fitting, but rather structured experimentation, exploration and statistical validation (or invalidation) of technical concepts.
Concepts exclusive to the feature set are as follows:
Day of Week
Directional Movement Index
Donchian Channel
█ OPERATIONAL
Initial Capital
The initial capital is defined as a monetary value denominated in a given base currency.
The default initial capital is set to 100,000.
The default base currency is set to the selected symbol's default base currency.
Users can adjust the initial capital and select an alternative base currency via strategy Settings/Properties.
Risk as Percentage of Equity
The equity is defined as the sum of initial capital, net profit and open profit.
The risk is defined as a percentage of equity per-trade. As a result, net profit outcomes are subject to compounding effects over time.
The default risk is set to 1% of equity.
Users can adjust the strategy's per-trade risk via strategy Settings/Inputs/STRATEGY.
For further information on how the risk is applied in practice, refer to the position sizing section below.
Unit of Value
The unit of value is defined as a decimal precision factor that converts user-defined point or pip distances into actual price units used by the selected symbol.
Different symbols express price movement using different conventions. For example, some symbols are quoted directly in whole price points, while others use pips or fractional point increments. The unit of value provides a normalisation layer that allows all distance-based logic in the strategy to operate consistently across symbols.
Examples:
A unit of value of 1 corresponds to a price increment of 1.0.
A unit of value of 10 corresponds to a price increment of 0.1.
A unit of value of 100 corresponds to a price increment of 0.01.
A unit of value of 1000 corresponds to a price increment of 0.001.
A unit of value of 10000 corresponds to a price increment of 0.0001.
Users should consult their broker’s published symbol specifications to confirm how price movement is defined for the symbols they intend to backtest. Incorrect configuration of the unit of value may result in misaligned stop distances, targets and/or risk calculations.
The default unit of value is set to 1.
Users can adjust the unit of value via strategy Settings/Inputs/STRATEGY.
Stop Buffer
The stop buffer is defined as the number of points or pips beyond a stop loss level required for the level to be considered clearly breached.
The default stop buffer is set to 0 points/pips.
Users can adjust the stop buffer via strategy Settings/Inputs/STRATEGY.
Risk Range
The risk range is defined as the difference between the entry price and the stop loss price (inclusive of the stop buffer) for any given trade.
Position Sizing
Position sizing determines the quantity of contracts, shares or units opened for each trade based on the user-defined risk and the selected symbol’s pricing structure.
"syminfo.pointvalue" is a built-in Pine Script variable that defines the number of underlying units contained within a single contract for any given symbol, and is critical for accurate position size calculations.
The position size is calculated as follows:
The risk range is multiplied by the syminfo.pointvalue to convert the price movement into its monetary equivalent.
The user-defined risk amount (expressed as a percentage of equity) is divided by this monetary risk per unit to determine the position size.
This ensures that each trade risks a consistent proportion of account equity regardless of point or pip based quoting conventions, symbol price scale or contract specifications.
While the strategy targets a fixed percentage of equity risk per-trade, the exact risk applied cannot always be matched precisely due to symbol-specific constraints such as contract sizing and margin requirements. In these cases, the strategy opens the largest permissible position that does not violate operational constraints, resulting in a realised risk that is as close as possible to the user-defined risk without exceeding it.
For further information on the syminfo.pointvalue variable, please refer to:
www.tradingview.com
Margin
The margin is defined as the minimum percentage of a position’s notional value that must be covered by the strategy’s available equity in order for TradingView's strategy tester to simulate opening and maintaining that position. For example, a margin setting of 25% means the simulated account must hold equity equal to at least 25% of the position’s notional value in order to enter or maintain that trade, the remaining 75% is considered provided by the simulated broker.
A lower margin percentage allows the account to open larger positions relative to its equity, because the required equity portion is smaller. Conversely, a higher margin percentage demands more of the account's equity be committed to any given position.
When the account’s equity falls below the required margin, the strategy tester emulates a margin call event, in which the broker emulator forcibly closes or reduces positions so that remaining positions no longer exceed available equity relative to the margin requirement. This behaviour is documented as part of TradingView’s margin/leverage feature for strategies.
Margin settings in a strategy are used solely for simulation purposes and do not automatically match any broker’s real-world margin requirements (which can vary by broker, asset class and symbol). Users should consult their broker’s published specifications for further details.
The default margin is set to 25% for both long and short positions.
Users can adjust the margin for long and short positions independently via strategy Settings/Properties/MARGIN.
For further information on the strategy tester's margin functionality, please refer to:
www.tradingview.com
www.tradingview.com
Pyramiding
The pyramiding count is defined as the maximum number of open positions permitted at any one time. TradingView's strategy tester does not facilitate hedging, as such, long entries will close any open short positions and short entries will close any open long positions.
The default pyramiding count is set to 100.
Users can adjust the pyramiding count via strategy Settings/Properties.
For further information on TradingView's strategy tester and broker emulator, please refer to:
www.tradingview.com
Spread
The spread is defined as the difference between a given symbol's bid (buy) price and ask (sell) price.
Typical spreads vary by broker and symbol. Some brokers offer fixed spreads on certain symbols, while others offer variable spreads that fluctuate with market conditions. Users should consult their broker's published specifications for further details.
Commission
The commission is defined as a transaction cost applied by a broker and may be expressed as a percentage of position size, a per-contract fee or a fixed fee per-transaction.
Commission structures vary by broker and symbol. Some brokers charge no explicit commission and instead generate revenue through the spread or other indirect sources, while others will typically apply one of the three aforementioned commission types, depending on the product offered. Users should consult their broker's published specifications for further details.
The default commission is set to 0.005% of position size.
Users can select and adjust the commission type via strategy Settings/Properties/COST SIMULATION.
█ CORE STRATEGY
Green and Red Candles
A green candle is defined as a candle that closes at or above its open price and a red candle is defined as a candle that closes below its open price.
Swing Highs and Swing Lows
A swing high is defined as a green candle, or a series of consecutive green candles, followed by a single red candle that completes the swing and forms the peak.
A swing low is defined as a red candle, or a series of consecutive red candles, followed by a single green candle that completes the swing and forms the trough.
Peak and Trough Prices
The peak price of a complete swing high is either the high of the red candle that completes the swing high or the high of the preceding green candle, depending on which is higher.
The trough price of a complete swing low is either the low of the green candle that completes the swing low or the low of the preceding red candle, depending on which is lower.
Fixed Reward-to-Risk
Fixed reward-to-risk is defined as a user-defined reward multiple for a given unit of risk.
Variable Reward-to-Risk
Variable reward-to-risk is defined as a path-dependent reward multiple for a given unit of risk.
Swing High Swing Low (SHSL) Strategy
The SHSL strategy uses swing lows for core long entry conditions and swing highs for core short entry conditions. The strategy is designed for standard OHLC candlestick charts only and will not behave as intended on other chart types.
All entries are processed at candle close and use the candle close price for the entry price.
Long stop losses are anchored to the most recent trough and short stop losses are anchored to the most recent peak.
Users can choose between long-only and short-only configurations, or alternatively simulate trades in both directions (long-short). However, when the "Both" option is selected, long entries will close any open short positions and short entries will close any open long positions (as mentioned in the pyramiding sub-section above). This can and will result in variable reward-to-risk outcomes.
The default direction is set to "Long" for a long-only configuration.
The default exit type is set to "Target" for a fixed reward-to-risk configuration.
Long targets are determined by adding a user-defined multiple of the risk range to the entry price and short targets are determined by subtracting a user-defined multiple of the risk range from the entry price.
Even when using a fixed reward-to-risk configuration, realised reward-to-risk outcomes may vary due to market gaps, particularly when positions are held across session boundaries or market closures. Gaps can cause stop losses or exits to be executed at prices materially different from those implied by the strategy’s static distance calculations. Users who wish to minimise gap-related variability may consider applying the close at end of session filter (see core filters section below), accepting that this introduces its own form of reward-to-risk variability.
The default reward-to-risk is set to 1.
Users can adjust strategy parameters via strategy Settings/Inputs/STRATEGY. Selecting a non-target exit type removes profit targets and renders the reward-to-risk input inactive.
Trailing Stop Loss
A trailing stop loss is defined as an exit type that dynamically moves a stop loss level in a favourable direction when a predefined condition is met. For example, a predefined point move or the formation of a higher trough or lower peak.
Risk Range Trailing Stop Loss
The risk range trailing stop loss is defined as a trailing stop mechanism that activates once price has moved favourably by one full risk range. Upon activation, the stop loss is moved to breakeven and subsequently trails favourable price movement by the risk range into profit.
Users can apply this exit type by selecting "Trail" via strategy Settings/Inputs/STRATEGY.
Trend Trailing Stop Loss
The trend trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher troughs (for longs) or lower peaks (for shorts).
Users can apply this exit type by selecting "Trend Trail" via strategy Settings/Inputs/STRATEGY.
Candle Trailing Stop Loss
The candle trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher candle lows (for longs) or lower candle highs (for shorts).
Users can apply this exit type by selecting "Candle Trail" via strategy Settings/Inputs/STRATEGY.
Opposing Candle Colour Close
The opposing candle colour close exit type is defined as an exit condition that closes any long positions when a new red candle forms and closes any short positions when a new green candle forms.
Users can apply this exit type by selecting "Opposing Candle" via strategy Settings/Inputs/STRATEGY.
█ CORE FILTERS
Minimum Risk Range Filter
The minimum risk range filter is defined as an entry filter that invalidates trade signals with a risk range below a user-defined threshold.
The default minimum risk range is set to 4 points/pips.
Users can adjust the minimum risk range via strategy Settings/Inputs/RISK RANGE FILTER.
It is recommended that users set the minimum risk range at least 1–2 points/pips above the selected symbol’s spread to invalidate trades that would be completely impractical under realistic trading conditions.
Time Zone
The time zone is defined using either an IANA region identifier (e.g. Europe/London, America/New_York) or a fixed UTC/GMT offset (e.g. UTC+1, GMT-05:30). Fixed offsets do not account for daylight saving time.
The default time zone is set to Europe/London.
Users can change the time zone via strategy Settings/Inputs/TIME ZONE.
For further information on time zone configuration, please refer to:
data.iana.org
en.wikipedia.org
Session Filter
The session filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined intraday trading session, with session start and end times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, session boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered or held beyond the intended session end, users should configure the session end time at least one full timeframe period earlier than the desired practical session close. For example, on a 5-minute chart with a desired session end at 22:00, the session should typically be configured to end at 21:55. This ensures that no new trades are taken at the final session close and that any session-dependent exit logic is applied before the session ends in practice.
When using custom or non-standard timeframes where the desired session end does not align cleanly with candle boundaries, it is recommended that users set the session end two full timeframe periods earlier than the desired session end. This provides an additional safety buffer, ensuring the strategy avoids taking trades near the session boundary.
By default, the session filter is set to false and the default session is set to "2300-2155".
Users can apply the session filter and adjust session boundaries via strategy Settings/Inputs/SESSION FILTER.
Close At End of Session Filter
The close at end of session filter is defined as an exit filter that closes all open positions when the active trading session ends, provided that the session filter is appropriately configured and applied.
When enabled, the strategy monitors the session filter state and detects the transition from an active session to an inactive session. All open trades are closed on the first candle that falls outside the defined session window. This ensures that no positions are carried beyond the user-defined trading session.
The close at end of session filter operates independently of entry conditions and other exit types. When enabled, it will force the closure of all open positions at session end regardless of the selected exit configuration.
Enabling the close at end of session filter can result in variable reward-to-risk outcomes. Because positions are forcibly closed at session end regardless of stop loss or target placement, exits may occur at prices that differ from those implied by the fixed reward-to-risk configuration. This behaviour is intentional and reflects a design trade-off between enforcing strict session boundaries and allowing trades to reach their predefined directional objectives, regardless of how severely distorted the realised reward-to-risk outcomes could be in the event of price gaps.
By default, the close at end of session filter is set to false.
Users can apply the close at end of session filter via strategy Settings/Inputs/CLOSE AT END OF SESSION FILTER.
Users should also ensure that the session filter is applied and that session boundaries are configured appropriately with respect to candle timestamp behaviour, as described in the session filter section above.
Sample Period Filter
The sample period filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined date-time range, with start and end date-times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, sample period boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered beyond the intended sample period end, users should configure the sample period end date-time at least one full timeframe period earlier than the desired practical sample period end date-time. For example, on a 5-minute chart with a desired end date-time of 01/01/2026 22:00, the end date-time should typically be configured to 01/01/2026 21:55.
The default sample period start and end date-times are set to 01/01/1900 00:00 and 01/01/3000 00:00, respectively.
Users can adjust the sample period via strategy Settings/Inputs/SAMPLE PERIOD FILTER.
█ GENERIC FILTERS
Generic Filter Behaviour
Unless otherwise stated:
"None" inputs return true.
Filters return true only when their selected condition is satisfied.
Close Above-Equal/Below Filter
The close price above-equal/below filter is defined as an entry filter that evaluates the most recent candle close price relative to a given time-series value and invalidates trade signals that do not satisfy a user-defined directional condition.
"Above-Equal" returns true when the most recent candle close price is greater than or equal to any given time-series value.
"Below" returns true when the most recent candle close price is less than any given time-series value.
Minimum Percentage Change Positive-Flat/Negative Filter
The minimum percentage change filter is an entry filter that measures the relative change of a time-series value over a configurable historical window and applies a directional threshold condition, invalidating trade signals that do not meet the directional threshold criteria.
The filter compares the current value to its value n bars ago and computes the percentage difference. A signal returns true only if this percentage change satisfies both:
The selected directional requirement.
The user-defined minimum percentage change magnitude.
"Positive-Flat" direction logic:
Accepts values that have increased or remained unchanged, provided the percentage change is greater than or equal to the minimum threshold.
"Negative" direction logic:
Accepts values that have decreased, provided the magnitude of the decrease meets or exceeds the minimum threshold.
When the minimum threshold is set to 0%, the filter behaves as a pure directional check:
"Positive-Flat" accepts ≥ 0% changes.
"Negative" accepts < 0% changes only.
Basic and Exclusive Rejection Filters
The basic rejection filter is defined as an entry filter that evaluates swing-based wick or body rejections of a given price level and invalidates trade signals that do not satisfy the rejection criteria.
For long trades, "Rejection" returns true when all three of the following conditions are met:
The previous candle open is above a given rejection price.
The trough price is less than or equal to a given rejection price.
The green candle that completes the swing closes above a given rejection price.
For short trades, "Rejection" returns true when all three of the following conditions are met:
The previous candle open is below a given rejection price.
The peak price is greater than or equal to a given rejection price.
The red candle that completes the swing closes below a given rejection price.
The exclusive rejection filter is defined as an entry filter that meets basic rejection filter criteria for only one user-defined price level from a set of given price levels. If the rejection criteria is met for more than one of the given price levels the filter will return false.
Basic and Multi-Part Trend Filters
Basic and multi-part trend filters are defined as entry filters that evaluate changes in time-series values from one period to the next and invalidate trade signals that do not satisfy a user-defined trend condition.
Basic trends operate independently of prior trend state, whereas multi-part trends are defined by the presence or absence of preceding trend sequences. The multi-part trend states are distinguished numerically and the conditions are bound to a user-defined trend count.
"Basic Uptrend" returns true when a time-series value is greater than the preceding value. For example, a basic volume uptrend filter returns true if the most recent candle's volume is greater than the preceding candle's volume.
"Basic Downtrend" returns true when a time-series value is less than the preceding value. For example, a basic volume downtrend filter returns true if the most recent candle's volume is less than the preceding candle's volume.
"Uptrend" returns true while a multi-part uptrend state is valid. The uptrend state begins when a new basic uptrend forms following a basic downtrend and remains valid until a new basic downtrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part uptrend conditions will return true.
"Downtrend" returns true while a multi-part downtrend state is valid. The downtrend state begins when a new basic downtrend forms following a basic uptrend and remains valid until a new basic uptrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part downtrend conditions will return true.
█ FEATURE SET D SPECIFIC FILTERS
All feature set specific indicators use the same calculations as the built-in TradingView indicators unless otherwise stated in the relevant filter sub-section. While users do not need to apply the indicators for the strategy to function, they can of course apply the relevant indicators as visual aids if they so desire.
For further information on how to apply built-in TradingView indicators, please refer to:
www.tradingview.com
Day of Week (DOW) Filter
The DOW filter is defined as an entry filter that invalidates trade signals that fall outside of a user-defined day of the week (configured to the strategy's time zone).
The default mode for the DOW filter is set to "None".
Users can apply the DOW filter via strategy Settings/Inputs/DAY OF WEEK (DOW) FILTER.
Directional Movement Index (DMI) Filters
The default DMI inputs are as follows:
DI length is set to 14.
ADX smoothing length is set to 14.
Users can adjust the DMI inputs via strategy Settings/Inputs/DIRECTIONAL MOVEMENT INDEX (DMI).
The positive DMI above-equal/below negative DMI filter is an entry filter that evaluates the relative positioning of the positive and negative DMI values and invalidates trade signals that do not satisfy a user-defined directional condition.
The default mode for the positive DMI above-equal/below negative DMI filter is set to "None".
The positive DMI above-equal/below ADX filter is an entry filter that evaluates the relative positioning of the positive DMI and ADX values and invalidates trade signals that do not satisfy a user-defined directional condition.
The default mode for the positive DMI above-equal/below ADX filter is set to "None".
The negative DMI above-equal/below ADX filter is an entry filter that evaluates the relative positioning of the negative DMI and ADX values and invalidates trade signals that do not satisfy a user-defined directional condition.
The default mode for the negative DMI above-equal/below ADX filter is set to "None".
Users can apply up to three DMI minimum percent change and trend filters (see generic filters section above), one for each of the DMI values (positive, negative, adx).
The minimum percent change positive-flat/negative filter defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The trend filter defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the DMI filters and adjust filter parameters via strategy Settings/Inputs/DMI FILTERS.
Donchian Channel (DC) Filters
The default DC length is set to 14.
Users can adjust the DC length via strategy Settings/Inputs/DONCHIAN CHANNEL (DC).
The DC bandwidth increasing/decreasing filter is defined as an entry filter that evaluates whether the distance between the DC high and DC low values is expanding or contracting over a configurable lookback period.
The default mode for the DC bandwidth increasing/decreasing filter is set to "None".
The default DC bandwidth increasing/decreasing lookback is set to 3.
The default mode for the close above-equal/below DC median (see generic filters section above) filter is set to "None".
The DC median rejection filter is defined as an exclusive rejection filter (see generic filters section above) that will only return true if the DC median value is rejected exclusive of the other two DC values.
By default, the DC median rejection filter is set to false.
Users can apply the DC filters and adjust filter parameters via strategy Settings/Inputs/DC FILTERS.
█ ALERTS
Users can set alerts for any given strategy configuration via the alerts dialogue box.
Users must first ensure that the correct condition (the strategy title) is selected from the first drop-down list in the alert dialogue box's condition field.
Default alert messages have been configured for both entries and exits so that users can more effectively distinguish between long and short entries and exits while using long-short configurations.
To get alerts for both entries and exits the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "Order fills only". When using "Order fills only" with long-short configurations, it is recommended that users define their alert via the alert name field and use only the default {{strategy.order.alert_message}} call in the alert message field.
Alert conditions generated by "Order fills only" are evaluated after entry conditions have been satisfied and operational constraints (risk, position size and margin requirements) have been applied. As such, trade signals that would result in position sizes exceeding the simulated account's margin constraints will not generate alerts.
To get alerts for entries only the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "alert() function calls only".
The default alert messages generated by "Order fills only" are as follows:
"long entry".
"long exit".
"short entry".
"short exit".
The default alert messages generated by "alert() function calls only" are as follows:
"long entry".
"short entry".
Alert conditions generated by "alert() function calls only" are operational-constraint-agnostic and will generate alerts whenever entry conditions are satisfied, regardless of the simulated account's margin constraints.
For further information on setting and managing alerts, please refer to:
www.tradingview.com
www.tradingview.com
www.tradingview.com
█ LIMITATIONS AND CONSIDERATIONS
Backtesting
Backtest results should always be interpreted cautiously. Strategy performance can vary significantly across time periods and sample sets. While strong historical performance does not guarantee future results, poor historical performance reliably indicates a weak strategy when sample sizes are statistically meaningful.
Statistical Significance and Path-Dependent Outcomes (Overfitting)
In statistical practice, sample sizes of 100 observations are sometimes cited as a rough lower bound for certain forms of basic significance testing. In the context of trading strategy evaluation, such sample sizes are rarely sufficient to produce results that are meaningfully reliable or replicable. Based on practical experience, sample sizes closer to 1,000 observations or more are generally required before performance characteristics begin to stabilise. As a general rule, larger sample sizes increase the reliability and replicability of observed results.
Path dependence refers to situations in which outcomes are determined not only by initial conditions, but by the specific and unique sequence of price movements over a given time period.
Even with large sample sizes, favourable net profit outcomes should be interpreted with caution when they are primarily driven by either variable reward-to-risk configurations or fixed reward-to-risk configurations that employ unrealistically high reward multiples. In both cases, performance is often strongly influenced by path-dependent effects, making such outcomes less reliable and less replicable.
Fixed reward-to-risk configurations are generally less susceptible to path dependence when the reward multiple is kept within reasonable bounds. However, empirical studies and practitioner research suggest that reward multiples above approximately 3:1 increasingly exhibit the same path-dependent characteristics observed in variable reward-to-risk strategies.
Bar Magnifier
Due to the limitations of OHLC data, intra-bar price movement cannot be precisely determined.
When both stop loss and target levels are reached within the same candle, assumptions are made by the strategy tester.
Pine Script's bar magnifier partially mitigates this limitation by evaluating lower-timeframe data. However, this feature is available only to TradingView Premium users and remains inherently limited.
For further information on the bar magnifier functionality, please refer to:
www.tradingview.com
www.tradingview.com
TradingView Premium users can enable bar magnifier via strategy Settings/Properties/FILL ORDERS.
Processing Orders at Candle Close
Backtests cannot accurately account for slippage between signal generation and trade execution.
A practical mitigation is to use fixed-distance stop losses and targets rather than absolute price levels, a feature supported by many brokers and APIs.
Empirical Probabilities
Empirical probabilities are derived directly from observed outcomes rather than from theoretical models or assumed distributions. In the context of trading, they are calculated by measuring the relative frequency of events (such as wins and losses) across a large sample of historical trades.
Unlike conditional or model-based probabilities, empirical probabilities make no assumptions. Their validity relies primarily on sample size and the consistency of the rules used to generate observations, making them particularly relevant for trading systems evaluated under the law of large numbers.
Empirical probabilities are most useful for comparative analysis, such as assessing how different configurations, filters or exit mechanisms alter the statistical behaviour of a strategy under identical conditions. They are not intended to represent true predictive probabilities or to imply stable future performance.
To study empirical probabilities for comparative purposes, it is recommended that users set commission and both long and short margin values to 0% in order to maximise sample size. However, users should not interpret any resulting profits as realistic. Setting commission and margin (in particular) to 0% produces highly distorted outcomes that are not representative of realistic live trading conditions.
█ DISCLAIMER
This Pine Script strategy is provided for educational purposes only and does not constitute financial advice in any form.
Pine Script®策略
ATR Reversal Master TX Futures | Auto Long & Short with ProfesProduct Features: Taiwan Futures (TX)
Fully automated ATR-based reversal trading (long & short entries/exits)
Professional Chinese panel showing trend, position, condition price, distance, ATR, and win rate
Long/short arrow signals with adjustable vertical offset
Configurable ATR period and multiplier; strategy core logic is locked for safety
Single-direction condition price tracking for secure reversals
Ideal For:
Traders who want to use ATR for reversal strategies
Users who need real-time Chinese panel monitoring of market dynamics
功能特色:台指期 完全自動化反手交易(多空自動進出) 中文專業面板,顯示趨勢、持倉、條件價、距離、ATR、勝率 多空箭頭提示,可調上下位移 ATR倍數與週期可調,策略核心安全鎖死 單方向條件價追蹤,安全反手 適合對象: 想用ATR策略反手操作的交易者 需要即時中文面板監控市場動態的使用者
Pine Script®策略
Squared9 Pro v1Squared9 Pro v1.0 (strategy) combines classic Gann geometry with modern momentum checks to find high-conviction reversal zones.
The strategy requires:
1. Price to be within a user-defined percentage of Gann levels (based on recent pivot highs/lows and Square of Nine calculations).
2. Divergence on Stochastic and/or MACD (price and indicator moving in opposite directions).
3. Current price to respect the trend direction on a higher timeframe EMA.
4. A candle with a strong body relative to its range.
Here's what it looks for:
- Price is close to important Gann levels (calculated from recent swing highs/lows using Square of Nine math — shown as colored horizontal lines).
- Stochastic and MACD indicators show divergence (price makes new high/low but indicators do not — a classic reversal clue).
- The overall trend on a higher timeframe (default 4-hour) supports the trade direction via a 50-period EMA filter.
- The current candle has a strong directional body (not a doji or tiny range — minimum body size is adjustable).
When these line up, a green triangle appears below the bar for a potential long entry, or a red triangle above for short. Stop-loss and take-profit are set automatically using ATR multiples (default 1.7× for stop, 3.2× for target), with an optional trailing stop.
All settings (lookback periods, tolerances, ATR multipliers, etc.) can be changed in the inputs panel.
This script is designed for traders who want confluence-based signals rather than relying on a single indicator.
Feedback is welcome.
Pine Script®策略
Blue Chip Strategy V5V5 Long-Term Swing Strategy (4H / Daily Trend)
This strategy is designed for traders who want consistent, rules-based swing trades without staring at screens all day. V5 focuses on high-quality long-term setups by combining:
-Higher-timeframe trend alignment
-Structured pullback entries
-Volatility confirmation
-ATR-based risk management
The goal is simple: participate in institutional trends, not noise. How the strategy works:
-Trades are taken on the 4-hour chart
-Overall bias is guided by the Daily trend
-Entries occur only after controlled pullbacks, not breakouts
-Risk is defined at entry using ATR-based stops
-Winners are allowed to run, losers are cut quickly
This creates fewer trades — but higher quality ones.
What this strategy is NOT
❌ Not a scalping system
❌ Not a high-frequency bot
❌ Not news- or hype-driven
❌ Not designed for crypto or penny stocks
V5 is built for US large-cap stocks with clean structure and institutional liquidity.
Pine Script®策略
BBDC SCIsmart breakout + trend-following system by Speed Coding Infotech, built to identify high-probability moves using a hybrid of BBDC structure and Donchian Channel breakout logic.
This script is engineered with automation-first design, meaning it supports clean webhook inputs such as API Key, Symbol, and Strategy Tag — making it ready for alert-based execution.
🔹 What makes it different?
• BBDC + Donchian fusion logic (trend + breakout confirmation)
• Flexible MA basis selection (SMA/EMA supported)
• Precision controls: Length, StdDev, Offset
• Day-wise trade filter (Mon–Fri toggle system)
• Long Only / Short Only smart control
• Qty & Risk:Reward optional TP system
⚡ Best Use:
Intraday + Swing traders who want a clean system with adjustable filters and automation support.
⚠️ Disclaimer: This tool is for educational use only. Markets are risky—always test before live trading.
Pine Script®策略
US100/500 0DTEGamma momentum outbreak and mean reversion
Utilize signal to catch strong momentum with low ATR and catch mean reversion for asymmetric one sided trend resulted from 0DTE profit taken
Pine Script®策略
70To see straight is to glimpse tomorrow, projecting a linear vision that does not fear time. But when the gaze curves toward the past, reality multiplies into reflected fires, distorting the truth through the filter of experience. At this intersection of intuition and analysis, our fund is born—a financial ecosystem where philosophy transforms into algorithm.
The core of our strategy is not just profit, but Lucidity.
Imagine starting with a capital of €50,000: from 2024 to the present, this plan has navigated the markets not as a gamble, but as a sensory mastery of the subject matter.
The First Fire (F1 - The Voice): The predicate that breaks through the market's silence to capture the exact equity moment.
The Second Fire (F2 - Management of the "Fault"): The awareness that prevents "paralysis by analysis," protecting capital when self-observation becomes excessive.
The Third Fire (F3 - Vibrational Extraction): The ability to extract vibrational thought from the chaos of volatility, discerning the straight path.
We have encoded this triad into a system that avoids boredom and overthinking, alternating the "senses" to maintain a perpetually fresh understanding. Choosing to participate in this project means investing not just in an asset, but in a method that balances passivity and activity, responding to market calls only when they coincide with a determined, lucid thought.
Our projection, supported by a logic that scales leverage only when success is confirmed, aims for a growth that is not just numerical, but structural. It is time to move beyond the overlapping lenses that distort the truth of profit. We invite you to enter a world where every choice is the result of a balanced sequence, starting from objective data to dominate the most volatile sentiment. Investing with us means stopping looking at the reflection and starting to see, finally, tomorrow.
📈 Strategy Estimate (Based on your tests)
Initial Capital: €50,000.
Control Logic: "Obiettivo 70" (Target 70) strategy for solid and consistent growth.
Protection: Active safety threshold to preserve the bulk of the capital in case of a market "fault."
Pine Script®策略
Q1 Hourly Breakout Strategy [Full Time & Risk Management]This is a highly customizable Hourly Breakout Strategy designed to capture momentum shifts at the start of specific hours. It automatically identifies an "Opening Range" (default 15 minutes) at the beginning of an hour and triggers a trade when the price confirms a breakout above or below that range.
Unlike standard breakout scripts, this strategy offers institutional-grade time filtering, allowing you to surgically select exactly when the strategy is active down to the specific Hour, Day of the Week, and even the Week of the Month.
📈 How It Works
The Range: At the start of every enabled hour, the script tracks the High and Low for a user-defined duration (e.g., the first 15 minutes).
The Box: Once the duration is over, a visual box is locked in place.
The Trigger: A candle close outside of this box triggers an entry (Long for bullish breakout, Short for bearish).
The Exit: Trades are managed via fixed Stop Loss and Take Profit percentages.
🛠 Key Features
1. Flexible Range Duration
You are not locked into a specific timeframe. You can set the "Range Duration" to any value (e.g., 5 min, 15 min, 30 min).
Works on any chart timeframe smaller than your range (e.g., use a 1m or 3m chart for a 15m range).
2. Advanced Time Filtering
Hourly Filter: specific checkboxes for every hour of the futures session (18:00 to 15:00). Easily disable choppy "lunch hours" or low-volume overnight sessions.
Daily Filter: Select specific trading days (e.g., skip Fridays or Sundays).
Week of Month Filter: Unique logic allows you to enable/disable specific weeks (e.g., avoid Week 1 for NFP or Week 5 for end-of-month flows).
3. Robust Risk Management
% of Equity Sizing: Automatically calculates position size based on your account balance to control risk (essential for backtesting Futures like NQ/MNQ on smaller accounts).
Fixed Contract Sizing: Option to switch to a fixed number of contracts.
4. Visual Aids
Draws the "Opening Range" box on the chart for visual backtesting.
Plots confirmation dots and entry markers (L/S) to clearly show signal generation.
⚙️ How to Use
Apply the strategy to a low-timeframe chart (e.g., 1m, 3m, or 5m).
In Settings, adjust "Range Duration" to your preferred opening window (Default: 15 mins).
Use the "Active Trading Hours" and "Active Weeks" checkboxes to filter out bad market conditions.
Adjust SL/TP percentages to match the volatility of the asset you are trading.
Disclaimer: This strategy is for educational and backtesting purposes. Past performance does not guarantee future results. Always manage your risk.
Pine Script®策略
Professional Price Action Strategy [Session Filter]STRATEGY ARCHITECTURE: PROFESSIONAL PRICE ACTION WITH INTRADAY PRECISION
1. DYNAMIC SUPPORT AND RESISTANCE ENGINE
The foundation of this strategy lies in its ability to identify High-Probability Zones rather than static lines.
Pivot-Point Integration: The script calculates Swing Highs and Lows over a user-defined period (defaulting to 15 bars). These represent historical turning points where institutional order flow has previously reversed.
Multi-Timeframe (MTF) Verification: By pulling data from a Higher Timeframe (HTF), such as the 30-minute chart, the strategy filters out "noisy" support levels on the 5-minute chart. Only levels respected by the "Big Picture" are utilized for entries.
Real-Time Recalculation: Levels are not static; they update dynamically at the start of every candle to adapt to expanding volatility or shifting market structures.
2. DURATION-SPECIFIC TRADING SESSIONS
To maximize profitability, the strategy focuses on Market Liquidity Windows.
NY Open Filter: Users can toggle a specific session (e.g., 09:30 – 16:00 EST). This ensures the strategy only operates when volume is highest, avoiding the "dead zones" of the Asian session where price often moves sideways.
Session Liquidation: A built-in safety mechanism automatically closes all open positions at the end of the trading day. This eliminates Overnight Gap Risk, ensuring your capital is not exposed to unpredictable news events during market close.
3. DUAL-MODE ENTRY MECHANISM
This strategy capitalizes on the two primary states of the market: Continuation and Reversal.
A. Volume-Confirmed Breakouts
Confirmation: Price must not only cross a resistance level but close above it.
Volume Surge: To prevent "bull traps," the breakout candle must exhibit volume significantly higher than the average of the last 10 bars.
B. Candlestick-Confirmed Bounces
Pattern Alignment: The strategy scans for Hammer, Shooting Star, and Engulfing patterns specifically when the price is touching a HTF Support or Resistance level.
Validation: A "bounce" is only valid if the candlestick pattern is completed, signaling that the level has successfully held and buyers or sellers have regained control.
4. INSTITUTIONAL-GRADE RISK MANAGEMENT
Consistency is achieved through mathematical discipline rather than guessing.
1:2 Risk-to-Reward Ratio (RR): Every trade is mechanically programmed so that the potential profit is exactly twice the size of the potential loss. This means a win rate of even 40% can maintain a growing equity curve.
Dynamic Breakeven (BE) Trigger: As soon as the price reaches 50% of the way to the profit target, the Stop Loss is automatically moved to the Entry Price. This "locks in" a risk-free trade, protecting the initial capital.
Weekend Guardrail : Using the dayofweek function, the script completely halts all trading on Saturdays and Sundays. This protects the user from low-liquidity spikes and irregular weekend pricing.
5. VISUAL INTERFACE AND USER CUSTOMIZATION
The script is designed to be as informative as it is functional.
On-Chart Plotting: HTF levels are drawn as continuous lines, allowing the trader to see "Headroom" (the distance to the next major resistance) at a glance.
Background Shading: The active trading session is highlighted with a light background tint, providing immediate visual feedback on whether the "Time Filter" is currently permitting trades.
Pine Script®策略
Neural Network SPXL Strategy(NNSS)NNSS acts as a Visual Dashboard for our proprietary backend algorithm, bringing high-performance computing signals directly to your chart.
🤖 The "Black Box" Edge Unlike lagging indicators (RSI, MACD), NNSS utilizes an external Statistical Probability Model. It analyzes market regimes and volatility to generate predictive, high-confidence signals.
🛡️ Risk-First Methodology Designed to outperform Buy & Hold by minimizing drawdowns.
Risk-On: Aggressively captures upside trends.
Risk-Off: Swiftly moves to CASH (0% Exposure) when systemic risk is detected.
🚀 Key Features
T+1 Action Plan: Clearly indicates the required action for the next market open.
Dynamic Positioning: Adjusts position sizing (e.g., 100%, 16%, 0%) daily based on model confidence.
🔒 Invite-Only Access This is a private quantitative strategy. To unlock access, please contact me directly via private message.
🤖 Automate This Strategy Precise execution at the T+1 Open is critical. Manual trading often leads to slippage. We recommend StratOne for a 100% hands-free experience.
👉 Start Automating: Search "NNSS" on StratOne.ai.
Disclaimer: For informational purposes only. Trading leveraged assets involves risk.
Pine Script®策略
Astra X v1.111353 StrategyAstra X – Trading Idea: Trade Only When The Market Is Clear
This idea is based on a simple belief:
The market becomes easier to trade when multiple timeframes show the same direction.
Instead of trying to predict tops or bottoms, this approach waits for confirmation from higher timeframes before entering a trade.
The Core Idea
Markets move in trends, but small timeframes can be noisy and confusing.
This idea looks at larger timeframes such as 1H, 6H, 8H, and Daily to understand the bigger picture.
If these timeframes agree that the market is trending, a trade becomes valid.
If they disagree, the safest decision is to stay out.
How The Idea Finds Opportunities
The strategy watches several things at the same time:
Moving averages to detect trend direction
Momentum indicators to measure strength
Volatility channels to understand price behavior
When multiple signals align, it suggests that the market may be entering a stable trend phase.
Trade Management Philosophy
Once a trade is opened, the focus shifts to risk control.
Profit targets and stop losses are not fixed numbers.
They are based on market volatility using ATR.
This allows trades to adapt to changing market conditions.
If the original trend signal disappears, the position is closed early.
The goal is to avoid staying in trades when the market structure changes.
What This Idea Tries To Avoid
Overtrading
Random entries during sideways markets
Holding losing trades too long
Summary
This idea focuses on trading with confirmation, not prediction.
It attempts to follow strong trends while managing risk using volatility-based exits.
The approach works best in markets that show clear directional movement.
This is a trading idea for educational and research purposes only. Always test and evaluate strategies before using them in live trading.
Pine Script®策略
Astra X v1 A Very Simple Trend StrategyAstra X v1 – A Very Simple Trend Strategy
This strategy is made to trade only when the market direction is clear.
It does not guess.
It waits for many signals to agree before entering a trade.
What does this strategy do?
If the price is clearly going up, it buys
If the price is clearly going down, it sells
If the price is unclear or messy, it does nothing
No random trades. No guessing.
How does it know the direction?
The strategy looks at the market from far away, not very close.
It checks higher timeframes like 1 hour, 6 hours, 8 hours, and 1 day to understand the real trend.
It uses:
Moving averages (EMA) to see trend direction
RSI and ADX to see if the move is strong
Keltner Channels to understand volatility
A trade is allowed only when several signals say the same thing.
When does it enter a trade?
Buy when multiple signals say the trend is going up
Sell when multiple signals say the trend is going down
Only one trade at a time.
No stacking and no overtrading.
When does it exit a trade?
There are two ways to exit:
1. Take profit or stop loss
Profit and loss levels are based on ATR
ATR follows market volatility, so exits are flexible
2. Early exit
If the entry signal is no longer valid
The trade is closed immediately
This helps avoid big losses when the trend changes.
Risk management
Each trade uses only a part of the account
Leverage is optional
Risk is known before entering the trade
Simple summary
Follow the trend
Trade only when many timeframes agree
Always know where to exit
Do not chase or guess
Not financial advice.
Always test before using real money.
Pine Script®策略
Astra X v1 Multi-Timeframe Trend Strategy with ATR TP/SL This strategy is built around trend confirmation across multiple higher timeframes, combined with volatility-based risk management.
The main idea is simple:
Only trade when multiple timeframes agree on direction, and
Let ATR decide take-profit and stop-loss instead of fixed percentages.
Strategy Concept
Instead of relying on a single indicator or timeframe, Astra X stacks confirmations from 1H to 1D to filter out noise and low-quality trades.
It is designed to:
Capture medium to long trend moves
Reduce overtrading
Adapt exits to market volatility
Entry Logic (High Level)
A trade is triggered when one of several predefined conditions is met.
Each condition represents a different trend or momentum structure, such as:
EMA crossovers on 6H, 8H, and Daily
Trend strength using ADX
Momentum confirmation using RSI and TSI
Volatility context using Keltner Channels
Both long and short signals are supported, depending on the condition.
Only one position is allowed at a time.
Exit Logic
There are two exit layers:
ATR-based take profit and stop loss
Take profit = ATR × multiplier
Stop loss = ATR × multiplier
Uses 1H ATR so exits adapt to current volatility
Early exit signal
If the original entry condition is invalidated
The position is closed immediately
This helps protect profits when the trend structure breaks early.
Risk and Position Sizing
Position size is based on account equity
Optional leverage support
Percentage-based execution model
Alert-ready for automation
Notes
Uses higher timeframe data with lookahead for strategy logic
Focused on trend continuation, not scalping
Best suited for BTC and high-liquidity markets
Final Thoughts
Astra X does not aim to predict tops or bottoms.
It focuses on aligning with the dominant trend, managing risk dynamically, and letting volatility define exits.
Not financial advice. Always backtest before live trading.
Pine Script®策略
Corrected NNSSThe NNSS system represents a sophisticated, institutional-grade approach to trading leveraged ETFs (specifically SPXL). This script acts as the **Visual Dashboard** for our proprietary backend algorithm, bringing high-performance computing signals directly to your TradingView chart.
**🤖 The "Black Box" Advantage**
Unlike standard indicators (RSI, MACD) that lag behind price, NNSS utilizes a complex **Statistical Probability Model** running on external servers. It analyzes market regimes, volatility structures, and historical patterns to generate high-confidence execution signals.
**🛡️ Risk-First Methodology**
Trading 3x leveraged ETFs requires precision. Our system prioritizes capital preservation:
* **Risk-On:** Aggressively captures upside during stable trends.
* **Risk-Off:** swiftly moves to **CASH (0% Exposure)** when the model detects elevated systemic risk or statistical anomalies.
**🚀 Key Features**
* **T+1 Action Plan:** The "T+1 PLAN" label clearly indicates the required action for the *next market open* (Buy, Add, Reduce, or Clear).
* **Dynamic Positioning:** The system doesn't just "Buy" or "Sell"; it intelligently adjusts position sizing (e.g., 100%, 16%, 0%) based on the model's confidence level.
* **Clarity:** No clutter. Only actionable signals are displayed.
* 🟩 **Green Labels:** Accumulation / Holding
* 🟥 **Red Labels:** Reduction / Liquidation / Cash Preservation
**📊 Performance Goal**
The strategy is engineered to deliver a superior **Profit Factor** compared to a standard Buy & Hold approach by minimizing drawdowns during bear markets and corrections.
**🔒 Invite-Only Access**
This is a private quantitative strategy. The source code is protected to maintain the integrity of our proprietary logic.
**👉 How to Get Access**
To unlock this strategy and receive daily signal updates, please check the **Signature** below or contact me directly via private message.
---
*Disclaimer: This script is for informational purposes only. Trading leveraged assets involves significant risk. Past performance is not indicative of future results.*
Pine Script®策略
15 min orb//@version=5
strategy("15min ORB Retest Strategy", overlay=true, default_qty_type=strategy.fixed, default_qty_value=2, initial_capital=50000, commission_type=strategy.commission.cash_per_contract, commission_value=2.50)
// ========== INPUTS ==========
entryLevel = input.string("Top/Bottom", "Entry Level", options= )
stopPoints = input.float(5.0, "Stop Loss (Points)", minval=0.1)
tpPoints = input.float(10.0, "Take Profit (Points)", minval=0.1)
// ========== TIME SETTINGS (Mountain Time = UTC-7 or UTC-6 depending on DST) ==========
// TradingView uses UTC, so adjust based on your MT offset
// For simplicity, using session strings. Adjust if needed for DST.
orbSession = "0600-0615:1234567" // 6:00-6:15 AM MT (adjust UTC offset as needed)
tradeSession = "0700-0730:1234567" // 7:00-7:30 AM MT
// ========== ORB BOX CALCULATION ==========
var float boxHigh = na
var float boxLow = na
var float boxMid = na
var bool boxSet = false
var bool tradeToday = false
var bool breakoutUp = false
var bool breakoutDown = false
// Detect ORB session (6:00-6:15 AM MT)
inOrbSession = not na(time(timeframe.period, orbSession, "America/Denver"))
if inOrbSession and not boxSet
boxHigh := high
boxLow := low
boxSet := true
else if inOrbSession and boxSet
boxHigh := math.max(boxHigh, high)
boxLow := math.min(boxLow, low)
// Calculate midpoint
if not na(boxHigh) and not na(boxLow)
boxMid := (boxHigh + boxLow) / 2
// Reset daily
if ta.change(time('D'))
boxSet := false
tradeToday := false
breakoutUp := false
breakoutDown := false
boxHigh := na
boxLow := na
boxMid := na
// ========== DRAW BOX ==========
var line topLine = na
var line bottomLine = na
var line midLine = na
if boxSet and not na(boxHigh)
if na(topLine)
topLine := line.new(bar_index, boxHigh, bar_index + 1, boxHigh, color=color.green, width=2)
bottomLine := line.new(bar_index, boxLow, bar_index + 1, boxLow, color=color.red, width=2)
midLine := line.new(bar_index, boxMid, bar_index + 1, boxMid, color=color.gray, width=1, style=line.style_dashed)
else
line.set_x2(topLine, bar_index)
line.set_x2(bottomLine, bar_index)
line.set_x2(midLine, bar_index)
// ========== BREAKOUT DETECTION ==========
inTradeSession = not na(time(timeframe.period, tradeSession, "America/Denver"))
// Breakout = 1m close outside box
if boxSet and not na(boxHigh) and not breakoutUp and not breakoutDown
if close > boxHigh
breakoutUp := true
if close < boxLow
breakoutDown := true
// ========== MIDPOINT INVALIDATION (with re-setup) ==========
if breakoutUp and close < boxMid
breakoutUp := false // Allow re-setup
if breakoutDown and close > boxMid
breakoutDown := false // Allow re-setup
// ========== RETEST & ENTRY LOGIC ==========
longCondition = false
shortCondition = false
if boxSet and inTradeSession and not tradeToday
// LONG: breakout up, retest top or midpoint
if breakoutUp
if entryLevel == "Top/Bottom" and close <= boxHigh and close >= boxHigh - 0.25
longCondition := true
if entryLevel == "Midpoint" and close <= boxMid and close >= boxMid - 0.25
longCondition := true
// SHORT: breakout down, retest bottom or midpoint
if breakoutDown
if entryLevel == "Top/Bottom" and close >= boxLow and close <= boxLow + 0.25
shortCondition := true
if entryLevel == "Midpoint" and close >= boxMid and close <= boxMid + 0.25
shortCondition := true
// ========== EXECUTE TRADES ==========
if longCondition
strategy.entry("Long", strategy.long)
strategy.exit("TP/SL", "Long", stop=close - stopPoints, limit=close + tpPoints)
tradeToday := true
if shortCondition
strategy.entry("Short", strategy.short)
strategy.exit("TP/SL", "Short", stop=close + stopPoints, limit=close - tpPoints)
tradeToday := true
// ========== PLOT SIGNALS ==========
plotshape(longCondition, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, title="Long Entry")
plotshape(shortCondition, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, title="Short Entry")
Pine Script®策略
Pine Script®策略
Mutanabby_AI | 5 TP + SL + Breakeven (Fill-based)This is a strategy where all market fluctuations occur.
Pine Script®策略
Neural Network SPXL Strategy(Public Visualizer)The NNSS system represents a sophisticated, institutional-grade approach to trading leveraged ETFs (specifically SPXL). This script acts as the **Visual Dashboard** for our proprietary backend algorithm, bringing high-performance computing signals directly to your TradingView chart.
**🤖 The "Black Box" Advantage**
Unlike standard indicators (RSI, MACD) that lag behind price, NNSS utilizes a complex **Statistical Probability Model** running on external servers. It analyzes market regimes, volatility structures, and historical patterns to generate high-confidence execution signals.
**🛡️ Risk-First Methodology**
Trading 3x leveraged ETFs requires precision. Our system prioritizes capital preservation:
* **Risk-On:** Aggressively captures upside during stable trends.
* **Risk-Off:** swiftly moves to **CASH (0% Exposure)** when the model detects elevated systemic risk or statistical anomalies.
**🚀 Key Features**
* **T+1 Action Plan:** The "T+1 PLAN" label clearly indicates the required action for the *next market open* (Buy, Add, Reduce, or Clear).
* **Dynamic Positioning:** The system doesn't just "Buy" or "Sell"; it intelligently adjusts position sizing (e.g., 100%, 16%, 0%) based on the model's confidence level.
* **Clarity:** No clutter. Only actionable signals are displayed.
* 🟩 **Green Labels:** Accumulation / Holding
* 🟥 **Red Labels:** Reduction / Liquidation / Cash Preservation
**📊 Performance Goal**
The strategy is engineered to deliver a superior **Profit Factor** compared to a standard Buy & Hold approach by minimizing drawdowns during bear markets and corrections.
**🔒 Invite-Only Access**
This is a private quantitative strategy. The source code is protected to maintain the integrity of our proprietary logic.
**👉 How to Get Access**
To unlock this strategy and receive daily signal updates, please check the **Signature** below or contact me directly via private message.
---
*Disclaimer: This script is for informational purposes only. Trading leveraged assets involves significant risk. Past performance is not indicative of future results.*
Pine Script®策略
Swing Strategy Feature Set C [theEccentricTrader]█ OVERVIEW
This swing strategy is part of a broader research and exploration framework designed to encourage users to experiment with a variety of technical concepts and evaluate the comparative effectiveness of different strategy configurations. For example, users can first configure a core strategy as a benchmark, then iteratively test a range of feature configurations as additional entry conditions and compare their performance against one another and against the core strategy.
Feature Set C includes concepts beginning with the letter "C" and forms part of a larger swing strategy suite that covers a wide range of technical concepts. The objective of the suite is not curve-fitting, but rather structured experimentation, exploration and statistical validation (or invalidation) of technical concepts.
Concepts exclusive to the feature set are as follows:
Candle Trend
Candlestick Patterns
Chande Momentum Oscillator
Chandelier Exit
Chart Patterns
Commodity Channel Index
Coppock Curve
█ OPERATIONAL
Initial Capital
The initial capital is defined as a monetary value denominated in a given base currency.
The default initial capital is set to 100,000.
The default base currency is set to the selected symbol's default base currency.
Users can adjust the initial capital and select an alternative base currency via strategy Settings/Properties.
Risk as Percentage of Equity
The equity is defined as the sum of initial capital, net profit and open profit.
The risk is defined as a percentage of equity per-trade. As a result, net profit outcomes are subject to compounding effects over time.
The default risk is set to 1% of equity.
Users can adjust the strategy's per-trade risk via strategy Settings/Inputs/STRATEGY.
For further information on how the risk is applied in practice, refer to the position sizing section below.
Unit of Value
The unit of value is defined as a decimal precision factor that converts user-defined point or pip distances into actual price units used by the selected symbol.
Different symbols express price movement using different conventions. For example, some symbols are quoted directly in whole price points, while others use pips or fractional point increments. The unit of value provides a normalisation layer that allows all distance-based logic in the strategy to operate consistently across symbols.
Examples:
A unit of value of 1 corresponds to a price increment of 1.0.
A unit of value of 10 corresponds to a price increment of 0.1.
A unit of value of 100 corresponds to a price increment of 0.01.
A unit of value of 1000 corresponds to a price increment of 0.001.
A unit of value of 10000 corresponds to a price increment of 0.0001.
Users should consult their broker’s published symbol specifications to confirm how price movement is defined for the symbols they intend to backtest. Incorrect configuration of the unit of value may result in misaligned stop distances, targets and/or risk calculations.
The default unit of value is set to 1.
Users can adjust the unit of value via strategy Settings/Inputs/STRATEGY.
Stop Buffer
The stop buffer is defined as the number of points or pips beyond a stop loss level required for the level to be considered clearly breached.
The default stop buffer is set to 0 points/pips.
Users can adjust the stop buffer via strategy Settings/Inputs/STRATEGY.
Risk Range
The risk range is defined as the difference between the entry price and the stop loss price (inclusive of the stop buffer) for any given trade.
Position Sizing
Position sizing determines the quantity of contracts, shares or units opened for each trade based on the user-defined risk and the selected symbol’s pricing structure.
"syminfo.pointvalue" is a built-in Pine Script variable that defines the number of underlying units contained within a single contract for any given symbol, and is critical for accurate position size calculations.
The position size is calculated as follows:
The risk range is multiplied by the syminfo.pointvalue to convert the price movement into its monetary equivalent.
The user-defined risk amount (expressed as a percentage of equity) is divided by this monetary risk per unit to determine the position size.
This ensures that each trade risks a consistent proportion of account equity regardless of point or pip based quoting conventions, symbol price scale or contract specifications.
While the strategy targets a fixed percentage of equity risk per-trade, the exact risk applied cannot always be matched precisely due to symbol-specific constraints such as contract sizing and margin requirements. In these cases, the strategy opens the largest permissible position that does not violate operational constraints, resulting in a realised risk that is as close as possible to the user-defined risk without exceeding it.
For further information on the syminfo.pointvalue variable, please refer to:
www.tradingview.com
Margin
The margin is defined as the minimum percentage of a position’s notional value that must be covered by the strategy’s available equity in order for TradingView's strategy tester to simulate opening and maintaining that position. For example, a margin setting of 25% means the simulated account must hold equity equal to at least 25% of the position’s notional value in order to enter or maintain that trade, the remaining 75% is considered provided by the simulated broker.
A lower margin percentage allows the account to open larger positions relative to its equity, because the required equity portion is smaller. Conversely, a higher margin percentage demands more of the account's equity be committed to any given position.
When the account’s equity falls below the required margin, the strategy tester emulates a margin call event, in which the broker emulator forcibly closes or reduces positions so that remaining positions no longer exceed available equity relative to the margin requirement. This behaviour is documented as part of TradingView’s margin/leverage feature for strategies.
Margin settings in a strategy are used solely for simulation purposes and do not automatically match any broker’s real-world margin requirements (which can vary by broker, asset class and symbol). Users should consult their broker’s published specifications for further details.
The default margin is set to 25% for both long and short positions.
Users can adjust the margin for long and short positions independently via strategy Settings/Properties/MARGIN.
For further information on the strategy tester's margin functionality, please refer to:
www.tradingview.com
www.tradingview.com
Pyramiding
The pyramiding count is defined as the maximum number of open positions permitted at any one time. TradingView's strategy tester does not facilitate hedging, as such, long entries will close any open short positions and short entries will close any open long positions.
The default pyramiding count is set to 100.
Users can adjust the pyramiding count via strategy Settings/Properties.
For further information on TradingView's strategy tester and broker emulator, please refer to:
www.tradingview.com
Spread
The spread is defined as the difference between a given symbol's bid (buy) price and ask (sell) price.
Typical spreads vary by broker and symbol. Some brokers offer fixed spreads on certain symbols, while others offer variable spreads that fluctuate with market conditions. Users should consult their broker's published specifications for further details.
Commission
The commission is defined as a transaction cost applied by a broker and may be expressed as a percentage of position size, a per-contract fee or a fixed fee per-transaction.
Commission structures vary by broker and symbol. Some brokers charge no explicit commission and instead generate revenue through the spread or other indirect sources, while others will typically apply one of the three aforementioned commission types, depending on the product offered. Users should consult their broker's published specifications for further details.
The default commission is set to 0.005% of position size.
Users can select and adjust the commission type via strategy Settings/Properties/COST SIMULATION.
█ CORE STRATEGY
Green and Red Candles
A green candle is defined as a candle that closes at or above its open price and a red candle is defined as a candle that closes below its open price.
Swing Highs and Swing Lows
A swing high is defined as a green candle, or a series of consecutive green candles, followed by a single red candle that completes the swing and forms the peak.
A swing low is defined as a red candle, or a series of consecutive red candles, followed by a single green candle that completes the swing and forms the trough.
Peak and Trough Prices
The peak price of a complete swing high is either the high of the red candle that completes the swing high or the high of the preceding green candle, depending on which is higher.
The trough price of a complete swing low is either the low of the green candle that completes the swing low or the low of the preceding red candle, depending on which is lower.
Fixed Reward-to-Risk
Fixed reward-to-risk is defined as a user-defined reward multiple for a given unit of risk.
Variable Reward-to-Risk
Variable reward-to-risk is defined as a path-dependent reward multiple for a given unit of risk.
Swing High Swing Low (SHSL) Strategy
The SHSL strategy uses swing lows for core long entry conditions and swing highs for core short entry conditions. The strategy is designed for standard OHLC candlestick charts only and will not behave as intended on other chart types.
All entries are processed at candle close and use the candle close price for the entry price.
Long stop losses are anchored to the most recent trough and short stop losses are anchored to the most recent peak.
Users can choose between long-only and short-only configurations, or alternatively simulate trades in both directions (long-short). However, when the "Both" option is selected, long entries will close any open short positions and short entries will close any open long positions (as mentioned in the pyramiding sub-section above). This can and will result in variable reward-to-risk outcomes.
The default direction is set to "Long" for a long-only configuration.
The default exit type is set to "Target" for a fixed reward-to-risk configuration.
Long targets are determined by adding a user-defined multiple of the risk range to the entry price and short targets are determined by subtracting a user-defined multiple of the risk range from the entry price.
Even when using a fixed reward-to-risk configuration, realised reward-to-risk outcomes may vary due to market gaps, particularly when positions are held across session boundaries or market closures. Gaps can cause stop losses or exits to be executed at prices materially different from those implied by the strategy’s static distance calculations. Users who wish to minimise gap-related variability may consider applying the close at end of session filter (see core filters section below), accepting that this introduces its own form of reward-to-risk variability.
The default reward-to-risk is set to 1.
Users can adjust strategy parameters via strategy Settings/Inputs/STRATEGY. Selecting a non-target exit type removes profit targets and renders the reward-to-risk input inactive.
Trailing Stop Loss
A trailing stop loss is defined as an exit type that dynamically moves a stop loss level in a favourable direction when a predefined condition is met. For example, a predefined point move or the formation of a higher trough or lower peak.
Risk Range Trailing Stop Loss
The risk range trailing stop loss is defined as a trailing stop mechanism that activates once price has moved favourably by one full risk range. Upon activation, the stop loss is moved to breakeven and subsequently trails favourable price movement by the risk range into profit.
Users can apply this exit type by selecting "Trail" via strategy Settings/Inputs/STRATEGY.
Trend Trailing Stop Loss
The trend trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher troughs (for longs) or lower peaks (for shorts).
Users can apply this exit type by selecting "Trend Trail" via strategy Settings/Inputs/STRATEGY.
Candle Trailing Stop Loss
The candle trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher candle lows (for longs) or lower candle highs (for shorts).
Users can apply this exit type by selecting "Candle Trail" via strategy Settings/Inputs/STRATEGY.
Opposing Candle Colour Close
The opposing candle colour close exit type is defined as an exit condition that closes any long positions when a new red candle forms and closes any short positions when a new green candle forms.
Users can apply this exit type by selecting "Opposing Candle" via strategy Settings/Inputs/STRATEGY.
█ CORE FILTERS
Minimum Risk Range Filter
The minimum risk range filter is defined as an entry filter that invalidates trade signals with a risk range below a user-defined threshold.
The default minimum risk range is set to 4 points/pips.
Users can adjust the minimum risk range via strategy Settings/Inputs/RISK RANGE FILTER.
It is recommended that users set the minimum risk range at least 1–2 points/pips above the selected symbol’s spread to invalidate trades that would be completely impractical under realistic trading conditions.
Time Zone
The time zone is defined using either an IANA region identifier (e.g. Europe/London, America/New_York) or a fixed UTC/GMT offset (e.g. UTC+1, GMT-05:30). Fixed offsets do not account for daylight saving time.
The default time zone is set to Europe/London.
Users can change the time zone via strategy Settings/Inputs/TIME ZONE.
For further information on time zone configuration, please refer to:
data.iana.org
en.wikipedia.org
Session Filter
The session filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined intraday trading session, with session start and end times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, session boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered or held beyond the intended session end, users should configure the session end time at least one full timeframe period earlier than the desired practical session close. For example, on a 5-minute chart with a desired session end at 22:00, the session should typically be configured to end at 21:55. This ensures that no new trades are taken at the final session close and that any session-dependent exit logic is applied before the session ends in practice.
When using custom or non-standard timeframes where the desired session end does not align cleanly with candle boundaries, it is recommended that users set the session end two full timeframe periods earlier than the desired session end. This provides an additional safety buffer, ensuring the strategy avoids taking trades near the session boundary.
By default, the session filter is set to false and the default session is set to "2300-2155".
Users can apply the session filter and adjust session boundaries via strategy Settings/Inputs/SESSION FILTER.
Close At End of Session Filter
The close at end of session filter is defined as an exit filter that closes all open positions when the active trading session ends, provided that the session filter is appropriately configured and applied.
When enabled, the strategy monitors the session filter state and detects the transition from an active session to an inactive session. All open trades are closed on the first candle that falls outside the defined session window. This ensures that no positions are carried beyond the user-defined trading session.
The close at end of session filter operates independently of entry conditions and other exit types. When enabled, it will force the closure of all open positions at session end regardless of the selected exit configuration.
Enabling the close at end of session filter can result in variable reward-to-risk outcomes. Because positions are forcibly closed at session end regardless of stop loss or target placement, exits may occur at prices that differ from those implied by the fixed reward-to-risk configuration. This behaviour is intentional and reflects a design trade-off between enforcing strict session boundaries and allowing trades to reach their predefined directional objectives, regardless of how severely distorted the realised reward-to-risk outcomes could be in the event of price gaps.
By default, the close at end of session filter is set to false.
Users can apply the close at end of session filter via strategy Settings/Inputs/CLOSE AT END OF SESSION FILTER.
Users should also ensure that the session filter is applied and that session boundaries are configured appropriately with respect to candle timestamp behaviour, as described in the session filter section above.
Sample Period Filter
The sample period filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined date-time range, with start and end date-times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, sample period boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered beyond the intended sample period end, users should configure the sample period end date-time at least one full timeframe period earlier than the desired practical sample period end date-time. For example, on a 5-minute chart with a desired end date-time of 01/01/2026 22:00, the end date-time should typically be configured to 01/01/2026 21:55.
The default sample period start and end date-times are set to 01/01/1900 00:00 and 01/01/3000 00:00, respectively.
Users can adjust the sample period via strategy Settings/Inputs/SAMPLE PERIOD FILTER.
█ GENERIC FILTERS
Generic Filter Behaviour
Unless otherwise stated:
"None" inputs return true.
Filters return true only when their selected condition is satisfied.
Close Above-Equal/Below Filter
The close price above-equal/below filter is defined as an entry filter that evaluates the most recent candle close price relative to a given time-series value and invalidates trade signals that do not satisfy a user-defined directional condition.
"Above-Equal" returns true when the most recent candle close price is greater than or equal to any given time-series value.
"Below" returns true when the most recent candle close price is less than any given time-series value.
Minimum and Maximum Boundary Filters
Minimum and maximum boundary filters are defined as entry filters used to constrain time-series values to predefined minimum and/or maximum thresholds, invalidating trade signals that do not satisfy a user-defined threshold criteria. The filters consist of two independent threshold components, minimum (above-equal) and maximum (below-equal), which may be applied individually or together.
When both components are applied simultaneously the filters act as a value range constraint, invalidating trade signals that fall outside of the specified bounds.
"Above-Equal" returns true when the evaluated value is greater than or equal to the user-defined minimum boundary.
"Below-Equal" returns true when the evaluated value is less than or equal to the user-defined maximum boundary.
Minimum Percentage Change Positive-Flat/Negative Filter
The minimum percentage change filter is an entry filter that measures the relative change of a time-series value over a configurable historical window and applies a directional threshold condition, invalidating trade signals that do not meet the directional threshold criteria.
The filter compares the current value to its value n bars ago and computes the percentage difference. A signal returns true only if this percentage change satisfies both:
The selected directional requirement.
The user-defined minimum percentage change magnitude.
"Positive-Flat" direction logic:
Accepts values that have increased or remained unchanged, provided the percentage change is greater than or equal to the minimum threshold.
"Negative" direction logic:
Accepts values that have decreased, provided the magnitude of the decrease meets or exceeds the minimum threshold.
When the minimum threshold is set to 0%, the filter behaves as a pure directional check:
"Positive-Flat" accepts ≥ 0% changes.
"Negative" accepts < 0% changes only.
Basic and Exclusive Rejection Filters
The basic rejection filter is defined as an entry filter that evaluates swing-based wick or body rejections of a given price level and invalidates trade signals that do not satisfy the rejection criteria.
For long trades, "Rejection" returns true when all three of the following conditions are met:
The previous candle open is above a given rejection price.
The trough price is less than or equal to a given rejection price.
The green candle that completes the swing closes above a given rejection price.
For short trades, "Rejection" returns true when all three of the following conditions are met:
The previous candle open is below a given rejection price.
The peak price is greater than or equal to a given rejection price.
The red candle that completes the swing closes below a given rejection price.
The exclusive rejection filter is defined as an entry filter that meets basic rejection filter criteria for only one user-defined price level from a set of given price levels. If the rejection criteria is met for more than one of the given price levels the filter will return false.
Basic and Multi-Part Trend Filters
Basic and multi-part trend filters are defined as entry filters that evaluate changes in time-series values from one period to the next and invalidate trade signals that do not satisfy a user-defined trend condition.
Basic trends operate independently of prior trend state, whereas multi-part trends are defined by the presence or absence of preceding trend sequences. The multi-part trend states are distinguished numerically and the conditions are bound to a user-defined trend count.
"Basic Uptrend" returns true when a time-series value is greater than the preceding value. For example, a basic volume uptrend filter returns true if the most recent candle's volume is greater than the preceding candle's volume.
"Basic Downtrend" returns true when a time-series value is less than the preceding value. For example, a basic volume downtrend filter returns true if the most recent candle's volume is less than the preceding candle's volume.
"Uptrend" returns true while a multi-part uptrend state is valid. The uptrend state begins when a new basic uptrend forms following a basic downtrend and remains valid until a new basic downtrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part uptrend conditions will return true.
"Downtrend" returns true while a multi-part downtrend state is valid. The downtrend state begins when a new basic downtrend forms following a basic uptrend and remains valid until a new basic uptrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part downtrend conditions will return true.
█ FEATURE SET C SPECIFIC FILTERS
All feature set specific indicators use the same calculations as the built-in TradingView indicators unless otherwise stated in the relevant filter sub-section. While users do not need to apply the indicators for the strategy to function, they can of course apply the relevant indicators as visual aids if they so desire.
For further information on how to apply built-in TradingView indicators, please refer to:
www.tradingview.com
Candle Trend Filter
The candle trend filter is an entry filter that evaluates short-term directional candle behaviour as a state-based trend, defined by transitions between candle colours.
A green candle trend begins when a green candle forms following one or more red candles. The trend remains valid while consecutive green candles continue to form. The green candle trend terminates when a red candle forms, completing the sequence.
A red candle trend begins when a red candle forms following one or more green candles. The trend remains valid while consecutive red candles continue to form. The red candle trend terminates when a green candle forms, completing the sequence.
In the context of the core swing strategy, candle trends and swing confirmation are structurally synchronised but directionally inverted. Swing lows, which trigger long entries, are confirmed only at the termination of red candle trends, when a green candle completes the trough. Conversely, swing highs, which trigger short entries, are confirmed only at the termination of green candle trends, when a red candle completes the peak. As a result, long entries inherently occur following completed red candle trends and short entries inherently occur following completed green candle trends. This makes green candle trends incompatible with long entries and red candle trends incompatible with short entries.
The default mode for the candle trend filter is set to "None".
If the candle trend filter mode is set to "Green", the filter will return false for long trades. Conversely, if the candle trend filter mode is set to "Red", the filter will return false for short trades.
The candle trend count defines the number of consecutive same-colour candles required to form a valid candle trend condition for the filter. The opposing-colour candle that follows is not part of the trend itself, but serves to terminate the trend and confirm its completion.
The default candle trend count is set to 3.
Users can apply the candle trend filter and adjust trend count via strategy Settings/Inputs/CANDLE TREND FILTER.
Candlestick Pattern Filter
The candlestick patterns used in this script are the same as those included in my candlestick patterns library and indicator. Link below for library and indicator, respectively:
The candlestick pattern filter is an entry filter that validates trade signals based on the presence of a user-selected candlestick pattern.
Separate filters are provided for long and short entries. Each filter evaluates only patterns that are directionally compatible with the corresponding core entry condition.
Patterns that are structurally incompatible with the core swing logic are evaluated using a one-candle offset. This is necessary where a pattern would otherwise coincide with, or conflict with, the candle used to confirm the core swing high or swing low condition. In these cases, the offset ensures that the candlestick pattern can still be included in the feature set, regardless of its traditional bullish or bearish classification.
The default long and short candlestick pattern filter modes are set to "None".
Users can apply the candlestick pattern filter via strategy Settings/Inputs/CANDLESTICK PATTERN FILTERS.
Chande Momentum Oscillator (CMO) Filters
The default CMO inputs are as follows:
Source is set to "Close".
Length is set to 14.
Users can adjust the CMO inputs via strategy Settings/Inputs/CHANDE MOMENTUM OSCILLATOR (CMO).
The CMO minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply above-equal filter is set to false.
Above-equal threshold is set to -100.
Apply below-equal filter is set to false.
Below-equal threshold is set to 100.
The CMO minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The CMO trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the CMO filters and adjust filter parameters via strategy Settings/Inputs/CMO FILTERS.
Chandelier Exit (CE) Filters
Users can apply up to two independent close above-equal/below filters (see generic filters section above), one for each of the two CE values (long and short).
The default mode for the close above-equal/below filters is set to "None".
The CE rejection filter is defined as an exclusive rejection filter (see generic filters section above) that will only return true if the user-defined CE value is rejected exclusive of the other one.
The default CE rejection filter mode is set to "None".
The long CE above-equal/below short CE filter is an entry filter that evaluates the relative positioning of the long and short CE values and invalidates trade signals that do not satisfy a user-defined directional condition.
"Above-Equal" returns true when long CE is greater than or equal to short CE.
"Below" returns true when long CE is less than short CE.
Users can apply the CE filters and adjust filter parameters via strategy Settings/Inputs/CE FILTERS.
Chart Pattern Filter
The chart patterns used in this script are the same as those included in my chart patterns library and indicator. Link below for library and indicator, respectively:
The chart pattern filter is an entry filter that validates trade signals based on the presence of a user-selected chart pattern.
Separate filters are provided for long and short entries. Each filter evaluates only patterns that are directionally compatible with the corresponding core entry condition.
The default long and short chart pattern filter modes are set to "None".
Users can apply the chart pattern filter via strategy Settings/Inputs/CHART PATTERN FILTERS.
Commodity Channel Index (CCI) Filters
The default CCI length is set to 20.
Users can adjust the CCI inputs via strategy Settings/Inputs/COMMODITY CHANNEL INDEX (CCI).
The CCI minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The CCI trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the CCI filters and adjust filter parameters via strategy Settings/Inputs/CCI FILTERS.
Coppock Curve (CC) Filters
The default CC inputs are as follows:
Long CC length is set to 10.
Short CC length is set to 14.
CC smoothing length is set to 11.
Users can adjust the CC inputs via strategy Settings/Inputs/COPPOCK CURVE (CC).
The CC above-equal/below zero filter is defined as an entry filter that evaluates the CC value relative to the zero line and invalidates trade signals that do not satisfy a user-defined directional condition.
"Above-Equal" returns true when the CC value is greater than or equal to zero.
"Below" returns true when the CC value is less than zero.
The default CC above-equal/below zero filter mode is set to "None".
The CC minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The CC trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the CC filters and adjust filter parameters via strategy Settings/Inputs/CC FILTERS.
█ ALERTS
Users can set alerts for any given strategy configuration via the alerts dialogue box.
Users must first ensure that the correct condition (the strategy title) is selected from the first drop-down list in the alert dialogue box's condition field.
Default alert messages have been configured for both entries and exits so that users can more effectively distinguish between long and short entries and exits while using long-short configurations.
To get alerts for both entries and exits the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "Order fills only". When using "Order fills only" with long-short configurations, it is recommended that users define their alert via the alert name field and use only the default {{strategy.order.alert_message}} call in the alert message field.
Alert conditions generated by "Order fills only" are evaluated after entry conditions have been satisfied and operational constraints (risk, position size and margin requirements) have been applied. As such, trade signals that would result in position sizes exceeding the simulated account's margin constraints will not generate alerts.
To get alerts for entries only the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "alert() function calls only".
The default alert messages generated by "Order fills only" are as follows:
"long entry".
"long exit".
"short entry".
"short exit".
The default alert messages generated by "alert() function calls only" are as follows:
"long entry".
"short entry".
Alert conditions generated by "alert() function calls only" are operational-constraint-agnostic and will generate alerts whenever entry conditions are satisfied, regardless of the simulated account's margin constraints.
For further information on setting and managing alerts, please refer to:
www.tradingview.com
www.tradingview.com
www.tradingview.com
█ LIMITATIONS AND CONSIDERATIONS
Backtesting
Backtest results should always be interpreted cautiously. Strategy performance can vary significantly across time periods and sample sets. While strong historical performance does not guarantee future results, poor historical performance reliably indicates a weak strategy when sample sizes are statistically meaningful.
Statistical Significance and Path-Dependent Outcomes (Overfitting)
In statistical practice, sample sizes of 100 observations are sometimes cited as a rough lower bound for certain forms of basic significance testing. In the context of trading strategy evaluation, such sample sizes are rarely sufficient to produce results that are meaningfully reliable or replicable. Based on practical experience, sample sizes closer to 1,000 observations or more are generally required before performance characteristics begin to stabilise. As a general rule, larger sample sizes increase the reliability and replicability of observed results.
Path dependence refers to situations in which outcomes are determined not only by initial conditions, but by the specific and unique sequence of price movements over a given time period.
Even with large sample sizes, favourable net profit outcomes should be interpreted with caution when they are primarily driven by either variable reward-to-risk configurations or fixed reward-to-risk configurations that employ unrealistically high reward multiples. In both cases, performance is often strongly influenced by path-dependent effects, making such outcomes less reliable and less replicable.
Fixed reward-to-risk configurations are generally less susceptible to path dependence when the reward multiple is kept within reasonable bounds. However, empirical studies and practitioner research suggest that reward multiples above approximately 3:1 increasingly exhibit the same path-dependent characteristics observed in variable reward-to-risk strategies.
Bar Magnifier
Due to the limitations of OHLC data, intra-bar price movement cannot be precisely determined.
When both stop loss and target levels are reached within the same candle, assumptions are made by the strategy tester.
Pine Script's bar magnifier partially mitigates this limitation by evaluating lower-timeframe data. However, this feature is available only to TradingView Premium users and remains inherently limited.
For further information on the bar magnifier functionality, please refer to:
www.tradingview.com
www.tradingview.com
TradingView Premium users can enable bar magnifier via strategy Settings/Properties/FILL ORDERS.
Processing Orders at Candle Close
Backtests cannot accurately account for slippage between signal generation and trade execution.
A practical mitigation is to use fixed-distance stop losses and targets rather than absolute price levels, a feature supported by many brokers and APIs.
Empirical Probabilities
Empirical probabilities are derived directly from observed outcomes rather than from theoretical models or assumed distributions. In the context of trading, they are calculated by measuring the relative frequency of events (such as wins and losses) across a large sample of historical trades.
Unlike conditional or model-based probabilities, empirical probabilities make no assumptions. Their validity relies primarily on sample size and the consistency of the rules used to generate observations, making them particularly relevant for trading systems evaluated under the law of large numbers.
Empirical probabilities are most useful for comparative analysis, such as assessing how different configurations, filters or exit mechanisms alter the statistical behaviour of a strategy under identical conditions. They are not intended to represent true predictive probabilities or to imply stable future performance.
To study empirical probabilities for comparative purposes, it is recommended that users set commission and both long and short margin values to 0% in order to maximise sample size. However, users should not interpret any resulting profits as realistic. Setting commission and margin (in particular) to 0% produces highly distorted outcomes that are not representative of realistic live trading conditions.
█ DISCLAIMER
This Pine Script strategy is provided for educational purposes only and does not constitute financial advice in any form.
Pine Script®策略
Pine Script®策略






















