US 30 year hourly bond model

Studies that have been contributed to the community by other users. If you’ve got something useful to share, that’s great!
User avatar
Mark Brown
Posts: 182
Joined: 29 Nov 2016
Has thanked: 114 times
Been thanked: 18 times

US 30 year hourly bond model

Postby Mark Brown » 30 Dec 2022

Old one but a good one... maybe someone can gleam something from this MB

Shortcut to Discovery

Computerized Trading System

Development and Modeling

Presented by:

Mark Brown

The Year 2001

Dallas, Texas

Copyright © 2001 by Mark Brown, All rights reserved. No portion or part of this publication may be reproduced or distributed in any form or by any means, or stored in an electronic data base or electronic retrieval system, without the prior written consent and permission of the author.

Disclaimer

Hypothetical performance results may have inherent limitations, some which are described below. No representation is being made that any account will or is likely to achieve profits or losses similar to those shown. In fact, there are frequently sharp differences between hypothetical performance results and the actual results achieved by any particular trade platform. One of the limitations hypothetical performance results is the boy or generally prepared with the benefit of hindsight. In addition, hypothetical trading does not involve financial risk,and no hypothetical trading record can completely account for the impact of financial risk in actual trading. For example, the ability to withstand losses or to adhere to a particular trading program in spite of trading losses are material points which can also adversely affect actual trading results. There are numerous other factors related to the markets in general or to the implementation of any specific trading program which cannot be fully accounted for in the preparation of hypothetical performance results and all of which can adversely affect the actual trading results. All trading systems and strategies in this book are intended for educational purposes only, to provide a perspective of different market concepts. They're not meant to recommend or promote any trading system or approach. Your advised to do your own research and testing to determine the validity of a trading idea.


Introduction

Within this document the full disclosure of building a two switch trading model will be detailed.

Creating a Mechanical Trading Model

Detailed and outlined below are the primary building blocks one can use to construct a successful, fully mechanical trading model. Establishing and utilizing core techniques, ideas and strategies that have been rigorously tested, a firm foundation is established on which many mechanical trading systems can be created and built upon for trading a broad range of markets.

Foundational Components for the System Trader

Modeling Mechanics

Understated, would be the use of the word "complex," to describe the process required to develop a robust and fully mechanical trading model or system. Only with the advent of the computer have we been able to analyze and test theories and ideas which would have been previously impossible to calculate in a practical, thorough and timely manner.

Mental Conditioning

Psychological attitude is a key element to any endeavor and trading is not an exception. The researcher’s mind must be open and free from misconceptions. Throughout the development process, an open mind and the attitude that anything is possible must be preserved as well as actively pursued. A tenacious commitment and a passion for the process of discovery are also good traits to acquire and cultivate.

Strategy Process

If we are to have any success trading the markets, we must rely upon a well-planned mechanical strategy. A mechanical system is nothing more than an idea, which has been tested and then, automated. Mechanical research allows a trader to discern a good idea from a bad idea. Being able to examine facts and not rely upon human emotions will provide the trader a much more solid foundation for a successful trading system. Modeling a system produces a significant benefit in that capital is preserved through the process of being able to reject many ideas when subjected to computerized back testing. Mechanical trading will not, by itself, overcome the emotional side and aspects of trading. However, after a period of testing, time and real-time trading experience, you will be able to gain confidence if you have a sound method and system.

Capital Commitment

Long-term commitment to mechanically trading the markets requires proper capitalization coupled with a total commitment to following the system. The capitalization and investment that is required to endure the inevitable system draw-downs is not to be taken lightly. It is highly recommended that capital allocated to trading the markets or a respective system be only the "risk capital" portion of a person's total available investment portfolio. Typically, it would not be unreasonable to expect a perfectly sound/robust trading methodology to exceed its tested maximum historical draw-down percentage by a factor of two (2). This unforeseen and statistically more valid draw-down calculation will, more often than not, happen sometime in the future. A serious and also very common detriment to capitalization is the desire to over trade.

Money Management

