<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: FMZQuant</title>
    <description>The latest articles on DEV Community by FMZQuant (@fmzquant).</description>
    <link>https://dev.to/fmzquant</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1448536%2Fbd689c08-70c0-43b7-a1c0-505e03f3aa22.jpg</url>
      <title>DEV Community: FMZQuant</title>
      <link>https://dev.to/fmzquant</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/fmzquant"/>
    <language>en</language>
    <item>
      <title>Multi-Indicator Synergistic Reversal Trading Strategy</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Tue, 29 Jul 2025 02:51:04 +0000</pubDate>
      <link>https://dev.to/fmzquant/multi-indicator-synergistic-reversal-trading-strategy-2k6m</link>
      <guid>https://dev.to/fmzquant/multi-indicator-synergistic-reversal-trading-strategy-2k6m</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0f7rtdlwghpt3v0gsivr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0f7rtdlwghpt3v0gsivr.png" alt=" " width="800" height="385"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmoc9qmc8soo643q6eoh0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmoc9qmc8soo643q6eoh0.png" alt=" " width="800" height="411"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br&gt;
The Multi-Indicator Synergistic Reversal Trading Strategy is a comprehensive technical analysis trading system that integrates signals from multiple technical indicators to identify potential market reversal points. Rather than relying on a single indicator, this strategy requires confirmation from at least two indicators to trigger trading signals, thereby increasing the reliability of trading decisions. The strategy primarily combines RSI (Relative Strength Index), MACD (Moving Average Convergence Divergence), Bollinger Bands, Exponential Moving Averages, and volume indicators to form a comprehensive trading decision framework.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Principles&lt;/strong&gt;&lt;br&gt;
The core principle of this strategy is to capture market reversal signals through multi-indicator confirmation, with the following implementation logic:&lt;/p&gt;

&lt;p&gt;Technical Indicator Calculations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Short-term EMA(20) and long-term EMA(50) to determine overall trend direction&lt;/li&gt;
&lt;li&gt;RSI(10) to identify oversold conditions&lt;/li&gt;
&lt;li&gt;MACD(7,21,3) to capture momentum changes&lt;/li&gt;
&lt;li&gt;Bollinger Bands(20,2) to determine if prices are returning to the mean&lt;/li&gt;
&lt;li&gt;Volume compared to its 20-period average to confirm volume support&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Entry Condition Calculations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When RSI is below 33, indicating a possible oversold condition&lt;/li&gt;
&lt;li&gt;MACD line crosses above the signal line, indicating positive momentum shift&lt;/li&gt;
&lt;li&gt;Price re-enters the Bollinger Band from below, suggesting a potential rebound&lt;/li&gt;
&lt;li&gt;Price is above the long-term EMA, confirming an uptrend environment&lt;/li&gt;
&lt;li&gt;Volume is greater than its 20-period average, providing sufficient transaction support&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Signal Generation Mechanism:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Buy signal: When at least two of the above five conditions are met&lt;/li&gt;
&lt;li&gt;Sell signal: When the MACD line crosses below the signal line&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This design allows the strategy to capture rebound opportunities after oversold conditions while trading within the overall trend environment, and reduces false signals by requiring multiple conditions to be met simultaneously.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Advantages&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Multi-Indicator Confirmation: By requiring multiple indicators to confirm simultaneously before triggering a signal, the strategy significantly reduces the possibility of false signals and improves trading accuracy.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Flexible Signal Triggering Mechanism: Only two out of the five conditions need to be met to trigger a signal. This design ensures signal quality while not being overly strict, adapting to market variability.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Comprehensive Market Perspective: Simultaneously considers price trends (EMA), momentum (MACD), overbought/oversold conditions (RSI), volatility (Bollinger Bands), and volume, covering multiple market dimensions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Clear Exit Strategy: Uses MACD crossover as a clear exit signal, avoiding indecision caused by subjective judgment.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Excellent Visualization: The strategy intuitively displays various technical indicators and signals on the chart, making it easy for traders to analyze and understand market conditions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Parameter Customizability: All key parameters can be adjusted through inputs, allowing the strategy to adapt to different market environments and trading styles.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Risks&lt;/strong&gt;&lt;br&gt;
Overtrading Risk: Since only two out of five conditions need to be met to trigger a trade, the strategy may generate too many trading signals in certain market environments, increasing trading costs.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Solution: Consider increasing the number of required conditions, for example, requiring at least three conditions to be met before triggering a trade.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trend Reversal Risk: Although the strategy includes trend confirmation conditions (price above long-term EMA), in strongly downward trends, rebounds may be short-lived and insufficient to form profitable trades.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Solution: Consider adding a trend strength filter, such as requiring the short-term EMA to cross above the long-term EMA, or adding an ADX indicator to confirm trend strength.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Parameter Sensitivity: Strategy performance largely depends on input parameter settings, and different markets and timeframes may require different parameters.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Solution: Conduct comprehensive backtesting and parameter optimization to find the best parameter combinations for specific markets and timeframes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Commission Impact: The strategy sets a 0.075% commission, but in actual trading, the commission structure may be more complex, including slippage, spreads, etc.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Solution: Use more realistic cost estimates in backtesting and consider setting minimum profit targets to ensure positive net returns from trades.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Market Noise Interference: In highly volatile markets, technical indicators may be affected by noise, producing false signals.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Solution: Consider adding time filters or volatility filters, and increasing signal triggering thresholds during high volatility periods.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Strategy Optimization Directions&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Dynamic Parameter Adjustment:&lt;br&gt;
Currently, the strategy uses fixed parameters. Consider dynamically adjusting parameters based on market volatility. For example, increase the Bollinger Band multiplier or extend moving average periods in high-volatility markets. This would make the strategy better adapt to different market environments and reduce false signals in unsuitable market conditions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add Timeframe Confirmation:&lt;br&gt;
Consider adding multi-timeframe analysis, requiring the trend direction of larger timeframes to be consistent with the current timeframe before trading. This top-down approach ensures that trades are conducted with support from the larger trend, increasing the success rate.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Incorporate Stop-Loss Mechanisms:&lt;br&gt;
The current strategy only closes positions when the MACD crosses below the signal line, lacking an effective stop-loss mechanism. Consider adding ATR-based stop-losses or using recent lows as stop-loss points to limit maximum losses per trade.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Optimize Position Management:&lt;br&gt;
The strategy currently uses a fixed proportion (10% of account equity) for trading. Consider volatility-based or risk-adjusted position management. For example, reduce positions in high-volatility markets, increase positions in low-volatility markets, or adjust position size based on signal strength.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add Profit Targets:&lt;br&gt;
In addition to the current exit conditions, consider adding profit targets based on risk-reward ratios. For example, when the price reaches 2 times the ATR from the entry point, close half the position and let the remaining position run. This ensures a certain profit while not missing out on major trends.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Seasonality or Time Filtering:&lt;br&gt;
Analyze whether there are specific seasonal patterns or times of day when the strategy performs better, and optimize trading times accordingly. For example, if certain markets show poorer signal quality during Asian trading sessions, choose not to trade during these periods.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Signal Strength Grading:&lt;br&gt;
Assign different weights to different condition combinations to create a signal strength indicator. For example, when RSI and MACD trigger simultaneously, they may have a higher success rate than other combinations and should be allocated a larger position.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Integrate Fundamental Filters:&lt;br&gt;
Consider avoiding trading during important economic data releases or events, or add assessments of overall market sentiment, for example, by filtering through the VIX index or other sentiment indicators.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The Multi-Indicator Synergistic Reversal Trading Strategy is a well-designed technical analysis trading system that provides a comprehensive market analysis framework by integrating multiple technical indicators. Its core advantage lies in the multi-indicator confirmation mechanism, which effectively reduces false signals that might come from a single indicator while maintaining sufficient flexibility to adapt to market changes.&lt;/p&gt;

&lt;p&gt;The strategy is particularly suitable for finding rebound opportunities after oversold conditions but also ensures trades are conducted in favorable market environments through trend confirmation conditions. By reasonably setting the required number of conditions (at least two conditions must be met), the strategy achieves a balance between signal quality and signal quantity.&lt;/p&gt;

&lt;p&gt;Although there are some risks, such as overtrading and parameter sensitivity, these issues can be resolved through further optimization. In particular, optimization directions such as dynamic parameter adjustment, multi-timeframe confirmation, comprehensive stop-loss mechanisms, and risk-based position management all have the potential to further improve the strategy's robustness and profitability.&lt;/p&gt;

&lt;p&gt;Overall, this is a strategy framework with a good foundation. Traders can make appropriate adjustments and optimizations based on their risk preferences and market environment to achieve better trading results.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy source code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*backtest
start: 2024-07-21 00:00:00
end: 2025-07-19 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT","balance":2000000}]
*/

//@version=6
strategy("XRP Trend &amp;amp; Signal Strategy V2", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent, commission_value=0.075)

// === User Inputs ===
shortMaLen = input.int(20, "Short EMA Length", minval=1)
longMaLen  = input.int(50, "Long EMA Length", minval=1)

rsiLen = input.int(10, "RSI Length")
rsiOversold = input.int(33, "RSI Oversold Level")

macdFast = input.int(7, "MACD Fast Length")
macdSlow = input.int(21, "MACD Slow Length")
macdSignal = input.int(3, "MACD Signal Length")

bbLength = input.int(20, "BB Length")
bbMult = input.float(2.0, "BB Multiplier")

// === Calculations ===
emaShort = ta.ema(close, shortMaLen)
emaLong = ta.ema(close, longMaLen)

rsi = ta.rsi(close, rsiLen)

[macdLine, macdSig, macdHistogram] = ta.macd(close, macdFast, macdSlow, macdSignal)

basis = ta.sma(close, bbLength)
deviation = bbMult * ta.stdev(close, bbLength)
bbUpper = basis + deviation
bbLower = basis - deviation

// === Entry Conditions ===
rsiBuy = rsi &amp;lt; rsiOversold
macdCrossUp = ta.crossover(macdLine, macdSig)
priceReentersBB = close &amp;gt; bbLower and close[1] &amp;lt; bbLower
trendUp = close &amp;gt; emaLong
volumeFilter = volume &amp;gt; ta.sma(volume, 20)

conditionsMet = 0
conditionsMet := rsiBuy ? conditionsMet + 1 : conditionsMet
conditionsMet := macdCrossUp ? conditionsMet + 1 : conditionsMet
conditionsMet := priceReentersBB ? conditionsMet + 1 : conditionsMet
conditionsMet := trendUp ? conditionsMet + 1 : conditionsMet
conditionsMet := volumeFilter ? conditionsMet + 1 : conditionsMet

buyCondition = conditionsMet &amp;gt;= 2
sellCondition = ta.crossunder(macdLine, macdSig)

// === Plot Signals ===
plotshape(buyCondition, title="Buy Arrow", location=location.belowbar, style=shape.labelup, color=color.lime, text="BUY", textcolor=color.black)
plotshape(sellCondition, title="Sell Arrow", location=location.abovebar, style=shape.labeldown, color=color.red, text="SELL", textcolor=color.white)

plotshape(rsiBuy, title="RSI Trigger", location=location.belowbar, color=color.blue, style=shape.circle, size=size.small)
plotshape(macdCrossUp, title="MACD Trigger", location=location.belowbar, color=color.fuchsia, style=shape.triangleup, size=size.small)
plotshape(priceReentersBB, title="BB Re-entry", location=location.belowbar, color=color.orange, style=shape.xcross, size=size.small)

plot(macdLine, title="MACD Line", color=color.green)
plot(macdSig, title="MACD Signal", color=color.red)
plot(macdHistogram, title="MACD Histogram", color=color.purple, style=plot.style_columns, linewidth=1)

plot(emaShort, title="Short EMA", color=color.orange)
plot(emaLong, title="Long EMA", color=color.yellow)
plot(bbUpper, title="BB Upper", color=color.blue)
plot(bbLower, title="BB Lower", color=color.blue)
plot(basis, title="BB Basis", color=color.gray)

// === Alerts ===
alertcondition(buyCondition, title="Buy Signal", message="XRP Reversal Buy Signal Triggered")
alertcondition(sellCondition, title="Sell Signal", message="XRP Reversal Sell Signal Triggered")

// === Strategy Entries ===
if buyCondition
    strategy.entry("Long", strategy.long)
if sellCondition
    strategy.close("Long")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Strategy parameters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6ufyv4thbyrbcqgi5g4r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6ufyv4thbyrbcqgi5g4r.png" alt=" " width="800" height="314"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The original address: &lt;a href="https://www.fmz.com/strategy/502244" rel="noopener noreferrer"&gt;Multi-Indicator Synergistic Reversal Trading Strategy&lt;/a&gt;&lt;/p&gt;

</description>
      <category>trading</category>
      <category>strategy</category>
      <category>indicator</category>
      <category>reversal</category>
    </item>
    <item>
      <title>Multi-Level Trend Momentum Trading Strategy with ATR Risk Management System</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Tue, 29 Jul 2025 01:58:41 +0000</pubDate>
      <link>https://dev.to/fmzquant/multi-level-trend-momentum-trading-strategy-with-atr-risk-management-system-36</link>
      <guid>https://dev.to/fmzquant/multi-level-trend-momentum-trading-strategy-with-atr-risk-management-system-36</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F49gmkjgpqzh0b9d2ry2e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F49gmkjgpqzh0b9d2ry2e.png" alt=" " width="800" height="386"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feswf305a22rt34xtmnu9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feswf305a22rt34xtmnu9.png" alt=" " width="800" height="410"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br&gt;
The Multi-Level Trend Momentum Trading Strategy with ATR Risk Management System is a short-term intraday trading strategy designed specifically for the 15-minute timeframe. This strategy cleverly combines price action signals from candlestick reversal patterns with momentum confirmation from the MACD indicator to identify high-probability trade entry points. The strategy employs ATR-based dynamic stop loss and take profit levels to manage risk and maximize returns, adjusting to current market volatility. Additionally, the strategy labels key price levels on the chart, allowing traders to clearly understand entry points, stop loss levels, and target profit points.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Principles&lt;/strong&gt;&lt;br&gt;
The core principle of this strategy is to capture trading opportunities in the early stages of market trend changes through a dual confirmation system that combines price patterns and technical indicators. Specifically, the strategy is based on the following key components:&lt;/p&gt;

&lt;p&gt;Candlestick Pattern Recognition:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bullish signals: including bullish engulfing patterns and hammers&lt;/li&gt;
&lt;li&gt;Bearish signals: including bearish engulfing patterns and shooting stars&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;MACD Momentum Confirmation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bullish signal: MACD line crosses above the signal line&lt;/li&gt;
&lt;li&gt;Bearish signal: MACD line crosses below the signal line&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trade Signal Generation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Long condition: Bullish candlestick pattern + MACD bullish signal&lt;/li&gt;
&lt;li&gt;Short condition: Bearish candlestick pattern + MACD bearish signal&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Risk Management:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Uses the ATR (Average True Range) indicator to dynamically set stop loss and profit levels&lt;/li&gt;
&lt;li&gt;Stop loss distance = 1.5 × ATR&lt;/li&gt;
&lt;li&gt;Profit target = 2.0 × ATR&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This multi-layer confirmation mechanism ensures the reliability of trading signals, while the ATR risk management system adjusts risk-reward parameters according to actual market volatility, making the strategy highly adaptable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Advantages&lt;/strong&gt;&lt;br&gt;
After in-depth analysis of the strategy code, the following key advantages can be summarized:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Dual Confirmation Mechanism: Combining price action (candlestick patterns) and momentum indicators (MACD) can significantly reduce false signals and improve trade success rates. The strategy only triggers a trade when two independent analytical methods give consistent signals simultaneously.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Dynamic Risk Management: ATR-based stop loss and profit levels automatically adjust according to market volatility, avoiding the inflexibility issues associated with fixed points. During periods of high volatility, stops are wider; during periods of low volatility, stops are tighter.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Clear Visual Feedback: The strategy plots trading signals and key price levels (entry price, stop loss level, profit target) on the chart, allowing traders to intuitively understand trading logic and risk management.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Flexible Parameter Settings: The strategy allows users to adjust MACD parameters, ATR calculation periods, and stop loss/profit multipliers, which can be optimized according to personal risk preferences and specific market environments.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Integrated Money Management: By using a percentage of equity to determine position size, the strategy incorporates basic money management functionality, helping to control risk exposure for each trade.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Risks&lt;/strong&gt;&lt;br&gt;
Despite the strategy's sound design, there are still some potential risks and limitations:&lt;/p&gt;

&lt;p&gt;False Signals in Ranging Markets: In consolidating markets without clear trends, MACD may produce frequent crossover signals which, combined with candlestick patterns, could lead to overtrading and consecutive losses.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Solution: Consider adding additional filtering conditions, such as trend indicators or volatility thresholds, to avoid trading in ranging markets.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Slippage Risk During Extreme Market Events: During major news or black swan events, markets may gap quickly, causing actual stop loss execution prices to be far below preset levels.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Solution: Consider using maximum stop loss amount limits and reduce positions or pause trading before expected high-volatility events (such as important economic data releases).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Parameter Optimization Adaptability Issues: Over-optimizing MACD parameters and ATR multipliers may cause the strategy to perform well on historical data but poorly in future market environments.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Solution: Conduct robustness testing, verifying strategy performance across different market conditions and time periods to avoid overfitting.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lack of Handling Mechanism for Consecutive Signals: When multiple trading signals appear consecutively, the strategy has no clear processing logic, potentially leading to overtrading or missing better entry points.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Solution: Implement signal filtering logic, such as setting minimum interval times or limiting the number of trades within a specific time period.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Optimization Directions&lt;/strong&gt;&lt;br&gt;
Based on the above analysis, the strategy can be optimized in the following areas:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Add Trend Filters: Introduce trend identification components (such as moving average direction or ADX indicator) to only trade in confirmed trend directions, avoiding too many signals in oscillating markets. This can improve the strategy's precision and reduce losing trades caused by false signals.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Optimize Entry Timing: The current strategy enters at the open of the next candle after a signal appears, potentially missing optimal price levels. Consider using limit orders to enter at specific price zones or designing more refined entry mechanisms.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Implement Partial Profit Taking: When prices reach certain profit levels (such as 1×ATR), consider closing positions in batches, with some portion continuing to be held for higher target prices. This allows for securing basic profits while letting winners run.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add Time Filters: Some markets have better volatility and liquidity during specific trading sessions. Time filtering conditions can be added to only look for trading signals during the most active market sessions (such as when European and American markets overlap).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Integrate Market Sentiment Indicators: Introduce volatility indicators (such as VIX or ATR change rates) to evaluate the current market environment, automatically adjusting stop loss levels or trading frequency during periods of extreme volatility.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Optimize Money Management: Implement more sophisticated money management algorithms, such as the Kelly criterion or fixed risk ratio methods, to dynamically adjust position sizes based on the strategy's historical win rate and profit/loss ratio.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The Multi-Level Trend Momentum Trading Strategy with ATR Risk Management System is a well-designed short-term trading system that provides a reliable method for generating trading signals by combining candlestick pattern analysis and MACD momentum confirmation. Its ATR-based dynamic risk management system enables the strategy to adapt to different market volatility conditions, while clear visual feedback and labeling functions help traders better understand and execute trading plans.&lt;/p&gt;

&lt;p&gt;Despite some potential risks, such as false signals in ranging markets and slippage in extreme market conditions, these issues can be effectively mitigated through the suggested optimization measures, including adding trend filters, optimizing entry mechanisms, implementing partial profit strategies, and integrating market sentiment indicators. Furthermore, further refinement of the money management system will help control overall risk and optimize long-term returns.&lt;/p&gt;

&lt;p&gt;Overall, this strategy provides intraday short-term traders with a structured trading framework that combines key elements of technical analysis, risk management, and execution visualization. By reasonably setting parameters and implementing the suggested optimization measures, traders can further enhance the strategy's robustness and profitability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy source code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*backtest
start: 2025-06-20 00:00:00
end: 2025-07-20 00:00:00
period: 15m
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT","balance":2000000}]
*/

