Dynamics Algorithmic Day-Trading, the best choice for Hive-Engine users [EN-ES]

Have you ever thought about a way for everyone to win in trading, because there is one? We present to you a dynamic algorithmic strategy that we have optimized based on the on-chain data in Hive-Engine.

Alguna vez ha pensado en una manera en que todos ganen en el trading, pues la hoy le presentamos una estrategia algorítmica dinámica que hemos optimizado a partir de los datos onchain en Hive-Engine.


pexelsnataliyavaitkevich7173040_low.jpg
Image taken from Nataliya Vaitkevich at free stock at

Imagen tomada de Nataliya Vaitkevich del stock gratuito en

pexel.com

Initial Words // Palabras Iniciales

For many, trading is seen as betting, where in order for some to win, others must lose, to some extent it is, especially in future operations, but the spot market has other more ethical properties. There are healthy variants where the way of trading guarantees liquidity for exchanges and everyone wins, only he who is dominated by greed loses. An ethical trading algorithm takes into account not only the profits it generates but also the impact it causes on the market and its impact on users.

Those users with significant liquidity can create market offers, help their growth, and manipulate it. It is common to see how whales in their avariciousness establish harmful strategies such as Pump and Dump, Spoofing, Wash Trading and Insider Trading. Faced with this difficulty, only risk mitigation, using appropriate data, and establishing collaborative strategies that penalize malicious actors with losses is the way.

The way we propose for adequate risk mitigation and an operation that benefits all users is the Dynamic Algorithmic Trading In general terms, Dynamic Algorithmic trading is an investment technique that uses computer algorithms based on technical and fundamental analysis, as well as on market behavior patterns and historical data. The biggest advantage for the commons users is that the algorithms are not subject to human emotions, such as fear or greed, which can lead to irrational investment decisions, in addition, the algorithms can be customized to adapt to the needs and objectives of each investor, which increases the effectiveness of the investment strategy when personalization maximizes the desired impact this can be reflected as a multivariate optimization problem.

The #HIVE blockchain has exceptional characteristics, the most significant after its almost absence of fee, is that there is no anonymity possible. So it is possible to identify the operation of each user and their interaction with the rest. From a Data Scientist's point of view #HIVE is a holy grail of information.

Para muchos el trading es visto como las apuestas, donde para que unos ganen otros deben perder, hasta cierto punto lo es, sober todo en operaciones de future, pero el mercado al contado tiene otras propiedades más éticas. Hay variantes sanas donde la forma de operar garantiza liquidez para los intercambios y todos ganan, solo pierde quien es dominado por la codicia. Un algoritmo de trading ético no solo tiene en cuenta los beneficios que genera sino el impacto que provoca en el mercado y su incidencia sobre los usuarios.


Aquellos usuarios que poseen gran liquidez pueden crear ofertas de mercado y ayudar a su crecimiento, pero también manipularlo. Es común ver como las ballenas en su avaricia establecen estrategias dañinas como: Pump and Dump, Spoofing, Wash Trading y Insider Trading. Ante esta dificultad solo la mitigación de riesgos, utilizar los datos apropiados y establecer estrategias colectivas que penalicen con pérdidas a los actores malisiosos es la vía.


La vía que le proponemos para una mitigación de riesgos adecuada y una operativa que beneficie a todos los usuarios es el Trading Algoritmico Dinámico. En términos generales el Trading Algoritmico Dinámico es una técnica de inversión que utiliza algoritmos informáticos basados en el análisis técnico y fundamental, así como en patrones de comportamiento del mercado y datos históricos. La mayor ventaja para los usuarios cumunes, es que los algoritmos no están sujetos a las emociones humanas, como el miedo o la codicia, lo que puede llevar a decisiones de inversión irracionales, además, los algoritmos pueden ser personalizados para adaptarse a las necesidades y objetivos de cada inversor, lo que aumenta la eficacia de la estrategia de inversión, cuando la personalización maximiza el impacto buscado este se puede reflajar como un problema de optimización multivariada.


La blockchain de #HIVE posee carácterísticas excepcionales, la más significativa luego de su casi ausencia de fee, es que no hay anonimato posible. Por lo que es posible identificar la operativa de cada usuario y su interacción con el resto. Desde el punto de vista de un Científico de Datos #HIVE es un santo grial de información.

Basics of Hive-Engine // Fundamentos de Hive-Engine


hiveenginelogo
Hive-Engine Logo

Hive-Engine is the L2 layer of #Hive that makes it possible to execute smart contracts and manage various tokens. Although it does not yet allow the free deployment of smart contracts, it does have the ability to create tokens with hardly any codes required. From the point of view of trading, the most attractive tokens are those with Pegged value because a mechanism, usually an arbitrage bot such as @hive-combine, @mcbot, or @konvik-btc (to name a few), is responsible for equalizing their price with respect to the rest of the markets where HIVE is listed, both CEX as DEX, in the latter, those linked to the @leofinance ecosystem such as CubDefi and PolyCub.