Common types of money management would include the use of fixed stop loss amounts and trailing stops. Stop reversals and increasing/decreasing leverage via pyramiding of the underlining trading vehicle are also actively utilized for money management. Though not commonly thought of as a money management technique, diversification of assets can also be achieved by trading a broad range of markets. Other examples of money management may incorporate not only a portfolio of markets, but also a portfolio of trading models. The expected benefit of this type of diversification is primarily to limit market exposure to any one market or system.

Timing Implementation

Timing is probably one of the most important factors when it comes to mechanical system trading. It is critical that the performance of the tested model be executed in real-time as accurately portraying the historical testing as reasonably possible. It serves no purpose to historically test a mechanical model and then not execute the model according to the same rigid statistical standards in real-time trading. It is very difficult for the human eye concentrating on the hard right edge of a chart to visualize the same success that might be seen with the longer-term view that the historical testing has produced. For this reason, the models trade signals for buying, selling and money management must be executed with precision and timeliness. The primary goal of the mechanical trader should be, as practically possible, to replicate in real-time trading the same results as the model produced in historical testing.

Discipline and Execution of Trading Signals

Emotions are the primary villain in hindering the trader, as it pertains to successful mechanical trading. When real money is being traded and is at risk, the historical testing and logic, which was so well thought out and planned for the system, is often quickly abandoned. This is a very common occurrence and one, which is hard to overcome even for the seasoned veteran. Experience, perseverance and dedication are critical ongoing aspects of every successful trader's personality composite. Commitment and focus of the long-term goal to become successful at implementing mechanical trading strategies should not be discarded because of short-term price volatility.

Visual Cues vs. Actual Trade Statistics

Throughout my professional career as a mechanical model developer, there's one thing that I have observed which stands out beyond all other lessons. It can be stated as this - the human eye is often unable to extract a non-biased opinion of how well a system looks on a chart vs. the actual numbers and statistical representation of the same system.

Modern technical analysis programs have created this phenomenon. Many software packages are capable of producing automated buy and sell signals (arrows) when a system is applied to a chart. These charting programs typically offset the sell arrow a few ticks above the high of the entry bar, and offset the buy arrow a few ticks below the low of the entry bar. Admittedly, this practice seems to be an innocent act of improper programming or data management committed by the software vendor. Ultimately, this practice is misleading and caution is in order.

Furthermore, this method of arrow placement can be very deceiving to the casual observer who views a seemingly profitable system applied to a chart. These arrows, more than likely, do not accurately portray the actual entry of the system. For example, the arrows in fact are placed there as a marker to identify the bar of entry, while the actual entry is found somewhere within the confines of the high/low of the bar. This practice of offsetting the arrows can be very misleading without looking at the actual entries.

An example would be where you casually observe that the placement of the buy/sell arrows of the system seemingly look profitable. However, if you look closely within the actual high/low of the entry bar you'll see a small flag indicating the actual entry point of the system. Notice that the sale price flag is often lower than the following buy flag. Note however that the actual corresponding sell arrow itself is higher than the following buy arrow. This casual observance of our eyes to focus upon the seemingly obvious, is in fact a wrong assumption that the trade was profitable.

Components of Building a Position Model

Primary Components, Switches

Switches will be acquired by thoroughly testing specific market price action which will then be separated into non-trending and trending samples. Through the unique use of switches, combinations will then be implemented. Switches can be more easily explained as a method the trading model must use to gain permission to place a trade or to implement other strategies such as money management.

Non-Trending Switches

First, consider the market to be traded and its respective volatility. Tests should be conducted to understand what the underlying structure of each particular market is. Most markets will fall into some category of tradable ranges that reoccur over time. Non-trending ranges rather than trending price action will dominate most markets. Each market must be individually examined and it must be determined what is the predominate price action and volatility.

Once it is determined that non-trending price action is the predominant makeup of the targeted market, concentrated efforts of model building and testing can begin. The primary objective should be to encapsulate the non-trending price action with an algorithm that is as profitable as possible. It should be noted that when viewing the system statistics they might appear to be lackluster. This can be attributed to the losses, which will occur when the subject market trends.