//@version=5
strategy("Gold 15m Candle + MACD Strategy with SL/TP &amp;amp; Price Levels", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

// === MACD Settings ===
fastLength = input.int(12, title="MACD Fast Length")
slowLength = input.int(26, title="MACD Slow Length")
signalSmoothing = input.int(9, title="MACD Signal Smoothing")
[macdLine, signalLine, _] = ta.macd(close, fastLength, slowLength, signalSmoothing)

macdBullish = ta.crossover(macdLine, signalLine)
macdBearish = ta.crossunder(macdLine, signalLine)

// === Candlestick Patterns ===
// Bullish Engulfing
bullishEngulfing = close[1] &amp;lt; open[1] and close &amp;gt; open and close &amp;gt; open[1] and open &amp;lt; close[1]
// Bearish Engulfing
bearishEngulfing = close[1] &amp;gt; open[1] and close &amp;lt; open and close &amp;lt; open[1] and open &amp;gt; close[1]
// Hammer (bullish)
hammer = close &amp;gt; open and (high - low) &amp;gt; 2 * (open - close) and (close - low) / (0.001 + high - low) &amp;gt; 0.6
// Shooting Star (bearish)
shootingStar = open &amp;gt; close and (high - low) &amp;gt; 2 * (open - close) and (high - open) / (0.001 + high - low) &amp;gt; 0.6

// === Entry Signals ===
longSignal = (bullishEngulfing or hammer) and macdBullish
shortSignal = (bearishEngulfing or shootingStar) and macdBearish

// === ATR-Based SL/TP ===
atrLen = input.int(14, title="ATR Length")
atr = ta.atr(atrLen)

slMultiplier = input.float(1.5, title="Stop Loss (x ATR)")
tpMultiplier = input.float(2.0, title="Take Profit (x ATR)")

// Variables to hold current trade levels
var float entryPrice = na
var float stopLossPrice = na
var float takeProfitPrice = na

// === Execute Entry and calculate levels on next bar after signal ===
if longSignal
    strategy.entry("Long", strategy.long)
    entryPrice := close  // Entry price at signal candle close (approximate next candle open)
    stopLossPrice := entryPrice - slMultiplier * atr
    takeProfitPrice := entryPrice + tpMultiplier * atr
    strategy.exit("Long Exit", from_entry="Long", stop=stopLossPrice, limit=takeProfitPrice)

if shortSignal
    strategy.entry("Short", strategy.short)
    entryPrice := close
    stopLossPrice := entryPrice + slMultiplier * atr
    takeProfitPrice := entryPrice - tpMultiplier * atr
    strategy.exit("Short Exit", from_entry="Short", stop=stopLossPrice, limit=takeProfitPrice)

// === Plot Signals ===
plotshape(longSignal, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")
plotshape(shortSignal, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")

// === Plot Entry, SL, TP Levels ===
plot(entryPrice, title="Entry Price", color=color.yellow, style=plot.style_linebr, linewidth=2)
plot(stopLossPrice, title="Stop Loss", color=color.red, style=plot.style_linebr, linewidth=2)
plot(takeProfitPrice, title="Take Profit", color=color.green, style=plot.style_linebr, linewidth=2)

// === Labels for price levels on chart ===
if (strategy.position_size &amp;gt; 0)
    label.new(bar_index, entryPrice, text="Entry: " + str.tostring(entryPrice, format.mintick), color=color.yellow, style=label.style_label_left, yloc=yloc.price, size=size.small)
    label.new(bar_index, stopLossPrice, text="SL: " + str.tostring(stopLossPrice, format.mintick), color=color.red, style=label.style_label_left, yloc=yloc.price, size=size.small)
    label.new(bar_index, takeProfitPrice, text="TP: " + str.tostring(takeProfitPrice, format.mintick), color=color.green, style=label.style_label_left, yloc=yloc.price, size=size.small)
else if (strategy.position_size &amp;lt; 0)
    label.new(bar_index, entryPrice, text="Entry: " + str.tostring(entryPrice, format.mintick), color=color.yellow, style=label.style_label_left, yloc=yloc.price, size=size.small)
    label.new(bar_index, stopLossPrice, text="SL: " + str.tostring(stopLossPrice, format.mintick), color=color.red, style=label.style_label_left, yloc=yloc.price, size=size.small)
    label.new(bar_index, takeProfitPrice, text="TP: " + str.tostring(takeProfitPrice, format.mintick), color=color.green, style=label.style_label_left, yloc=yloc.price, size=size.small)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Strategy parameters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzxla6uub5klbfltl3v4x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzxla6uub5klbfltl3v4x.png" alt=" " width="800" height="212"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The original address: &lt;a href="https://www.fmz.com/strategy/502248" rel="noopener noreferrer"&gt;Multi-Level Trend Momentum Trading Strategy with ATR Risk Management System&lt;/a&gt;&lt;/p&gt;

</description>
      <category>trading</category>
      <category>strategy</category>
      <category>momentum</category>
      <category>trend</category>
    </item>
    <item>
      <title>Multi-Indicator Synchronized Trend Following Strategy</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Tue, 29 Jul 2025 01:08:22 +0000</pubDate>
      <link>https://dev.to/fmzquant/multi-indicator-synchronized-trend-following-strategy-1onb</link>
      <guid>https://dev.to/fmzquant/multi-indicator-synchronized-trend-following-strategy-1onb</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9pnwl94c66oskmbrvgvl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9pnwl94c66oskmbrvgvl.png" alt=" " width="800" height="387"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiswt7cjd86gcl3wh6q84.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiswt7cjd86gcl3wh6q84.png" alt=" " width="800" height="387"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br&gt;
The Multi-Indicator Synchronized Trend Following Strategy is a comprehensive trading system that combines multiple technical indicators designed to capture strong market trends. This strategy integrates an Exponential Moving Average (EMA) bundle, Supertrend indicator, Higher Highs/Lower Lows (HH/LL) breakouts, and key support/resistance levels as stop-loss points, forming a multi-layered trading decision framework. The strategy primarily operates during the London trading session (UTC 8:00-16:59) to ensure execution in the most liquid market conditions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Principles&lt;/strong&gt;&lt;br&gt;
The core principle of this strategy is to identify robust trend directions and potential entry points through the confirmation of multiple indicators while managing risk using key price levels. The specific principles are as follows:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;EMA Bundle for Trend Direction: The strategy employs four different period EMAs (25, 75, 140, and 355) to confirm trend direction through their alignment and price positioning relative to them. An uptrend is confirmed when shorter-term EMAs are above longer-term EMAs in sequential order; conversely for downtrends.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Supertrend Indicator Confirmation: Utilizes the Supertrend indicator (multiplier 3.0, ATR period 10) as a trend confirmation tool, enhancing signal reliability.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Higher Highs/Lower Lows (HH/LL) Breakout Validation: Long entries are confirmed when price breaks above previous highs (HH); short entries when price breaks below previous lows (LL). This ensures entries only when price has momentum behind the breakout.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Key Support/Resistance as Stop-Loss: Uses pivot points as automatic stop-loss locations, providing objective exit points for trades.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Session Filtering: Executes trades only during the London trading session (UTC 8:00-16:59), avoiding less liquid market periods.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Long entry conditions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Supertrend indicator shows uptrend&lt;/li&gt;
&lt;li&gt;Closing price above EMA25 and EMA75&lt;/li&gt;
&lt;li&gt;EMA25 above EMA75&lt;/li&gt;
&lt;li&gt;EMA75 above EMA140&lt;/li&gt;
&lt;li&gt;EMA140 above EMA355&lt;/li&gt;
&lt;li&gt;Current high breaks above previous high&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Short entry conditions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Supertrend indicator shows downtrend&lt;/li&gt;
&lt;li&gt;Closing price below EMA25 and EMA75&lt;/li&gt;
&lt;li&gt;EMA25 below EMA75&lt;/li&gt;
&lt;li&gt;EMA75 below EMA140&lt;/li&gt;
&lt;li&gt;EMA140 below EMA355&lt;/li&gt;
&lt;li&gt;Current low breaks below previous low&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Strategy Advantages&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Multiple Confirmations Reduce False Signals: By requiring consistency across multiple indicators, the strategy significantly reduces false signals, only trading when high-probability trends are established.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Adaptive Trend Identification: The multi-period combination of EMAs can adapt to different market states, identifying trend changes across various timeframes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Objective Entry and Exit Points: The strategy utilizes clear technical conditions and price levels for entries and exits, reducing the impact of subjective judgment.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Intelligent Risk Management: Using pivot points as stop-loss locations automatically adjusts risk levels according to market structure, providing an adaptive risk control mechanism.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Session Filtering Enhances Win Rate: By restricting trading time to the London session, the strategy focuses on high-liquidity, moderate-volatility market environments, improving trade quality.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Combined Logic of Trend and Breakout: Merges the advantages of trend following (EMAs and Supertrend) with breakout trading (HH/LL), capable of both capturing major trends and executing precise entries at key price levels.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Risks&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Over-reliance on Technical Indicators: The strategy depends on the coordinated action of multiple technical indicators, which may generate misleading signals during extreme market volatility or indicator failure. The solution is to introduce fundamental filters or volatility adjustment mechanisms.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Delayed Trend Entry: Due to the requirement for multiple confirmations, the strategy may enter trends late, missing some profit from the initial phase. Consider adding a more sensitive fast-entry rule using smaller position sizes for preliminary trades.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Potentially Distant Stop-Loss Points: Using pivot points as stops may result in wider stop distances, increasing per-trade risk. Implement a stepped stop-loss strategy or introduce ATR-based dynamic stops to control risk.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;EMA Crossover Lag: EMAs as lagging indicators may respond inadequately during sharp market reversals. Consider adding leading indicators like RSI or MACD divergence to provide early warnings of potential trend changes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Session Restrictions May Miss Important Moves: Trading only during the London session may miss significant moves in other sessions. Consider adding special rules for important economic data release periods or extending to other major trading sessions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Parameter Sensitivity: Fixed EMA periods and Supertrend parameters may perform inconsistently across different market environments. Recommend parameter optimization or implementing adaptive parameter adjustment mechanisms.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Optimization Directions&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Adaptive Parameter Adjustment: Automatically adjust EMA periods and Supertrend parameters based on market volatility to adapt to different market environments. For example, use longer EMA periods in high-volatility markets and shorter periods in low-volatility markets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add Volume Filters: Introduce volume confirmation mechanisms to ensure breakout trades are only executed with volume support, significantly improving breakout signal reliability.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Integrate Market Structure Analysis: Add market structure recognition algorithms such as support/resistance zone identification and market range definition to avoid overtrading in ranging markets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Optimize Profit-Taking Mechanisms: The current strategy lacks explicit profit-taking mechanisms. Implement multi-level profit-taking strategies based on target price levels, time, or volatility to lock in profits more effectively.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add Reversal Warning Indicators: Integrate overbought/oversold signals from oscillators (such as RSI or CCI) to provide warnings when trends may be exhausting, avoiding entries at trend endpoints.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Introduce Multi-Timeframe Analysis: Use higher timeframe trend direction as a trading filter condition, executing trades only when higher timeframe trend direction aligns, improving the strategy's win rate.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Dynamic Position Sizing: Adjust position size based on trend strength and market volatility, increasing positions in strong trends and reducing positions in weak trends or high-volatility markets to optimize capital efficiency.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The Multi-Indicator Synchronized Trend Following Strategy is a well-designed comprehensive trading system that demonstrates excellent performance in identifying and following market trends through multi-layered technical indicator confirmation. The strategy is particularly suitable for medium to long-term trend traders, effectively capturing major market trends while providing an objective risk management framework.&lt;/p&gt;

&lt;p&gt;The core advantage of the strategy lies in its multiple confirmation mechanism, significantly improving trading signal reliability through EMA bundle alignment, Supertrend direction, price breakouts, and session filtering. Meanwhile, market structure-based stop-loss settings provide intelligent risk control solutions.&lt;/p&gt;

&lt;p&gt;However, the strategy also has some inherent limitations, such as indicator lag, parameter sensitivity, and session restrictions. By implementing the suggested optimization measures—adaptive parameter adjustment, volume confirmation, market structure analysis, profit-taking optimization, reversal warnings, multi-timeframe analysis, and dynamic position sizing—the strategy's robustness and adaptability can be further enhanced.&lt;/p&gt;

&lt;p&gt;Overall, this strategy demonstrates the systematic application of technical analysis by integrating multiple indicators and technical conditions to provide a comprehensive and objective framework for trading decisions. For traders willing to implement appropriate optimization and risk management, this is a trend-following system with practical value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy source code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*backtest
start: 2025-03-01 00:00:00
end: 2025-07-19 08:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT","balance":2000000}]
*/


//@version=5
strategy("Auto ST + EMA Bundle + HHLL + Pivot SL", overlay=true, margin_long=100, margin_short=100)

// — User Inputs
ema1Len = input.int(25, "EMA 25")
ema2Len = input.int(75, "EMA 75")
ema3Len = input.int(140, "EMA 140")
ema4Len = input.int(355, "EMA 355")
superMult = input.float(3.0, "Supertrend Multiplier")
superATR = input.int(10, "Supertrend ATR Period")
pivotLen = input.int(5, "Pivot Lookback")

// — EMA calculations
ema25 = ta.ema(close, ema1Len)
ema75 = ta.ema(close, ema2Len)
ema140 = ta.ema(close, ema3Len)
ema355 = ta.ema(close, ema4Len)
plot(ema25, color=color.orange)
plot(ema75, color=color.blue)
plot(ema140, color=color.green)
plot(ema355, color=color.purple)

// — Supertrend
[st, direction] = ta.supertrend(superMult, superATR)
upTrend = direction &amp;gt; 0
downTrend = direction &amp;lt; 0
hline(0, "Zero", color.gray)
plot(st, color=upTrend ? color.green : color.red, style=plot.style_line)

// — HH / LL detection
var float prevHigh = na
var float prevLow = na
prevHigh := ta.highest(high, pivotLen)[1]
prevLow := ta.lowest(low, pivotLen)[1]

// — Entry Conditions
longCond = upTrend and close &amp;gt; ema25 and close &amp;gt; ema75 and ema25 &amp;gt; ema75 and ema75 &amp;gt; ema140 and ema140 &amp;gt; ema355 and high &amp;gt; prevHigh
shortCond = downTrend and close &amp;lt; ema25 and close &amp;lt; ema75 and ema25 &amp;lt; ema75 and ema75 &amp;lt; ema140 and ema140 &amp;lt; ema355 and low &amp;lt; prevLow

// — Pivots for stop-loss
pivotHigh = ta.pivothigh(high, pivotLen, pivotLen)
pivotLow = ta.pivotlow(low, pivotLen, pivotLen)

// — Entry &amp;amp; Exit
if (longCond)
    strategy.entry("Long", strategy.long)
    if not na(pivotLow)
        strategy.exit("Exit Long", "Long", stop=pivotLow)

if (shortCond)
    strategy.entry("Short", strategy.short)
    if not na(pivotHigh)
        strategy.exit("Exit Short", "Short", stop=pivotHigh)

// — London session filter
inSession = (hour &amp;gt;= 8 and hour &amp;lt; 17)  // London 08:00–16:59 UTC
if not inSession
    strategy.close_all(comment="outside session")

// — Plot HH/LL for reference
plotshape(high == prevHigh, title="HH", style=shape.triangleup, location=location.abovebar, color=color.green, size=size.tiny)
plotshape(low == prevLow, title="LL", style=shape.triangledown, location=location.belowbar, color=color.red, size=size.tiny)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Strategy parameters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbpm58rs8vc4sjbtbaty6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbpm58rs8vc4sjbtbaty6.png" alt=" " width="800" height="246"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The original address: &lt;a href="https://www.fmz.com/strategy/502250" rel="noopener noreferrer"&gt;Multi-Indicator Synchronized Trend Following Strategy&lt;/a&gt;&lt;/p&gt;

</description>
      <category>trend</category>
      <category>indicator</category>
      <category>strategy</category>
      <category>cryptocurrency</category>
    </item>
    <item>
      <title>RSI and Bollinger Bands Oversold Bounce Quantitative Trading Strategy</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Mon, 28 Jul 2025 09:13:16 +0000</pubDate>
      <link>https://dev.to/fmzquant/rsi-and-bollinger-bands-oversold-bounce-quantitative-trading-strategy-1c3k</link>
      <guid>https://dev.to/fmzquant/rsi-and-bollinger-bands-oversold-bounce-quantitative-trading-strategy-1c3k</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0svehrt1yuf8fislgiip.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0svehrt1yuf8fislgiip.png" alt=" " width="800" height="388"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4sczunta3kjif6ibrp7k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4sczunta3kjif6ibrp7k.png" alt=" " width="800" height="406"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br&gt;
This strategy is a quantitative trading approach that combines the Relative Strength Index (RSI) and Bollinger Bands to identify potential bounce opportunities in oversold market conditions. The strategy looks for situations where the price touches or falls below the lower Bollinger Band while the RSI simultaneously indicates oversold conditions. With a 5% take profit and 2% stop loss setup, the strategy aims to capture reasonable returns while controlling risk. This multi-indicator approach provides more reliable trading signals and reduces the risks associated with false breakouts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Principles&lt;/strong&gt;&lt;br&gt;
The strategy is based on the synergistic effect of two main technical indicators:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Bollinger Bands: Consisting of a 20-day Simple Moving Average (SMA) as the middle band, with upper and lower bands set at 2 standard deviations above and below. Bollinger Bands reflect price volatility, and when price touches or breaks below the lower band, it often indicates that the market may be in an oversold condition.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Relative Strength Index (RSI): Using a 14-period setting, when the RSI falls below 30, the market is considered oversold, suggesting a potential bounce opportunity.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The trading logic is as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Entry condition: Price closes at or below the lower Bollinger Band, RSI is below 30, and there is currently no open position.&lt;/li&gt;
&lt;li&gt;Exit condition: Take profit when price reaches 1.05 times the entry price (5% gain), or stop loss when price falls to 0.98 times the entry price (2% loss).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The strategy uses barstate.isconfirmed to ensure trades are executed only after the candle closes, avoiding false signals that might occur during candle formation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Advantages&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Multi-indicator Confirmation: By combining RSI and Bollinger Bands, the strategy provides more reliable trading signals. Single indicators can be misleading, while multiple indicators working together filter out many false signals.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Clear Risk Management: The strategy incorporates a 5% take profit and 2% stop loss, creating a risk-reward ratio of 2.5:1, which aligns with healthy trading risk management principles.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Simple and Clear Logic: Trading rules are intuitive and easy to understand, without complex conditional judgments, making monitoring and adjustment straightforward.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Based on Statistical Principles: Bollinger Bands are based on normal distribution theory, with prices theoretically spending only about 5% of time outside the bands. Combined with RSI oversold signals, this further improves the success rate.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Flexible Parameter Settings: The strategy allows adjustment of Bollinger Band length, multiplier, RSI period, and oversold threshold, making it adaptable to different market environments.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Fully Automated: The strategy can be executed fully automatically, reducing emotional interference and improving trading discipline.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Risks&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Ranging Market Risk: In prolonged sideways markets, prices may repeatedly touch the lower Bollinger Band and trigger multiple trades, but lack sufficient upward momentum to reach the take profit point, resulting in consecutive small losses.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Trending Downward Risk: In strong downtrends, prices may continue to make new lows. Even though RSI and Bollinger Bands indicate oversold conditions, the market may continue to decline, triggering stop losses.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Parameter Sensitivity: Different market environments may require different parameter settings. Fixed parameters may perform poorly when market conditions change.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Slippage and Commission Impact: The strategy sets a 0.1% commission, but in actual trading, slippage can further increase trading costs, especially in volatile markets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Lack of Volume Confirmation: The current strategy only considers price and technical indicators without incorporating volume or market structure factors, potentially missing important market information.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Risk mitigation methods include: setting stricter entry conditions, such as requiring RSI rebound confirmation; adding trend filters to avoid counter-trend trading in strong trends; adjusting parameters for different markets; and considering the inclusion of volume or other indicators as auxiliary confirmation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Optimization Directions&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Add Trend Filters: Consider adding long-period moving averages (such as 50 or 200-day MA) as trend filters, only considering long positions when the average is pointing upward or price is above the average, avoiding counter-trend operations in downtrends.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Optimize Entry Confirmation Mechanism: Consider waiting for RSI to show an upturn or for price to close above the lower Bollinger Band after an oversold signal appears before entering, reducing false signals and improving success rates.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Dynamic Stop Loss and Take Profit: Replace fixed percentage stop loss and take profit with ATR (Average True Range) based dynamic levels to better adapt to changes in market volatility.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Incorporate Volume Analysis: Add volume confirmation to entry conditions, such as requiring increased volume when signals trigger, indicating higher market acceptance of the reversal.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Time Filters: Avoid high volatility periods such as important economic data releases, or use different parameter settings for different trading sessions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add Market Environment Adaptive Mechanism: Automatically adjust Bollinger Band multipliers and RSI thresholds based on market volatility (such as VIX index or ATR values) to maintain stable performance across different market environments.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add Position Management Logic: Consider partial profit-taking and position scaling strategies, such as partially closing positions when reaching certain profit levels to protect gains while allowing remaining positions to continue profiting.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Explore Machine Learning Optimization: Use machine learning algorithms to automatically optimize parameter combinations or predict which oversold signals are more likely to lead to successful bounces.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The RSI and Bollinger Bands Oversold Bounce Quantitative Trading Strategy is a structurally simple but logically rigorous quantitative trading system. By using Bollinger Bands to identify extreme price areas and confirming oversold conditions with RSI, it effectively captures potential market reversal points. The strategy incorporates reasonable risk control measures, including clear stop loss and take profit levels.&lt;/p&gt;

&lt;p&gt;While the strategy has advantages such as multi-indicator confirmation and clear risk management, it may face challenges in strongly trending or prolonged ranging markets. To improve robustness, consider adding trend filters, optimizing entry confirmation mechanisms, implementing dynamic stop loss and take profit levels, and incorporating volume analysis among other optimization directions.&lt;/p&gt;

&lt;p&gt;This strategy is particularly suitable for medium to short-term traders, especially in relatively stable but volatile market environments. Through continuous monitoring and optimization, this strategy has the potential to become an effective tool in a trading portfolio, providing stable oversold bounce trading opportunities for investors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy source code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*backtest
start: 2024-07-22 00:00:00
end: 2025-07-20 08:00:00
period: 2d
basePeriod: 2d
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT","balance":2000000}]
*/

//@version=6
strategy(
 "RSI + Bollinger Bands Long Strategy",
 overlay=true,
 default_qty_type=strategy.percent_of_equity,
 default_qty_value=100,
 commission_type=strategy.commission.percent,
 commission_value=0.1
 )

// Parameters
bbLength = input.int(20, "BB Length")
bbMult = input.float(2.0, "BB Multiplier")
rsiLength = input.int(14, "RSI Length")
rsiOversold = input.int(30, "RSI Oversold Level")

// Bollinger Bands hesaplama
basis = ta.sma(close, bbLength)
dev = bbMult * ta.stdev(close, bbLength)
upperBB = basis + dev
lowerBB = basis - dev

// RSI calculation
rsi = ta.rsi(close, rsiLength)

// Bollinger Bands and RSI plots
plot(basis, "BB Basis", color=color.orange)
plot(upperBB, "BB Upper", color=color.blue)
plot(lowerBB, "BB Lower", color=color.blue)
plot(rsi, "RSI", color=color.purple)
hline(rsiOversold, "RSI Oversold", color=color.green)

// Long condition: price below or equal to the lower band, RSI oversold, no position, bar close
longCondition = (close &amp;lt;= lowerBB) and (rsi &amp;lt; rsiOversold) and (strategy.position_size &amp;lt;= 0) and barstate.isconfirmed

if (longCondition)
    strategy.entry("Long", strategy.long)

// TP and SL
if (strategy.position_size &amp;gt; 0)
    entryPrice = strategy.position_avg_price
    takeProfit = entryPrice * 1.05
    stopLoss = entryPrice * 0.98
    strategy.exit("Long Exit", from_entry="Long", limit=takeProfit, stop=stopLoss)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Strategy parameters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flbg39v24u1mhqnzhpkuz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flbg39v24u1mhqnzhpkuz.png" alt=" " width="800" height="145"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The original address:&lt;a href="https://www.fmz.com/strategy/502332" rel="noopener noreferrer"&gt;RSI and Bollinger Bands Oversold Bounce Quantitative Trading Strategy&lt;/a&gt;&lt;/p&gt;

</description>
      <category>trading</category>
      <category>strategy</category>
      <category>cryptocurrency</category>
      <category>bollinger</category>
    </item>
    <item>
      <title>New York Liquidity Reversal Breakout Trading Strategy</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Mon, 28 Jul 2025 09:07:51 +0000</pubDate>
      <link>https://dev.to/fmzquant/new-york-liquidity-reversal-breakout-trading-strategy-5ec3</link>
      <guid>https://dev.to/fmzquant/new-york-liquidity-reversal-breakout-trading-strategy-5ec3</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4e1x5vunm15dwsdppssd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4e1x5vunm15dwsdppssd.png" alt=" " width="800" height="223"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgd2v1wgnfwzqzi5nu1kf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgd2v1wgnfwzqzi5nu1kf.png" alt=" " width="800" height="201"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br&gt;
The New York Liquidity Reversal Breakout Trading Strategy is a quantitative trading system focused on the New York trading session, designed to capture market reversals by identifying liquidity area breakouts around previous day's high and low levels, combined with price action confirmation signals. The core of the strategy is to look for price reversal patterns after breaking previous day's extremes during the New York market hours (8:00 AM to 10:30 AM ET), using candlestick pattern confirmations and employing a fixed risk-reward ratio for trade management. This strategy specifically targets reversal scenarios following liquidity hunts, capitalizing on market participants' behavioral responses to key price levels.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Principles&lt;/strong&gt;&lt;br&gt;
This strategy is based on market liquidity theory and price action analysis, with its core operating principles as follows:&lt;/p&gt;

&lt;p&gt;Time Filtering: The strategy operates exclusively during the New York trading session (8:00 AM to 10:30 AM ET), which is a period of high market activity and volatility.&lt;/p&gt;

&lt;p&gt;Liquidity Area Definition: Previous day's high and low points are used as key liquidity areas, which typically attract a large number of orders and become focal points for market participants.&lt;/p&gt;

&lt;p&gt;Liquidity Hunt Identification:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Long condition: Price breaks below the previous day's low (sweepLow) but closes above it, indicating bullish control.&lt;/li&gt;
&lt;li&gt;Short condition: Price breaks above the previous day's high (sweepHigh) but closes below it, indicating bearish control.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Price Action Confirmation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Long confirmation: Bullish engulfing pattern (bullishEngulf) confirms the long signal.&lt;/li&gt;
&lt;li&gt;Short confirmation: Bearish engulfing pattern (bearishEngulf) confirms the short signal.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trade Frequency Control: The strategy limits trading to one entry per direction per session per asset per day, preventing overtrading.&lt;/p&gt;

&lt;p&gt;Risk Management: Fixed stop loss (10 pips) and take profit based on risk-reward ratio (default 3:1) ensure consistency in money management.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Advantages&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Market Psychology Exploitation: The strategy effectively leverages market participants' behavioral patterns at key price levels, particularly reversal opportunities following liquidity traps.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Time Filtering Effectiveness: By focusing on the New York trading session, the strategy captures the market's most liquid and volatile time window, enhancing signal quality.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Multiple Confirmation Mechanisms: Combines price breakouts, reversal confirmations, and engulfing patterns as multiple confirmation mechanisms, reducing false signal risks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Clear Risk Management: Employs preset stop-loss and risk-reward-based take-profit settings, making money management more standardized and systematic.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Trade Frequency Control: Limiting to one trade per direction per asset per day avoids overtrading and accumulation of trading costs.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Streamlined Efficient Design: The strategy logic is clear and concise, with minimal computational burden, suitable for real-time market analysis and quick execution.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Visual References and Alert Functionality: Includes chart markers and alert functions for monitoring and executing trades.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Risks&lt;/strong&gt;&lt;br&gt;
False Signal Risk: Despite multiple confirmation mechanisms, market noise can still lead to false signals, especially on days with extremely low or high volatility.&lt;/p&gt;

&lt;p&gt;Solution: Consider adding additional filtering conditions, such as volatility indicators or trend confirmation indicators, to reduce false signals.&lt;/p&gt;

&lt;p&gt;Fixed Stop Loss Risk: Using a fixed pip stop loss may not be suitable for all market environments, potentially leading to premature stops in high-volatility situations.&lt;/p&gt;

&lt;p&gt;Solution: Consider using volatility-based dynamic stop losses, such as ATR (Average True Range) adjusted stop levels.&lt;/p&gt;

&lt;p&gt;Time Window Limitation: Focusing solely on the New York trading session may miss good opportunities in other sessions.&lt;/p&gt;

&lt;p&gt;Solution: The strategy could be extended to include London or Asian trading sessions, but would need optimization for each session's characteristics.&lt;/p&gt;

&lt;p&gt;Single Confirmation Pattern: Relying solely on engulfing patterns for confirmation may not be robust enough.&lt;/p&gt;

&lt;p&gt;Solution: Consider integrating other price action patterns or technical indicators as additional confirmation.&lt;/p&gt;

&lt;p&gt;Money Management Risk: Fixed risk-reward ratio may not adapt to all market conditions.&lt;/p&gt;

&lt;p&gt;Solution: Consider dynamically adjusting target profit points based on market volatility and support/resistance levels.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Optimization Directions&lt;/strong&gt;&lt;br&gt;
Dynamic Liquidity Area Definition: Currently, the strategy only uses the previous day's high and low as liquidity areas. Consider expanding to multi-day extreme points or key structural positions.&lt;/p&gt;

&lt;p&gt;Optimization Rationale: Multi-day extreme points typically accumulate more order flow, forming more significant liquidity areas that may provide higher quality reversal signals.&lt;/p&gt;

&lt;p&gt;Volatility Filtering: Add volatility indicators such as ATR to avoid trading in low-volatility environments or adjust parameters accordingly.&lt;/p&gt;

&lt;p&gt;Optimization Rationale: Reversal signals in low-volatility environments are typically of lower quality, while high-volatility environments require wider stop settings.&lt;/p&gt;

&lt;p&gt;Trend Direction Filtering: Add longer-term trend determination and only trade reversals in the trend direction.&lt;/p&gt;

&lt;p&gt;Optimization Rationale: Trading reversals in the direction of the trend typically has a higher success rate, potentially improving overall win rate.&lt;/p&gt;

&lt;p&gt;Multi-Timeframe Confirmation: Add confirmation signals from higher timeframes.&lt;/p&gt;

&lt;p&gt;Optimization Rationale: Signals from higher timeframes are typically more reliable and can reduce false breakouts.&lt;/p&gt;

&lt;p&gt;Dynamic Stop Loss and Target Setting: Adjust stop loss and target positions based on market volatility or key price levels.&lt;/p&gt;

&lt;p&gt;Optimization Rationale: Fixed pip stops don't adapt to all market conditions; dynamic adjustment can improve money management efficiency.&lt;/p&gt;

&lt;p&gt;Volume Confirmation: Add volume analysis to confirm the authenticity of breakouts and reversals.&lt;/p&gt;

&lt;p&gt;Optimization Rationale: Effective reversals are typically accompanied by volume characteristic changes; adding this dimension can improve signal quality.&lt;/p&gt;

&lt;p&gt;Machine Learning Parameter Optimization: Use machine learning methods to automatically adjust strategy parameters to adapt to different market environments.&lt;/p&gt;

&lt;p&gt;Optimization Rationale: Automated parameter optimization can improve strategy adaptability across different market conditions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The New York Liquidity Reversal Breakout Trading Strategy is a quantitative trading system based on market microstructure and price action, trading by identifying breakouts of key liquidity areas and subsequent reversal signals. The strategy's strengths lie in its clear logic, strict time filtering, clear risk management, and multiple confirmation mechanisms. Despite some limitations, such as fixed stop-loss settings and single time window trading, through the suggested optimization directions like dynamic liquidity area definition, volatility filtering, and multi-timeframe confirmation, strategy performance can be further enhanced. This strategy is particularly suitable for traders who understand market liquidity dynamics and price action, offering practical value for quantitative traders seeking high-probability reversal trading opportunities.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy source code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*backtest
start: 2025-06-22 00:00:00
end: 2025-07-11 00:00:00
period: 5m
basePeriod: 5m
exchanges: [{"eid":"Futures_Binance","currency":"SOL_USDT","balance":2000000}]
*/

//@version=6
strategy("NY Liquidity Reversal - Debug Mode", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=1, calc_on_order_fills=true, calc_on_every_tick=true)

// === User Inputs ===
sl_pips = input.int(10, "Stop Loss (pips)", minval=1)
rr_ratio = input.float(3.0, "Reward-to-Risk Ratio", minval=1.0)
tp_pips = sl_pips * rr_ratio
pip = syminfo.mintick * 10

// === Time Definitions ===
ny_start = timestamp("America/New_York", year, month, dayofmonth, 08, 00)
ny_end = timestamp("America/New_York", year, month, dayofmonth, 10, 30)
in_ny = (time &amp;gt;= ny_start and time &amp;lt;= ny_end)

// === Session Limiter ===
currentDay = dayofmonth + (month * 100) + (year * 10000)
var int lastTradeDay = na
canTradeToday = na(lastTradeDay) or (currentDay != lastTradeDay)

// === Previous Day High/Low ===
prevHigh = request.security(syminfo.tickerid, "D", high[1], lookahead=barmerge.lookahead_on)
prevLow = request.security(syminfo.tickerid, "D", low[1], lookahead=barmerge.lookahead_on)

// === Simplified Engulfing Logic ===
bullishEngulf = close &amp;gt; open and close &amp;gt; close[1] and open &amp;lt;= close[1]
bearishEngulf = close &amp;lt; open and close &amp;lt; close[1] and open &amp;gt;= close[1]

// === Liquidity Sweep with Confirmation ===
sweepHigh = high &amp;gt; prevHigh and close &amp;lt; prevHigh
sweepLow = low &amp;lt; prevLow and close &amp;gt; prevLow

longCondition = in_ny and canTradeToday and sweepLow and bullishEngulf
shortCondition = in_ny and canTradeToday and sweepHigh and bearishEngulf

// === Trade Execution ===
if longCondition
    entryPrice = close
    stopLoss = entryPrice - sl_pips * pip
    takeProfit = entryPrice + tp_pips * pip
    strategy.entry("Long", strategy.long)
    strategy.exit("Long TP/SL", from_entry="Long", stop=stopLoss, limit=takeProfit)
    label.new(bar_index, low, text="BUY", style=label.style_label_up, color=color.green, textcolor=color.white)
    lastTradeDay := currentDay

if shortCondition
    entryPrice = close
    stopLoss = entryPrice + sl_pips * pip
    takeProfit = entryPrice - tp_pips * pip
    strategy.entry("Short", strategy.short)
    strategy.exit("Short TP/SL", from_entry="Short", stop=stopLoss, limit=takeProfit)
    label.new(bar_index, high, text="SELL", style=label.style_label_down, color=color.red, textcolor=color.white)
    lastTradeDay := currentDay

// === Visual References ===
plot(prevHigh, title="Prev Day High", color=color.red, linewidth=1)
plot(prevLow, title="Prev Day Low", color=color.green, linewidth=1)

// === Alerts ===
alertcondition(longCondition, title="Long Signal", message="BUY Setup Triggered")
alertcondition(shortCondition, title="Short Signal", message="SELL Setup Triggered")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Strategy parameters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foj4pnybnkd0h67m024tk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foj4pnybnkd0h67m024tk.png" alt=" " width="800" height="87"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The original address: &lt;a href="https://www.fmz.com/strategy/502420" rel="noopener noreferrer"&gt;New York Liquidity Reversal Breakout Trading Strategy&lt;/a&gt;&lt;/p&gt;

</description>
      <category>breakout</category>
      <category>trading</category>
      <category>strategy</category>
      <category>liquidity</category>
    </item>
    <item>
      <title>Architecture Design and FMZ Implementation of the Self-Matching Trading Strategy</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Mon, 28 Jul 2025 08:32:27 +0000</pubDate>
      <link>https://dev.to/fmzquant/architecture-design-and-fmz-implementation-of-the-self-matching-trading-strategy-4l5</link>
      <guid>https://dev.to/fmzquant/architecture-design-and-fmz-implementation-of-the-self-matching-trading-strategy-4l5</guid>
      <description>&lt;h2&gt;
  
  
  ⚠️ Important Disclaimer
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;This article demonstrates a volume-boosting self-matching trading strategy intended solely for learning purposes related to trading system architecture. It fundamentally differs from traditional arbitrage or market-making strategies. The core idea of this strategy is to simulate volume through same-price buy-sell matching to obtain exchange rebates or tier-based trading fee discounts, rather than profiting from market inefficiencies.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The provided code is only a reference framework and has not been tested in live trading environments. The strategy implementation is purely for technical study and research, and has not been thoroughly validated under real market conditions. Readers must perform extensive backtesting and risk evaluation before considering any real-world application. Do not use this strategy for live trading without proper due diligence.&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;In the cryptocurrency market, market-making strategies serve not only to improve liquidity and facilitate trading, but also form a core component of many quantitative trading systems. Market makers quote both buy and sell prices, provide liquidity, and capture profits under various market conditions. Professional market-making systems are often highly sophisticated, involving ultra-low-latency optimization, advanced risk management modules, and cross-exchange arbitrage mechanisms. In this article, we explore the basic concept behind a volume-boosting self-matching trading strategy and demonstrate how to implement a simplified educational framework on the FMZ Quant Trading Platform.&lt;/p&gt;

&lt;p&gt;The main content is adapted from the original work "Market Making Strategy: Concepts and Implementation" by Zinan, with some optimizations and adjustments. While some coding practices may now appear outdated, this version recreated on the FMZ platform still offers valuable insights into the structure of trading algorithms and the fundamentals of self-matching trading logic.&lt;/p&gt;

&lt;h2&gt;
  
  
  Concept of Market Making Strategies
&lt;/h2&gt;

&lt;p&gt;A Market Making Strategy refers to a trading approach where a trader (market maker) places both buy and sell orders in the market simultaneously, thereby providing liquidity and contributing to market stability. This strategy not only helps maintain market depth but also offers counterparties for other traders. By quoting buy and sell prices across various price levels, market makers aim to profit from market fluctuations.&lt;/p&gt;

&lt;p&gt;In the context of cryptocurrency markets, market makers play a critical role—especially in markets with low trading volume or high volatility. By offering liquidity, market makers help reduce slippage and make it easier for other traders to execute orders at favorable prices.&lt;/p&gt;

&lt;p&gt;The core principle of traditional market-making strategies lies in capturing the bid-ask spread by providing liquidity. Market makers post buy orders at lower prices and sell orders at higher prices, profiting from the difference when orders are filled. For example, when the spot price in the market rises, market makers sell at a higher price and buy at a lower price, earning the difference. The primary sources of income include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Bid-ask spread:&lt;/strong&gt; Traditional market makers earn profits by placing limit buy and sell orders and capturing the price difference between the bid and ask.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Volume-based incentives:&lt;/strong&gt; The profitability of market makers is closely tied to the trading volume they provide. Higher volume not only leads to more frequent order fills and profit opportunities but also unlocks additional benefits:
1). &lt;strong&gt;Fee rebates:&lt;/strong&gt; Many exchanges offer fee rebates to incentivize liquidity provision. In some cases, makers receive negative fees—meaning the exchange pays the market maker for executed trades.
2). &lt;strong&gt;VIP tier discounts:&lt;/strong&gt; Reaching specific volume thresholds may qualify market makers for lower trading fees, reducing operational costs.
3). &lt;strong&gt;Market maker incentive programs:&lt;/strong&gt; Some exchanges run dedicated incentive programs that reward market makers based on the quality and consistency of their liquidity provision.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;However, market makers also face significant market risk, especially in highly volatile environments such as the cryptocurrency space. Rapid price swings may cause market makers’ quoted prices to deviate significantly from actual market conditions, potentially resulting in losses.&lt;/p&gt;

