Neural Network Price Differential Optimized Quantitative Trading Strategy

ATR ANN TANH OHLC4 volatility TIMEFRAME NEURAL NETWORK MACHINE LEARNING
Created on: 2025-06-23 11:39:44 Modified on: 2025-06-23 11:39:44
Copy: 5 Number of hits: 306
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Neural Network Price Differential Optimized Quantitative Trading Strategy  Neural Network Price Differential Optimized Quantitative Trading Strategy

Overview

The Neural Network Price Differential Optimized Quantitative Trading Strategy is a high-frequency trading system based on Artificial Neural Networks (ANN), specifically optimized for 1-second timeframes. This strategy utilizes neural networks to analyze short-term price differential movements, predicts price direction through forward propagation algorithms, and combines volatility filtering and session time control to optimize trading decisions. The core of the strategy lies in capturing minute price movement patterns to achieve stable trading performance with a high profit factor (3.754) in a high-frequency environment.

Strategy Principles

The strategy employs a three-layer neural network architecture with forward propagation to process price differential data:

  1. Input Layer (L0): Receives the percentage difference between the current OHLC4 (Open, High, Low, Close average) and a reference timeframe’s historical OHLC4 (default 15 seconds) as a single input neuron.

  2. First Hidden Layer (L1): Contains 5 neurons using hyperbolic tangent (tanh) as the activation function to perform non-linear transformation on the input data. Each neuron has pre-trained weights to capture specific patterns in price differentials.

  3. Second Hidden Layer (L2): Contains 33 neurons, also using tanh activation functions, processing the first hidden layer’s output through a more complex weight matrix.

  4. Output Layer (L3): A single neuron outputs the final prediction signal, with its value inverted to correct signal direction.

The trading logic revolves around the neural network output value (L3_0): - When L3_0 exceeds the entry threshold (default 0.003), a long signal is triggered - When L3_0 falls below the negative entry threshold (-0.003), a short signal is triggered - When L3_0 falls below the exit threshold (default 0.001), long positions are closed - When L3_0 rises above the negative exit threshold (-0.001), short positions are closed

The strategy also implements a triple filtering mechanism: - Cooldown Filter: After executing a trade, the system enforces a waiting period (default 60 seconds) - Volatility Filter: Using the ATR (Average True Range) indicator, trading only occurs when market volatility exceeds a minimum threshold (default 0.02) - Session Filter: Optionally restricting trading to specific market hours (default 9:00 to 16:00)

Strategy Advantages

  1. High-Precision Predictive Capability: The multi-layer structure of the neural network can capture complex non-linear relationships in price movements that traditional technical indicators struggle to identify. Especially in high-frequency environments, this structure can recognize short-term price patterns, providing more accurate entry and exit signals.

  2. Excellent Risk-Reward Ratio: The strategy achieves a profit factor of 3.754, meaning the total of profitable trades is 3.754 times the total of losing trades, which is an outstanding performance in quantitative strategies.

  3. Flexible Parameter Optimization Space: The strategy provides multiple adjustable parameters, including entry/exit thresholds, cooldown period length, reference timeframe, and minimum volatility requirements, allowing traders to optimize based on different market environments and trading instruments.

  4. Multiple Filtering Mechanisms: By integrating cooldown period, volatility, and trading session triple filtering, the strategy effectively reduces unnecessary trades and false signals, improving trade quality.

  5. Adaptation to High-Frequency Trading Environment: Optimized for 1-second timeframes, the strategy can fully leverage the characteristics of high-frequency trading to capture profit opportunities from short-term price fluctuations.

  6. Low-Latency Implementation: The strategy code structure is clear and efficient, with the neural network portion using pre-trained weights for direct calculation, eliminating the need for real-time training and ensuring low-latency execution in high-frequency environments.

Strategy Risks

  1. Overfitting Risk: The neural network model contains numerous preset weight parameters, risking overfitting to historical data. This may cause the strategy to perform worse in live trading than in backtesting, especially when market conditions change significantly. Mitigation approaches include: periodically retraining the neural network, using longer timeframe data for validation, and implementing robust risk management measures.

  2. Parameter Sensitivity: Strategy performance heavily depends on multiple parameter settings, such as entry/exit thresholds and cooldown period length. Minor changes in parameters may lead to significant fluctuations in strategy performance. It is recommended to find stable parameter combinations through parameter scanning and step testing, avoiding excessive optimization.

  3. High-Frequency Trading Risks: At the 1-second timeframe level, trading costs (such as spreads and slippage) can significantly impact strategy profitability. These costs should be fully considered before live trading, and realistic trading costs should be simulated in backtests.

  4. Technical Implementation Challenges: High-frequency strategies require trading systems with extremely low latency and high reliability. Any network delay, data delay, or execution delay may cause strategy failure. Ensure the use of professional-grade trading infrastructure and low-latency data sources.

  5. Market Volatility Risk: Under extreme market conditions (such as breaking news or liquidity drought), the neural network model may fail to accurately predict price movements, leading to substantial losses. It is advisable to set stop-loss measures and maximum daily loss limits, and to pause strategy operation during periods of extreme volatility.