The primary objective to building a non-trending model is to specifically isolate, with as much accuracy as possible, those particular price traits, which are most prevalent in the data series being tested.

Trending Switches

As previously stated, the particular markets primary price movement and volatility need to be considered when performing research to build a valid trending model. It is a valid statement that most all markets exhibit some trending tendencies given a long enough look back period. However, the algorithm that it would take to capture some of these extremely long-term trends would most likely simulate a buy/sell hold strategy.

The assumption that the trend is your friend is a mistake and should be avoided. If indeed a theory exists that a particular market has a higher tendency to trend - this may be valid - however, the data needs to validate this theory. One of the primary pitfalls of the human eye is the ability to focus in on that which it wishes to see, especially when a preconception exists, rather than the underlying statistical analysis.

The objective is to determine if there are, shorter term consistently repeatable price actions which can be utilized and capitalized upon. These short-term identifiable trends are most likely to have fewer occurrences than their counterpart non-trending price action. Through validated testing mentioned earlier, there are some markets which show trending characteristics as the primary market movement.

Combination Switches

As the name implies, this method of combining different strategies, attempts to capture the bulk of a market price movement. There are certainly other personality traits that markets can and to tend to exhibit. Through extensive testing, it has been determined that the majority of markets can be primarily broken down into two parts: trending and non-trending. This two-part method will be a solid foundation to build a system upon.

Create and design each model to specifically perform its role as accurately as possible. Then combine the resulting models using a switch algorithm. This results in the models being combined to reach the final objective of profitability on a single market.

It should be noted, that overall profitability of each system tested independently will more than likely be less than desirable. However, the objective is to create two components, which then perform their specific tasks independently. The desired effect of the outcome when combining these models is to have greater profitability than any one single model could have operating independently. This process is achieved through the utilization of switches, which are programmed in various combinations.

This is a very valuable concept and allows one to avoid many fallacies inherent in trading platform software programs. The whole concept of switches allows clearly conceptualized ideas to be isolated. A very simple example of the switch concept shown below:

• If such and such then switch 1 = 1

• If such and such then switch 2 = 1

• If switch 1 + switch 2 = 2 then do this

Secondary Components

Trade Profit Enhancements

Many items can be included to maximize performance of a constructed model. These items may be incorporated as switches and are more typically related to money management techniques. When used in the latter case, the code is simply appended to the end of the respective buying/selling conditions.

Other techniques may include algorithms which allow a position to be reversed as in the case of an always in the market position system (this can also be referred to a "stop and reverse" defined system.) These techniques may be stand-alone or incorporated alongside money management to form a composite system.

Summary

If the problem of seemingly random market data is to be conquered with a mechanical model, the modeling will need to separate the data into quantifiable sections. What these sections are and how they are defined is actually dictated by the market data itself. The primary focus should be upon price actions, which are most prevalent and validated within the data.

Specific models are developed independently to accurately encapsulate as much of the targeted price action as possible. These models are then combined through the use of switches to complete the base model. Other components, such as money management, can then be included to enhance overall performance.

Specialized Components of Model Building

Non-Trending

Components would include oscillators of various types and shorter term, price patterns. These price patterns are normally and specifically defined for a particular market because of the shorter term nature of trades typically taken in non-trending market conditions.

Caution needs to be exercised when establishing inputs of the non-trending components. Avoid long-term inputs and using short-term indicators. For the purpose of discussion, price patterns will also be included when the terminology associated with indicators is used.

Oscillators are often normalized between an upper and lower limit, then buy/sell zones are established for the oscillator. The oscillator can also be normalized over a zero line used as the reference point to enter long or short positions. There are a variety of short-term non-trending indicators covering a broad spectrum that can be used in model development and testing.

Trending

Components in their simplest forms would be defined as moving averages, trend-lines, price channels and extremely long-term oscillators. Trending market conditions, by their nature, are longer-term. Logically it is expected that longer-term inputs would most likely apply to indicators, which are being used to detect and follow trends.