&lt;h2&gt;
  
  
  Types of Market Making Strategies
&lt;/h2&gt;

&lt;p&gt;In the cryptocurrency market, market makers typically choose different strategies based on market conditions, trading volume, and volatility. Common types of market-making strategies include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Passive market making:&lt;/strong&gt; In this approach, the market maker places buy and sell limit orders based on market depth, historical volatility, and other indicators, then waits for the market to fill those orders. This strategy is characterized by low frequency and a conservative risk profile, relying on natural market movements to generate profit.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Active market making:&lt;/strong&gt; Active market makers dynamically adjust order prices and sizes in real time based on market conditions to improve execution probability. They often place orders close to the current mid-price, aiming to better capture opportunities from short-term volatility.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Volume-boosting self-matching strategy:&lt;/strong&gt; The focus of this article. A volume-boosting self-matching strategy involves placing simultaneous buy and sell orders at the same price to artificially increase trading volume. Unlike traditional market-making, this strategy is not designed to profit from bid-ask spreads. Instead, it seeks to benefit from exchange incentives such as fee rebates, VIP tier discounts, or liquidity mining rewards.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In a volume-boosting self-matching strategy, the market maker posts buy and sell orders at the same price level. While these trades do not generate profits from price differentials, they quickly accumulate trading volume. Profitability is entirely dependent on the exchange's incentive mechanisms rather than market inefficiencies or arbitrage.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key characteristics:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Same-price orders:&lt;/strong&gt; Unlike traditional market-making, buy and sell orders are placed at the same price, eliminating spread-based profits.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Volume-oriented execution:&lt;/strong&gt; The primary objective is to accumulate trade volume rapidly, not to exploit price arbitrage.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Incentive-driven profitability:&lt;/strong&gt; Returns are fully reliant on exchange incentives such as fee rebates, VIP tier benefits, or dedicated market maker reward programs.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Important distinction:&lt;/strong&gt;&lt;br&gt;
Compared to traditional market-making strategies, volume-boosting self-matching strategies do not generate profit by providing genuine market liquidity. Instead, they create trading volume artificially to capitalize on policy-driven rewards offered by exchanges. This type of strategy may carry regulatory or compliance risks in certain jurisdictions and must be carefully evaluated before any live trading deployment.&lt;/p&gt;
&lt;h2&gt;
  
  
  Profit Logic Behind Volume-Boosting Self-Matching Strategies
&lt;/h2&gt;

&lt;p&gt;Upon analyzing the code implementation, it becomes evident that the buy and sell prices are exactly the same in this strategy:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;make_duiqiao_dict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade_amount&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;mid_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;mid_price&lt;/span&gt;  &lt;span class="c1"&gt;# Med price
&lt;/span&gt;    &lt;span class="n"&gt;trade_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mid_price&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;price_precision&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Accurate transaction price
&lt;/span&gt;    &lt;span class="n"&gt;trade_dict&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;trade_price&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;trade_price&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;  &lt;span class="c1"&gt;# The same price is used for both buying and selling
&lt;/span&gt;        &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;trade_amount&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Actual Profit Mechanism
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Volume-boosting via self-matching&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The core objective of this strategy is to increase trading volume rapidly through high-frequency self-matching.&lt;/li&gt;
&lt;li&gt;Profit is derived from exchange incentives such as fee rebates, VIP tier upgrades, or liquidity mining rewards.&lt;/li&gt;
&lt;li&gt;This approach is applicable on exchanges that offer formal market maker incentive programs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Fee rebate mechanism&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The strategy relies on exchanges offering negative maker fees (maker rates are negative)&lt;/li&gt;
&lt;li&gt;By providing liquidity, the strategy earns rebates on filled orders.&lt;/li&gt;
&lt;li&gt;It requires the exchange to support market maker fee discounts or rebate structures.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Suitable Scenarios &amp;amp; Associated Risks
&lt;/h2&gt;