Strategy Optimization Directions

  1. Neural Network Architecture Optimization:

    • Consider introducing more input features, such as volume, volatility indicators, and price momentum indicators, to enhance model predictive capability
    • Try different hidden layer structures and neuron counts to find the optimal balance between complexity and generalization ability
    • Explore the effects of other activation functions (such as ReLU or Leaky ReLU), which perform better than tanh in some neural network applications
  2. Dynamic Parameter Adjustment Mechanism:

    • Implement entry/exit thresholds that adaptively adjust based on market states, such as increasing thresholds in high-volatility environments and decreasing them in low-volatility environments
    • Develop volatility-aware cooldown period adjustment algorithms to maintain optimal trading frequency across different market phases
  3. Integrated Prediction Framework:

    • Combine neural network models from multiple timeframes to form comprehensive prediction signals
    • Introduce machine learning meta-models to dynamically adjust weights of different prediction models
    • This approach can reduce the limitations of a single model and improve prediction stability
  4. Risk Management Enhancement:

    • Develop dynamic position sizing systems that adjust trading size based on model confidence and market conditions
    • Introduce machine learning-based stop-loss strategies to optimize the risk-reward ratio for each trade
    • Implement intraday session optimization to identify the time periods when the strategy performs best
  5. Real-time Learning and Adaptation:

    • Design online learning mechanisms enabling the neural network to continuously learn from new data and adapt to market changes
    • Implement automatic retraining triggers based on performance monitoring, actively updating the model when strategy performance declines
    • This approach can significantly improve the strategy’s lifespan and stability

Summary

The Neural Network Price Differential Optimized Quantitative Trading Strategy represents cutting-edge practice in modern quantitative trading, successfully applying artificial neural network technology to high-frequency trading. Through a carefully designed multi-layer neural network structure, the strategy can capture subtle patterns in short-term price movements and improve trade quality through multiple filtering mechanisms.

The profit factor of 3.754 demonstrates the strategy’s excellent performance in testing environments, but practical application still requires careful consideration of overfitting, parameter sensitivity, and risks specific to high-frequency trading. Through continuous optimization of the neural network architecture, implementation of dynamic parameter adjustments, and enhancement of risk management, this strategy has the potential to maintain long-term competitiveness in the highly competitive field of quantitative trading.

The key success factor of the strategy lies in combining complex neural network technology with practical trading logic, leveraging both the predictive capabilities of machine learning and the feasibility of actual trading. For experienced quantitative traders, this provides a scalable framework that can be further customized and optimized according to different markets and personal risk preferences.

