Fundamentals 13 min read

Master Intraday High‑Low Breakout Strategy with Python – Full Code & Explanation

This article explains the concept of intraday trading, details a popular high‑low breakout strategy for commodity futures, and provides a complete Python implementation with time‑based entry and exit rules, virtual position handling, and full source code for immediate testing.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Intraday High‑Low Breakout Strategy with Python – Full Code & Explanation

What is Intraday Trading

Intraday trading aims to profit from small price movements within the same trading day by opening and closing positions before the market closes, thereby avoiding overnight risk while still capturing short‑term opportunities.

Strategy Logic

The basic idea is to use a price channel formed by the previous day’s high and low (upper and lower bands). When the price breaks above the upper band a long position is opened; when it breaks below the lower band a short position is opened. Positions are closed either when the price crosses the opposite band or when the trading session approaches its end (after 14:50). A wide stop‑loss is applied: positions are only closed after the price moves beyond the opposite band, not immediately on a small reversal.

Strategy Coding

Import the time library and define global variables for virtual position ( mp), upper band ( on_line) and lower band ( under_line). import time Utility function to convert hour and minute into an integer for easy comparison.

def can_time(hour, minute):
    hour = str(hour)
    minute = str(minute)
    if len(minute) == 1:
        minute = "0" + minute
    return int(hour + minute)

Main tick handler retrieves the latest K‑line data, extracts timestamps, calculates the current hour and minute, and determines whether the current bar belongs to a new trading day. If it is a new day, the upper and lower bands are reset using the previous bar’s high and low multiplied by configurable factors ( up and down).

def onTick():
    _C(exchange.SetContractType, "MA888")
    bar_arr = _C(exchange.GetRecords)
    if len(bar_arr) < 10:
        return
    time_new = bar_arr[-1]['Time']
    time_local_new = time.localtime(time_new / 1000)
    hour_new = int(time.strftime("%H", time_local_new))
    minute_new = int(time.strftime("%M", time_local_new))
    day_new = int(time.strftime("%d", time_local_new))
    time_previous = bar_arr[-2]['Time']
    previous = time.localtime(time_previous / 1000)
    day_previous = int(time.strftime("%d", previous))
    global mp, on_line, under_line
    high = bar_arr[-2]['High']
    low = bar_arr[-2]['Low']
    if day_new != day_previous:
        on_line = high * up
        under_line = low * down
    can_trade = can_time(hour_new, minute_new)
    if can_trade < 930:
        if high > on_line:
            on_line = high * up
        if low < under_line:
            under_line = low * down
    if on_line - under_line < 10:
        return
    close_new = bar_arr[-1]['Close']
    # Close existing long position
    if mp > 0 and (close_new < under_line or can_trade > 1450):
        exchange.SetDirection("closebuy")
        exchange.Sell(close_new - 1, 1)
        mp = 0
    # Close existing short position
    if mp < 0 and (close_new > on_line or can_trade > 1450):
        exchange.SetDirection("closesell")
        exchange.Buy(close_new, 1)
        mp = 0
    # Open new positions during allowed trading window
    if mp == 0 and 930 < can_trade < 1450:
        if close_new > on_line:
            exchange.SetDirection("buy")
            exchange.Buy(close_new, 1)
            mp = 1
        elif close_new < under_line:
            exchange.SetDirection("sell")
            exchange.Sell(close_new - 1, 1)
            mp = -1

The program entry point runs an infinite loop, calling onTick() every second.

def main():
    while True:
        onTick()
        Sleep(1000)

This complete script can be copied, adjusted with appropriate parameters ( up, down), and back‑tested on the FMZ platform.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

algorithmic strategyQuantitative Financehigh‑low breakoutintraday tradingtrading code
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.