However, it should be noted that these longer-term inputs introduce lag. This lag can of course be detrimental to the profitability of the trading model. When using switches this concern is somewhat minimized. The longer-term trend following model is being calculated in the background, while the shorter-term non-trending model is active in producing the trades.

This technique essentially emulates a backup system, which has its calculations up to speed, ready to be implemented upon demand. This will hold true if the targeted market shows a preference to non-trending characteristics while these conditions will reverse when applied to the subject of a trending market.

Outline of Position Model Components

Entry Techniques

• Non-Trending entry method switch

• Trending entry method switch

• Combining the entry method switches

Money Management

Is another component that could possibly be implemented as a stand-alone system. Thus, it is a very powerful tool by itself - it can also be a detriment when improperly deployed with a successful trading system. Some trading models will incorporate their own dynamic money management by being able to reverse a position dynamically. Other models may only incorporate a catastrophic stop loss of some fixed amount. Variations of this stop theme would be to employ a dynamic stop loss amount calculated and based upon volatility.

Stop Techniques

Fixed Cost Stops

• Percentage stops

• Trailing stops

• Range stops

• No stops

• Target exits

Fixed Target Amounts

• Range based targets

• Percentage targets

• No targets

Timed Exits

• Exit after number of bars

• Exit if profitable

• Exit upon time of day

Other Strategies

Might include seasonal patterns such as a specific time or month of the year, week or time of the month, day of the week and time of the day. It is important to not overlook interesting strategies that can also be developed for possible future use within a system by utilizing system statistics such as: number of losing trades in a row, number of winning trades in a row, percentage of winners, percentage of losers, etc.

First Things First - Final Summary

The above items have been outlined to serve as a step by step guideline to building a successful model. The first basic steps in creating such a model should be to build the non-trending and trending components.

Analyzing the Results

Great care should be taken when analyzing the non-trending systems results. Large losing trades will generally occur when the non-trending model is caught in a counter-trend trade. These trades should be omitted from the system's results so concentration can be placed upon how well the model performed on non-trending price action.

Likewise, omission of extended non-trending system results should be utilized when modeling the trend following component. Concentration should be placed upon analyzing the results of how profitable the trending component performed at its specified task of trading the trend. Just as the price action itself should be broken down and analyzed, it is important to also analyze the performance and results of the systems.

Combining the Techniques

Once the non-trending and trending components have been tested and the results are satisfactory, they can then be combined to form a singular trading methodology and trading platform. The next step is incorporating switches within the new platform building on the success of the trend functions and methodology. The highly desired benefit of the switches is that they can be incorporated and deployed in an almost infinite combination, covering a wide spectrum of criteria. The truly significant core to this approach is that optimization determines the best possible combination of potential model components (switches) to be utilized.

Only after these steps are taken and accomplished with satisfactory results should the focus move forward implementing additional strategies such as (but not limited to) money management. By building the models first with no constraints, solidifies the foundation that the true personality and nature of a particular market has been defined by the best performing combination of the respective models.

Implementing Secondary Techniques

It will now be interesting to see what impact traditional money management strategies have upon the system as well as different ideas and concepts as the creative model process moves forward to finalizing the system. It is highly recommended that this combination of strategies and model performance be analyzed thoroughly. Satisfaction with the model results is a key element as well as the imperative aspect to fully comprehend and understand the development process, which rendered the model.

If total satisfaction of the finished model performance is not achieved at this point or the system is not meeting the desired criteria for a robust system, there is no purpose in continuing with any additional development of the model. To eliminate wasting time, simply go back and redevelop new non-trending and trending models. Then, go through the combination process again, being aware that perhaps only one of the models may need to be redesigned. If a model is found to have particularly good statistics, then it is most likely worthy to be set aside until a complementary model can be discovered which will enhance the overall profitability when combined to form a complete system.

