Archivos de Categoría: Sin categoría

Consensio Trading System. A view of a programmer (Part 3 of 3)

In previous parts, I described my toughts about Consensio. In this part, after watch this video, from Tyler Jenks:

I decided to implement something more complete than my previous Consensio Indicators. This is my rant about the topic.

I will coment things about the theory exposed in the video and some changes I made in order to acomodate the results in an indicator more siutable to be the base of an strategy (with easy compable values in order to make the conditions for entry/exit increase/decrease the positions in the asset more easy, using the point of view  of a programmer)

About the video

In the video, Tyler describes Consensio as a way of «categorize» the status of an asset: is in a bullish market?, in a bear one?, and how bear o bull is?
In all the video, Tyles uses 2 SMAs, the call them Intermediate SMA and Long SMA, and make comparisions with price. But instead os use the price values, uses a mini-SMA of 2 weeks to smooth the values, so, from now on, all this article will call the 3 data as Price, Short SMA, and Long SMA

In all the videos from Tyler, he uses weekly timeframe, with SMA values of 2, 7 and 30 weeks periods.

Tyles describes two variables to value the perform of an asset, first the «Directionalities»


If we have 3 different period SMAs, and we use 3 states to distinguiss the direction of each one (is going up, is flat or is going down), we can categorize the status of the «direction» of the asset in function of these combinations.

For example, in a full bull market, the SMAs, for price, short and long will be facing up, In the opposite, in a full bear market, the 3 SMAa will be facing down.

Ok, but how we categorize the rest of the posible states? For example, if only the long SMA is facing up and the short and the price are facing down?

As combinatorial result, there is 27 states. Tyler breaks those in 3 tables of 9 states, one for Bull level, other for Bear levels and another for Flat levels.

In his video, level 1 is more powerfull than level 9.

This are the tables of combinations (extracted from the video):

Tylers is taken this tables from an old presentation, maybe from a brochure. The thing about brochures is they are written with the presentation and the logos and the format in main, instead of rigurosity.

I study those tables and I think that simply are bad transcribed… for example, the Flat table values 5 and 8 have the same dfirectionalites, and the bull and bear tables gives more weight to price than the short SMA (I think the column titles are swapped)

With these tables, you can name the «directionality» of an asset, with something like: Bull 1, or Bear 3, etc.
This is cool from an investor poin of view, but as programmer, I like to include all on this in a simple value, positive from bull markets and negative for bear markets, in order to manage just a variable instead of jump into a nighmare of concatenated ‘if’ code like:  if bull then if bear then, etc, so I wrote my own tables, with the (I think) correct weights  and reorganize the values to reflect this: one unique level from -13 to 13 showing the direction of the asset.

13 will be the more bullish scenario, 0 mean totaly flat market and -13 the more bearish scenario.

These are my tables:


The second thing to measure the class of an asset mentioned in the video is called «Relativities».

Takes the denomination from the relative position of each SMAa with the others.
For study them, Tyler uses a simulation where he changes the price for a signal with a well know oscillation: a sine wave.

From this sine wave, calculates 2 SMAs, the short period and the long period. With this conditions, he studys the interaction of the 3 signals, watching the positional orders of them (witch is in the top, in the middle or in the bottom position).

In this figure, you can see the simulation:

Green will be the Price, Yellow the short SMA and Red the Long SMA.

We can see a full cycle: prices going up, a period of «flattiness» in the upper part of the sine waves and prices going down. (Also we can notice the «smoothiness» from the signals… a longer SMAs does not reach the same amplitude as the price or the sorter one…)
Also we can see that the first signal going up is the price, then the sort and then the large period SMA.

If we break down this full cycle, anotating the interactions of the signals, we (almost) get the complete order in witch the signals go from cero to high and viceversa. I say almost, because with this kind of signal you can not reach all the possible combinations of positional orders than the reality can achieve. In order to get the full picture we will need another combination of signals.
Because in the real world, with real price data, the prices does not oscillate as a sine waves, all these combinations are possible, so we need to categorize aswell.

If we do this exercise, all we get is 13 possibles combinations.
Tyler denominates those combinations with letters, from A to M and this is the table of possible combinations:

(P goes for Price, Short for the Short SMA and Long for the Long SMA)

In this case, if the asset transition from estate M to state A will be indicating that a new bull market is starting.
If a Bull market level 1 is starting to decline, It will be making transitions to upper lleters: to B, C, D etc, untill reach the G level (flat market or about to transitioning to bear market), and if this down trend continues, it will end in K, L, M states (if not reverse first).
So, this letters provides like a compass. I see this like a circle, if the letters increase, the cicle increase, from bull, to flat to bear, completing a full cycle.

