Bot de Trading Futuros Cripto con Python y Bybit

  • Save

Temas Principales e Ideas Clave:

  1. Advertencia sobre los Riesgos del Trading de Criptofuturos: El video comienza con una fuerte advertencia sobre los riesgos inherentes al trading de criptomonedas, especialmente los futuros. Se destaca la posibilidad de una pérdida total del capital y se insiste en la necesidad de comprender completamente lo que se está haciendo antes de operar.
  • Cita: «trading cryptocurrencies high risk trading Futures on cryptocurrencies extremely high risk so what I want to say is know what you’re doing and obviously this video is a technical guideline and not any form of investment advice if you ask me I would be very very sure about what I’m doing before getting into future trading on cryptocurrencies total loss of capital is possible and also probable and again this whole video is not an investment advice and is for educational purposes only»
  1. Naturaleza Educativa y Simplificada de la Estrategia: Se recalca que la estrategia de trading implementada en el bot es un ejemplo simplificado con fines educativos y no se recomienda para operar en un entorno real sin pruebas exhaustivas y una comprensión profunda.
  • Cita: «the strategy that I’m coding and I’m implementing here is simplified so I do not recommend to trade the strategy it’s just an example to get the bot going»
  1. Configuración Inicial y Conexión a la API de Bybit: El tutorial guía a los usuarios en la importación de las bibliotecas necesarias en Python (pandas, time, pybit), la configuración de las claves de la API de Bybit (clave y secreto), y la instanciación de un objeto cliente para interactuar con la plataforma de Bybit. Se destaca la importancia de utilizar el entorno de demostración («demo trading environment») para pruebas antes de operar en vivo.
  • Cita: «I’m importing my API key and my API secret here so this is just a python file storing my keys and I’m also importing HTTP from the bit Library second of all um instantiating a client object and this client variable is just the access to the byit platform so I can execute all kinds of functions… now I’m setting demo to true to connect to the demo trading environment so this is not the live environment if you leave that out then you get into the life trading environment so be cautious with that»
  1. Obtención y Procesamiento de Datos de Velas (Candlestick/Kline): Se presenta una función para obtener y transformar datos de velas desde la API de Bybit a un formato de DataFrame de pandas para facilitar su análisis. Esta función es reutilizada de un video anterior del autor.
  • Cita: «this function is nothing fancy and nothing new this is simply processing Candlestick or Kline data from the API… what this is just doing is taking an API response and it’s doing some data transformation so you end up with a lucid data frame»
  1. Definición de Parámetros de Trading y Estrategia: Se definen los parámetros clave de la estrategia, que en este ejemplo se basa en la detección de una caída del 1% en el precio de Bitcoin/USDT en los últimos 15 minutos para abrir una posición larga, con un objetivo de beneficio del 4% y un stop loss del 2%.
  • Cita: «the strategy is if the Assets in this case um trading the Bitcoin in relation to usdt when the asset is dropping by 1% within the last 15 minutes then I’m placing an order go long on the asset so I’m presuming a reversal and then I’m setting a Target profit to 4% and a stop loss oft 2%»
  1. Función para Obtener Datos Recientes: Se describe una función para obtener datos históricos de precios (velas de 1 minuto) de los últimos 15 minutos, utilizada para evaluar la condición de caída de precio.
  • Cita: «this function is just pulling data from now and then is going 15 minutes back just to see how the coin was moving over the last 15 minutes»
  1. Cálculo del Movimiento del Precio: Se implementa una función para calcular el cambio porcentual del precio entre el inicio y el final del período de observación (15 minutos), que se utiliza para determinar si se ha alcanzado el umbral de caída definido.
  • Cita: «what I’m doing here start price is I’m just pulling the close and I’m just icking for zero meaning I just start at this price so the price 1550 minutes ago and then I’m ending at the most recent price so the price as of now and then this function is just providing me the start price the end price and and this is the most important one h ere the difference»
  1. Colocación de Órdenes Largas a Mercado: Se presenta la función para colocar una orden de compra a mercado en Bybit.
  • Cita: «very straightforward you just place an order for the given symbol Side by and you just take a market order… pass the quantity and the time and force and this is just placing a long position Market order wise and then gives you the feedback that you opened a long position»
  1. Obtención del Precio de Entrada y Configuración de TP/SL: Se explica la necesidad de obtener el precio de ejecución de la orden (precio de entrada), lo cual se describe como «un poco complicado» en la API de Bybit en comparación con otras plataformas. La solución implementada es obtener la última orden abierta y extraer su precio promedio de ejecución. Con el precio de entrada, se calculan los precios de Take Profit y Stop Loss basados en los porcentajes definidos.
  • Cita: «at the same time and this is a bit tricky with the bit API you need to extract information from that order and it’s unfortunately a bit inconvenient for bybit to get order information… what I did here I just pulled the open orders and then just looked for the very last one and with that I’m getting the order details… I’m just using the order and then extract the average price price of the order and then convert it to a floating value and with that I’m calculating my target profit and stop loss price»
  1. Modificación de la Orden para Incluir TP/SL: Se destaca que en Bybit, es necesario modificar la orden original para añadir los parámetros de Take Profit y Stop Loss. Se muestra el código para realizar esta modificación a través de la API.
  • Cita: «once you calculated them you need to modify your order that’s also uh byit uh special reality or just a thing which you have to get used to so you send a modification to your current order… then Define the take profit as my take profit price and the stop-loss as my stop loss price and with that I amend the order»
  1. Verificación del Estado de las Posiciones: Se implementa una función para verificar si el bot ya tiene una posición abierta en el par de trading especificado. Esto es crucial para evitar la apertura de múltiples posiciones innecesarias.
  • Cita: «the reason behind this function is that we want to do the order management outside of the script so bit Knows Best in which positions you currently are right… this what this function is doing nothing more than that… client get positions so pull all my positions on a given symbol»
  1. Lógica Principal del Bot (RunBot Function): Se describe la función principal que ejecuta el bucle de trading. Esta función verifica continuamente si hay una posición abierta. Si no hay ninguna posición, obtiene los datos de precios recientes, calcula el movimiento del precio y, si se cumple la condición de caída, coloca una orden de compra larga con Take Profit y Stop Loss. Si ya hay una posición abierta, el bot simplemente espera sin realizar más acciones innecesarias.
  • Cita: «first of all you just run an infinite Loop and then you pull your current position if you are currently not in a position that is what is going to be triggered if the position size is zero… if my price difference is larger or equal to the drop thr threshold then I’m placing a long order… now what is happening if I am in a position and that is an important thing to to keep in mind here if you are in position just remember you always already have defined your t arget profit and your stoploss so the script has to do nothing in that case»
  1. Consideraciones Adicionales: El video menciona brevemente la posibilidad de utilizar websockets para obtener datos en tiempo real, lo cual podría ser una mejora en comparación con las solicitudes periódicas a la API. También se reitera que el desarrollo de bots de trading puede ser extenso y con muchas posibilidades de personalización.
  • Cita: «as I mentioned in the course of this video you can also work with uh websocket data streams also perfectly fine and maybe even better then you have to take care of that the data stream is running all the time so there a downside but probably better approach to do it as always with trading Bots this guy is the limit where do you start where do you stop»

Conclusiones:

El video proporciona una introducción práctica y didáctica al desarrollo de un bot de trading de futuros de criptomonedas en la plataforma Bybit utilizando Python. A través de un ejemplo de estrategia simplificada, se ilustran los pasos fundamentales para interactuar con la API de Bybit, incluyendo la obtención de datos, la toma de decisiones de trading basadas en reglas predefinidas, y la ejecución de órdenes con parámetros de gestión de riesgo (Take Profit y Stop Loss). Se hace un énfasis constante en los altos riesgos del trading de futuros y en la naturaleza educativa del código presentado, advirtiendo a los usuarios que no utilicen la estrategia sin una comprensión profunda y pruebas exhaustivas. El video también señala algunas particularidades de la API de Bybit, como la forma en que se obtienen los detalles de las órdenes y la necesidad de modificar las órdenes para incluir TP/SL. En general, el tutorial sirve como un buen punto de partida para aquellos interesados en automatizar estrategias de trading en Bybit utilizando Python, siempre recordando la importancia de la gestión de riesgos y la debida diligencia.convert_to_textConvertir en fuenteNotebookLM puede ofrecer respuestas inexactas. Compruébalas.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Scroll al inicio
Share via
Copy link