&lt;p&gt;✅ Suitable scenarios&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Exchanges with clear market maker rebate or incentive policies.&lt;/li&gt;
&lt;li&gt;Traders aiming to meet high trading volume requirements for VIP tier upgrades.&lt;/li&gt;
&lt;li&gt;Platforms that run liquidity mining or commission rebate campaigns.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;❌ Unsuitable scenarios&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Exchanges that do not offer fee rebates or incentives.&lt;/li&gt;
&lt;li&gt;Platforms with high transaction fees, where self-matching leads to net losses.&lt;/li&gt;
&lt;li&gt;Exchanges that explicitly prohibit wash trading or enforce restrictions on artificial volume.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;⚠️ Risk warnings&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If both buy and sell orders are filled simultaneously, the strategy may incur a net loss after fees.&lt;/li&gt;
&lt;li&gt;Changes in exchange policies may render the strategy unprofitable or non-viable.&lt;/li&gt;
&lt;li&gt;Continuous monitoring of fee structures and trading costs is required.&lt;/li&gt;
&lt;li&gt;The strategy may face compliance risks in jurisdictions where volume-boosting trading is regulated or restricted.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Self-Matching Strategy Architecture Analysis
&lt;/h2&gt;

&lt;p&gt;This section presents a simplified implementation of a volume-boosting self-matching strategy, inspired by the framework developed by Zinan. The focus is on how to accumulate trading volume through same-price buy and sell orders within a live exchange environment. The strategy architecture is structured around two main classes: MidClass and MarketMaker. These components are responsible for handling exchange interactions and executing the self-matching logic, respectively.&lt;/p&gt;

&lt;p&gt;The architecture follows a layered design, separating the exchange interface logic from the trading strategy logic. This ensures modularity, extensibility, and clean separation of concerns. The main components are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;MidClass: The exchange middle layer is responsible for interacting with the exchange interface to obtain market data, account information, order status, etc. This layer encapsulates all interactions with external exchanges to ensure that the trading logic and the exchange interface are decoupled.&lt;/li&gt;
&lt;li&gt;MarketMaker: The market making strategy class is responsible for executing the cross-trading strategy, generating pending orders, checking order status, updating strategy status, etc. It interacts with the exchange middle layer to provide specific market making and self-matching trading operations.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  MidClass
&lt;/h3&gt;

&lt;p&gt;MidClass is the middle layer of the exchange. Its main responsibility is to handle the interaction with the exchange, encapsulate all external API calls, and provide a simple interface for MarketMaker to use. Its architecture includes the following key functions:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Market data retrieval:&lt;/strong&gt;&lt;br&gt;
Fetches real-time market data such as tickers, order book depth, and candlestick data (K-lines). Regular updates are essential to ensure the strategy operates on up-to-date information.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Account information management:&lt;/strong&gt;&lt;br&gt;
Retrieves account data, including balances, available margin, and open positions. This is critical for capital allocation and risk control.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Order management:&lt;/strong&gt;&lt;br&gt;
Provides functionality to place, query, and cancel orders. This is the foundation of executing a market-making or self-matching strategy and ensures robust control over open orders.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Data Synchronization:&lt;/strong&gt;&lt;br&gt;
Maintains persistent connections with the exchange and updates internal state for use by the strategy layer.&lt;/p&gt;

&lt;p&gt;By encapsulating these features in MidClass, the strategy logic within MarketMaker remains focused on execution rather than infrastructure. This structure improves the maintainability and scalability of the system, making it easier to add support for different exchanges or optimize existing functions.&lt;/p&gt;
&lt;h3&gt;
  
  
  MarketMaker
&lt;/h3&gt;

&lt;p&gt;MarketMaker is the core class of the self-matching strategy, responsible for executing market-making operations and handling self-matching trades. Its architecture typically includes the following key modules:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Initialization:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Initialize the exchange middleware (MidClass) to retrieve exchange metadata such as trading pair details, precision, tick size, and order book depth.&lt;/li&gt;
&lt;li&gt;Initialize the market-making strategy, set up key parameters like order quantity, price spread, and execution intervals. These parameters directly affect how the strategy behaves and performs in the market.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Data refresh:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Periodic market data updates, including real-time account information, market price, depth, K-line, etc. These data provide basic information for executing strategies.&lt;/li&gt;
&lt;li&gt;The frequency of updates can be dynamically adjusted based on market volatility to ensure timely responses to market changes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. Self-matching execution logic:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Order book construction: Based on current market depth and price dynamics, construct a dictionary of orders (both bids and asks) with specified price and size. This is typically calculated using predefined strategy parameters.&lt;/li&gt;
&lt;li&gt;Self-matching execution: Once the order structure is ready, MarketMaker submits both buy and sell orders at the same price level to the market. The goal is to accumulate trade volume quickly via same-price order matching.&lt;/li&gt;
&lt;li&gt;Order status monitoring: During execution, MarketMaker will check the status of the order constantly to ensure that the pending order can be processed in time. If the order fails to be executed, it will adjust the pending order price or quantity until the order is completed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4. Strategy state update:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Strategy status update: Regularly update key performance indicators such as cumulative trading volume, filled order count, and total fees. These metrics allow real-time tracking of the strategy's performance.&lt;/li&gt;
&lt;li&gt;Dynamic risk management: The strategy adapts its behavior based on current market conditions. MarketMaker can modify execution logic in real time to reduce risk and maintain operational efficiency across varying market environments.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Self-Matching Strategy Logic Reconstruction
&lt;/h2&gt;

&lt;p&gt;The implementation of a self-matching strategy relies on precise market data and fast execution. The MarketMaker class monitors real-time market conditions and leverages same-price buy and sell orders (self-matching) to rapidly accumulate trading volume, which is the core objective of this strategy.&lt;/p&gt;
&lt;h3&gt;
  
  
  Initialization
&lt;/h3&gt;

&lt;p&gt;In the MarketMaker class's initialization method, the first step is to retrieve the exchange's precision settings, followed by initializing key strategy parameters such as quantity precision and price precision.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;precision_info&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_precision&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Get precision information
&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;price_precision&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;precision_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;price_precision&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Price precision
&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount_precision&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;precision_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount_precision&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Trading volume precision
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Generating the Self-Matching Order Dictionary
&lt;/h3&gt;

&lt;p&gt;At the heart of the self-matching strategy is the construction of an order dictionary containing both buy and sell orders at the same price level, along with their respective quantities. The code generates the dictionary of self-matching trading orders by calculating the middle price.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;make_duiqiao_dict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade_amount&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;mid_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;mid_price&lt;/span&gt;  &lt;span class="c1"&gt;# Mid Price
&lt;/span&gt;    &lt;span class="n"&gt;trade_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mid_price&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;price_precision&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Accurate transaction price
&lt;/span&gt;    &lt;span class="n"&gt;trade_dict&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;trade_price&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;trade_price&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;trade_amount&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Executing Self-Matching Trades
&lt;/h3&gt;

&lt;p&gt;According to the generated dictionary of self-matching trading orders, the self-matching trading transaction is executed. In the code, the create_order method of the exchange middle layer is called to place buy orders and sell orders at the same time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;make_trade_by_dict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;position_amount&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;can_buy_amount&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
        &lt;span class="n"&gt;buy_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;trade_price&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Pending buy order
&lt;/span&gt;        &lt;span class="n"&gt;sell_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;trade_price&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Pending sell order
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
            &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;buy_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;sell_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;init_time&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;time&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Order Status Monitoring
&lt;/h3&gt;

&lt;p&gt;The strategy periodically checks the status of active orders and handles any unfilled or partially filled ones. In the code, this is done by calling the GetOrder method from the exchange middleware (MidClass). Based on the returned order status, the strategy decides whether to cancel the orders. The self-matching order management logic includes the following key steps:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Fetching order status:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The strategy retrieves the current status of both the buy and sell orders through the exchange API.&lt;/li&gt;
&lt;li&gt;If the status retrieval fails (e.g., due to a missing order or network issue), the strategy cancels the corresponding order and removes it from the active tracking list.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Evaluating order status:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The status returned is used to determine whether the order is filled, partially filled, or still open.&lt;/li&gt;
&lt;li&gt;Typical order status include:
0(ORDER_STATE_PENDING): Order is open and waiting to be filled.
1(ORDER_STATE_CLOSED): Order has been completely filled.
2(ORDER_STATE_CANCELED): Order has been canceled.
3(ORDER_STATE_UNKNOWN): Order status is unknown or undefined.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. Handling order status:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Both orders unfilled:&lt;br&gt;
If both buy and sell orders remain unfilled (status 0), the strategy checks the polling interval (e.g., current_time % 5 == 0) to decide whether to cancel them.&lt;br&gt;
After cancellation, the strategy updates the order count and removes the orders from the internal record.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;One order filled, the other unfilled:&lt;br&gt;
If one side of the self-matching order pair is filled (status == 1) and the other remains unfilled (status == 0), the strategy uses the polling interval condition to decide whether to cancel the unfilled order.&lt;br&gt;
After cancelling an open order, update the volume and the list of open orders and remove the order from the record.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Both orders filled:&lt;br&gt;
If both the buy and sell orders are fully executed (status == 1), the strategy updates the trade volume counter, and the order pair is removed from the internal tracking list.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Unknown order status:&lt;br&gt;
If the order status is neither 0 nor 1, it is recorded as unknown status and logged.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4. Updating internal records:&lt;/strong&gt;&lt;br&gt;
After processing the order statuses, the strategy updates the total accumulated trade volume, the list of unfilled or partially filled orders, the order submission and cancellation counters.&lt;/p&gt;

&lt;h2&gt;
  
  
  Future Strategy Outlook
&lt;/h2&gt;

&lt;p&gt;The self-matching strategy presented in this article is primarily intended as an educational example for understanding the architectural design of trading frameworks. Its practical application in live trading is limited. For readers interested in real market-making strategies, we plan to introduce more advanced and practical models in future content:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Order book market-making strategy&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A true arbitrage-based approach that captures the bid-ask spread.&lt;/li&gt;
&lt;li&gt;Places limit orders between the best bid and ask to earn the spread profit.&lt;/li&gt;
&lt;li&gt;Closely aligns with the traditional profit model of professional market makers.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Dynamic market-making strategy&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Adapts quote prices in real-time based on market volatility.&lt;/li&gt;
&lt;li&gt;Integrates inventory management and risk control mechanisms.&lt;/li&gt;
&lt;li&gt;Suitable for adaptive execution across varying market conditions.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. Multi-level market-making strategy&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Places orders at multiple price levels simultaneously.&lt;/li&gt;
&lt;li&gt;Diversifies execution risk and enhances overall return stability.&lt;/li&gt;
&lt;li&gt;Closer to how professional market-making systems operate in production.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These upcoming strategies will emphasize realistic profit logic and robust risk management, providing quantitative traders with more actionable and valuable insights for developing production-ready systems.&lt;/p&gt;

&lt;h2&gt;
  
  
  Strategy Outlook
&lt;/h2&gt;

&lt;p&gt;Self-matching strategies that rely on exchange incentive policies, such as fee rebates, VIP tier upgrades, or liquidity mining rewards — are inherently vulnerable to changes in those policies. If an exchange adjusts its fee structure or removes such incentives, the strategy may become ineffective or even result in net losses. To mitigate this, the strategy must incorporate adaptability to policy changes, such as dynamic monitoring of fee rates and trading incentives, multiple profit sources to reduce over-reliance on a single incentive. fallback mechanisms or automatic shutdown triggers if profitability thresholds are not met. Moreover, self-matching strategies may raise regulatory red flags, as they can be interpreted as attempts to manipulate market volume. In many jurisdictions, such behavior may violate market integrity laws.&lt;/p&gt;

&lt;p&gt;Therefore, traders must stay updated on local legal and compliance requirements, consult with legal professionals when deploying volume-based strategies, avoid practices that could be construed as deceptive or manipulative.&lt;/p&gt;

&lt;p&gt;We hope readers use this strategy framework as a foundation to build more robust, compliant, and innovative trading systems. The true value of quantitative trading lies in continuous learning, experimentation, and refinement. May your journey in quant trading be insightful, adaptive, and rewarding!&lt;/p&gt;

&lt;h2&gt;
  
  
  Strategy Code
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MidClass&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;exchange_instance&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Initialize the exchange middle layer

        Args:
            exchange_instance: FMZ&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;s exchange structure
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_timestamp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;time&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Record initialization time
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;exchange_instance&lt;/span&gt;  &lt;span class="c1"&gt;# Save the exchange object
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetName&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Get the exchange name
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;trading_pair&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetCurrency&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Get the trading pair name (such as BTC_USDT)
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_precision&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Get the accuracy information of the trading pair

        Returns:
            Returns a dictionary containing precision information, or None on failure.
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="n"&gt;symbol_code&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetCurrency&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="n"&gt;ticker&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetTicker&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;symbol_code&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Backtesting system needs
&lt;/span&gt;        &lt;span class="n"&gt;exchange_info&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetMarkets&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;exchange_info&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;symbol_code&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Failed to obtain market information&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;GetLastError&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;

        &lt;span class="c1"&gt;# Get the accuracy information of the trading pair
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;precision_info&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;tick_size&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;TickSize&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;                  &lt;span class="c1"&gt;# Price accuracy
&lt;/span&gt;            &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount_size&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;AmountSize&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;              &lt;span class="c1"&gt;# Quantity accuracy
&lt;/span&gt;            &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;price_precision&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;PricePrecision&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;      &lt;span class="c1"&gt;# Price decimal places precision
&lt;/span&gt;            &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount_precision&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;AmountPrecision&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;    &lt;span class="c1"&gt;# Number of decimal places of precision
&lt;/span&gt;            &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;min_qty&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;MinQty&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;                      &lt;span class="c1"&gt;# Minimum order quantity
&lt;/span&gt;            &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;max_qty&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;MaxQty&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;                       &lt;span class="c1"&gt;# Maximum order quantity
&lt;/span&gt;        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;precision_info&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_account&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Get account information

        Returns:
            Returns True if the information is successfully obtained, and returns False if the information is failed.
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;

        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Account balance
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Account holdings
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;frozen_balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Freeze balance
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;frozen_stocks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Freeze positions
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_stocks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_equity&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;

        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;account_info&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetAccount&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Get account information
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;account_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Balance&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update account balance
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;account_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Stocks&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update the holdings
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;frozen_balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;account_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;FrozenBalance&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update frozen balance
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;frozen_stocks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;account_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;FrozenStocks&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update frozen positions
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;equity&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;frozen_balance&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;frozen_stocks&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;last_price&lt;/span&gt;

            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_balance&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_stocks&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_equity&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_balance&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_balance&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_stocks&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_stocks&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_balance&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_stocks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_stocks&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_equity&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_equity&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;frozen_balance&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_stocks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;frozen_stocks&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_equity&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_balance&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_stocks&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;last_price&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_balance&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_balance&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_stocks&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_stocks&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_equity&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_equity&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

                    &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Obtaining initial equity&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_equity&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;profit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;equity&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_equity&lt;/span&gt;
            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;profitratio&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;equity&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_equity&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_equity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;

            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;True&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;False&lt;/span&gt;  &lt;span class="c1"&gt;# Failed to obtain account information
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_ticker&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Get market price information (such as bid price, ask price, highest price, lowest price, etc.)

        Returns:
            Returns True if the information is successfully obtained, and returns False if the information is failed.
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;high_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# The highest price
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;low_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# The lowest price
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Ask price
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Bid price
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;last_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Latest transaction price
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;volume&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Trading volume
&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;ticker_info&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetTicker&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Get market price information
&lt;/span&gt;
            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;high_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ticker_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;High&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update highest price
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;low_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ticker_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Low&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update lowest price
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ticker_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Sell&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update ask price
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ticker_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Buy&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update bid price
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;last_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ticker_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Last&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update the latest transaction price
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;volume&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ticker_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Volume&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update trading volume
&lt;/span&gt;            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;True&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;False&lt;/span&gt;  &lt;span class="c1"&gt;# Failed to obtain market price information
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_depth&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Get depth information (list of pending orders for buy and sell orders)

        Returns:
            Returns True if the information is successfully obtained, and returns False if the information is failed.
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ask_orders&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Ask order list
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;bid_orders&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;---&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Bid order list
&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;depth_info&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetDepth&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Get depth information
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ask_orders&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;depth_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Asks&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update the sell order list
&lt;/span&gt;            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;bid_orders&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;depth_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Bids&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update buy order list
&lt;/span&gt;            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;True&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;False&lt;/span&gt;  &lt;span class="c1"&gt;# Failed to obtain depth information
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_ohlc_data&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;period&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;PERIOD_M5&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Get K-line information

        Args:
            period: K-line period, PERIOD_M1 refers to 1 minute, PERIOD_M5 refers to 5 minutes, PERIOD_M15 refers to 15 minutes,
            PERIOD_M30 means 30 minutes, PERIOD_H1 means 1 hour, PERIOD_D1 means one day.
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ohlc_data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetRecords&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;period&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Get K-line data
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;create_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;order_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Submit an order

        Args:
            order_type: Order type, &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt; refers to a buy order, &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt; refers to a sell order
            price: Order price
            amount: Order amount 

        Returns:
            Order ID number, which can be used to cancel the order
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;order_type&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;order_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Buy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Submit a buy order
&lt;/span&gt;            &lt;span class="k"&gt;except&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;False&lt;/span&gt;  &lt;span class="c1"&gt;# Buy order submission failed
&lt;/span&gt;
        &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;order_type&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;order_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Sell&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Submit a sell order
&lt;/span&gt;            &lt;span class="k"&gt;except&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;False&lt;/span&gt;  &lt;span class="c1"&gt;# Sell order submission failed
&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;order_id&lt;/span&gt;  &lt;span class="c1"&gt;# Returns the order ID
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_orders&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Get a list of uncompleted orders

        Returns:
            List of uncompleted orders
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;open_orders&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetOrders&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Get uncompleted orders
&lt;/span&gt;        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;open_orders&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;cancel_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;order_id&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Cancel a pending order

        Args:
            order_id: The ID number of the pending order you wish to cancel

        Returns:
            Returns True if the pending order is successfully cancelled, and returns False if the pending order is failed.
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;CancelOrder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Cancel the order
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;refresh_data&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Refresh information (account, market price, depth, K-line)

        Returns:
            If the refresh information is successfully returned, &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;refresh_data_finish!&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt; will be returned. Otherwise, the corresponding refresh failure information prompt will be returned.
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_ticker&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;  &lt;span class="c1"&gt;# Refresh market price information
&lt;/span&gt;            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;false_get_ticker&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_account&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;  &lt;span class="c1"&gt;# Refresh account information
&lt;/span&gt;            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;false_get_account&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_depth&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;  &lt;span class="c1"&gt;# Refresh depth information
&lt;/span&gt;            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;false_get_depth&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;

        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_ohlc_data&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Refresh K-line information
&lt;/span&gt;        &lt;span class="k"&gt;except&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;false_get_K_line_info&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;refresh_data_finish!&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Refresh successfully
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MarketMaker&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mid_class&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Initialize market making strategy

        Args:
            mid_class: Exchange middle layer object
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid_class&lt;/span&gt;  &lt;span class="c1"&gt;# Exchange middle layer object
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;precision_info&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_precision&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Get accuracy information
&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;done_amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;  &lt;span class="c1"&gt;# Completed transactions
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;price_precision&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;precision_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;price_precision&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Price precision
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount_precision&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;precision_info&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount_precision&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Trading volume precision
&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[]}&lt;/span&gt;  &lt;span class="c1"&gt;# Trading pairs with pending orders
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pending_orders&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;  &lt;span class="c1"&gt;# Uncompleted order status
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pending_order_count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;  &lt;span class="c1"&gt;# Number of pending orders
&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee_rate&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.08&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;

        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;chart&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;__isStock&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;tooltip&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;xDateFormat&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;%Y-%m-%d %H:%M:%S, %A&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;title&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;text&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Number of pending orders&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;xAxis&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;type&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;datetime&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;yAxis&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;title&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;text&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Number of pending orders&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;opposite&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="bp"&gt;False&lt;/span&gt;
            &lt;span class="p"&gt;},&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;series&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
                &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;name&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Buy order quantity&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;id&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Buy order quantity&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;data&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[]},&lt;/span&gt;
                &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;name&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Sell order quantity&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;id&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Sell order quantity&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;dashStyle&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;shortdash&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;data&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[]}&lt;/span&gt;
            &lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;refresh_data&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Refresh data (account, market price, depth, K-line)
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;refresh_data&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Refresh exchange data
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;position_amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nf"&gt;isinstance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;  &lt;span class="c1"&gt;# Holding positions
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;available_balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nf"&gt;isinstance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;  &lt;span class="c1"&gt;# Account balance
&lt;/span&gt;        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Check ticker&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_price&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;can_buy_amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;available_balance&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="nf"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_price&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Quantity available for purchase
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;mid_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_price&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_price&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;  &lt;span class="c1"&gt;# Mid Price
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;make_duiqiao_dict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade_amount&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;

        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Generate a dictionary of self-matching orders

        Args:
            trade_amount: Volume per transaction

        Returns:
            Dictionary list of self-matching orders
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;3 Create a dictionary for self-matching orders&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="n"&gt;mid_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;mid_price&lt;/span&gt;  &lt;span class="c1"&gt;# Mid price
&lt;/span&gt;
        &lt;span class="n"&gt;trade_price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mid_price&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;price_precision&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Accurate transaction price