Among the most important features are:

  • Zero commissions on operations, like the other mechanisms of the HIVE blockchain, only the RC are consumed, with their replenishment of 20% in 24 H. This makes it possible to exchange small amounts without incurring losses for commissions.
  • Deposit or withdrawal fees range from zero to 1%, depending on the deposited token, the source/destination network, and the deposit mechanism.
  • Bridges such as BeeSwap and LeoDEx allow interoperability with HIVE L1 with a fairly acceptable commission of 0.25%.
  • Limit operations, allow the peace of mind of choosing the bid/ask price without being aware of market changes. From the point of view of our algorithm, it is the most important property.
  • Several frontends to operate with Hive-Engine, our favorite is TribalDex.
  • The base token to which all pairs are referred is SWAP.HIVE, which has value linked to the HIVE.

Hive-Engine es la capa L2 de Hive que hace posible la ejecución de contratos inteligentes y el manejo de tokens diversos. Si bien aún no permite el libre despliegue de contratos inteligentes, si posee la capacidad de crear tokens sin apenas necesidad de códigos. Desde el punta de vista del trading los tokens más atractivos son los que tienen valor vinculado (Pegged) pues un mecanismo, por lo general un bot de arbitraje como @hive-combine, @mcbot o @konvik-btc (por mensionar algunos), se encarga de equlibrar su precio respecto al resto de los mercados donde está listado HIVE, tanto CEX como DEX, en estos últimos resulta significativo los vinculados al ecosistema de @leofinance como CubDefi y PolyCub.


Dentro de las características más importantes está:

  • Cero comisiones en las operaciones, al igual que los demás mecanismos de la blockchain de HIVE, solo se consumen los RC, con su reposición del 20% en 24 H. Esto posibilita que se puedan intercambiar cantidades pequeñas sin que esto incurra pérdidas por comisiones.
  • Comisiones de depósito o retiro que oscilan desde cero hasta el 1%, según el token depositado, la red de procedencia/destino y el mecanismo de depósito. Se destacan puentes como BeeSwap y LeoDEx que permiten una interoperatividad con HIVE L1 con una comisión bastante aceptable del 0.25%.
  • Operaciones de límite, estas permiten la tranquilidad de escoger el precio de oferta/demanda sin estar pendiente de los cambios del mercado. Desde el punto de vista de nuestro algoritmo es la propiedad más important.
  • Varios FrontsEnd para operar con Hive-Engine, nuestro favorito es TribalDex.
  • El token base al que están referido todos los pares es SWAP.HIVE, que tienen valor vinculado al HIVE.

Basic strategies // Estrategias Base


pexelsanetelusina4792509Idea_low.jpg
Image taken from Anete Lusina at free stock at

Imagen tomada de Anete Lusina del stock gratuito en

pexel.com

For ordinary users, understand this as users who interact with Hive-Engine through its frontends and not programmatically through its API, it is normal that they make buy/sell offers according to their own criteria depending on the trends of the spot market. Despite this, there are well-established strategies such as:

  • Scalping: Multiple buy and sell trades are made, in a short time window, usually up to 6 hours, the goal is to make small profits on each trade. From the user's point of view, this operation is strenuous as it requires the constant attention of the user.
  • Breakout Trading: Key support and resistance levels are identified in the market and wait for the price to break one of these levels before opening a position. Volume identification of bounce levels is key and may be subject to manipulation.
  • Swing Trading: An open position is held for several days or weeks. The position is usually linked to the fundamental analysis of the development and growth of the adoption and use cases of the chosen main token.
  • News Trading: It is based on taking advantage of important news and announcements that may affect the price of cryptocurrencies, such as halving or the recent FTX virus. This strategy demands that the user has a sufficient level of updated and truthful information.
  • DCA: Dollar-Cost Averaging (DCA) consists of investing a fixed amount of money in a cryptocurrency at regular intervals, regardless of the price of the cryptocurrency at that time. It seeks to reduce the impact of market volatility on your investment.

Except for the case of News Trading, the other strategies are part of the design of our algorithm, which we will detail in the next sections. We will accompany our explanation with mathematical expressions and code segments programmed in Python, the latter serves to automate the precise calculation of the positions but is not strictly necessary, a good calculator and a blog of notes are enough.

