The resource loading... loading...

hans123 intraday breakthrough strategy

Author: Goodness, Created: 2020-08-12 11:38:39, Updated: 2023-10-10 21:15:02

img

Preface

The “HANS123” strategy was first mainly applied to the foreign exchange market. Its trading method is relatively simple and belongs to the trend breakthrough system. This trading method can enter the market as soon as the trend is formed, so it is favored by many traders. So far, HANS123 has expanded a lot of versions, let’s understand and deploy the HANS123 strategy together.

img

Principle of Strategy

Some people believe that the opening of the market in the morning is the time when the market has the greatest divergence. After about 30 minutes, the market has fully digested all kinds of overnight information, and the price trend will tend to be rational and return to normal. In other words: the market trend in the first 30 minutes or so basically constitutes the overall trading pattern today.

  • Upper rail: the highest price within 30 minutes of opening
  • Lower rail: the lowest price within 30 minutes of opening

The relative high and low points generated at this time form the effective high and low points in the “Dow Theory”, and the HANS123 strategy is the trading logic established by this. In the domestic futures market, the market opens at 09:00 in the morning, and at 09:30 you can judge whether it is long or short today. When the price breaks through the high point upward, the price will easily continue to rise; when the price breaks through the low point downward, the price will easily continue to fall.

  • Long position opening: There is currently no holding position, and the price breaks above the upper rail
  • Short position opening: There is currently no holding position, and the price breaks below the lower rail

Although the breakthrough strategy can enter the market as soon as the trend is formed. But this advantage is also a double-edged sword. As a result of the sensitive entry, the price breakthrough failed. So it is necessary to set a stop loss. At the same time, in order to achieve the strategy logic of winning and losing, take profit must be set.

  • Long position stop loss: the current long position has reached the loss amount
  • Short position stop loss: the current short position has reached the loss amount
  • Take profit for long positions, hold long positions and reach the profit amount
  • Take profit for short positions, hold short positions and reach the profit amount

Strategy writing

Open in turn: fmz.com website> Login > Dashboard > Strategy Library > New Strategy > Click the drop-down menu in the upper right corner to select the Python language and start writing the strategy. Pay attention to the comments in the code below.

Step 1: Write the strategy framework

# Strategy main function
def onTick():
    pass


# Program entry
def main():
    while True: # enter infinite loop mode
        onTick() # execute strategy main function
        Sleep(1000) # Sleep for 1 second

Writing a strategy framework, this has been learned in the previous chapter, one is the onTick function, and the other is the main function, in which the onTick function is executed in an endless loop in the main function.

Step 2: Define global variables

up_line = 0 # upper rail
down_line = 0 # lower rail
trade_count = 0 # Number of transactions on the day

Because the upper and lower rails are only counted at the time of 09:30, and no statistics are done in the rest of the time, we need to write these two variables outside the loop. In addition, in order to limit the number of transactions in a day trading, the trade_count variable is also written outside the loop. Before using these two global variables in the main function of the onTick strategy, you need to use the global keyword to reference.

Step 3: Get the data

exchange.SetContractType("rb888") # Subscribe to futures varieties
bar_arr = _C(exchange.GetRecords, PERIOD_M1) # Get 1-minute K line array
current_close = bar_arr[-1]['Close'] # Get the latest price
if len(bar_arr) <50: # If less than 50 k line bars
    return # Return to continue waiting for data

To obtain data, first use the SetContractType function in the FMZ platform API to subscribe to futures varieties, and then use the GetRecords function to obtain the K-line array. You can also pass in the K-line array specifying PERIOD_M11 minutes when using the GetRecords function.

The next step is to obtain the latest price, which is used to determine the position relationship between the current price and the upper and lower rails. At the same time, when placing an order using the Buy or Sell function, you need to pass in the specified price. In addition, don’t forget to filter the number of k line bars, because if the number of k line bars is too few, there will be an error that cannot be calculated.

Step 4: Processing time function