In my indicator,I use this table but, instead of use an «Equal» comparison, I use «Equal» or crosses, in order to get all the crosses happening between 2 candles and show those in my indicator.
If I use strictly comparison in my code, in reality we will be loosing too many transitions, so, I instead of use an strictly comparison (A==B) I compare the percent of change between the 2 values and if is greater than a treshold (definable in the indicator) mark as «above», if is less tan the treshold is mark as «Below» and if is not greater or smaller tan the treshold (or if the 2 SMAs has crossed) I consider the 2 values as «Equal or Crossed» and take note of this and show the value of that transition in the indicator.

I made myself a sine wave generator, and  inyected his signal instead of price into my indicator, in order to see all the changes in state that this signals can offer to us.

Here you have a picture showing the starting of a bull market:

As usual, Green is price, Yellow is the short SMA and red the long one.

You can see in the lower part, the transition of the letterts, going from states J, K, L to A, B, C, until reach G letter, indicating a change is goint to take place.

This is the Bear cycle starting:

In this case, the letters goes from F, G to H, I, J K showing the progress of the sine waves in to the bear cycle.
Note that with this signals there are states missing, like the M, because is almost impossible with this simulation and those values than the 3 signals be equal or crosses at the same time (perhaps doing some tunning…) But this can happen in reality, so we include all the combinations.

How looks this kind of indicator with real prices?, let see some examples:


Here we can see the last bull cycle to the ATH, the falling in to bear market and raising again.
Of course, the indicator is delayed, because of the SMAs.

SPX 500


I like this indicator to «navigate» lists of tickers, and get in seconds a view of their status, and, if this is good, analyze in more detail with other tools.

The name of this indicator is Consensio REAL (Sorry for the lack of imagination choosing the name), and you can find it in Tradingview Public library.

In this URL you can find All of my published scripts in Tradingview: Nakitxu’s Tradingview Indicators, for now, all of them are open to the public.
Don’t hesitate in leave any comments of suggestions (and push the like & follow button… it helps)

Consensio Trading System. A view of a programmer (Part 2 of 3)

Note: This is Part 2 of a series, in the following link,  you have the previous Part 1:

In the first part, I talk about the development of the «Consensio with Signals» indicator.

This indicator works, but in a limited way. I have programed a strategy using this indicator and works, maybe some day I will publish all the results of backtesting different strategies.

Works, but, thinking about my Consensio implementation, there are things missing in the system.
For example, my indicator just look for the positional orders of the SMAs, does not take into account if the SMAs are rising, or falling, and only 6 levels of bull/bear starting to look a little bit insufficient for me, so, I decided incorporate a new variable into an indicator: use the distance of the price to the 3 SMAs, in a ponderated way: the distance of the price versus the long SMA has more weight than the short SMA or the medium SMA.

With this idea, I created this second Consensio script, this time called «Consensio Hystogram Forecasted» (yes, I now, Hystogram is bad spelled…)

Here is how it looks:

This is not an overlayed version, is an histogram, running in a separate space from the main graphic. Shows the bull/bear levels in the upper part and shows an histogram with positive and negative values, calculated from the distance between the price and the SMAs.

The values are calculated using different weights for the distances from the price to each SMAs. These porcentages are definables by the user, but the defaults are:

  • 50% for the SMA Long
  • 35% for the SMA medium
  • 15% for the SMA short

Once this value is calculated, is multiplied for the level of bull/bear and show in the histogram. This give us a little bit more of «whats is going on» info, but I still feeling that this work is not complete. My indicators are not using the change of direction of the SMAs, so… the work must continue!

This indicator is also availlable for any Tradingview user, you can find it in the Tradingview public library of indicators under the name «Consensio Hystogram Forecasted», and also you can find it in this URL: Consensio Hystogram Forecasted

In this URL you can find All of my published scripts in Tradingview: Nakitxu’s Tradingview Indicators, for now, all of them are open to the public.
Don’t hesitate in leave any comments of suggestions (and push the like & follow button… it helps)

Sonda cero para la fresadora X6-1500GT Parte 2

En la anterior entrada, Sonda cero para la fresadora X6-1500GT Parte 1 explicaba cómo he construido mi nueva sonda cero.
En esta entrada mostraré como la he calibrado, y podréis ver algunas pruebas de su funcionamiento.

El Script de la sonda