Example Trading Model Code{ begin comment

MB_Bond Model - Coding details of a two switch Trading Model.

Natural Hour Bond Model for real-time close on the hour data only. Also orders are done on Same Bar Close as signal bar.

The model itself consist of the following components.

1. The trending component called MB_ScaleBond.

• MB_ScaleBond Calculation

• MB ScaleBond User Function

2. The non-trending component called MB_PercentRatio.

• MB_PercentRatio Calculation

• MB PercentRatio User Function

3. The two component's are then combined give the buy/sell signals.

Included with this system are the following items.

Experimental secondary technique which may be considered as an enhancement.

1. The profit taking strategy called MB_EfficiencyRatio.

• MB_EfficiencyRatio Calculation

• MB EfficiencyRatio User Function end of comment }

Inputs: up(9),pdn(12),rlen(33),ds(2),sz(86),bz(32),dat(c),xcond(false);

{ Listed below is the variables to the system. } vars:bp(0),sp(0),hh(0),ll(99999),bflag(0),sflag(0),prbuy(0),prsell(0),pr(0),br(0),os(0),s(pdn),b(pup);

{ Listed below is the calculation of the user function MB_ScaleBond Function. This calculation is the net change of the commodity divided into its average value. Then it is smoothed by using and average. } if average(dat,36)>0 then br=dat/average(dat,36)else br=1;

br=100+(br-1)*2000;

os=average(br,3);

{ Listed below is the calculation of the MB_PercentRatio Function. This calculation uses the close values only. } value11=highest(dat,rlen)-lowest(dat,(rlen-ds)); if value11<>0 then

pr=98-((highest(dat,rlen)-dat)/value11)*102

else pr=0;

{ Listed below is the calculation of the non-trending method. A switch sets the value to either 1 for a buy or 1 for a sell. Either the buy or sell can be a value of 1 but neither can be the same value at the same time. } if pr>=bz and pr[1]<bz then begin prbuy=1;

prsell=0;

end;

if pr<=sz and pr[1]>sz then begin prsell=1;

prbuy=0;

end;

{ Listed below is the calculation used for the percentage swing above and below the ScaleBond Function. } s=1-pdn/100;

b=1+pup/100;

{ Listed below is the calculation of the trending method. A switch sets the value to either 1 for a buy or 1 for a sell. Either the buy or sell can be a value of 1 but neither can be the same value at the same time. } if os>hh then hh=os; sp=s*hh;

if os<sp then

begin

sflag=1;

bflag=0;

hh=os;

end;

if os <ll then ll=os; bp=b*ll;

if os>bp then begin bflag=1;

sflag=0;

ll=os;

end;

{ This condition attempts to eliminate the MB_PercentRatio Function from holding a flag value of 1 once it has accomplished it's objective. This allows reversal code to be implemented so that the model can flip it's position once it decides to do so. } if xcond=true then begin if pr > 85 then prsell=0; {x-condition} if pr < 32 then prbuy=0; {x-condition} end;

{ Listed below is the actual Buy/Sell command it combines the values from the two methods and looks for a total of 2 for a buy or a total of 2 for a sell. Either the buy or sell can be a value of 2 but neither can be the same value at the same time. } if prbuy+bflag=2 then buy close;

{condition1=playsound("D:\omega\buy.wav");} if prsell+sflag=2 then sell close;

{condition1=playsound("D:\omega\sell.wav");} {This part of the system turns the reversal on by setting the rev input to true. } input:risk(1500),rev(false),brz(90),srz(10),bse(3),show(false);

{ This part of the system stops and reverses a failed trade to attempt to recover losses. The value of the input can be inserted as a dollar amount. } if rev=true then begin

if BarsSinceEntry(0)>= bse and OpenPositionProfit<=-risk and pr>=srz and pr[1]<srz and bflag=1 then buy("rev2 buy") next bar on close stop;

if BarsSinceEntry(0)>= bse and OpenPositionProfit<=-risk and pr<=brz and pr[1]>brz and sflag=1 then sell("rev2 sell") next bar on close stop;

end;

{ This is the end of the main system. } { Below plots the user functions. } if show=true then begin