def current_time():
    current_time = bar_arr[-1]['Time'] # Get current K-line timestamp
    time_local = time.localtime(current_time / 1000) # Processing timestamp
    hour = time.strftime("%H", time_local) # Format the timestamp and get the hour
    minute = time.strftime("%M", time_local) # Format the timestamp and get the minute
    if len(minute) == 1:
        minute = "0" + minute
    return int(hour + minute)

When calculating the upper and lower rails and placing orders, it is necessary to judge whether the current time meets the trading time specified by us, so in order to facilitate the judgment, we need to deal with the specific hours and minutes of the current K-line.

Step 5: Calculate the upper and lower rails

global up_line, down_line, trade_count # Introduce global variables
current_time = current_time() # processing time
if current_time == 930: # If the latest K-line time is 09:30
    up_line = TA.Highest(bar_arr, 30,'High') + count # The highest price of the first 30 k line bars
    down_line = TA.Lowest(bar_arr, 30,'Low')-count # The lowest price of the first 30 ke line bars
    trade_count = 0 # Reset the number of transactions to 0

Step 6: Obtain positions

position_arr = _C(exchange.GetPosition) # Get position array
if len(position_arr) > 0: # If the position array length is greater than 0
    position_arr = position_arr[0] # Get position dictionary data
    if position_arr['ContractType'] =='rb888': # If the position symbol is equal to the subscription symbol
        if position_arr['Type']% 2 == 0: # If it is a long position
            position = position_arr['Amount'] # The number of assigned positions is a positive number
        else:
            position = -position_arr['Amount'] # Assign a negative number of positions
        profit = position_arr['Profit'] # Get position profit and loss
else:
    position = 0 # The number of assigned positions is 0
    profit = 0 # Assign position profit and loss to 0

Position status involves strategy logic. Our first ten lessons have always used virtual holding positions, but in a real trading environment, it is best to use the GetPosition function to obtain real position information, including: position direction, position profit and loss, number of positions, etc.

Step 7: Place an order

# If it is close to market closing or reach taking profit and stopping loss
if current_time > 1450 or profit > stop * 3 or profit < -stop:
    if position > 0: # If holding a long position
        exchange.SetDirection("closebuy") # Set transaction direction and type
        exchange.Sell(current_close-1, 1) # Close long order
    elif position <0: # If holding an empty order
        exchange.SetDirection("closesell") # Set transaction direction and type
        exchange.Buy(current_close + 1, 1) # Close short order
# If there is no current position, and it is less than the specified number of transactions, and within the specified trading time
if position == 0 and trade_count < 2 and 930 < current_time < 1450:
    if current_close > up_line: # If the price is greater than the upper line
        exchange.SetDirection("buy") # Set transaction direction and type
        exchange.Buy(current_close + 1, 1) # Open long order
        trade_count = trade_count + 1 # Increase the number of transactions
    elif current_close < down_line: # If the price is less than the lower line
        exchange.SetDirection("sell") # Set transaction direction and type
        exchange.Sell(current_close-1, 1) # Open a short order
        trade_count = trade_count + 1 # Increase the number of transactions

In order to avoid logic errors in the strategy, it is best to write the closing position logic before the opening position logic. In this strategy, when opening a position, first determine the current position status, whether it is within the specified trading time, and then determine the relationship between the current price and the upper and lower rails. To close a position is to first determine whether it is close to the closing of the market, or whether it has reached the taking profit and stopping loss conditions.

HANS123 is a very typical and very effective automated trading strategy. Its basic principle is to break through the highest or lowest price of the previous market within a certain period of time. The system can be applied to almost all foreign exchange products with stable profitability. This is also an early entry trading mode, with appropriate filtering technology, or can improve its odds of winning.

Complete strategy

Click to copy the complete strategy source code https://www.fmz.com/strategy/179805 backtest without configuration

End

The above is the principle and code analysis of the HANS123 strategy. In fact, the HANS123 strategy provides a better time to enter the market. You can also improve the time of exit according to your understanding of the market and understanding of the transaction, or according to the volatility of the variety To optimize parameters such as taking profit and stopping loss to achieve better results.


Related

More