Mi intención es fijar la sonda en una posición de la máquina (donde no me estorbe mucho), de tal forma que con una macro podré mover el spindle sobre ella y con otra macro podré hacer el cero con la herramienta que tenga instalada en ese momento.
Todas mis macros de movimiento (ir a home, ir a sonda, etc) los he programado de tal manera que hagan movimientos seguros en lo que respecta al eje Z, es decir, si el spindle está en medio de la máquina, a pocos milímetros de la base y pulso el botón de ‘ir a posición home’, el script, en lugar de mover los 3 ejes simultáneamente hacia la posición home, lo que hace es, primero eleva el eje Z y luego, mueve los ejes X e Y.
Con esta sencilla operación, puedo estar seguro que al pulsar el botón, la herramienta no chocará con alguna posible pieza que tenga en la base de la máquina.
Dicho esto, el script de hacer el cero lo he programado de tal manera que estando el eje Z en su posición superior, al ejecutar el script sea lo más rápido posible, la para lo cual, lo que hace es script es usar dos velocidades:

  • Baja a una velocidad rápida (F800 en el ejemplo) hasta detectar la sonda
  • Retrocede una pequeña distancia (en el ejemplo, 1mm)
  • Baja de nuevo, pero a una velocidad más lenta (F20 en el ejemplo) hasta detectar la sonda
  • Toma nota de la coordenada absoluta de máquina en donde se activó la sonda y la muestra en la barra de estado (y por tanto en el log) del Mach3
  • Hace el cero del eje Z en ese punto

Por supuesto, para usar este script, la máquina tiene que tener los ejes referenciados, sino no tendrás coordenadas absolutas de máquina fiables, para lo cual, tu máquina debería tener instalados detectores de posición inicial en sus 3 ejes.
Puedes ver aquí cómo instalar sensores de ‘Home’ en tu máquina: Añadiendo detectores a la fresadora X6-1500 GT

Tambien cabe mencionar… que si vas a probar este script con tu sonda conductiva… ten cuidado y modifica la velocidad de bajada rápida, o tu máquina podría pasarse de frenada estrellando la herramienta contra la sonda. En la sonda mediante pulsador esto no tiene problemas, porque el pulsador tiene cierto margen, ya que desde su punto de activación permite que la herramienta baje por lo menos otro milímetro más sin chocar.

Este es el código del script para hacer cero a 2 velocidades:

Rem	VBScript Para hacer cero en Z con la sonda cero

cRecorridoMaximo	=51		'Distancia máxima a bajar buscando la sonda (50 mm)
cRetroceso	=1		'Distancia a retroceder para hacer la pasada lenta (1mm)
cFRapido	  	=800		'F para bajar rápido
cFLento		=20		'F para bajar lento y detectar el cero 	

If GetOemLed (825) <> 0 Then 		'si la sonda está pulsada, mostramos error y no seguimos
    Message "(ERROR: La sonda cero está activada antes de empezar!!)" 'esto se vera en la status bar como mensaje

	ZRef = GetOEMLed(809)			'TRUE si el eje Z NO está referenciado

	If ZRef <> 0 Then		
	  Message "ERROR: El Eje Z debe estar referenciado"
	  AlturaDeSonda = GetUserDRO(1151)	'Obtiene la altura de sonda
	  CurrentFeed = GetOemDRO(818) 		'Obtiene el F actual

	  Rem Primera deteccion bajando rápido:
	  Code "F" & cFRapido	  			
	  ZNew = GetDro(2) - cRecorridoMaximo	'Cordenada Z meta de la sonda

	  Code "G31Z" &ZNew
	  While IsMoving()			'Esperamos a que la sonda se active

	  ZNew = GetVar(2002) 			'Obtenemos coordenada Z de donde ha tocado

	  Rem subimos un trozo para volver a bajar lento:
	  code "G0Z" & ZNew + cRetroceso		'Retrocedemos cRetroceso hacia arriba

	  Rem Y Bajamos lento:
	  Code "F" & cFLento			'Bajamos hacia la sonda, pero lentamente
	  ZNew = GetDro(2) - (cRetroceso+1)

	  Code "G31Z" &ZNew
	  While IsMoving()			'Esperamos a que la sonda se active
	  ZCero = GetOemDRO( 85 )			'Obtenemos Z (de máquina, no relativa) del cero detectado
	  Message "Z Absoluta detectada:" &ZCero

	  Call SetDro (2, AlturaDeSonda)		'Hacemos el cero de eje z en el alto de la sonda
	  Code "G4 P0.25" 			'Pausa

	  Code "F" &CurrentFeed 			'Volvemos a poner el F que habia antes de empezar el script

	  Rem Movemos el Z a posicion de Home:
	  z = GetOemDRO( 192 )			'Obtenemos la Z de posicion de home
	  code "G0G53Z" & z
	End If  	
End If                                 

Pruebas de funcionamiento

Aqui muestro el funcionamiento de la sonda y del script, una vez montado todo:

Ajuste de la altura de la sonda

Para poder hacer el cero, el script necesita saber a que altura está el punto justo donde el pulsador hace contacto respecto del suelo. En este vídeo muestro cómo averiguar esta altura, obteniendo el dato que poner luego en el campo ‘altura de sonda’ en la pantalla correspondiente del Mach3: