Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize dynamic ladder Breakthrough Strategy in python

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article is to share with you about how python implements the dynamic ladder breakthrough strategy. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

What is a breakthrough strategy?

We know that the price of the futures market evolves alternately with trends and shocks, and if we use only one way to grasp the trend, we can make money on the trend market. So what is the way to catch the trend? A relatively simple way is to use a breakthrough strategy. By setting the price up and down, or support level, pressure level, when the price exceeds the track, we think that the market is about to start, open positions to do long, and vice versa.

There are many different kinds of breakthrough strategies in the market, which can be roughly divided into: morphological breakthrough (including: double-shoulder type, head-shoulder type, neckline, trend line, etc.), index breakthrough (moving average, KDJ, ATR, etc.), channel breakthrough (new high and new low, support line and resistance line), volume breakthrough (trading volume, energy tide). Among them, in quantitative trading, the most commonly used are: index breakthrough and channel breakthrough.

Breakthrough strategy theory

In logic, there is a concept of "sufficient and unnecessary", that is to say, if there is A, there is not necessarily B, but if there is B, there must be A. Then B is the sufficient and unnecessary condition of A, that is, the sufficient and unnecessary condition, and An is the necessary and insufficient condition of B. Therefore, from the point of view of the results, the price may not form a trend after breaking through the key point, but the trend rising or falling is bound to break through the key price position.

In addition, in terms of the reasons for the breakthrough, the rise and fall of the market depends on the comparison of strength between buyers and sellers. When the price broke through the peak of the previous period, anyone who was short at any price in the previous period was tied up without exception, and some of them must have to accept losses and close out, which in turn contributed to the rally. On the contrary, when the market falls below the lowest price of the previous period, all those who are long at any point in the previous period will suffer floating losses, and some of them must stop their losses and close their positions, which is just right for the downtrend.

Policy logic

Ladder strategy, which is a more corny name, gets its name because it looks like steps on the chart, and was originally inspired by ladder stops. It is believed that people with solid trading experience should have a deep understanding: when the market is horizontal or wavering, it will deal a great blow to the cross-class system, often buying at the high point and selling at the low point. If the market continues, there will be continuous losses, and continuous loss signals will cause serious psychological burden and capital withdrawal pressure on traders. As shown below:

Through the use of channel technology, we can filter or reduce the price repeated winding, reduce some false signals, which is of great help to reduce invalid transactions. This strategy is not a traditional channel strategy. Instead, the adaptive channel is established in reverse according to the highest and lowest prices in the previous period. The adaptation mentioned here means that the retrospective date will be adjusted according to our logic. specifically, this strategy is changed by the rate of change of market volatility.

The composition of most channel strategies is determined by two factors, the first is the middle rail, and then calculate the channel width according to the middle rail, that is, up and down the rail. For example, the common Bollinger Belt Channel (BollingerBand) is first determined by an average line as the center line, and the width of the channel is determined by the standard deviation. The channel of the ladder strategy is not derived from the middle track, on the contrary: first calculate the upper and lower tracks of the channel according to the market volatility, and then calculate the middle track according to the width of the channel.

In addition, in determining the number of K lines at the highest and lowest points depends on how much room we are willing to give to the trade, the more K lines we use to determine the upper and lower tracks, the greater the room for change we give to programmed trading, accordingly, the greater the extent of profit pullback before the stop loss is triggered. The nearer the high or low point is, the faster the stop loss will be triggered. If you want the channel to be narrower, set it smaller, and if you want to make the channel wider, set it larger.

Set channel

On the track: if the lowest price of the K line is less than that of the previous K line, the upper track is equal to the highest price of the first N K lines.

Lower track: if the highest price of the K line is greater than that of the upper K line, the lower rail is equal to the lowest price of the first N K lines.

Middle rail: average of upper and lower rails

Admission conditions

Long entry: if there is no current position, and the price is higher than the track, buy and open the position.

Short entry: if there is no current position, and the price is less than the lower track, sell and open the position.

Appearance condition

Bullish exit: if you currently hold a long order and the price is less than the middle track, sell and close the position.

Short exit: if you currently hold a short order and the price of the weapon is higher than the middle track, buy and close the position.

In order to avoid overfitting, only one parameter is given when designing the strategy. Although there is only one parameter, it does not lose the flexibility of the strategy in the market. Moreover, the ladder strategy can not only adapt to domestic and foreign commodity futures, but also can be applied to A-share ETF, including outer disk ETF and reverse leverage ETF, as well as foreign exchange market. Of course, only adapt to some varieties, from the full variety statistics, this is a relatively universal strategy.