Para los usuarios comunes, entiéndase esto como usuarios que interactúa con Hive-Engine a través de sus FrontEnds y no programáticamente mediante su API, lo normal es que pongan ofertas de compra/venta según su criterio propio en dependencia de las tendencias del mercado al contado. Pese a esto hay estrategias bastante bien establecidas como:

  • Scalping: Se realizan múltiples operaciones de compra y venta, en una ventana de tiempo corta, generalmente hasta 6 horas, el objetivo es obtener pequeñas ganancias en cada operación. Desde el punto de vista del usuario esta operación es extenuante al necesitar la atensión constante del usuario.
  • Breakout Trading: Se identifican niveles clave de soporte y resistencia en el mercado y esperar a que el precio rompa uno de estos niveles antes de abrir una posición. La identificación por volumen de los niveles de rebote son clave y pueden estar sujetos a manipulación.
  • Swing Trading: Se mantiene una posición abierta durante varios días o semanas. La posición está por lo general vinculada al analisis fundadamental del desarrollo y crecimiento de la adopción y casos de uso del token principal escogido.
  • News Trading: Se basa en aprovechar las noticias y los anuncios importantes que pueden afectar el precio de las criptomonedas, como el halving o el reciente virus FTX. Esta estrategia demanda que el usuario tenga un suficiente nivel de información actulizada y verídica.
  • DCA: Dollar-Cost Averaging (DCA) consists en invertir una cantidad fija de dinero en una criptomoneda a intervalos regulates, independientemente del precio de la criptomoneda en ese momento. Se busca reducir el impacto de la volatilidad del mercado en su inversión.

Salvo el caso del News Trading, las demás estrategias forman parte del diseño de nuestro algoritmo, el cual le detallaremos en las próximas secciones. Acompañaremos nuestra explicación con expresiones matemáticas y segmentos de código programados en Python, estos últimos sirven para automatizar el cálculo preciso de las posiciones pero no son estrictamente necesarios, una buena calculadora y un blog de notas es sufficient.

Dynamics Algorithmic Day-Trading

Input parameters // Parámetros de entrada

  1. Table of tokens and holding // Tabla de tokens y tenencia
  2. Current price of each token relative to Hive // Precio actual de cada token relativo a Hive
    $P_x = \frac {P.Token}{P.Hive}$
  3. Maximum relative price in the last $kt$ days // Precio relativo máximo en los últimos $kt$ días
    ${P1}_{kt}=Max( Get MaxLastKtDays(P_x,kt), \frac {P_x}{pr} )$
    We use // Nosotros usamos
    $kt=58$, $pr=0.9625$
  4. Minimum relative price in the last $kt$ days // Precio relativo mínimo en los últimos $kt$ días
    ${P2}_{kt}=Min( Get MinLastKtDays(P_x,kt), {P_x}{pr} )$
  5. Volatility factor // Factor de volatilidad
    $F_v=\frac{{P1}{kt}-{P2}{kt}}{{P1}{kt}+{P2}{kt}}$
  6. Investment factor // Factor de inversión
    $F_i=\frac {F_v}{\sum F_v}$
  7. Number of investment points // Número de puntos de inversión
    $N_i=Int(N_k F_i)$, $N_k=18$
  8. Scale factor // Factor de escala
    $S_A=(\frac{{P1}{kt}}{{P2}{kt}})^{\frac{1}{N_i+1}}$
  9. Hive to invest // Hive para inverter
    $H_B=0.8HiveF_i$
Concept\TokenHIVEBTCHBD
Holding500.230.0034223123.45
$P_x$1.068030.354350932362.2902595552724194
${P1}_{kt}$1.071535.04864787722.8041556740310996
${P2}_{kt}$1.046561.463808250451.9751358370895942
$F_v$00.211467589687750780.173460822595253
$F_i$--0.5493686174879640.45063138251203605
$N_i$--98
$S_A$--1.04387675094028091.0397087129431561
$H_B$--219.84853082080338180.33546917919665

Algorithm // Algoritmo

The codes below are made in Python and use the numpy library.

Los códigos a continuación están hechos en Python y utilizan la librería numpy.

import numpy as np 
  1. Generate the investment points // Genere los puntos de inversión
ps=np.array([P2/SA**i for i in range(nk)])
print(ps)

Example of output for BTC // Ejemplo de salida para BTC:

[71535.04864788 68528.25161921 65647.83779070 62888.49496032
 60245.13421117 57712.88052627 55287.06379780 52963.21021423
 50737.03400954 48604.42955918]
  1. Select the buy points // Seleccione los puntos de compra
print(ps[np.where(ps<Px)])

Example of output for BTC // Ejemplo de salida para BTC:

[65647.83779070 62888.49496032 60245.13421117 57712.88052627
 55287.06379780 52963.21021423 50737.03400954 48604.42955918]
  1. Generate the amounts to buy // Genere los montos a comprar
cache = {0: np.double(0), 1: np.double(1)}

def fibonacci_of(n):
    if n in cache:  # Base case
        return cache[n]
    # Compute and cache the Fibonacci number
    cache[n] = fibonacci_of(n - 1) + fibonacci_of(n - 2)  
    return cache[n]