if prbuy+bflag=2 and prbuy[1]+bflag[1]<>2 then begin value55=TL_New(Date,Time,l-1,Date,Time,low-.125);

TL_SetStyle(value55,3);TL_SetColor(value55,4);

end;

if prsell+sflag=2 and prsell[1]+sflag[1]<>2 then begin value55=TL_New(Date,Time,H+1,Date,Time,h+.125); TL_SetStyle(value55,3);TL_SetColor(value55,6);

end;

end;

{ This is a modification to Perry Kaufman's efficiency ratio from his book Smarter Trading page 140. An oscillator that plots above and below zero has been made out of it and thresholds of upper and lower limits implemented. It's use is when a profitable move is underway and multiple contracts used, it could signal the peak of the price movement to take a profit. It also has other uses, such as when in a loosing trade it can signify when the worst current price movement has moved against you. So if you set tight some relief may come so that you do not exit the position at the worst possible moment. Also if in a drawdown with multiple contracts and the market comes back your way but still is not profitable, it could signal a point when to take off some of the contracts. } input:ertlen(10),ertavg(5),thold(5),tholdavg(100);

var:ert(0),ertup(0),ertdn(0);

ert = eff_osc(ertlen);

ertup=average(ert,tholdavg)+thold;

ertdn=average(ert,tholdavg)-thold;

var:dt(0),ptel(""); if prbuy+bflag=2 and ert>ertup and ert[1]<=ertup then begin ptel=("- Exit Long"); end;

if prsell+sflag=2 and ert<ertdn and ert[1]>=ertdn then begin ptel=("- Exit Short"); end;

[​IMG]​
if ert>=ertdn and ert<=ertup then begin ptel=("{ This is a Time converter by Rich Estrem which converts TS military time into regular time. } var:xtime(0),hr(""),min(""),tstr(""),tbr("");

if time<1300 then xtime=t else xtime=t-1200;

hr="00"+NumToStr(xtime/100,0);

hr=RightStr(hr,2);

min=RightStr(NumToStr(t,0),2);

tstr=hr+":"+min;

if t > 1200 then tbr=tstr + "pm" else tbr=tstr+"am";

{ Below is a print to log command for the date, time, Exit Potential. } print(ELDateToString(DATE),"",tbr,""," Exit Potential","",ptel);

MB_ScaleBond User Function

{ User Function : MB_ScaleBond Used in the MB_Bond Model }

input: dat(numeric); var:br(0),sb(0);

if average(dat,36)>0 then br=dat/average(dat,36)else br=1;

br=100+(br-1)*2000;

MB_ScaleBond=average(br,3);

MB_PercentRatio User Function

{ User Function : MB_PercentRatio Used in the MB_Bond Model }

input : dat(numeric),rlen(NumericSimple),vol(numeric),sfac(numeric),efac(numeric);

Value1 = Highest(dat,rlen) - Lowest(dat,(rlen-vol));

if Value1 <> 0 then

MB_Pratio = sfac - ((Highest(dat,rlen) - dat) / Value1) * efac else

MB_Pratio = 0;

MB_EfficiencyRatio User Function

{ User Function : MB_Eff_Osc Used in the MB_Bond Model } input:ertlen(numeric);

vars:dt(0),vt(0),ert(0),ert2(0), fastest(2/(8+1)),slowest(2/(30+1)),return(0);

if (@currentbar=1)then begin fastest = 2/(8+1);

slowest = 2/(30+1);end;

dt = c[0]-c[ertlen];

vt = @summation(@absvalue(c[0]-c[1]),ertlen);

if (vt<>0)

then MB_Eff_Osc = (dt/vt)*10;


About the Author

Mark Brown is a professional trader and mechanical systems advocate with an extensive background providing and trading proprietary models for various institutional firms.

He has developed trading software platforms for both Windows and Linux operating systems, is a licensed data vendor of the Chicago Board of Trade and has spoken at conferences for the Chicago Mercantile Exchange education center.

Return to “User Contributed Studies and Indicator Library”