Strategy writing

According to the above strategy logic, we can implement the trading strategy on the inventor quantitative trading platform. Open: fmz.com > Log in > Control Center > Policy Library > New Policy > Click the drop-down menu in the upper right corner to select the Python language and start writing the policy. Pay attention to the comments in the code below.

Step 1: write a strategy framework

This has been learned in the previous chapter, one is the onTick function, and the other is the main function, where the onTick function is executed in an infinite loop in the main function, as follows:

Def onTick (): passdef main (): while True: onTick () Sleep (1000)

Step 2: define global variables

First of all, the upper and lower tracks in the strategy are defined, because the upper and lower tracks in our strategy are calculated according to certain conditions, that is to say, the lower track is recalculated only when the current highest price is greater than the highest price of the previous K line; only when the current lowest price is less than the lowest price of the previous K line, the upper track is recalculated. So we have to define the upper and lower orbit variables outside the onTick main function.

Up_line = 0 # upper rail under_line = 0 # lower rail mp = 0 # used to control virtual positions

In addition, we need to define the global variable virtual position mp. At the beginning of the policy, the default is short position mp=0. When multiple orders are opened, virtual positions are reset to mp=1, when short orders are opened, virtual positions are reset to mp=-1, and when multiple orders or short orders are leveled, virtual positions are reset to mp=0. In this way, we only need to judge the value of mp when judging the construction logic to get the position.

Step 3: calculate the upper rail, lower rail and middle rail

Because before calculating these data, we must first obtain the historical K-line basic data, and the way to obtain these basic data is also very simple, first subscribe to futures varieties, and then call the GetRecords method in the inventor quantitative API. Then, because the Highest and Lowest methods in the talib library are used to calculate the upper and lower tracks, these two methods need to input periodic parameters, but if there is not enough K-line data, its value cannot be calculated normally, so it is necessary to judge the length of K-line data here. If the length of K-line is not long enough to calculate its value, skip it directly.

Then, we obtain the highest and lowest prices of the current K line and the upper K line respectively, and define the value of the lower track by comparing the highest price of the current K line with that of the previous K line. If the current highest price is greater than the highest price of the previous K line, recalculate the lower track; similarly, if the current lowest price is less than the previous K line, recalculate the upper track. Finally, the average of the upper rail and the lower rail is the middle rail.

Exchange.SetContractType ("rb000") # subscription futures variety bars = exchange.GetRecords () # get K-line array if len (bars)

< cycle_length + 1: # 如果K线数组的长度太小,所以直接返回 returnclose0 = bars[len(bars) - 1].Close; # 获取当根K线收盘价high0 = bars[len(bars) - 1].High; # 获取当根K线最高价high2 = bars[len(bars) - 2].High; # 获取上根K线最高价low0 = bars[len(bars) - 1].Low; # 获取当根K线最低价low1 = bars[len(bars) - 2].Low; # 获取上根K线最低价highs = TA.Highest(bars, cycle_length, 'High'); # 获取前cycle_length根K线最高价的最高价lows = TA.Lowest(bars, cycle_length, 'Low'); # 获取前cycle_length根K线最低价的最低价global up_line, under_line, mp # 使用全局变量if high0 >

High2: # if the highest price of the root K line is greater than the highest price of the upper K line under_line = lows # re-assign the lower track to: the lowest price of the former cycle_length root K line if low0

< low1: # 如果当根K线最低价小于上根K线最低价 up_line = highs # 把上轨重新赋值为:前cycle_length根K线最高价的最高价middle_line = (lows + highs) / 2; # 计算中轨的值 这里有一个地方需要注意,可能细心的朋友已经发现了,我们在计算上轨和下轨的时候,用到了talib库中的Highest和Lowest函数,因为在发明者量化软件中已经内置了这两个常用的函数,所以我们不需要像前几节那样在策略开头导入talib库,并且在使用内置函数的时候,其写法也略有不同,具体可以查看下方的代码。 第4步:下单交易 有了上轨、下轨、中轨的值,就可以配合当前的最新价格开平仓交易了,我们可以回过头再看下之前设计的交易逻辑:如果当前没有持仓,并且价格大于上轨 * 1.05,买入开仓。如果当前没有持仓,并且价格小于下轨 * 0.95,卖出开仓。如果当前持有多单,并且价格小于中轨,卖出平仓。如果当前持有空单,兵器价格大于中轨,买入平仓。 if mp == 0 and close0 >

