{"id":40940,"date":"2025-11-06T14:10:00","date_gmt":"2025-11-06T06:10:00","guid":{"rendered":"https:\/\/www.tejwin.com\/?post_type=insight&#038;p=40940"},"modified":"2025-11-14T10:14:05","modified_gmt":"2025-11-14T02:14:05","slug":"impulse-macd-futures-trading-strategy","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/","title":{"rendered":"Impulse MACD Futures Trading Strategy"},"content":{"rendered":"\n<figure class=\"wp-block-image aligncenter size-full is-resized is-style-default\"><img fetchpriority=\"high\" decoding=\"async\" width=\"2048\" height=\"1365\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u5f71\u50cf-1.jpeg\" alt=\"\" class=\"wp-image-40780\" style=\"width:800px;height:auto\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u5f71\u50cf-1.jpeg 2048w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u5f71\u50cf-1-300x200.jpeg 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u5f71\u50cf-1-1024x683.jpeg 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u5f71\u50cf-1-150x100.jpeg 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u5f71\u50cf-1-768x512.jpeg 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u5f71\u50cf-1-1536x1024.jpeg 1536w\" sizes=\"(max-width: 2048px) 100vw, 2048px\" \/><figcaption class=\"wp-element-caption\">Photo by <a href=\"https:\/\/unsplash.com\/@moneyphotos?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash\" target=\"_blank\" rel=\"noopener\">rc.xyz NFT gallery<\/a> on <a href=\"https:\/\/unsplash.com\/photos\/a-pile-of-money-sitting-on-top-of-a-wooden-floor-o-MyHqEEHoM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash\" target=\"_blank\" rel=\"noopener\">Unsplash<\/a><\/figcaption><\/figure>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_81 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-69d8f5da81c7e\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"ez-toc-cssicon\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-69d8f5da81c7e\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#Introduction\" >Introduction<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#Investment_Instrument_and_Backtesting_Period\" >Investment Instrument and Backtesting Period<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#Core_Logic\" >Core Logic<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#1_Indicator_System\" >1. Indicator System<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#2_Entry_Siganl\" >2. Entry Siganl<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#3Exit_Risk_Management\" >3.Exit &amp; Risk Management<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#4_Contract_Rolling\" >4. Contract Rolling<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#1%E3%80%81_Environment_Setup_and_Required_Packages\" >1\u3001 Environment Setup and Required Packages<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#11_Data_Import\" >1.1 Data Import<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#12_Import_Required_Packages\" >1.2 Import Required Packages<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#2%E3%80%81_Indicator_Calculation_Functions\" >2\u3001 Indicator Calculation Functions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#3%E3%80%81Building_the_Zipline_Trading_Strategy\" >3\u3001Building the Zipline Trading Strategy<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#31_initialize_Function_Strategy_Initialization\" >3.1&nbsp;initialize&nbsp;Function: Strategy Initialization<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#32_daily_trade_Function_Daily_Trading_and_Risk_Management\" >3.2&nbsp;daily_trade&nbsp;Function: Daily Trading and Risk Management<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#Data_Retrieval_and_Indicator_Calculation\" >Data Retrieval and Indicator Calculation<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#Signal_Generation\" >Signal Generation<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#Position_Management_and_the_Role_of_get_tx_chain_state\" >Position Management and the Role of&nbsp;_get_tx_chain_state<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#Trailing_Stop-Loss_Logic\" >Trailing Stop-Loss Logic<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#33_roll_futures_Function_Futures_Contract_Rollover\" >3.3&nbsp;roll_futures&nbsp;Function: Futures Contract Rollover<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#4_Running_the_Backtest\" >4. Running the Backtest<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-21\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#5%E3%80%81Strategy_Performance_Analysis\" >5\u3001Strategy Performance Analysis<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-22\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#51_Calculating_Key_Performance_Indicators_KPIs\" >5.1 Calculating Key Performance Indicators (KPIs)<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-23\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#GitHub_Source_Code\" >GitHub Source Code<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-24\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#Further_Reading\" >Further Reading<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-25\" href=\"https:\/\/www.tejwin.com\/en\/insight\/impulse-macd-futures-trading-strategy\/#Related_Links\" >Related Links<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Introduction\"><\/span>Introduction<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>LazyBear is a highly influential indicator developer on the internationally renowned trading platform, TradingView. He has created a large number of popular custom technical indicators, and his open-source code has inspired countless quantitative traders and technical analysis enthusiasts around the world. LazyBear&#8217;s indicators often focus on reducing the lag of traditional indicators and incorporate unique market observations to better capture trends and momentum.<\/p>\n\n\n\n<p>One of his representative works, the &#8220;Impulse MACD,&#8221; is adopted here. This indicator is not a traditional Moving Average Convergence Divergence (MACD), but rather a significantly improved version. It uses a zero-lag Double Exponential Moving Average (DEMA) to respond more quickly to price changes and combines a smoothed high-low price channel (SMMA) to determine market &#8220;impulse.&#8221;<\/p>\n\n\n\n<p>The core idea is that trading signals are more valuable only when price momentum aligns with the trend direction. This helps to filter out some of the noise typically found in ranging markets.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Investment_Instrument_and_Backtesting_Period\"><\/span>Investment Instrument and Backtesting Period<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>This study focuses exclusively on the Taiwan Stock Index Futures (TX) as the sole trading instrument. The analysis and backtesting are based on daily high, low, and closing price data. Since the indicators used in the strategy\u2014such as DEMA and SMMA\u2014require a historical &#8220;warm-up&#8221; period to initialize properly, with the longest calculation window set to 30 days, sufficient prior data is necessary before the actual backtest can begin.<\/p>\n\n\n\n<p>To ensure the stability and reliability of all generated trading signals, the backtesting period is set from&nbsp;<strong>January 1, 2019, to September 12, 2025<\/strong>. This timeframe provides ample historical context for accurate indicator initialization and ensures the rigor and validity of the testing results.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Core_Logic\"><\/span>Core Logic<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"1_Indicator_System\"><\/span><strong>1. Indicator System<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Calculate the average of High, Low, and Close prices (HLC\/3).<\/li>\n\n\n\n<li>Apply a&nbsp;<strong>zero-lag Double Exponential Moving Average (DEMA)<\/strong>&nbsp;to capture price movements more responsively.<\/li>\n\n\n\n<li>Use the relationship between price and a&nbsp;<strong>Smoothed Moving Average (SMMA) channel<\/strong>&nbsp;built from high and low prices to derive the main momentum indicator,&nbsp;<strong><code>md<\/code><\/strong>&nbsp;(fast line).<\/li>\n\n\n\n<li>Smooth the&nbsp;<code>md<\/code>&nbsp;using a Simple Moving Average to obtain the signal line,&nbsp;<strong><code>sb<\/code><\/strong>&nbsp;(slow line).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"2_Entry_Siganl\"><\/span>2. <strong>Entry Siganl<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A&nbsp;<strong>buy signal<\/strong>&nbsp;is generated when the fast line&nbsp;<code>md<\/code>&nbsp;crosses&nbsp;<strong>above<\/strong>&nbsp;the slow line&nbsp;<code>sb<\/code>.<\/li>\n\n\n\n<li>A&nbsp;<strong>sell signal<\/strong>&nbsp;is generated when the fast line&nbsp;<code>md<\/code>&nbsp;crosses&nbsp;<strong>below<\/strong>&nbsp;the slow line&nbsp;<code>sb<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"3Exit_Risk_Management\"><\/span>3.<strong>Exit &amp; Risk Management<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Implement a&nbsp;<strong>trailing stop-loss mechanism<\/strong>&nbsp;based on the&nbsp;<strong>Average True Range (ATR)<\/strong>.<\/li>\n\n\n\n<li>The stop-loss level adjusts dynamically as the price moves in favor of the open position, aiming to&nbsp;<strong>lock in profits<\/strong>&nbsp;while maintaining&nbsp;<strong>strict control over downside risk<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"4_Contract_Rolling\"><\/span>4. <strong>Contract Rolling<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Before the futures contract reaches expiration, the strategy&nbsp;<strong>automatically closes the expiring position<\/strong>&nbsp;and opens an identical position in the&nbsp;<strong>next front-month contract<\/strong>, ensuring continuity and accuracy throughout the backtest period.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"1%E3%80%81_Environment_Setup_and_Required_Packages\"><\/span>1\u3001 Environment Setup and Required Packages<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"11_Data_Import\"><\/span><strong>1.1 Data Import<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>First, we need to configure the&nbsp;<strong>TEJ API key<\/strong>&nbsp;to access the data source. Then, using environment variables, we specify the required instruments for backtesting\u2014<strong>Taiwan Stock Index Futures (TX)<\/strong>&nbsp;and the&nbsp;<strong>market index (IR0001)<\/strong>\u2014as well as the desired data period.<\/p>\n\n\n\n<p>Finally, we use the&nbsp;<code>zipline ingest<\/code>&nbsp;command to import this data into&nbsp;<strong>Zipline\u2019s local database<\/strong>, preparing it for use in the backtesting process.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"12_Import_Required_Packages\"><\/span><strong>1.2 Import Required Packages<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Import the necessary Python packages for this strategy, including&nbsp;<strong>pandas<\/strong>,&nbsp;<strong>numpy<\/strong>,&nbsp;<strong>talib<\/strong>, and core components from the&nbsp;<strong>Zipline<\/strong>&nbsp;framework.<br><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"2%E3%80%81_Indicator_Calculation_Functions\"><\/span>2\u3001 Indicator Calculation Functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>To implement the&nbsp;<strong>Impulse MACD<\/strong>&nbsp;strategy, we need to define two essential helper functions:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>_smma<\/strong>: Calculates the&nbsp;<strong>Smoothed Moving Average (SMMA)<\/strong>, which serves as the foundation for the subsequent indicator logic.<\/li>\n\n\n\n<li><strong>calculate_indicators<\/strong>: This function integrates all indicator calculations, including HLC\/3, ATR, SMMA of the high-low price channel, and finally the fast line&nbsp;<strong>md<\/strong>&nbsp;and the slow line&nbsp;<strong>sb<\/strong>. It forms the core of the strategy\u2019s signal generation.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"3%E3%80%81Building_the_Zipline_Trading_Strategy\"><\/span>3\u3001Building the Zipline Trading Strategy<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3.1-initialize-%E5%87%BD%E6%95%B8%EF%BC%9A%E7%AD%96%E7%95%A5%E5%88%9D%E5%A7%8B%E5%8C%96\"><span class=\"ez-toc-section\" id=\"31_initialize_Function_Strategy_Initialization\"><\/span><strong>3.1&nbsp;<code>initialize<\/code>&nbsp;Function: Strategy Initialization<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>In the&nbsp;<code>initialize<\/code>&nbsp;function, we define all the&nbsp;<strong>one-time settings<\/strong>&nbsp;required before the backtest begins. These include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Strategy Parameters<\/strong>: Set the time periods needed for indicator calculations (<code>ma_len<\/code>,&nbsp;<code>sig_len<\/code>) and the multiplier for ATR-based stop-loss (<code>atr_multiplier<\/code>).<\/li>\n\n\n\n<li><strong>Asset Definition<\/strong>: Define the&nbsp;<code>continuous_future<\/code>&nbsp;object representing the futures contract to be traded.<\/li>\n\n\n\n<li><strong>Transaction Costs<\/strong>: Configure commission and slippage models to make the backtest results more realistic and closer to live trading conditions.<\/li>\n\n\n\n<li><strong>Benchmark Setting<\/strong>: Set the&nbsp;<strong>Taiwan Weighted Index Total Return (IR001)<\/strong>&nbsp;as the benchmark for performance comparison.<\/li>\n\n\n\n<li><strong>Scheduling<\/strong>: Use&nbsp;<code>schedule_function<\/code>&nbsp;to arrange daily execution of the main trading logic (<code>daily_trade<\/code>) and post-market checks for futures contract rolling (<code>roll_futures<\/code>).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"32_daily_trade_Function_Daily_Trading_and_Risk_Management\"><\/span><strong>3.2&nbsp;<code>daily_trade<\/code>&nbsp;Function: Daily Trading and Risk Management<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>This function is called&nbsp;<strong>on each trading day<\/strong>&nbsp;and serves as the&nbsp;<strong>core logic of the strategy<\/strong>. The main steps are as follows:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Data_Retrieval_and_Indicator_Calculation\"><\/span><strong>Data Retrieval and Indicator Calculation<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Fetch the latest historical price data and call the&nbsp;<code>calculate_indicators<\/code>&nbsp;function to compute the&nbsp;<strong><code>md<\/code><\/strong>,&nbsp;<strong><code>sb<\/code><\/strong>, and&nbsp;<strong><code>atr<\/code><\/strong>&nbsp;values.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Signal_Generation\"><\/span><strong>Signal Generation<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Generate a&nbsp;<strong>buy signal<\/strong>&nbsp;or&nbsp;<strong>sell signal<\/strong>&nbsp;based on the&nbsp;<strong>golden cross<\/strong>&nbsp;or&nbsp;<strong>death cross<\/strong>&nbsp;between&nbsp;<code>md<\/code>&nbsp;(fast line) and&nbsp;<code>sb<\/code>&nbsp;(slow line).<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Position_Management_and_the_Role_of_get_tx_chain_state\"><\/span><strong>Position Management and the Role of&nbsp;<code>_get_tx_chain_state<\/code><\/strong><span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>When working with futures, it&#8217;s&nbsp;<strong>not sufficient<\/strong>&nbsp;to simply check whether the current continuous contract (<code>context.future<\/code>) exists in&nbsp;<code>context.portfolio.positions<\/code>.<\/p>\n\n\n\n<p>This is because during a&nbsp;<strong>contract rollover<\/strong>, the actual position may still be held in the&nbsp;<strong>expiring contract<\/strong>, while&nbsp;<code>context.future<\/code>&nbsp;already points to the&nbsp;<strong>new front-month contract<\/strong>.<\/p>\n\n\n\n<p>A simple position check might mistakenly assume there is&nbsp;<strong>no open position<\/strong>, resulting in a new order being placed. This can lead to&nbsp;<strong>multiple open positions across different contract months<\/strong>&nbsp;(i.e., unintended overexposure).<\/p>\n\n\n\n<p>To avoid this, the helper function&nbsp;<strong><code>_get_tx_chain_state<\/code><\/strong>&nbsp;iterates through all open positions and checks whether the asset\u2019s&nbsp;<code>root_symbol<\/code>&nbsp;is&nbsp;<code>'TX'<\/code>. This allows the strategy to&nbsp;<strong>accurately determine the total number of contracts held across the entire TX futures chain<\/strong>&nbsp;(<code>root_qty<\/code>), preventing duplicate entries during rollover periods.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Trailing_Stop-Loss_Logic\"><\/span><strong>Trailing Stop-Loss Logic<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>No Open Position<\/strong>:<br>If no position is currently held, enter a new&nbsp;<strong>long or short<\/strong>&nbsp;position based on the generated signal.<\/li>\n\n\n\n<li><strong>Open Position Exists<\/strong>:<br>If a position is currently open, activate the&nbsp;<strong>ATR-based trailing stop-loss mechanism<\/strong>.<br>The stop-loss level&nbsp;<strong>only moves in the direction favorable to the position<\/strong>&nbsp;(to protect profits) and is implemented using Zipline\u2019s&nbsp;<code>StopOrder<\/code>.<br>If the stop level needs adjustment, the existing stop order is&nbsp;<strong>canceled<\/strong>&nbsp;and replaced with an&nbsp;<strong>updated stop order<\/strong>&nbsp;at the new level.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"33_roll_futures_Function_Futures_Contract_Rollover\"><\/span><strong>3.3&nbsp;<code>roll_futures<\/code>&nbsp;Function: Futures Contract Rollover<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>This function is executed after the market closes each day to check whether the currently held futures contract is&nbsp;<strong>approaching expiration (within 5 days)<\/strong>. If so, it will automatically:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Close the position<\/strong>&nbsp;in the expiring contract<\/li>\n\n\n\n<li><strong>Open a new position<\/strong>&nbsp;with the same quantity in the&nbsp;<strong>next-month contract<\/strong><\/li>\n\n\n\n<li><strong>Place an initial trailing stop-loss order<\/strong>&nbsp;for the new position<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"4_Running_the_Backtest\"><\/span>4. Running the Backtest<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Set the parameters for the backtest, including the&nbsp;<strong>start and end dates<\/strong>,&nbsp;<strong>initial capital<\/strong>, and other relevant settings. Then, call the&nbsp;<code>run_algorithm<\/code>&nbsp;function to launch the entire backtesting process. The results will be stored in the&nbsp;<strong><code>results<\/code><\/strong>&nbsp;object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"5%E3%80%81Strategy_Performance_Analysis\"><\/span>5\u3001Strategy Performance Analysis<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"51_Calculating_Key_Performance_Indicators_KPIs\"><\/span><strong>5.1 Calculating Key Performance Indicators (KPIs)<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>After the backtest is completed, we extract data from the&nbsp;<code>results<\/code>&nbsp;object to calculate key performance metrics for both the strategy and the market benchmark. These include&nbsp;<strong>cumulative return<\/strong>,&nbsp;<strong>annualized return<\/strong>,&nbsp;<strong>Sharpe ratio<\/strong>,&nbsp;<strong>maximum drawdown<\/strong>, and more. The results are then printed for easy comparison.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" width=\"280\" height=\"521\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.00.28.png\" alt=\"\" class=\"wp-image-40794\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.00.28.png 280w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.00.28-161x300.png 161w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.00.28-81x150.png 81w\" sizes=\"(max-width: 280px) 100vw, 280px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" width=\"266\" height=\"515\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.01.38.png\" alt=\"\" class=\"wp-image-40796\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.01.38.png 266w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.01.38-155x300.png 155w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.01.38-77x150.png 77w\" sizes=\"(max-width: 266px) 100vw, 266px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"666\" height=\"173\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.01.27.png\" alt=\"\" class=\"wp-image-40798\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.01.27.png 666w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.01.27-300x78.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.01.27-150x39.png 150w\" sizes=\"(max-width: 666px) 100vw, 666px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"734\" height=\"442\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.48.09.png\" alt=\"\" class=\"wp-image-40805\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.48.09.png 734w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.48.09-300x181.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.48.09-150x90.png 150w\" sizes=\"(max-width: 734px) 100vw, 734px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"765\" height=\"688\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.48.26.png\" alt=\"\" class=\"wp-image-40807\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.48.26.png 765w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.48.26-300x270.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.48.26-150x135.png 150w\" sizes=\"(max-width: 765px) 100vw, 765px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"796\" height=\"461\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.47.54.png\" alt=\"\" class=\"wp-image-40809\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.47.54.png 796w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.47.54-300x174.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.47.54-150x87.png 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-11-06-\u4e0a\u534811.47.54-768x445.png 768w\" sizes=\"(max-width: 796px) 100vw, 796px\" \/><\/figure>\n\n\n\n<div style=\"border: 1px black; border-style: solid none; text-align: center; border-color: #296580; padding: 24px; margin-top: 24px; margin-bottom: 24px;\"><br \/>\n<p style=\"margin: 0px; font-size: 24px; font-weight: bold; line-height: 1.5;\">\u3010TQuant Lab Backtesting System\u3011Solving Your Quantitative Finance Pain Points<\/p>\n<br \/>\n<div style=\"margin-top: 32px;\"><a style=\"border: none; border-radius: 4px; background-color: #296580; color: white; font-size: 20px; width: fit-content; text-decoration: none; padding: 12px 30px 12px 30px;\" href=\"https:\/\/tquant.tejwin.com\/\" target=\"_blank\" rel=\"noopener\">Click here to register as a member and start your free trial<\/a><\/div>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"GitHub_Source_Code\"><\/span>GitHub Source Code<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong><a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/example\/TQ-Future_Impluse_MACD_\u671f\u8ca8\u4ea4\u6613\u7b56\u7565.ipynb\" target=\"_blank\" rel=\"noopener\">Click to View on GitHub<\/a><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Further_Reading\"><\/span>Further Reading<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/\"><strong>Golden Cross Futures Trading Strategy (MTX)<\/strong><\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.tejwin.com\/en\/insight\/lstm-stock-price-prediction-part-2\/\"><strong>Verifying LSTM Stock Price Prediction Effectiveness Using TQuant Lab<\/strong><\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Related_Links\"><\/span>Related Links<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>TQuant Lab Github<\/strong><\/a><\/li>\n\n\n\n<li><a class=\"ek-link\" href=\"https:\/\/tquant.tejwin.com\/\" target=\"_blank\" rel=\"noopener\"><strong>TQuant Lab \u9996\u9801<\/strong><\/a><\/li>\n<\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>LazyBear is a highly influential indicator developer on the internationally renowned trading platform, TradingView. He has created a large number of popular custom technical indicators, and his open-source code has inspired countless quantitative traders and technical analysis enthusiasts around the world. LazyBear&#8217;s indicators often focus on reducing the lag of traditional indicators and incorporate unique market observations to better capture trends and momentum.<\/p>\n<p>One of his representative works, the &#8220;Impulse MACD,&#8221; is adopted here. This indicator is not a traditional Moving Average Convergence Divergence (MACD), but rather a significantly improved version. It uses a zero-lag Double Exponential Moving Average (DEMA) to respond more quickly to price changes and combines a smoothed high-low price channel (SMMA) to determine market &#8220;impulse.&#8221;<\/p>\n<p>The core idea is that trading signals are more valuable only when price momentum aligns with the trend direction. This helps to filter out some of the noise typically found in ranging markets.<\/p>\n","protected":false},"featured_media":40781,"template":"","tags":[3063,2962,3176,2371,2988,3166],"insight-category":[3509,1356],"class_list":["post-40940","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-backtesting-2","tag-market-data","tag-python-2","tag-python","tag-quantitative-analysis","tag-tquant-lab-2","insight-category-fintech-en","insight-category-tquant-lab-en"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/40940","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight"}],"about":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/types\/insight"}],"version-history":[{"count":31,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/40940\/revisions"}],"predecessor-version":[{"id":42121,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/40940\/revisions\/42121"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media\/40781"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=40940"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=40940"},{"taxonomy":"insight-category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight-category?post=40940"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}