&lt;/span&gt;
        &lt;span class="n"&gt;trade_dict&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;trade_price&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;trade_price&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;trade_amount&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Returns the market order dictionary:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;make_trade_by_dict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Execute transactions according to the transaction dictionary

        Args:
            trade_dict: transaction dictionary
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;4 Start trading by dictionary&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;refresh_data&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Refresh data
&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Current account funds: Coin balance: &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;position_amount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Funds balance: &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;can_buy_amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Check open positions: Coin limit: &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;position_amount&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Funding restrictions: &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;can_buy_amount&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;position_amount&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;can_buy_amount&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="n"&gt;buy_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;trade_price&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Pending buy order
&lt;/span&gt;                &lt;span class="n"&gt;sell_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;trade_price&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Pending sell order
&lt;/span&gt;
                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
                    &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;buy_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;sell_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;init_time&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;time&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                &lt;span class="p"&gt;})&lt;/span&gt;

                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;last_time&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;time&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Update last transaction time
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;handle_pending_orders&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Processing unfulfilled orders
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="n"&gt;pending_orders&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_orders&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Get uncompleted orders
&lt;/span&gt;        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pending_orders&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;pending_orders&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cancel_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Cancel uncompleted orders
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;check_order_status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;current_time&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
        Check order status
        current_time: Polling check times
        &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;1 Start order information check&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_pending&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_pending&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;copy&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
            &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Check the order:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

            &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;buy_order_status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetOrder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Get buy order status
&lt;/span&gt;                &lt;span class="n"&gt;sell_order_status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetOrder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Get sell order status
&lt;/span&gt;            &lt;span class="k"&gt;except&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;cancel&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cancel_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Cancel buy order
&lt;/span&gt;                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cancel_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Cancel sell order
&lt;/span&gt;                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Remove order
&lt;/span&gt;                &lt;span class="k"&gt;return&lt;/span&gt;

            &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Check the order:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_pending&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_pending&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current_time&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Check pending orders and cancel pending orders (two unfinished)&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;current_time&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cancel_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Cancel buy order
&lt;/span&gt;                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cancel_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Cancel sell order
&lt;/span&gt;                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pending_order_count&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;  &lt;span class="c1"&gt;# The number of pending orders increases by 1
&lt;/span&gt;                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Remove order
&lt;/span&gt;
            &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]}&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;}:&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;ORDER_STATE_PENDING&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_pending&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;ORDER_STATE_PENDING&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_pending&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current_time&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Check pending orders and cancel pending orders (part one is not yet completed)&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;done_amount&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update transaction volume
&lt;/span&gt;                    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;ORDER_STATE_PENDING&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_amount&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Price&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Cancel the buy order and add the unfinished buy list&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
                        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cancel_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Cancel buy order
&lt;/span&gt;                        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pending_orders&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;buy&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt;  &lt;span class="c1"&gt;# Record uncompleted orders
&lt;/span&gt;                        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Before clearing:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
                        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Clear id:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Remove order
&lt;/span&gt;                        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;After clearing:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
                    &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;ORDER_STATE_PENDING&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_amount&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Price&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Cancel the sell order and add it to the unfinished sell list&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
                        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cancel_order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell_id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Cancel sell order
&lt;/span&gt;                        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pending_orders&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;sell&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt;  &lt;span class="c1"&gt;# Record uncompleted orders
&lt;/span&gt;                        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Before clearing:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
                        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Clear id:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Remove order
&lt;/span&gt;                        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;After clearing:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

            &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Both orders have been completed&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_amount&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_amount&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Price&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Price&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Completion status:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;done_amount&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amount&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Update transaction volume
&lt;/span&gt;                &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Remove order
&lt;/span&gt;            &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Two orders are in unknown status:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Unknown order status:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;buy_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;sell_order_status&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
                &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Unknown order information:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;traded_pair&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;update_status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;

        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;refresh_data&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

        &lt;span class="n"&gt;table1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;type&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;table&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;title&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Account information&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;cols&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Initial funds&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Existing funds&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Self-matching buy amount&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Self-matching sell  amount&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Fee rate&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Total return&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Rate of return&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
            &lt;span class="p"&gt;],&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;rows&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
                &lt;span class="p"&gt;[&lt;/span&gt;   
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init_equity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;equity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_amount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
                    &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_amount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
                    &lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
                    &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;profit&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="nf"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;profitratio&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;%&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
                &lt;span class="p"&gt;],&lt;/span&gt;
            &lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="nc"&gt;LogStatus&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Initialization time: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;strftime&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%Y-%m-%d %H&lt;/span&gt;&lt;span class="si"&gt;:&lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="n"&gt;M&lt;/span&gt;&lt;span class="si"&gt;:&lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="n"&gt;S&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;, time.localtime(self.exchange_mid.init_timestamp))&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;`&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;table1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;`&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Last execution time: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nf"&gt;_D&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="nc"&gt;LogProfit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;profit&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;&amp;amp;&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;plot_pending&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;

        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Number of knock-on orders:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_pending&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_pending&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;obj_chart&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Chart&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;chart&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;now_time&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;time&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="c1"&gt;# Update pending order buy volume data
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;obj_chart&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;now_time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;buy_pending&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
        &lt;span class="c1"&gt;# Update pending order selling volume data
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;obj_chart&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;now_time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sell_pending&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="sh"&gt;'''&lt;/span&gt;&lt;span class="s"&gt;
    Main function, running market making strategy
    &lt;/span&gt;&lt;span class="sh"&gt;'''&lt;/span&gt;
    &lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;IO&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;simulate&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;IO&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;trade_super_margin&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;target_amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;  &lt;span class="c1"&gt;# Target transaction volume
&lt;/span&gt;    &lt;span class="n"&gt;trade_amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.01&lt;/span&gt;  &lt;span class="c1"&gt;# Volume per transaction
&lt;/span&gt;    &lt;span class="n"&gt;trade_dict&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;  &lt;span class="c1"&gt;# Initialize transaction dictionary
&lt;/span&gt;
    &lt;span class="n"&gt;exchange_mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;MidClass&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Initialize the exchange middle layer
&lt;/span&gt;    &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;refresh_data&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;  &lt;span class="c1"&gt;# Refresh data
&lt;/span&gt;    &lt;span class="n"&gt;market_maker&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;MarketMaker&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exchange_mid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Initialize market making strategy
&lt;/span&gt;
    &lt;span class="n"&gt;check_times&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;done_amount&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;target_amount&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# Loop until the target transaction volume is reached
&lt;/span&gt;        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
        &lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;check_order_status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;check_times&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Check order status
&lt;/span&gt;        &lt;span class="nc"&gt;Sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Wait 1 second
&lt;/span&gt;        &lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;refresh_data&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# Refresh data
&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;traded_pairs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# Price moves, market orders are cancelled, wait until all orders are completed, and create a new order dictionary
&lt;/span&gt;
            &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;2 The number of trading pairs on the market is less than 1&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;trade_dict&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;make_duiqiao_dict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;trade_amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Generate a dictionary of pending orders
&lt;/span&gt;            &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;New trading dictionary&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# Check if the dictionary is not empty
&lt;/span&gt;            &lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;make_trade_by_dict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;trade_dict&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Execute a trade
&lt;/span&gt;
        &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Market making quantity:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;done_amount&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;dui_qiao&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# Record transaction volume
&lt;/span&gt;
        &lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;plot_pending&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update_status&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

        &lt;span class="n"&gt;check_times&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

    &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;position_amount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;market_maker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;can_buy_amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Record holdings and available purchase quantities
&lt;/span&gt;    &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Existing orders:&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetOrders&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;  &lt;span class="c1"&gt;# Record existing orders
&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;onexit&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="nc"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Execute the sweep function&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_balance&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_stocks&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;_G&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;init_equity&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From: &lt;a href="https://www.fmz.com/bbs-topic/10706" rel="noopener noreferrer"&gt;An Overview of Market Making Strategies in Crypto: Architecture Design and FMZ Implementation of the Self-Matching Trading Strategy&lt;/a&gt;&lt;/p&gt;

</description>
      <category>trading</category>
      <category>strategy</category>
      <category>cryptocurrency</category>
      <category>market</category>
    </item>
    <item>
      <title>Dual-Timeframe Momentum CCI Trend Following Trading Strategy</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Fri, 25 Jul 2025 03:03:11 +0000</pubDate>
      <link>https://dev.to/fmzquant/dual-timeframe-momentum-cci-trend-following-trading-strategy-3ek9</link>
      <guid>https://dev.to/fmzquant/dual-timeframe-momentum-cci-trend-following-trading-strategy-3ek9</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuqn89n94wgvvly9ztn4l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuqn89n94wgvvly9ztn4l.png" alt=" " width="800" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F80jknpuhq6zw7s1x5fe5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F80jknpuhq6zw7s1x5fe5.png" alt=" " width="800" height="413"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br&gt;
The Dual-Timeframe Momentum CCI Trend Following Trading Strategy is a quantitative trading system that combines long and short period Commodity Channel Index (CCI) indicators, specifically designed to identify and capture strong trending market conditions. This strategy cleverly utilizes a 50-period long-term CCI to determine the primary market trend direction, while employing a 5-period short-term CCI to capture momentum changes and entry timing. This dual-timeframe approach not only effectively filters out false signals but also provides precise entry points in the early stages of trends, maximizing profit capture during the core trend movement. The strategy supports two-way trading, allowing users to flexibly enable or disable short selling based on their risk preferences, making it adaptable to different market environments and trading requirements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Principles&lt;/strong&gt;&lt;br&gt;
The core logic of this strategy is based on CCI indicator zero-line crossovers and momentum change theory, with specific operational principles as follows:&lt;/p&gt;

&lt;p&gt;Long Entry Conditions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Long-period CCI(50) current and previous values are both greater than 0, indicating an upward market trend&lt;/li&gt;
&lt;li&gt;Short-period CCI(5) crosses above the zero line, indicating a shift to positive short-term momentum&lt;/li&gt;
&lt;li&gt;Ensures that only one signal is triggered within the current trend cycle, avoiding repeated entries&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Long Exit Conditions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Long-period CCI(50) crosses below the zero line, indicating a potential shift to a downward trend&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Short Entry Conditions (only when short selling is enabled):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Long-period CCI(50) current and previous values are both less than 0, indicating a downward market trend&lt;/li&gt;
&lt;li&gt;Short-period CCI(5) crosses below the zero line, indicating a shift to negative short-term momentum&lt;/li&gt;
&lt;li&gt;Similarly ensures that only one signal is triggered within the current trend cycle&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Short Exit Conditions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Long-period CCI(50) crosses above the zero line, indicating a potential shift to an upward trend&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The strategy tracks trend cycle states through variables inPositiveCciLongCycle, firstCrossoverOccurred, and firstCrossunderOccurred, ensuring that only one trade is executed within a trend cycle, effectively avoiding frequent trading in oscillating markets and unnecessary commission losses.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Advantages&lt;/strong&gt;&lt;br&gt;
Through in-depth code analysis, this strategy demonstrates several significant advantages:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Dual Confirmation of Trend and Momentum: By combining long-period and short-period CCI indicators, it forms a dual confirmation mechanism for trend direction and entry timing, significantly reducing the risk of false signals.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Precise Entry Timing: The strategy identifies momentum changes through short-period CCI zero-line crossovers, providing more precise entry points in the early stages of trends, improving capital utilization efficiency.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Avoidance of Frequent Trading: Through the single-entry-per-cycle mechanism, it effectively avoids frequent trading in oscillating markets, reducing transaction costs.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Flexible Trading Modes: Supports long-only or two-way trading, allowing users to adjust according to market environment and personal preferences, adapting to different market conditions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Clear Visual Feedback: The strategy provides intuitive visual indicators, including CCI indicator lines and trade signal markers, facilitating analysis and backtest verification.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Parameter Adjustability: Users can adjust long and short CCI period parameters based on different market and instrument characteristics, enhancing strategy adaptability.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Risks&lt;/strong&gt;&lt;br&gt;
Despite the rational design of this strategy, there are still the following potential risks:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Trend Reversal Risk: In cases of sudden strong trend reversals, the long-period CCI may not cross the zero line in time, causing delayed exit signals and potentially giving back accumulated profits. The solution is to introduce profit-taking mechanisms or add more sensitive exit indicators.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Poor Performance in Range-Bound Markets: In long-term sideways or trendless market environments, the strategy may produce multiple ineffective signals, leading to losses. It is recommended to use this strategy when the market is confirmed to be in a clear trend.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Parameter Sensitivity: The choice of CCI period parameters significantly impacts strategy performance, and different markets may require different parameter settings. It is recommended to find suitable parameter combinations for specific markets through backtesting optimization.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Single Indicator Dependency: The strategy relies solely on the CCI indicator, lacking auxiliary confirmation from other technical indicators or price patterns, potentially increasing the risk of false signals. Consider adding additional filtering conditions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Insufficient Capital Management: The code uses fixed proportion position management (100% of capital), which may bring excessive risk in highly volatile markets. It is recommended to dynamically adjust position size based on market volatility.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Optimization Directions&lt;/strong&gt;&lt;br&gt;
Based on code analysis, this strategy can be optimized in the following directions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Add Filtering Conditions: Combine with other technical indicators such as moving averages, RSI, or MACD to build multiple confirmation mechanisms, improving signal quality. This optimization is necessary because a single CCI indicator may produce misleading signals in certain market environments, and multiple indicators can complement each other's shortcomings.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Introduce Adaptive Parameters: Design CCI period parameters to automatically adjust based on market volatility, enabling the strategy to adapt to different market phases. This optimization helps the strategy maintain stable performance in different volatility environments.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Improve Capital Management: Introduce ATR-based dynamic position management, automatically adjusting position size based on market volatility, balancing returns and risk. This improvement allows the strategy to control risk in highly volatile markets while fully leveraging opportunities in low-volatility trends.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add Stop-Loss and Take-Profit Mechanisms: Design dynamic stop-loss and take-profit strategies based on market volatility, protecting existing profits and limiting single trade losses. This can prevent significant profit drawdowns caused by delayed reactions of the long-period CCI.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Time-Period Optimization: Adjust strategy parameters or trading logic for different trading sessions (such as opening, closing) to adapt to the market characteristics of each time period. Markets often exhibit different volatility and trend characteristics during different periods, and targeted optimization can improve strategy stability.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add Drawdown Control: Design maximum drawdown control mechanisms that automatically reduce positions or pause trading when strategy performance is poor, preventing consecutive losses. This mechanism helps the strategy protect itself in unfavorable market environments.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The Dual-Timeframe Momentum CCI Trend Following Trading Strategy is an efficient trend-following system based on the CCI indicator, using the synergy between long and short period CCIs to identify market trend direction while capturing optimal entry timing. The strategy design is simple yet effective, particularly suitable for clearly trending markets. Although there are certain risks related to parameter sensitivity and single indicator dependency, through the suggested optimization directions, including multiple indicator combinations, adaptive parameters, and improved capital management mechanisms, the robustness and adaptability of the strategy can be significantly enhanced. For quantitative investors pursuing trend trading, this strategy provides an ideal starting point that can be further customized and optimized according to individual needs and market characteristics. In practical application, it is recommended to combine thorough backtesting and simulated trading to verify the strategy's performance in specific markets, and continuously adjust and refine strategy parameters and logic based on backtest results.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy source code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*backtest
start: 2024-07-03 00:00:00
end: 2025-07-01 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"DOGE_USDT"}]
*/

// @version=6
// @description= Trend-following trading strategy based on the Commodity Channel Index (CCI) and price action confirmation. 
// The strategy focuses on identifying momentum-driven trends with entry and exit conditions.
// @author: withoutbug
strategy("Momentum CCI Trend Following Strategy",
     overlay=false, 
     initial_capital=10000, 
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=100,
     commission_type=strategy.commission.percent,
     commission_value=0.075,
     margin_long=0,
     margin_short=0)

// Input parameters
cciLongPeriod = input.int(50, "Long CCI Period", minval=1)
cciShortPeriod = input.int(5, "Short CCI Period", minval=1)
twoWayTrading = input(false, "Enable Short Order Book")



// Calculate CCI
cciLong = ta.cci(hlc3, cciLongPeriod)
cciShort = ta.cci(hlc3, cciShortPeriod)

cciLongCrossUnderZero = ta.crossunder(cciLong, 0)
cciShortCrossOverZero = ta.crossover(cciShort, 0)

cciLongCrossOverZero = ta.crossover(cciLong, 0)
cciShortCrossUnderZero = ta.crossunder(cciShort, 0)


// Track CCI Long &amp;gt; 0 state and first crossover
var bool inPositiveCciLongCycle = false
var bool firstCrossoverOccurred = false
var bool firstCrossunderOccurred = false

// Update CCI Long cycle state
firstCrossoverOccurred := false
firstCrossunderOccurred := false

// Buy conditions
buySignal = strategy.position_size==0 and cciLong &amp;gt; 0 and cciLong[1] &amp;gt; 0 and  cciShortCrossOverZero and firstCrossoverOccurred == false
if buySignal
    firstCrossoverOccurred := true

// Exit conditions
exitLong = strategy.position_size&amp;gt;0 and cciLongCrossUnderZero

// Sell conditions
sellSignal = strategy.position_size==0 and cciLong &amp;lt; 0 and cciLong[1] &amp;lt; 0 and  cciShortCrossUnderZero and firstCrossunderOccurred == false
if sellSignal
    firstCrossunderOccurred := true

// Exit conditions
exitShort = strategy.position_size&amp;lt;0 and cciLongCrossOverZero


// Strategy logic
if (buySignal)
    strategy.entry("Long", strategy.long)

if (exitLong)
    strategy.close("Long", comment="CCI Exit Long")

if (sellSignal and twoWayTrading)
    strategy.entry("Short", strategy.short)

if (exitShort and twoWayTrading)
    strategy.close("Short", comment="CCI Exit Short")


// Plot CCI indicators on the panel
plot(cciLong, title="Long CCI", color = cciLong&amp;gt;=0 ? color.green:color.red, linewidth=2, style = plot.style_area)
plot(cciShort, title="Short CCI", color=color.yellow, linewidth=1)


hline(0, "Zero Line", color=color.gray, linestyle=hline.style_solid)

// Plot buy and sell signals on the panel
plotshape(buySignal, title="Buy Signal", location=location.bottom, color=color.green, style=shape.triangleup, size=size.tiny)
plotshape(exitLong, title="exitLong", location=location.top, color=color.red, style=shape.triangledown, size=size.tiny)


plotshape(sellSignal, display = twoWayTrading?display.pane:display.none, title="Sell Signal", location=location.top, color=color.red, style=shape.triangledown, size=size.tiny)
plotshape(exitShort, display = twoWayTrading?display.pane:display.none, title="exitShort", location=location.bottom, color=color.green, style=shape.triangleup, size=size.tiny)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Strategy parameters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7uju2k3z08mxb8ew2f90.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7uju2k3z08mxb8ew2f90.png" alt=" " width="800" height="115"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The original address: &lt;a href="https://www.fmz.com/strategy/500323" rel="noopener noreferrer"&gt;Dual-Timeframe Momentum CCI Trend Following Trading Strategy&lt;/a&gt;&lt;/p&gt;

</description>
      <category>trading</category>
      <category>strategy</category>
      <category>momentum</category>
      <category>timeframe</category>
    </item>
    <item>
      <title>Trend-Confirmed Inverted Fair Value Gap Strategy with Dynamic Trailing Stop-Loss</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Fri, 25 Jul 2025 02:01:01 +0000</pubDate>
      <link>https://dev.to/fmzquant/trend-confirmed-inverted-fair-value-gap-strategy-with-dynamic-trailing-stop-loss-489e</link>
      <guid>https://dev.to/fmzquant/trend-confirmed-inverted-fair-value-gap-strategy-with-dynamic-trailing-stop-loss-489e</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faclu1orocnj4yhlf9v3b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faclu1orocnj4yhlf9v3b.png" alt=" " width="800" height="224"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe5x52ajtmo222mu5jdmx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe5x52ajtmo222mu5jdmx.png" alt=" " width="800" height="209"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Overview&lt;/strong&gt;&lt;br&gt;
This strategy is a trading system based on Inverted Fair Value Gaps (IFVG), combined with trend confirmation and dynamic trailing stop-loss mechanisms. The strategy first identifies Fair Value Gaps (FVG) in the market, then looks for reversal signals of these gaps, while using Simple Moving Averages (SMA) to confirm the overall market trend, and finally implements dynamic trailing stop-losses based on Average True Range (ATR) to optimize risk management. This multi-confirmation mechanism aims to improve the reliability of trading signals while protecting profits through dynamic stop-losses.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Principles&lt;/strong&gt;&lt;br&gt;
The core of this strategy is to identify and capitalize on the reversal of Fair Value Gaps (FVG). The strategy principles can be divided into the following key steps:&lt;/p&gt;

&lt;p&gt;FVG Identification: The strategy first detects Fair Value Gaps, which are price areas formed when the lowest price of a candle is higher than the highest price of the previous candle (bullish FVG) or when the highest price of a candle is lower than the lowest price of the previous candle (bearish FVG). These areas represent price levels that were not traded during rapid market movements.&lt;/p&gt;

&lt;p&gt;IFVG Confirmation: When price returns to the FVG area and shows a reversal signal, an Inverted Fair Value Gap (IFVG) is formed. Specifically, IFVG is confirmed when the price is higher than the high point of a bullish FVG and the closing price is higher than the opening price, or when the price is lower than the low point of a bearish FVG and the closing price is lower than the opening price.&lt;/p&gt;

&lt;p&gt;Trend Confirmation: The strategy uses 50-period and 200-period Simple Moving Averages (SMA) to determine market trends. An uptrend is confirmed when the short-term SMA (50-period) is above the long-term SMA (200-period); conversely, a downtrend is confirmed.&lt;/p&gt;

&lt;p&gt;Entry Conditions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Long Condition: When IFVG forms, price is below the IFVG low, and the market is in an uptrend&lt;/li&gt;
&lt;li&gt;Short Condition: When IFVG forms, price is above the IFVG high, and the market is in a downtrend&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Risk Management:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Initial stop-loss is set at 0.5% from the entry price&lt;/li&gt;
&lt;li&gt;Take-profit target is set at 1.5% from the entry price&lt;/li&gt;
&lt;li&gt;Dynamic trailing stop-loss is activated when profit reaches half of the take-profit target (0.75%)&lt;/li&gt;
&lt;li&gt;The trailing stop is dynamically adjusted based on ATR(14), ensuring a larger price buffer when market volatility increases&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Strategy Advantages&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Multi-confirmation Mechanism: This strategy combines price structure (IFVG), trend direction (SMA), and dynamic risk management (ATR) to form a multi-layer filtering system, significantly reducing false signals.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Market Structure Driven: By identifying FVG and IFVG, the strategy can capture changes in market microstructure, which often represent short-term imbalances in buying and selling forces and potential directional opportunities.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Trend Consistency: By confirming the overall trend direction through SMA crossovers, the strategy only trades in the direction of the trend, avoiding the high risk of counter-trend trading.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Dynamic Risk Management: The strategy not only sets fixed stop-loss and take-profit levels but also implements ATR-based dynamic trailing stops that adaptively adjust protection levels based on market volatility.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Profit Protection Mechanism: When a trade reaches half of the preset profit, the stop-loss automatically moves above the breakeven point, ensuring that trades don't turn from profitable to losing.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Timeframe Flexibility: Although backtesting was conducted on a 1-minute timeframe, the core logic of the strategy (FVG, trend confirmation, and dynamic stop-loss) can be applied to various timeframes.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Risks&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;FVG Reliability Issues: In highly volatile markets, FVGs may appear frequently but not all have trading value, potentially leading to overtrading. The solution is to add additional filtering conditions, such as requiring FVGs to have a minimum width or to form near key price levels.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Trend Definition Limitations: Using only two SMAs to define trends may generate false signals in oscillating markets. The solution is to add additional trend confirmation indicators, such as ADX (Average Directional Index) to measure trend strength.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Stop-Loss Too Tight Risk: A fixed 0.5% stop-loss may be too tight in some highly volatile instruments and easily triggered by market noise. The solution is to link stop-loss settings with ATR, making them adapt to the volatility characteristics of different instruments.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Drawdown Management Insufficiency: When the market suddenly reverses, trailing stops may not respond quickly enough, leading to increased drawdowns. The solution is to set a maximum acceptable drawdown threshold, exiting immediately once exceeded.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Parameter Sensitivity: Strategy performance is highly sensitive to parameters such as SMA periods, stop-loss percentages, and ATR multipliers. The solution is to find robust parameter combinations through backtesting optimization and regularly reassess.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Optimization Directions&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Multiple Timeframe Analysis Integration: Incorporating FVG and trend information from higher timeframes into the decision-making process can improve signal quality. For example, requiring signals on a 1-minute chart to align with FVG and trend directions on 15-minute or 1-hour charts.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Dynamic Take-Profit Mechanism: The current strategy uses a fixed percentage take-profit, which can be improved to an ATR-based dynamic take-profit, or automatically adjust take-profit targets based on market volatility.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Adaptability to Reversal and Ranging Markets: Add market environment recognition logic, using the current strategy in clear trend periods and adopting different entry and exit criteria during consolidation periods.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Volume Confirmation: Integrate volume analysis to verify the validity of FVG and IFVG. Truly meaningful price gaps are usually accompanied by significant volume changes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Machine Learning Optimization: Use machine learning algorithms to identify the most predictive combination of FVG features, such as gap size, formation speed, relationship with support/resistance, etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Adaptive Parameter Adjustment: Develop a mechanism that allows the strategy to automatically adjust its parameters based on recent market performance, such as widening stop-loss ranges when volatility increases.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Enhanced Position Management: The current strategy uses a fixed position size (10 units), which can be improved to a dynamic position management system based on volatility and risk metrics, increasing exposure on high-confidence signals and reducing it in uncertain markets.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The Trend-Confirmed Inverted Fair Value Gap Strategy with Dynamic Trailing Stop-Loss is a multi-layered trading system that organically combines price structure analysis (FVG and IFVG), trend confirmation (SMA), and dynamic risk management (ATR trailing stop-loss). The main advantages of this strategy lie in its multi-confirmation mechanism and adaptive risk management, effectively filtering low-quality signals and protecting realized profits.&lt;/p&gt;

&lt;p&gt;However, the strategy also faces challenges such as FVG reliability, trend definition limitations, and parameter sensitivity. Future optimization directions include integrating multiple timeframe analysis, developing dynamic take-profit mechanisms, improving adaptability in different market environments, and introducing machine learning techniques to optimize signal quality and parameter selection.&lt;/p&gt;

&lt;p&gt;Through these improvements, the strategy has the potential to develop into a more robust and adaptive trading system capable of maintaining consistent performance under various market conditions. Particularly by enhancing its responsiveness to changes in market structure and volatility, the strategy can better adapt to changing market environments, improving long-term profitability and stability of capital growth.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy source code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*backtest
start: 2025-05-31 00:00:00
end: 2025-06-30 00:00:00
period: 1m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"BNB_USDT"}]
args: [["RunMode",1,358374]]
*/

//@version=6
strategy("Inverted FVG Strategy with Trend Check and Trailing Stops", default_qty_value = 10, overlay=true)

// Function to detect FVG
fvgDetected(src, high, low) =&amp;gt;
    float prevHigh = na
    float prevLow = na
    float prevClose = na
    float fvgHigh = na
    float fvgLow = na
    bool fvg = false
    if (not na(src[3]))
        prevHigh := high[3]
        prevLow := low[3]
        prevClose := src[3]
        if (src[2] &amp;gt; prevClose and low[2] &amp;gt; prevHigh) or (src[2] &amp;lt; prevClose and high[2] &amp;lt; prevLow)
            fvg := true
            fvgHigh := low[2] &amp;gt; prevHigh ? high[2] : na
            fvgLow := high[2] &amp;lt; prevLow ? low[2] : na
    [fvg, fvgHigh, fvgLow]

// Detect FVG on the chart
[fvg, fvgHigh, fvgLow] = fvgDetected(close, high, low)

// Detect IFVG - Inversion of FVG
bool ifvg = false
float ifvgHigh = na
float ifvgLow = na

if (fvg)    
    if (high[1] &amp;gt; fvgHigh and close[1] &amp;gt; open[1]) or (high[1] &amp;lt; fvgLow and close[1] &amp;lt; open[1])
        ifvg := true
        ifvgHigh := close[1] &amp;gt; open[1] ? high[1] : na
        ifvgLow := close[1] &amp;lt;  open[1] ? low[1] : na

// Plot FVG and IFVG zones for visualization
plot(ifvgHigh, title="IFVG High", color=color.red, linewidth=2, style=plot.style_cross)
plot(ifvgLow, title="IFVG Low", color=color.red, linewidth=2, style=plot.style_cross)

// Trend Check using Simple Moving Averages
smaShort = ta.sma(close, 50)  // Short term SMA
smaLong = ta.sma(close, 200)  // Long term SMA
bool uptrend = false
bool downtrend = false

uptrend := smaShort &amp;gt; smaLong  // Up trend if short SMA is above long SMA
downtrend := smaShort &amp;lt; smaLong  // Down trend if short SMA is below long SMA

// Plot SMAs for visualization
plot(smaShort, title="SMA Short", color=color.blue, linewidth=1)
plot(smaLong, title="SMA Long", color=color.orange, linewidth=1)

// Trading logic with trend confirmation
longCondition = ifvg and close &amp;lt; ifvgLow and uptrend
shortCondition = ifvg and close &amp;gt; ifvgHigh and downtrend

// Risk Definition - Percentage of use
stopLoss = 0.005   // 0.5% stop loss
takeProfit = 0.015  // 1.5% take profit

if (longCondition and strategy.position_size == 0)
    strategy.entry("Long", strategy.long)
    stopPrice = close * (1 - stopLoss)
    limitPrice = close * (1 + takeProfit)
    strategy.exit("Initial Long Exit", "Long", stop=stopPrice, limit=limitPrice)

if (shortCondition and strategy.position_size == 0)
    strategy.entry("Short", strategy.short)
    stopPrice = close * (1 + stopLoss)
    limitPrice = close * (1 - takeProfit)
    strategy.exit("Initial Short Exit", "Short", stop=stopPrice, limit=limitPrice)

// ATR for dynamic trailing stop
atr = ta.atr(14)

// Trailing Stop for Long Position if the trade has moved &amp;gt; 0.5% (half of takeProfit)
if (strategy.position_size &amp;gt; 0)
    profitThreshold = takeProfit * 0.5  // 1.5% profit threshold
    if (close - strategy.position_avg_price &amp;gt;= strategy.position_avg_price * profitThreshold)
        // Move your stop loss to breakeven plus a little profit
        trailingStopLong = math.max(strategy.position_avg_price * (1 + profitThreshold), close - (atr * 2))
        strategy.exit("Trailing Stop Long", "Long", stop=trailingStopLong)

// Trailing Stop for Short Position if the trade has moved &amp;gt; 0.5% (half of takeProfit)
if (strategy.position_size &amp;lt; 0)
    profitThreshold = takeProfit * 0.5  // 1.5% profit threshold
    if (strategy.position_avg_price - close &amp;gt;= strategy.position_avg_price * profitThreshold)
        // Move your stop loss to breakeven plus a little profit
        trailingStopShort = math.min(strategy.position_avg_price * (1 - profitThreshold), close + (atr * 2))
        strategy.exit("Trailing Stop Short", "Short", stop=trailingStopShort)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The original address: &lt;a href="https://www.fmz.com/strategy/500331" rel="noopener noreferrer"&gt;Trend-Confirmed Inverted Fair Value Gap Strategy with Dynamic Trailing Stop-Loss&lt;/a&gt;&lt;/p&gt;

</description>
      <category>strategy</category>
      <category>cryptocurrency</category>
      <category>trading</category>
      <category>trend</category>
    </item>
    <item>
      <title>Supply and Demand Order Block Breakout Strategy with Volume Filter</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Fri, 25 Jul 2025 01:09:32 +0000</pubDate>
      <link>https://dev.to/fmzquant/supply-and-demand-order-block-breakout-strategy-with-volume-filter-jn1</link>
      <guid>https://dev.to/fmzquant/supply-and-demand-order-block-breakout-strategy-with-volume-filter-jn1</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxes839vob1oqscj9emkm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxes839vob1oqscj9emkm.png" alt=" " width="800" height="228"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdzgj7lx6jivj9s2sjl4e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdzgj7lx6jivj9s2sjl4e.png" alt=" " width="800" height="206"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br&gt;
The Supply and Demand Order Block Breakout Strategy with Volume Filter is a quantitative trading strategy that combines fractal theory, volume confirmation, and order block concepts from technical analysis. The strategy identifies key fractal points in historical price data and uses volume filtering mechanisms to determine potential supply and demand zones. Trading signals are executed when price breaks through these critical zones. The core concept leverages order block effects in the market, where large capital creates buying and selling pressure zones at specific price levels, with volume validation to enhance signal reliability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Principles&lt;/strong&gt;&lt;br&gt;
The strategy's core principle is based on fractal theory and order block concepts. First, the strategy identifies potential supply and demand zones by calculating price fractal points within specified periods. An up fractal is defined as the highest price level within the specified period, while a down fractal represents the lowest price level within the same timeframe. To improve signal quality, the strategy incorporates a volume filtering mechanism that requires the fractal point's volume to exceed a specified multiple of the 20-period simple moving average volume.&lt;/p&gt;

&lt;p&gt;When a valid up fractal is identified, the strategy marks this level as a resistance zone and waits for an upward price breakout. When price breaks above the up fractal, the strategy interprets this as a change in supply and demand dynamics, where the former resistance zone transforms into a support zone, triggering a long position entry. Conversely, when a valid down fractal is identified, the strategy marks this level as a support zone. When price breaks below this level, the former support zone becomes a resistance zone, triggering a short position entry.&lt;/p&gt;

&lt;p&gt;The strategy allows users to choose between two breakout confirmation methods: wick plus body breakout and pure body breakout. The wick plus body breakout mode uses high and low prices as breakout confirmation criteria, while the pure body breakout mode uses closing prices for confirmation. The volume filtering mechanism validates breakout effectiveness by comparing current volume against historical average volume multiples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Advantages&lt;/strong&gt;&lt;br&gt;
The strategy possesses several significant advantages. First, the volume filtering mechanism substantially improves signal reliability. Traditional fractal breakout strategies are prone to false breakout signals, while volume confirmation effectively filters out weak breakouts with insufficient volume, ensuring trading signals only occur under adequate market participation.&lt;/p&gt;

&lt;p&gt;Second, the strategy is based on order block theory, providing a solid market logic foundation. Order blocks represent concentrated buying and selling activities by large capital at specific price levels, often forming important support and resistance levels. When price breaks through these critical zones, it typically indicates significant market structure changes, providing traders with high-probability entry opportunities.&lt;/p&gt;

&lt;p&gt;Third, the strategy demonstrates excellent adaptability and configurability. Users can adjust parameters such as fractal periods and volume multiples according to different market environments and personal preferences. The choice of breakout types also provides additional flexibility, allowing traders to select the most suitable confirmation method based on market characteristics.&lt;/p&gt;

&lt;p&gt;Finally, the strategy maintains clear and concise logic that is easy to understand and implement. Through well-defined fractal identification, volume filtering, and breakout confirmation processes, the strategy avoids complex technical indicator combinations, reducing over-optimization risks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Risks&lt;/strong&gt;&lt;br&gt;
Despite numerous advantages, the strategy also presents certain potential risks requiring attention. First, the strategy heavily depends on volume data. In situations where volume data is inaccurate or market liquidity is poor, the volume filtering mechanism may produce misjudgments, leading to missed valid trading opportunities or false signals.&lt;/p&gt;

&lt;p&gt;Second, the strategy suffers from lag issues. Due to the need to wait for fractal point confirmation and breakout occurrence, the strategy's entry timing may lag behind optimal entry points. This lag could affect profitability in rapidly changing market environments.&lt;/p&gt;

&lt;p&gt;Third, the strategy lacks explicit stop-loss and take-profit mechanisms. While the strategy can identify entry timing, it doesn't provide corresponding risk management measures. During severe market volatility or breakout failures, traders may face significant loss risks.&lt;/p&gt;

&lt;p&gt;To mitigate these risks, traders should combine other technical analysis tools for signal confirmation, set reasonable stop-loss and take-profit levels, and dynamically adjust strategy parameters based on market conditions. Additionally, comprehensive backtesting and validation across different market environments are recommended.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Optimization Directions&lt;/strong&gt;&lt;br&gt;
The strategy offers multiple optimization directions. First, implementing a dynamic volume threshold mechanism could be beneficial. The current strategy uses fixed volume multiples as filtering conditions, but market volume characteristics change over time. By introducing adaptive volume thresholds, the strategy can dynamically adjust filtering standards based on actual market conditions, improving adaptability.&lt;/p&gt;

&lt;p&gt;Second, adding comprehensive risk management modules is recommended. Stop-loss and take-profit levels can be set based on volatility, support and resistance levels, or fixed percentages. Position management mechanisms could also be considered, adjusting trade sizes based on signal strength and market volatility.&lt;/p&gt;

&lt;p&gt;Third, incorporating multi-timeframe analysis could enhance performance. The current strategy operates within a single timeframe, but combining higher timeframe trend analysis could improve success rates. For example, executing trading signals only when higher timeframe trends align.&lt;/p&gt;

&lt;p&gt;Fourth, optimizing fractal identification algorithms presents opportunities for improvement. Current fractal identification is relatively simple; more complex methods could be considered, such as pattern-based fractal identification or composite fractal identification combining other technical indicators.&lt;/p&gt;

&lt;p&gt;Finally, adding signal filtering mechanisms is advisable. Additional technical indicators (such as RSI, MACD) could filter trading signals, or market sentiment indicators could adjust strategy sensitivity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The Supply and Demand Order Block Breakout Strategy with Volume Filter is a comprehensive quantitative trading strategy combining fractal theory, volume analysis, and order block concepts. The strategy identifies key price fractal points, incorporates volume confirmation mechanisms, and executes trading operations when price breaks through important supply and demand zones.&lt;/p&gt;

&lt;p&gt;The strategy's main advantages include solid theoretical foundation, good signal quality, and high configurability. The volume filtering mechanism effectively improves signal reliability, while order block theory provides clear market logic support. However, the strategy also presents potential risks, including dependency on volume data, signal lag, and lack of risk management mechanisms.&lt;/p&gt;

&lt;p&gt;Through optimization measures such as introducing dynamic volume thresholds, comprehensive risk management modules, multi-timeframe analysis, and signal filtering mechanisms, the strategy's performance and stability can be further enhanced. For quantitative traders, this strategy provides an effective market structure analysis tool that helps identify high-probability trading opportunities.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy source code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*backtest
start: 2024-07-07 00:00:00
end: 2025-07-05 10:18:00
period: 3m
basePeriod: 3m
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

//@version=5
strategy("Supply and Demand - Order Block Strategy with Volume Filter", overlay=true)

// ═══════════════════════════════════════════════════════════════════════════════════
// 📊 INPUT SETTINGS
// ═══════════════════════════════════════════════════════════════════════════════════
breakType = input.string("Wick+Body", title="Fractal Break Type:", options=["Wick+Body", "Body"])
n = input.int(title="Periods", defval=5, minval=3, tooltip="Number of periods for fractal lookback")

// 🔊 Volume Filter
enableVolumeFilter = input.bool(true, "Enable Volume Filter", group="Volume Filter")
volumeMultiplier = input.float(1.5, "Volume Multiplier", minval=1.0, maxval=3.0, step=0.1, group="Volume Filter", tooltip="Fractal must have volume &amp;gt; average volume * this multiplier")

// ═══════════════════════════════════════════════════════════════════════════════════
// 📈 TECHNICAL INDICATORS
// ═══════════════════════════════════════════════════════════════════════════════════
avgVolume = ta.sma(volume, 20)

// ═══════════════════════════════════════════════════════════════════════════════════
// 📦 FRACTAL CALCULATION WITH VOLUME FILTER
// ═══════════════════════════════════════════════════════════════════════════════════

// Original fractal calculation
upFractal = high[n] == ta.highest(high, n)
downFractal = low[n] == ta.lowest(low, n)

// 🔊 Enhanced fractal with volume confirmation
upFractalValid = upFractal and (not enableVolumeFilter or volume[n] &amp;gt; avgVolume * volumeMultiplier)
downFractalValid = downFractal and (not enableVolumeFilter or volume[n] &amp;gt; avgVolume * volumeMultiplier)

var float topValue = na
var float bottomValue = na
var topBreakBlock = false
var bottomBreakBlock = false

topBreakCheckSource = breakType == "Wick+Body" ? high : close
bottomBreakCheckSource = breakType == "Wick+Body" ? low : close

// New up fractal - only if volume criteria met
if upFractalValid
    topBreakBlock := false
    topValue := high[n]

// New down fractal - only if volume criteria met
if downFractalValid
    bottomBreakBlock := false
    bottomValue := low[n]

// ═══════════════════════════════════════════════════════════════════════════════════
// 🚀 ENTRY LOGIC
// ═══════════════════════════════════════════════════════════════════════════════════

// Top break
if ta.crossover(topBreakCheckSource, topValue) and not topBreakBlock
    topBreakBlock := true
    if strategy.position_size &amp;lt;= 0
        strategy.entry("Long", strategy.long)

// Bottom break
if ta.crossunder(bottomBreakCheckSource, bottomValue) and not bottomBreakBlock
    bottomBreakBlock := true
    if strategy.position_size &amp;gt;= 0
        strategy.entry("Short", strategy.short)


// ═══════════════════════════════════════════════════════════════════════════════════
// 🎨 PLOTS
// ═══════════════════════════════════════════════════════════════════════════════════
plotshape(downFractalValid, style=shape.triangleup, location=location.belowbar, offset=-n, color=color.new(color.gray,80), size = size.tiny)
plotshape(upFractalValid, style=shape.triangledown, location=location.abovebar, offset=-n, color=color.new(color.gray,80), size = size.tiny)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Strategy parameters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnfizcd9jcc3gr0c7atxf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnfizcd9jcc3gr0c7atxf.png" alt=" " width="800" height="193"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The original address: &lt;a href="https://www.fmz.com/strategy/500467" rel="noopener noreferrer"&gt;Supply and Demand Order Block Breakout Strategy with Volume Filter&lt;/a&gt;&lt;/p&gt;

</description>
      <category>breakout</category>
      <category>strategy</category>
      <category>cryptocurrency</category>
      <category>trading</category>
    </item>
    <item>
      <title>Relative Volume Percentage Momentum Trading Strategy</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Thu, 24 Jul 2025 03:05:49 +0000</pubDate>
      <link>https://dev.to/fmzquant/relative-volume-percentage-momentum-trading-strategy-220n</link>
      <guid>https://dev.to/fmzquant/relative-volume-percentage-momentum-trading-strategy-220n</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fquyqbjn1resqy0jzpirx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fquyqbjn1resqy0jzpirx.png" alt=" " width="800" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmn35hz8rzlvgffiglaq2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmn35hz8rzlvgffiglaq2.png" alt=" " width="800" height="408"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br&gt;
The Relative Volume Percentage Momentum Trading Strategy is a comprehensive trading system that combines volume momentum analysis, price action filtering, breakout detection, and dynamic stop-loss/take-profit logic. The core of this strategy is calculating a Williams %R-like indicator for relative volume (RVPR), paired with dual moving average filters (Fast and Slow) to identify moments of volume expansion or contraction. The strategy further refines entry conditions through configurable price action filters based on different types of candle formations. This strategy is particularly suitable for traders looking to identify reversals or continuation setups based on relative volume spikes and candle behavior, providing highly adaptable long and short trading signals.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Principles&lt;/strong&gt;&lt;br&gt;
The core principle of this strategy is transforming volume data into a percentage range, using a Williams %R-like calculation to analyze the relationship between current volume and its historical range. The strategy uses the following key components to generate trading signals:&lt;/p&gt;

&lt;p&gt;Relative Volume %R Oscillator: Compares the current volume with historical volume highs and lows, calculating the relative position. This indicator is similar to Williams %R in the price domain but applied to volume data.&lt;/p&gt;

&lt;p&gt;Dual Moving Average Filter: The strategy uses two volume moving averages (Fast and Slow), with options for various smoothing algorithms (SMA, EMA, JMA, T3, Super Smoother, etc.). When volume is greater than the Fast MA, and Fast MA is greater than Slow MA, it indicates an upward volume trend, potentially a long signal; vice versa for short.&lt;/p&gt;

&lt;p&gt;Price Action Filter: Further filters trading signals based on different candle patterns:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Simple Mode: Basic up/down candles&lt;/li&gt;
&lt;li&gt;Filtered Mode: Range-based strength confirmation&lt;/li&gt;
&lt;li&gt;Aggressive Mode: Momentum-based breakout&lt;/li&gt;
&lt;li&gt;Inside Mode: Reversal candle patterns&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Breakout Filter: Optionally excludes trades near 5-bar highs/lows to avoid poor risk-reward trades.&lt;/p&gt;

&lt;p&gt;Stop Loss and Take Profit System: Dynamic SL/TP mechanism based on ATR (Average True Range), with configurable multipliers to adjust the distance of SL and TP.&lt;/p&gt;

&lt;p&gt;Timed Exit: Option to exit trades after a fixed number of candles.&lt;/p&gt;

&lt;p&gt;Long entry conditions include: volume greater than Fast MA, Fast MA greater than Slow MA, Relative Volume %R greater than threshold, price passing the long directional filter, and optionally below recent breakout high. Short entry conditions are the opposite, with positions closed when the set exit conditions are triggered.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Advantages&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Multi-dimensional Analysis: The strategy combines volume, price action, and dynamic SL/TP, providing a comprehensive market analysis framework.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Highly Customizable: The strategy offers multiple adjustable parameters, including trade direction control, different price action filtering modes, volume moving average type selection, etc., allowing traders to customize according to their style and market preferences.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Intelligent Entry Filtering: By combining volume momentum and price action patterns, the strategy can identify higher probability trading opportunities, avoiding low-quality trading signals.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Flexible Exit Mechanisms: The strategy provides time and price-based exit options, including fixed bar exit and ATR-based dynamic SL/TP, making risk management more flexible and effective.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Adaptable to Various Market Environments: Through different price action modes (Simple, Filtered, Aggressive, Inside), the strategy can adapt to different market conditions, including trending and ranging markets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Advanced Technical Indicator Integration: The strategy incorporates multiple advanced moving average types, such as JMA (Jurik Moving Average), T3, and Super Smoother, which excel in reducing noise and capturing true trends.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Risks&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Parameter Optimization Risk: As the strategy contains multiple adjustable parameters, there is a risk of over-optimization, potentially leading to excellent historical backtesting performance but poor live trading results. The solution is to use forward testing and robustness analysis to ensure parameters maintain stability across different market conditions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;False Breakout Risk: Volume spikes do not always accompany sustainable price movements, and the strategy may generate false signals in fake breakouts. This risk can be mitigated by adding additional confirmation indicators or delaying entries.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Market Environment Dependency: The strategy's performance may be inconsistent in different market environments (e.g., high volatility vs. low volatility). It is recommended to test the strategy's performance under various market conditions before implementation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Stop Loss Trigger Risk: Using ATR-based stops may be triggered when volatility suddenly expands. Consider using volatility-adjusted stop multipliers or setting stops at key support/resistance levels for more effectiveness.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Inflexible Time Exit: Fixed bar exits may close profitable trades too early or losing trades too late. Consider combining trend or momentum indicators to dynamically adjust exit timing.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Computational Complexity: The strategy uses multiple complex moving average algorithms and condition combinations, potentially increasing computational burden and leading to execution delays. In real-time trading, it may be necessary to simplify some computation-intensive indicators.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Optimization Directions&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Dynamic Threshold Adjustment: The current strategy uses a fixed Relative Volume %R threshold (27); consider implementing adaptive thresholds that automatically adjust based on recent volume volatility. This would make the strategy better adapt to different market conditions and seasonal changes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Multi-timeframe Confirmation: Introduce higher timeframe confirmation signals, trading only in the direction of the larger trend, which can improve the strategy's win rate and risk-reward ratio. For example, only execute long signals on the hourly chart when the daily trend is upward.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Volume Quality Analysis: In addition to relative volume, incorporate volume divergence indicators or volume distribution analysis to assess volume quality rather than just quantity. This helps distinguish healthy trend-confirming volume from potential exhaustion signals.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Intelligent Stop Loss/Take Profit: The current ATR-based SL/TP can be improved to a more intelligent system, for example, based on key support/resistance positions, or using volatility-adjusted stops, tightening stops in low volatility periods and widening them in high volatility periods.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Integrate Market Structure: Incorporating price structure analysis (such as support/resistance, trendlines, price channels) into the strategy can improve the quality of entry and exit points.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Risk Management Enhancement: Implement dynamic position sizing, based on current market volatility and recent strategy performance, increasing positions in high win-rate environments and reducing them in uncertain periods.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Machine Learning Integration: Using machine learning algorithms to dynamically optimize strategy parameters or predict which price action filter is most effective in current market conditions can further improve strategy performance.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The Relative Volume Percentage Momentum Trading Strategy is a comprehensive and flexible trading system that provides traders with a powerful tool to identify potential market opportunities by combining volume analysis, various price action filters, and dynamic risk management techniques. The core strengths of this strategy lie in its adaptability and customizability, allowing traders to adjust according to personal preferences and market conditions.&lt;/p&gt;

&lt;p&gt;This strategy is particularly suitable for traders seeking reversal or trend continuation signals based on volume confirmation. By using a Williams %R style relative volume indicator, the strategy can identify volume spike points, which often represent important shifts in market sentiment or trend acceleration. Meanwhile, multiple price action filtering options allow traders to choose more conservative or aggressive entry conditions based on their risk preferences and trading style.&lt;/p&gt;

&lt;p&gt;While the strategy offers many advantages, traders should be aware of potential over-optimization risks and market environment dependencies. Through continuous testing and adjustment, combined with the suggested optimization directions, traders can further enhance the robustness and long-term profitability of this strategy. Ultimately, as with all trading strategies, the key to success lies in thoroughly understanding its principles, wisely managing risk, and continuously evaluating its performance under different market conditions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy source code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*backtest
start: 2024-07-04 00:00:00
end: 2025-07-02 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © GabrielAmadeusLau