Up_line: # if the current short position and the latest price is greater than the above track exchange.SetDirection ("buy") # set the trading direction and type exchange.Buy (close0, 1) # open multiple orders mp = 1 # set the value of virtual positions, that is, there are multiple orders if mp = = 0 and close0

< under_line: # 如果当前空仓,并且最新价小于下轨 exchange.SetDirection("sell") # 设置交易方向和类型 exchange.Sell(close0 - 1, 1) # 开空单 mp = -1 # 设置虚拟持仓的值,即有空单 if mp >

0 and close0

< middle_line: # 如果当前持有多单,并且最新价小于中轨 exchange.SetDirection("closebuy") # 设置交易方向和类型 exchange.Sell(close0 - 1, 1) # 平多单 mp = 0 # 设置虚拟持仓的值,即空仓 if mp < 0 and close0 >

Middle_line: # if you currently hold a short order and the latest price is greater than medium Rail exchange.SetDirection ("closesell") # set the trading direction and type exchange.Buy (close0, 1) # flat order mp = 0 # set the value of virtual position, that is, short position

If statement is used to issue an order transaction. If the condition is true, set the transaction direction and type first, that is, open much, open empty, flat much, flat empty. Then call the Buy or Sell in the inventor's quantification software to place the order function, and finally reset the virtual position after placing the order.

Complete policy code

Backteststart: 2015-02-22 00:00:00end: 2019-10-29 00:00:00period: 1hexchanges: [{"eid": "Futures_CTP" "currency": "FUTURES"}]'# external parameter cycle_length = 10 defines the global variable up_line = upper rail under_line = lower rail mp = "used to control virtual positions def onTick (): exchange.SetContractType (" rb000 ") # subscription futures variety bars = exchange.GetRecords () # get K-line array if len (bars)

< cycle_length + 1: # 如果K线数组的长度太小,所以直接返回 return close0 = bars[len(bars) - 1].Close; # 获取当根K线收盘价 high0 = bars[len(bars) - 1].High; # 获取当根K线最高价 high2 = bars[len(bars) - 2].High; # 获取上根K线最高价 low0 = bars[len(bars) - 1].Low; # 获取当根K线最低价 low1 = bars[len(bars) - 2].Low; # 获取上根K线最低价 highs = TA.Highest(bars, cycle_length, 'High'); # 获取前cycle_length根K线最高价的最高价 lows = TA.Lowest(bars, cycle_length, 'Low'); # 获取前cycle_length根K线最低价的最低价 global up_line, under_line, mp # 使用全局变量 if high0 >

High2: # if the highest price of the root K line is greater than the highest price of the upper K line under_line = lows # re-assign the lower track to: the lowest price of the former cycle_length root K line if low0

< low1: # 如果当根K线最低价小于上根K线最低价 up_line = highs # 把上轨重新赋值为:前cycle_length根K线最高价的最高价 middle_line = (lows + highs) / 2; # 计算中轨的值 if mp == 0 and close0 >

Up_line: # if the current short position and the latest price is greater than the above track exchange.SetDirection ("buy") # set the trading direction and type exchange.Buy (close0, 1) # open multiple orders mp = 1 # set the value of virtual positions, that is, there are multiple orders if mp = = 0 and close0

< under_line: # 如果当前空仓,并且最新价小于下轨 exchange.SetDirection("sell") # 设置交易方向和类型 exchange.Sell(close0 - 1, 1) # 开空单 mp = -1 # 设置虚拟持仓的值,即有空单 if mp >

0 and close0

< middle_line: # 如果当前持有多单,并且最新价小于中轨 exchange.SetDirection("closebuy") # 设置交易方向和类型 exchange.Sell(close0 - 1, 1) # 平多单 mp = 0 # 设置虚拟持仓的值,即空仓 if mp < 0 and close0 >

Middle_line: # if you currently hold a short order and the latest price is greater than medium Rail exchange.SetDirection ("closesell") # set the trading direction and type exchange.Buy (close0, 1) # flat single mp = 0 # set the value of virtual position, that is, short position def main (): while True: onTick () Sleep (1000) Thank you for your reading! This is the end of this article on "how to achieve dynamic ladder Breakthrough Strategy in python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report