def fibovalsup(tot,st,n,pe):
    sm=np.array([fibonacci_of(i) for i in range(st,st+n) ])
    one=np.ones(n)
    smp=sm.sum()
    return tot*(pe*one/n + (1.0-pe)*sm/smp)

l=ps[np.where(ps<Px)].size
print(fibovalsup(Hb,3,l,0.35)/ps[np.where(ps<Px)])

Example of output for BTC // Ejemplo de salida para BTC:

[0.00017739 0.00020129 0.00024377 0.00030715 0.00041228 0.00058345
 0.00086873 0.00134474]
  1. Select the sells points // Seleccione los puntos de venta
print(ps[np.where(ps>Px)])

Example of output for BTC // Ejemplo de salida para BTC:

[71535.04864788 68528.25161921]
  1. Generate the amounts to sell // Genere los montos a vender
def fibovalsdown(tot,st,n,pe):
    sm=np.array([fibonacci_of(st+n+1-i) for i in range(st,st+n) ])
    smp=sm.sum()
    one=np.ones(n)
    return tot*(pe*one/n + (1.0-pe)*sm/smp)
l=ps[np.where(ps>Px)].size
HS=Holding*0.8
print(fibovalsdown(HS,3,l,0.35))

Example of output for BTC // Ejemplo de salida para BTC:

[0.00166552 0.00107232]
  1. Repeat from the first step for each token // Repita desde el primer paso para cada token

Elements to consider // Elementos a considerar

The parameters and constants that we have used went through an optimization process through simulation for a wider collection of tokens with linked value, with the parameters present here it was possible to minimize losses in market downturns. Initially, we performed the operation of calculating the orders daily, then we convinced ourselves that it was not necessary, because it was sufficient to wait for exchange orders to be executed until the exchanged value exceeded $10%$ of the total value.

Although we have been applying this method since December 12, 2022, we are waiting to make it public when we reach $200% of the initial invested value, while optimizing the parameters and constants.

This algorithm in its previous stage was applied by my brother @ertytux, which served him to acquire a Moderna cell phone from the investment of the rewards earned by his posts. More details in the post Celebrating my 44th birthday in a big way, Thanks #Hive 🎉 [EN-ES]

A friend who has also started using the algorithm has asked us a very interesting question: What happens if everyone applies his algorithm? To answer we carried out a series of simulations assuming the same daily exchange amount registered in Hive-Engine in the selected tokens, the result was impressive and encouraged us to share it with everyone: The Hive price destabilizes around the $0.65$ value, the collective action resembles the HBD operation.

If you are encouraged to try it you can contact us and for a symbolic value we share the complete script for Jupyter in Google Colab where most of the process has been automated.

Los parámetros y constantes que hemos utilizado pasaron por un proceso de optimización mediante simulación para una colección más amplia de tokens con valor vinculado, con los parámetros acá presentes se logró minimizar las pérdidas en las caídas del mercado. Inicialmente realizamos la operativa de calcular las órdenes diariamente, luego nos convencimos que no era necesario, pues era sufficient esperar a que se ejecutaran órdenes de intercambio hasta que el valor intercambiado superara el $10%$ del valor total.

Pese a que llevamos aplicando este método desde el 12 de Diciembre de 2022, esperamos para hacerlo público al alcanzar el $200%$ del valor inicial invertido, a la vez que íbamos optimizando los parámetros y constantes.

Este algoritmo en su étapa previa fue aplicado por mi hermano @ertytux, el cual le sirvió para adquirir un celular moderno a partir de la inversión de las recompensas ganadas por sus post. Más detalles en el post Celebrando en grande mis 44 años, Gracias #Hive 🎉 [ES-EN]

Un amigo que también ha comenzado a utilizar el algortimo nos ha hecho una pregunta muy interezante: ¿Qué sucede si todos aplican su algoritmo? Para responder realizamos una serie de simulaciones asumiendo el mismo monto de intercambio diário registrado en Hive-Engine en los token selectos, el resultado fue impresionante y nos animó a compartirlo con todos: El precio de Hive se destabiliza alrededor del valor $0.65$, el accionar collectivo se asemeja a la operativa de HBD.

Si se anima a intentanrlo nos puede contactar y por un valor simbólico le compartimos el script completo para Jupyter en Google Colab donde la mayor parte del proceso se ha automatizado.


image.png
Screenshot of the accumulated balance, the units are omitted, but the $200%$ trend is clearly seen.
Captura de pantalla del saldo acumulado, se omiten las unidades, pero se ve claramente la tendencia $200%$.


And remember:
Freedom exists only when it belongs to everyone.

Thank you for reading us, we hope we have added something to your knowledge or reaffirmed the one you have.

Y recuerda:
La libertad existe solo cuando pertenece a todos.
Gracias por leernos, esperamos haber agregado algo a su conocimiento o reafirmado el que tiene.

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center