//@version=6
strategy("Relative Volume Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// === Input: Trade Direction === //
tradeDirection = input.string("Long Only", title="Trade Direction", options=["Long Only", "Short Only", "Both"], group="Strategy Settings")
dirBarModeL     = input.string("Simple", title="Long Directional Bar Mode", options=["Simple", "Filtered", "Aggressive", "Inside", "Filtered &amp;amp; Aggressive", "Filtered &amp;amp; Aggressive &amp;amp; Inside", "Without"], group="Strategy Settings")
dirBarModeS     = input.string("Inside", title="Short Directional Bar Mode", options=["Simple", "Filtered", "Aggressive", "Inside", "Filtered &amp;amp; Aggressive", "Filtered &amp;amp; Aggressive &amp;amp; Inside", "Without"], group="Strategy Settings")
useBreakout  = input.bool(true, "Use Breakout Filter", group="Strategy Settings")
useSLTP = input.bool(false, "Use Stop Loss &amp;amp; Take Profit", group="Strategy Settings")
atrSLMult = input.float(1, "ATR SL Multiplier", step = 0.05, group="Strategy Settings")
atrTPMult = input.float(1.75, "ATR TP Multiplier", step = 0.05, group="Strategy Settings")


// === Input: MA Function Selector === //
// — T3 Moving Average Function —
// src    = input source (e.g. rsi1, close, etc.)
// length = smoothing length (period)
// a      = T3 alpha (commonly between 0.7 and 0.9)
t3(src, length, a) =&amp;gt;
    e1 = ta.ema(src, length)
    e2 = ta.ema(e1, length)
    e3 = ta.ema(e2, length)
    e4 = ta.ema(e3, length)
    e5 = ta.ema(e4, length)
    e6 = ta.ema(e5, length)
    c1 = -a * a * a
    c2 = 3 * a * a + 3 * a * a * a
    c3 = -6 * a * a - 3 * a - 3 * a * a * a
    c4 = 1 + 3 * a + a * a * a + 3 * a * a
    c1 * e6 + c2 * e5 + c3 * e4 + c4 * e3

// == Jurik MA == //
jma(float src, int length, float power, float phase) =&amp;gt; 
    phaseRatio = phase &amp;lt; -100 ? 0.5 : phase &amp;gt; 100 ? 2.5 : phase / 100 + 1.5
    beta = 0.45 * (length - 1) / (0.45 * (length - 1) + 2)
    alpha = math.pow(beta, power)
    JMA = 0.0
    e0 = 0.0
    e0 := (1 - alpha) * src + alpha * nz(e0[1])
    e1 = 0.0
    e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])
    e2 = 0.0
    e2 := (e0 + phaseRatio * e1 - nz(JMA[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
    JMA := e2 + nz(JMA[1])

//===== 2 Pole Super Smoother Filter =====//
superSmoother(float Series, float Period) =&amp;gt;
    var float ALPHA =  math.pi * math.sqrt(2.0) / Period
    var float BETA  =  math.exp(-ALPHA )
    var float COEF2 = -math.pow(BETA, 2)
    var float COEF1 =  math.cos( ALPHA ) * 2.0 * BETA
    var float COEF0 =  1.0 - COEF1 - COEF2
    float sma2   = math.avg(Series, nz(Series[1], Series))
    float smooth = na, smooth := COEF0 *      sma2      +
                                 COEF1 *  nz(smooth[1]) +
                                 COEF2 *  nz(smooth[2])

// === MA Selector === //
ma(source, length, type) =&amp;gt;
    type == "SMA"       ? ta.sma(source, length) :
     type == "EMA"       ? ta.ema(source, length) :
     type == "SMMA (RMA)"? ta.rma(source, length) :
     type == "WMA"       ? ta.wma(source, length) :
     type == "VWMA"      ? ta.vwma(source, length) :
     type == "HMA"       ? ta.hma(source, length) : 
     type == "ALMA"      ? ta.alma(source, length, 0.85, 6) :
     type == "LSMA"      ? ta.linreg(source, length, 0) :
     type == "Optimal MA"? math.avg(ta.alma(source, length, 0.85, 6), ta.rma(source, length), ta.sma(source, length)) :
     type == "JMA"       ? jma(source, length, 2, 50) :        
     type == "Super Smoother" ? superSmoother(source, length) :
     type == "T3"        ? t3(source, length, 0.7) :
                          na

// === Input Parameters === //
rvolRLength       = input.int(112, title="Relative Volume %R Length", minval=1, group="Relative Volume", tooltip="%R used for scaling from 0 to 100, I prefer 73 or 112.")
rvolmaTypeInput   = input.string("Optimal MA" , "Type", options = ["None", "SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA", "ALMA", "LSMA", "Optimal MA", "JMA", "Super Smoother", "T3"], group = "Relative Volume")
rvolFastLength    = input.int(7, title="Relative Volume Fast MA", minval=1, group="Relative Volume")
rvolSlowLength    = input.int(161, title="Relative Volume Slow MA", minval=1, group="Relative Volume")
exitBars          = input.int(18, title="Bars Until Exit", group="Strategy Settings", tooltip="Exit trade after N bars")
rvolThreshold = input.int(27, "Minimum Relative Volume %R Threshold", group="Relative Volume")

// === Williams %R for Volume === //
wpr(src, length) =&amp;gt;
    max_ = ta.highest(src, length)
    min_ = ta.lowest(src, length)
    (100 * (src - max_) / (max_ - min_)) * -1

// === Volume MAs === //
rvol      = wpr(volume, rvolRLength)
rvolFast  = ma(volume, rvolFastLength, rvolmaTypeInput)
rvolSlow  = ma(volume, rvolSlowLength, rvolmaTypeInput)

// === Price Action Filters === //
up            = close &amp;gt; open
upRange       = low &amp;gt; low[1] and close &amp;gt; high[1]
upRange_Aggr  = close &amp;gt; close[1] and close &amp;gt; open[1]
insideDayUp   = close &amp;lt; close[1] and close[1] &amp;lt; close[2] and close[2] &amp;lt; close[3] and close[3] &amp;lt; close[4] and close[4] &amp;lt; close[5] //and not (close &amp;gt; close[1])
down          = close &amp;lt; open
downRange     = high &amp;lt; high[1] and close &amp;lt; low[1]
downRange_Aggr= close &amp;lt; close[1] and close &amp;lt; open[1]
insideDayDown = close &amp;gt; close[1] and close[1] &amp;gt; close[2] and close[2] &amp;gt; close[3] and close[3] &amp;gt; close[4] and close[4] &amp;gt; close[5] //and not (close &amp;lt; close[1])
breakoutHigh = ta.highest(high, 5)
breakoutLow  = ta.lowest(low, 5)

// === Mode-Based Filter Logic === //
longBarOK =
     dirBarModeL == "Simple" ? up :
     dirBarModeL == "Filtered"  ? upRange :
     dirBarModeL == "Aggressive"? upRange_Aggr :
     dirBarModeL == "Inside"? insideDayUp : 
     dirBarModeL == "Filtered &amp;amp; Aggressive" ? upRange or upRange_Aggr :
     dirBarModeL == "Filtered &amp;amp; Aggressive &amp;amp; Inside" ? upRange or upRange_Aggr or insideDayUp :
     dirBarModeL == "Without"   ? true : false

shortBarOK =
     dirBarModeS == "Simple" ? down :
     dirBarModeS == "Filtered"  ? downRange :
     dirBarModeS == "Aggressive"? downRange_Aggr :
     dirBarModeS == "Inside"? insideDayDown :
     dirBarModeS == "Filtered &amp;amp; Aggressive"? downRange or downRange_Aggr or insideDayDown :
     dirBarModeS == "Filtered &amp;amp; Aggressive &amp;amp; Inside"? upRange_Aggr or insideDayDown :
     dirBarModeS == "Without"   ? true : false

// === Entry &amp;amp; Exit Logic === //
longCondition  = volume &amp;gt; rvolFast and rvolFast &amp;gt; rvolSlow and longBarOK  and rvol &amp;gt; rvolThreshold and (not useBreakout or close &amp;lt; breakoutHigh)
shortCondition = volume &amp;lt; rvolFast and rvolFast &amp;lt; rvolSlow and shortBarOK and rvol &amp;lt; (100 - rvolThreshold) and (not useBreakout or close &amp;gt; breakoutLow)

exitLongCondition  = strategy.opentrades &amp;gt; 0 and strategy.opentrades.entry_bar_index(0) + exitBars &amp;lt;= bar_index and strategy.opentrades.entry_id(0) == "Long"
exitShortCondition = strategy.opentrades &amp;gt; 0 and strategy.opentrades.entry_bar_index(0) + exitBars &amp;lt;= bar_index and strategy.opentrades.entry_id(0) == "Short"

atr = ta.atr(math.round(math.avg(rvolFastLength, rvolSlowLength)))
longSL = useSLTP ? close - atrSLMult * atr : na
longTP = useSLTP ? close + atrTPMult * atr : na
shortSL = useSLTP ? close + atrSLMult * atr : na
shortTP = useSLTP ? close - atrTPMult * atr : na

// === Strategy Execution === //
if (tradeDirection == "Long Only" or tradeDirection == "Both")
    if (longCondition)
        strategy.entry("Long", strategy.long, stop=longSL, limit=longTP)

if (tradeDirection == "Short Only" or tradeDirection == "Both")
    if (shortCondition)
        strategy.entry("Short", strategy.short, stop=shortSL, limit=shortTP)

if (exitLongCondition)
    strategy.close("Long")

if (exitShortCondition)
    strategy.close("Short")

// === Plotting === //
plot(rvol, title="Relative Volume %R", color=color.orange, style = plot.style_columns, format = format.price)
plot(rvolFast, title="Fast Volume MA", color=color.green, format = format.volume)
plot(rvolSlow, title="Slow Volume MA", color=color.red, format = format.volume)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Strategy parameters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr9tahueeu8sufqq0n5ar.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr9tahueeu8sufqq0n5ar.png" alt=" " width="800" height="544"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The original address: &lt;a href="https://www.fmz.com/strategy/500482" rel="noopener noreferrer"&gt;Relative Volume Percentage Momentum Trading Strategy&lt;/a&gt;&lt;/p&gt;

</description>
      <category>momentum</category>
      <category>trading</category>
      <category>strategy</category>
      <category>cryptocurrency</category>
    </item>
    <item>
      <title>RSI-Adaptive T3 and Squeeze Momentum Hybrid Trading System</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Thu, 24 Jul 2025 02:03:56 +0000</pubDate>
      <link>https://dev.to/fmzquant/rsi-adaptive-t3-and-squeeze-momentum-hybrid-trading-system-15a9</link>
      <guid>https://dev.to/fmzquant/rsi-adaptive-t3-and-squeeze-momentum-hybrid-trading-system-15a9</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frxtzubow4ay8aum2es2z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frxtzubow4ay8aum2es2z.png" alt=" " width="800" height="389"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzbfc2c7570p3y7ywq1ba.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzbfc2c7570p3y7ywq1ba.png" alt=" " width="800" height="407"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br&gt;
The RSI-Adaptive T3 and Squeeze Momentum Hybrid Trading System is a dynamic trend-following strategy that combines an RSI-responsive T3 moving average with Squeeze Momentum detection. This strategy adapts in real-time to market volatility to enhance entry precision and optimize risk management. The core of the system lies in the T3 moving average length that dynamically adjusts according to RSI values, while also integrating Bollinger Bands and Keltner Channels to identify trend buildup phases. This design enables the strategy to capture the early phase of a trend and generate consistent entry signals, making it suitable for traders from beginner to advanced levels.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Principles&lt;/strong&gt;&lt;br&gt;
The core principles of this strategy are based on two main components: the RSI-responsive T3 moving average and the Squeeze Momentum indicator.&lt;/p&gt;

&lt;p&gt;First, the RSI-responsive T3 is an adaptive moving average whose length parameter dynamically adjusts according to RSI values. When RSI values are low, indicating potential oversold conditions, the T3 length increases to provide a smoother trend line; when RSI values are high, indicating potential overbought conditions, the T3 length decreases to provide a more sensitive trend line. The T3 moving average itself is an advanced smoothing technique that applies EMA multiple times with specific coefficients to reduce lag while maintaining smoothness.&lt;/p&gt;

&lt;p&gt;Second, the Squeeze Momentum indicator combines Bollinger Bands and Keltner Channels to identify market compression and release phases. When Bollinger Bands are inside Keltner Channels, it's considered a "squeeze" state, indicating reduced market volatility with potential for a breakout; when Bollinger Bands break outside Keltner Channels, it's considered a "squeeze release" state, indicating increased market volatility with potential for a new trend. The momentum value is calculated using linear regression, reflecting the direction and strength of price changes relative to a midpoint.&lt;/p&gt;

&lt;p&gt;The trading logic is as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Long Entry: When T3 crosses upward above its previous value, momentum is positive, and the squeeze has just been released&lt;/li&gt;
&lt;li&gt;Short Entry: When T3 crosses downward below its previous value, momentum is negative, and the squeeze has just been released&lt;/li&gt;
&lt;li&gt;Exit (Reversal): When the opposite condition to the entry is triggered, the position is reversed&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Strategy Advantages&lt;/strong&gt;&lt;br&gt;
In-depth analysis of the strategy code reveals the following significant advantages:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Strong Adaptability: The T3 length adjusts dynamically based on RSI values, allowing the strategy to adapt to different market conditions. It becomes more sensitive in highly volatile markets and more stable in steady markets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;High Signal Quality: By combining T3 crossovers, momentum direction, and squeeze release as triple confirmation, the strategy significantly improves the quality of trading signals and reduces false signals.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Early Trend Capture: The strategy is specifically designed to capture the early phases of trends, offering greater sensitivity compared to traditional trend-following methods.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Visual Support: The strategy provides visual representation of T3 slope direction, squeeze status, and momentum bars, enabling traders to quickly analyze trends and execute trades.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Excellent Performance: According to backtest data, the strategy demonstrated a profit factor of 2.01 and a win rate of 47.8% on the BTC/USD 30-minute chart, with a net profit of 173.16 units and a maximum drawdown of only 5.77%.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Hybrid System Benefits: The strategy fuses the characteristics of trend-reversal and momentum breakout detection systems, enabling it to identify both trend direction and confirm momentum strength.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Risks&lt;/strong&gt;&lt;br&gt;
Despite its many advantages, the strategy also presents some potential risks:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Parameter Sensitivity: The strategy uses multiple parameters (RSI length, T3 minimum and maximum lengths, Bollinger Bands and Keltner Channel parameters, etc.), and improper parameter selection could lead to significant performance degradation. The solution is to conduct comprehensive parameter optimization and robustness testing.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Market Condition Limitations: In ranging markets or markets without clear trends, the strategy may generate frequent false signals. The solution is to add market environment filters or adjust strategy parameters for specific market conditions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Lag Risk: Although the T3 moving average reduces lag, any system based on moving averages has some degree of lag. The solution is to incorporate leading indicators or optimize T3 parameters.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Overtrading Risk: Under certain market conditions, the strategy may generate too many trading signals, increasing trading costs. The solution is to implement trade frequency limitations or add signal confirmation mechanisms.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Backtest Overfitting Risk: The strategy may perform well on specific historical data but underperform in future market conditions. The solution is to conduct cross-market, cross-timeframe backtesting validation and forward testing.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Optimization Directions&lt;/strong&gt;&lt;br&gt;
Based on code analysis, the strategy can be optimized in the following directions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Adaptive Parameter Optimization: Not only can the T3 length be adaptively adjusted, but the multipliers for Bollinger Bands and Keltner Channels can also be dynamically adjusted based on market volatility to adapt to different market environments.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Market State Filtering: Add market state recognition mechanisms to employ different trading strategies or parameters in different market states (trending, ranging, consolidating).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Stop-Loss and Profit-Taking Mechanisms: The current strategy primarily relies on reverse signals for exits. Adding dynamic stop-loss and profit targets based on ATR or volatility can better control risk and lock in profits.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Volume Analysis Integration: Incorporating volume indicators to confirm trend strength can improve signal quality. Especially during squeeze release phases, increased volume can confirm the validity of breakouts.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Multi-Timeframe Analysis: Integrating signal confirmation mechanisms across multiple timeframes can enhance the strategy's robustness. For example, executing trades only when the higher timeframe trend direction is consistent.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Machine Learning Optimization: Using machine learning algorithms to optimize parameter selection and signal generation logic can help the strategy better adapt to different market environments.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These optimization directions are important because they can significantly improve the strategy's robustness and adaptability, reduce false signals, enhance profitability, and better control risk.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The RSI-Adaptive T3 and Squeeze Momentum Hybrid Trading System is an innovative quantitative trading strategy that achieves high-precision early trend capture and momentum confirmation by combining adaptive T3 moving averages with squeeze momentum indicators. The strategy not only has a solid theoretical foundation and clear logic but also demonstrates good performance in actual backtesting.&lt;/p&gt;

&lt;p&gt;The main advantages of the strategy lie in its adaptability and signal quality, as it can dynamically adjust parameters based on market conditions while reducing false signals through multiple confirmation mechanisms. However, users should also be aware of potential risks such as parameter sensitivity and market condition limitations.&lt;/p&gt;

&lt;p&gt;By optimizing market state filtering, stop-loss mechanisms, volume analysis, and multi-timeframe confirmation, the strategy has the potential to further improve its robustness and profitability. For traders seeking highly repeatable and adaptive trading tools, this is a worthy option to consider.&lt;/p&gt;

&lt;p&gt;It's important to emphasize that although the strategy has performed well on historical data, past performance does not guarantee future results. Traders applying this strategy should always use appropriate money management and risk control measures.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy source code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*backtest
start: 2024-07-04 00:00:00
end: 2025-07-02 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PakunFX

//@version=6
strategy("RSI-Adaptive T3 + Squeeze Momentum Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// ====== User Inputs ======
src = close
rsiLen = input.int(14, 'RSI Length', group="T3")
minLen = input.int(5, 'Min T3 Length', group="T3")
maxLen = input.int(50, 'Max T3 Length', group="T3")
v = input.float(0.7, 'T3 Volume Factor', step=0.01, maxval=2, minval=0.1, group="T3")

length = input(27, title="BB Length", group="Squeeze")
mult = input(2.0, title="BB MultFactor", group="Squeeze")
lengthKC = input(20, title="KC Length", group="Squeeze")
multKC = input(1.5, title="KC MultFactor", group="Squeeze")
useTrueRange = input(true, title="Use TrueRange (KC)", group="Squeeze")

// ====== T3 Calculation ======
rsi = ta.rsi(src, rsiLen)
rsi_scale = 1 - rsi / 100
len = math.round(minLen + (maxLen - minLen) * rsi_scale)

pine_ema(s, l) =&amp;gt;
    alpha = 2 / (l + 1)
    sum = 0.0
    sum := na(sum[1]) ? s : alpha * s + (1 - alpha) * nz(sum[1])
    sum

e1 = pine_ema(src, len)
e2 = pine_ema(e1, len)
e3 = pine_ema(e2, len)
e4 = pine_ema(e3, len)
e5 = pine_ema(e4, len)
e6 = pine_ema(e5, len)

c1 = -v * v * v
c2 = 3 * v * v + 3 * v * v * v
c3 = -6 * v * v - 3 * v - 3 * v * v * v
c4 = 1 + 3 * v + v * v * v + 3 * v * v
t3 = c1 * e6 + c2 * e5 + c3 * e4 + c4 * e3

// ====== Squeeze Momentum Calculation ======
basis = ta.sma(src, length)
dev = multKC * ta.stdev(src, length)
upperBB = basis + dev
lowerBB = basis - dev

ma = ta.sma(src, lengthKC)
kcrange = useTrueRange ? ta.tr : (high - low)
kcrangema = ta.sma(kcrange, lengthKC)
upperKC = ma + kcrangema * multKC
lowerKC = ma - kcrangema * multKC

sqzOn = (lowerBB &amp;gt; lowerKC) and (upperBB &amp;lt; upperKC)
sqzOff = (lowerBB &amp;lt; lowerKC) and (upperBB &amp;gt; upperKC)

midLine = (ta.highest(high, lengthKC) + ta.lowest(low, lengthKC)) / 2
val = ta.linreg(src - (midLine + ta.sma(close, lengthKC)) / 2, lengthKC, 0)

// ====== Strategy Logic ======
longCondition = ta.crossover(t3, t3[1]) and val &amp;gt; 0 and sqzOff
shortCondition = ta.crossunder(t3, t3[1]) and val &amp;lt; 0 and sqzOff

if (longCondition)
    strategy.entry("Long", strategy.long)
if (shortCondition)
    strategy.entry("Short", strategy.short)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Strategy parameters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhdq17ifxqezd5o1ofyq4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhdq17ifxqezd5o1ofyq4.png" alt=" " width="800" height="424"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The original address: &lt;a href="https://www.fmz.com/strategy/500483" rel="noopener noreferrer"&gt;RSI-Adaptive T3 and Squeeze Momentum Hybrid Trading System&lt;/a&gt;&lt;/p&gt;

</description>
      <category>momentum</category>
      <category>trading</category>
      <category>cryptocurrency</category>
      <category>rsi</category>
    </item>
    <item>
      <title>MACD and Moving Average Momentum Crossover Short-Term Trend Optimization Trading Strategy</title>
      <dc:creator>FMZQuant</dc:creator>
      <pubDate>Thu, 24 Jul 2025 01:03:10 +0000</pubDate>
      <link>https://dev.to/fmzquant/macd-and-moving-average-momentum-crossover-short-term-trend-optimization-trading-strategy-ij8</link>
      <guid>https://dev.to/fmzquant/macd-and-moving-average-momentum-crossover-short-term-trend-optimization-trading-strategy-ij8</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9c7ssrh4gkoe8ijl25ij.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9c7ssrh4gkoe8ijl25ij.png" alt=" " width="800" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fevjaafkorrn4meplf0bj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fevjaafkorrn4meplf0bj.png" alt=" " width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br&gt;
This strategy is a short-term trading system that combines MACD (Moving Average Convergence Divergence) with multiple moving averages, primarily applied to short-period charts and specifically designed to capture short-term momentum shifts in the market. The core logic involves identifying high-probability trend reversal points through multiple technical indicators working in tandem, including crossovers between fast and slow EMAs (Exponential Moving Averages), crossovers between MACD line and signal line, and the relationship between price and moving averages. The strategy also incorporates strict risk management mechanisms, including trade cooldown periods, consecutive loss limits, and daily maximum loss percentage controls to protect account capital.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Principles&lt;/strong&gt;&lt;br&gt;
The operation of this strategy is based on the principle of collaborative confirmation from multiple technical analysis indicators, with detailed logic as follows:&lt;/p&gt;

&lt;p&gt;Moving Average System: The strategy employs three EMA lines - a 5-period fast EMA, a 13-period slow EMA, and a 50-period trend EMA. These three lines represent short-term, medium-term, and long-term trends respectively.&lt;/p&gt;

&lt;p&gt;MACD Indicator Settings: Uses standard MACD parameters (12,26,9) to capture momentum changes and confirm trend direction.&lt;/p&gt;

&lt;p&gt;Multiple Confirmation Entry Conditions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bullish Signal: Fast EMA crosses above Slow EMA + MACD line crosses above Signal line + MACD histogram is positive and increasing + Price is above all EMAs&lt;/li&gt;
&lt;li&gt;Bearish Signal: Fast EMA crosses below Slow EMA + MACD line crosses below Signal line + MACD histogram is negative and decreasing + Price is below all EMAs&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Risk Management Mechanisms:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Trade Cooldown: A specific number of periods must elapse after each trade before initiating the next one&lt;/li&gt;
&lt;li&gt;Consecutive Loss Limit: Trading stops after reaching a set number of consecutive losses per day&lt;/li&gt;
&lt;li&gt;Daily Loss Limit: Trading stops when daily losses reach a specific percentage of the account&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Fixed Holding Period: The strategy employs a fixed holding time of 4 candles (approximately 2 minutes), a design particularly suited for capturing short-term price movements.&lt;/p&gt;

&lt;p&gt;At the code level, the strategy implements complete signal generation, risk control, and graphical visualization functions, enabling traders to intuitively monitor market conditions and strategy performance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy Advantages&lt;/strong&gt;&lt;br&gt;
Through in-depth analysis of the strategy's code implementation, the following significant advantages can be summarized:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Multiple Confirmation Mechanism: Combining EMA crossover, MACD crossover, and price position triple confirmation significantly improves signal reliability and reduces the risk of false breakouts.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Trend Direction Filtering: Confirms the larger timeframe trend direction through the 50-period EMA, only entering trades in alignment with the main trend, avoiding the high risk of counter-trend trading.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Dynamic Risk Management: The built-in trade cooldown mechanism prevents overtrading; consecutive loss limits and daily loss percentage controls effectively protect account capital.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Strong Adaptability: Strategy parameters can be adjusted according to different market conditions and personal risk preferences, demonstrating strong adaptability.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Visualization of Trading Signals: Clear graphical markers intuitively display trading signals, facilitating real-time monitoring and decision-making.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Precise Time Management: Built-in timer functionality helps traders accurately grasp entry timing and holding periods.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Complete Strategy Framework: The code implements a complete closed loop from signal generation to trade execution to risk management, serving as a foundational framework for building other short-term trading systems.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Strategy Risks&lt;/strong&gt;&lt;br&gt;
Despite the strategy's refined design, the following potential risks still exist:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Short-term Volatility Sensitivity: Since the strategy targets short-period charts, it is extremely sensitive to market noise and short-term fluctuations, potentially leading to frequent false signals. Solution: Additional filtering conditions can be added, such as volatility indicators or support/resistance confirmation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Rapid Market Reversal Risk: In highly volatile markets, prices may quickly reverse after position entry, and the 2-minute fixed holding period may be insufficient to respond. Solution: Dynamic stop-loss mechanisms can be added or holding times can be extended/shortened under specific market conditions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Transaction Cost Impact: Frequent trading will generate significant fee costs, potentially eroding strategy profits. Solution: Optimize entry conditions, reduce low-quality signals, and improve trade success rates.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Indicator Lag: Both EMA and MACD are lagging indicators and may miss optimal entry points in rapidly changing markets. Solution: Incorporate leading indicators such as Relative Strength Index (RSI) or stochastic indicators for confirmation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Parameter Sensitivity: Strategy performance is sensitive to EMA and MACD parameter settings, and parameter changes may lead to performance differences. Solution: Conduct comprehensive backtesting and parameter optimization to find the most stable parameter combination.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Optimization Directions&lt;/strong&gt;&lt;br&gt;
Based on in-depth analysis of the code, the strategy can be optimized in the following directions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Adaptive Parameter Adjustment: Dynamically adjust EMA and MACD parameters based on market volatility, enabling the strategy to better adapt to different market environments. This optimization can be implemented by calculating the recent Average True Range (ATR), using longer-period parameters in high-volatility markets and shorter-period parameters in low-volatility markets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Time Filter: Add trading time filters to avoid low-liquidity periods and major economic data release times, which will effectively reduce false signals and improve win rates.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Dynamic Stop-Loss/Take-Profit: Replace the fixed holding period with a dynamic stop-loss/take-profit mechanism based on market volatility, such as setting stop-loss positions using ATR multiples.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Volume Confirmation: Incorporate volume analysis into the signal confirmation system, only trading when supported by volume, improving signal quality.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Machine Learning Enhancement: Introduce simple machine learning algorithms to score and filter signals based on historical data, prioritizing high-probability successful trading patterns.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Multi-Timeframe Analysis: Extend the current strategy to include higher timeframe trend confirmation, ensuring trade direction aligns with larger cycle trends.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Capital Management Optimization: Implement more sophisticated money management algorithms, dynamically adjusting position sizes based on signal strength, recent strategy performance, and market volatility.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These optimization directions can effectively enhance the strategy's stability and profitability while reducing risk levels, making it more suitable for live trading environments.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The Multi-Momentum Confirmation MACD and Moving Average Crossover Short-Term Trend Optimization Trading Strategy is a well-designed short-term trading system that provides a complete trading solution for short-term markets through the synergy of multiple technical indicators and strict risk management. The core advantages of the strategy lie in its multiple confirmation mechanisms and comprehensive risk control system, which give it high reliability in capturing short-term trend reversal points.&lt;/p&gt;

&lt;p&gt;However, as a short-term trading strategy, it also faces challenges such as market noise, false signals, and transaction costs. By implementing the optimization directions proposed in this article, especially adaptive parameter adjustment, dynamic stop-loss/take-profit, and multi-timeframe analysis, the strategy's robustness and long-term performance can be significantly enhanced.&lt;/p&gt;

&lt;p&gt;It is worth noting that any trading strategy requires thorough backtesting and simulated trading verification, and appropriate adjustments based on individual risk tolerance and market understanding. This strategy provides a solid foundational framework that traders can customize according to their own needs to create a trading system that suits them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy source code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*backtest
start: 2024-07-03 00:00:00
end: 2025-07-02 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"BNB_USDT"}]
*/

//@version=5
strategy("MACD + MA 2-Min Binary Options Strategy (Strategy Mode)", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// === INPUTS ===
emaFastLen = input.int(5, "Fast EMA Length")
emaSlowLen = input.int(13, "Slow EMA Length")
emaTrendLen = input.int(50, "Trend EMA Length")
macdSrc = input.source(close, "MACD Source")
macdFastLen = input.int(12, "MACD Fast Length")
macdSlowLen = input.int(26, "MACD Slow Length")
macdSignalLen = input.int(9, "MACD Signal Smoothing")
tradeCooldown = input.int(10, "Cooldown Bars Between Trades")
maxLossStreak = input.int(3, "Max Consecutive Losses (Daily)")
dailyEquityLossLimit = input.float(5.0, "Max Daily Loss %", step=0.1)

// === MOVING AVERAGES ===
emaFast = ta.ema(close, emaFastLen)
emaSlow = ta.ema(close, emaSlowLen)
emaTrend = ta.ema(close, emaTrendLen)

// === MACD ===
[macdLine, signalLine, _] = ta.macd(macdSrc, macdFastLen, macdSlowLen, macdSignalLen)
macdHist = macdLine - signalLine

// === CONDITIONS ===
longCond = ta.crossover(emaFast, emaSlow) and ta.crossover(macdLine, signalLine) and macdHist &amp;gt; 0 and close &amp;gt; emaFast and close &amp;gt; emaSlow and close &amp;gt; emaTrend
shortCond = ta.crossunder(emaFast, emaSlow) and ta.crossunder(macdLine, signalLine) and macdHist &amp;lt; 0 and close &amp;lt; emaFast and close &amp;lt; emaSlow and close &amp;lt; emaTrend

// === TRADE FILTERING ===
var int lastTradeBar = na
canTrade = na(lastTradeBar) or (bar_index - lastTradeBar &amp;gt; tradeCooldown)

var int lossStreak = 0
var float dailyProfit = 0.0
var int prevDay = na
newDay = (dayofmonth != prevDay)
if newDay
    lossStreak := 0
    dailyProfit := 0.0
prevDay := dayofmonth

// === TRACK EQUITY ===
var float lastEquity = strategy.equity
profitToday = strategy.equity - lastEquity
lastEquity := strategy.equity

// Update daily PnL
if not newDay
    dailyProfit += profitToday

// Trade rules
allowLossLimit = (strategy.equity - lastEquity) / lastEquity * 100 &amp;gt; -dailyEquityLossLimit
allowTrade = canTrade and lossStreak &amp;lt; maxLossStreak and allowLossLimit

// === PLOT SIGNALS ===
plotshape(longCond and allowTrade, title="CALL Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="CALL")
plotshape(shortCond and allowTrade, title="PUT Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="PUT")

// === PLOT EMAs ===
plot(emaFast, title="EMA 5", color=color.orange)
plot(emaSlow, title="EMA 13", color=color.blue)
plot(emaTrend, title="EMA 50", color=color.purple)

// === ALERTS ===
alertcondition(longCond, title="CALL Alert", message="CALL Signal (Buy) detected!")
alertcondition(shortCond, title="PUT Alert", message="PUT Signal (Sell) detected!")

// === TIMER ===
timeSinceBar = (timenow - time) / 1000  // seconds since bar opened
secondsPerBar = (time - time[1]) / 1000
barCountdown = secondsPerBar - timeSinceBar
plot(barCountdown, title="Bar Countdown (sec)", color=color.gray, linewidth=1, style=plot.style_line)

// === STRATEGY EXECUTION ===
if (longCond and allowTrade)
    strategy.entry("CALL", strategy.long)
    lastTradeBar := bar_index

if (shortCond and allowTrade)
    strategy.entry("PUT", strategy.short)
    lastTradeBar := bar_index

// Exit after 4 bars (2 minutes on 30s timeframe)
if strategy.position_size != 0
    isCall = strategy.opentrades.entry_id(0) == "CALL"
    isPut = strategy.opentrades.entry_id(0) == "PUT"
    barsInTrade = bar_index - strategy.opentrades.entry_bar_index(0)
    if barsInTrade &amp;gt;= 4
        stratClose = false
        if isCall and close &amp;gt; strategy.opentrades.entry_price(0)
            lossStreak := 0
            stratClose := true
        else if isPut and close &amp;lt; strategy.opentrades.entry_price(0)
            lossStreak := 0
            stratClose := true
        else
            lossStreak += 1
            stratClose := true
        if stratClose
            strategy.close("CALL")
            strategy.close("PUT")

// === PLOT EQUITY ===
plot(strategy.equity, title="Equity Curve", color=color.green, linewidth=2, style=plot.style_line)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Strategy parameters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe3pm0z2zk1vmab5h0jis.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe3pm0z2zk1vmab5h0jis.png" alt=" " width="800" height="348"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The original address: &lt;a href="https://www.fmz.com/strategy/500484" rel="noopener noreferrer"&gt;MACD and Moving Average Momentum Crossover Short-Term Trend Optimization Trading Strategy&lt;/a&gt;&lt;/p&gt;

</description>
      <category>trading</category>
      <category>strategy</category>
      <category>crossover</category>
      <category>average</category>
    </item>
  </channel>
</rss>