Strategy source code
/*backtest
start: 2024-06-23 00:00:00
end: 2025-06-21 08:00:00
period: 2h
basePeriod: 2h
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

//@version=5
strategy("ANN Strategy v2 (Optimized for 1s)", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// === INPUTS ===
entryThreshold = input.float(0.003, title="Entry Threshold")
exitThreshold  = input.float(0.001, title="Exit Threshold")
cooldownBars   = input.int(60, title="Cooldown (bars)")  // 60 seconds cooldown
timeframe      = input.timeframe("1", title="Reference Timeframe")  // 1-minute diff reference
minVolatility  = input.float(0.02, title="Min ATR (Volatility Filter)")
useSession     = input.bool(true, title="Use Session Filter")

// === UTILITY FUNCTIONS ===
getDiff() =>
    prev = request.security(syminfo.tickerid, timeframe, ohlc4[1])
    now = ohlc4
    (now - prev) / prev

linear(v) => v
tanh(v) => (math.exp(v) - math.exp(-v)) / (math.exp(v) + math.exp(-v))

// === ANN FORWARD PROPAGATION ===
l0_0 = linear(getDiff())

l1 = array.new_float()
array.push(l1, tanh(l0_0 * 0.8446488687))
array.push(l1, tanh(l0_0 * -0.5674069006))
array.push(l1, tanh(l0_0 * 0.8676766445))
array.push(l1, tanh(l0_0 * 0.5200611473))
array.push(l1, tanh(l0_0 * -0.2215499554))

// === Layer 2 weights ===
w2 = array.from(    0.3341657935, -2.0060003664, 0.8606354375, 0.9184846912, -0.8531172267,    -0.0394076437, -0.4720374911, 0.2900968524, 1.0653326022, 0.3000188806,    -0.559307785, -0.9353655177, 1.2133832962, 0.1952686024, 0.8552068166,    -0.4293220754, 0.8484259409, -0.7154087313, 0.1102971055, 0.2279392724,    0.9111779155, 0.2801691115, 0.0039982713, -0.5648257117, 0.3281705155,    -0.2963954503, 0.4046532178, 0.2460580977, 0.6608675819, -0.8732022547,    0.8810811932, 0.6903706878, -0.5953059103, -0.3084040686, -0.4038498853,    -0.5687101164, 0.2736758588, -0.2217360382, 0.8742950972, 0.2997583987,    0.0708459913, 0.8221730616, -0.7213265567, -0.3810462836, 0.0503867753,    0.4880140595, 0.9466627196, 1.0163097961, -0.9500386514, -0.6341709382,    1.3402207103, 0.0013395288, 3.4813009133, -0.8636814677, 41.3171047132,    1.2388217292, -0.6520886912, 0.3508321737, 0.6640560714, 1.5936220597,    -0.1800525171, -0.2620989752, 0.056675277, -0.5045395315, 0.2732553554,    -0.7776331454, 0.1895231137, 0.5384918862, 0.093711904, -0.3725627758,    -0.3181583022, 0.2467979854, 0.4341718676, -0.7277619935, 0.1799381758,    -0.5558227731, 0.3666152536, 0.1538243225, -0.8915928174, -0.7659355684,    0.6111516061, -0.5459495224, -0.5724238425, -0.8553500765, -0.8696190472,    0.6843667454, 0.408652181, -0.8830470112, -0.8602324935, 0.1135462621,    -0.1569048216, -1.4643247888, 0.5557152813, 1.0482791924, 1.4523116833,    0.5207514017, -0.2734444192, -0.3328660936, -0.7941515963, -0.3536051491,    -0.4097807954, 0.3198619826, 0.461681627, -0.1135575498, 0.7103339851,    -0.8725014237, -1.0312091401, 0.2267643037, -0.6814258121, 0.7524828703,    -0.3986855003, 0.4962556631, -0.7330224516, 0.7355772164, 0.3180141739,    -1.083080442, 1.8752543187, 0.3623326265, -0.348145191, 0.1977935038,    -0.0291290625, 0.0612906199, 0.1219696687, -1.0273685429, 0.0872219768,    0.931791094, -0.313753684, -0.3028724837, 0.7387076712, 0.3806140391,    0.2630619402, -1.9827996702, -0.7741413496, 0.1262957444, 0.2248777886,    -0.2666322362, -1.124654664, 0.7288282621, -0.1384289204, 0.2395966188,    0.6611845175, 0.0466048937, -0.1980999993, 0.8152350927, 0.0032723211,    -0.3150344751, 0.1391754608, 0.5462816249, -0.7952302364, -0.7520712378,    -0.0576916066, 0.3678415302, 0.6802537378, 1.1437036331, -0.8637405666,    0.7016273068, 0.3978601709, 0.3157049654, -0.2528455662, -0.8614146703,    1.1741126834, -1.4046408959, 1.2914477803, 0.9904052964, -0.6980155826)


l2 = array.new_float()
for i = 0 to 32
    sum = 0.0
    for j = 0 to 4
        weight = array.get(w2, i * 5 + j)
        sum += weight * array.get(l1, j)
    array.push(l2, tanh(sum))

// === Output layer weights ===
weights_out = array.from(    -0.1366382003, 0.8161960822, -0.9458773183, 0.4692969576, 0.0126710629,    -0.0403001012, -0.0116244898, -0.4874816289, -0.6392241448, -0.410338398,    -0.1181027081, 0.1075562037, -0.5948728252, 0.5593677345, -0.3642935247,    -0.2867603217, 0.142250271, -0.0535698019, -0.034007685, -0.3594532426,    0.2551095195, 0.4214344983, 0.8941621336, 0.6283377368, -0.7138020667,    -0.1426738249, 0.172671223, 0.0714824385, -0.3268182144, -0.0078989755,    -0.2032828145, -0.0260631534, 0.4918037012)


sum_out = 0.0
for i = 0 to array.size(l2) - 1
    sum_out += array.get(weights_out, i) * array.get(l2, i)

// === Final ANN output (inverted for signal correction) ===
l3_0 = -tanh(sum_out)

// === TRADE FILTERS ===
volatility = ta.atr(14)
isVolOkay = volatility > minVolatility

isSession = (hour >= 9 and hour < 16)  // Adjust to your market hours
sessionOkay = useSession ? isSession : true

// === SIGNAL LOGIC ===
var string activeTrade = "none"
var int lastTradeBar = na
canTrade = (na(lastTradeBar) or (bar_index - lastTradeBar > cooldownBars)) and isVolOkay and sessionOkay

enterLong  = l3_0 > entryThreshold  and activeTrade != "long"  and canTrade
exitLong   = l3_0 < exitThreshold   and activeTrade == "long"
enterShort = l3_0 < -entryThreshold and activeTrade != "short" and canTrade
exitShort  = l3_0 > -exitThreshold  and activeTrade == "short"

// === STRATEGY EXECUTION ===
if barstate.isrealtime
    if enterLong
        strategy.entry("Long", strategy.short)
        activeTrade := "long"
        lastTradeBar := bar_index

    if exitLong
        strategy.close("Long")
        activeTrade := "none"

    if enterShort
        strategy.entry("Short", strategy.long)
        activeTrade := "short"
        lastTradeBar := bar_index

    if exitShort
        strategy.close("Short")
        activeTrade := "none"

// === PLOTTING ===
bgcolor(activeTrade == "long" ? color.new(color.green, 85) : activeTrade == "short" ? color.new(color.red, 85) : na)
plot(l3_0, title="ANN Output (Inverted)", color=color.aqua, linewidth=2)