Help Trailingstop

O código está completo
Após recebe a mensagem do telegram
Eu preciso abrir uma ordem de trailingstop 10% e colocar um stoploss de 20%

Mas a ordem executa aparece o breakeven que se comporta de forma diferente e o stop não fecha minha posição

The code is complete
After receiving the telegram message
I need to open a 10% trailingstop order and place a 20% stoploss

But the order is executed and the breakeven appears, which behaves differently and the stop does not close my position

from telegram.ext import Updater, MessageHandler, Filters
from binance.client import Client
from binance.helpers import round_step_size
import ccxt
import re

def extract_trade_info(message_text):
# Usando expressão regular para extrair o símbolo
match = re.search(r’:bar_chart:\s+(\S+)', message_text)
if match:
symbol = match.group(1)
else:
print(“Não foi possível extrair o símbolo.”)
return None

action_line = [line for line in message_text.split('\n') if '🔴' in line or '🟢' in line]
if not action_line:
    print("Não foi possível encontrar a linha de ação.")
    return None

action = action_line[0].split()[1].upper()
target_price = float(re.search(r'🎯\s+([\d.]+)', message_text).group(1))

return symbol, action, target_price

def get_tick_size(symbol, client):
info = client.futures_exchange_info()
for item in info[‘symbols’]:
if item[‘symbol’] == symbol:
for f in item[‘filters’]:
if f[‘filterType’] == ‘PRICE_FILTER’:
return float(f[‘tickSize’])

def get_rounded_price(symbol, price, client):
tick_size = get_tick_size(symbol, client)
return round_step_size(price, tick_size)

def calculate_stop_loss_and_gain(current_price, stop_loss_percentage, take_profit_percentage):
stop_loss_price = current_price * (1 - stop_loss_percentage / 100)
take_profit_price = current_price * (1 + take_profit_percentage / 100)
return stop_loss_price, take_profit_price

def message_handler(update, context):
print(“Handling message:”, update.effective_message.text)

chat_id = update.effective_chat.id
message_text = update.effective_message.text
print(f"Nova mensagem no grupo {chat_id}: {message_text}")

# Criar instância do cliente Binance
binance_api_key = 'API'
binance_api_secret = 'SECRET'
client = Client(binance_api_key, binance_api_secret)

# Inicializa current_price com 0
current_price = 0

# Tentar extrair informações
trade_info = extract_trade_info(message_text)
if trade_info:
    print(f"Informações extraídas: {trade_info}")

    # Desempacota as informações da ordem
    symbol = trade_info[0]
    action = trade_info[1]
    target_price = trade_info[2]

    # Adapte os valores conforme necessário
    amount = 0.1  # Valor desejado
    leverage = 30  # Alavancagem desejada
    stop_loss_percentage = 0.02  # Porcentagem para o stop loss
    stop_loss_price = current_price * (1 - stop_loss_percentage / 100)
    take_profit_percentage = 0.02  # Porcentagem para o take profit (stop gain)
    activate_price_percentage = 1.5  # Substitua pelo valor desejado
    activate_price = current_price * (1 + activate_price_percentage / 100)       
    
    
    try:
        # Conecta-se à API da Binance usando a ccxt para o mercado futuro
        exchange = ccxt.binance({
            'apiKey': binance_api_key,
            'secret': binance_api_secret,
            'future': {
                'enableRateLimit': True,
                'defaultType': 'future',
            },
        })
    

        # Adiciona 'USDT' ao símbolo se não estiver presente
        if 'USDT' not in symbol:
            symbol_with_usdt = f"{symbol}USDT"
        else:
            symbol_with_usdt = symbol

        try:
            ticker = exchange.fetch_ticker(symbol_with_usdt)
            current_price = ticker['ask']  # last

            current_price = get_rounded_price(symbol_with_usdt, current_price, client)

            stop_loss_price, take_profit_price = calculate_stop_loss_and_gain(current_price, stop_loss_percentage, take_profit_percentage)

            # Inicialize a variável stop_loss_order
            stop_loss_order = None

            # Obtenha o preço médio atual
            price = float(client.get_avg_price(symbol=symbol)['price'])

            # Obtenha o tick_size usando a função get_tick_size
            tick_size = get_tick_size(symbol, client)

            # Defina a porcentagem desejada para o stop loss
            stop_loss_percent = 5 / 20

            # Calcule o novo stopPrice
            stopPrice = round_step_size(price - (price * (stop_loss_percent / 100)), tick_size)

            # Configurações específicas do mercado futuro
            symbol_with_usdt = symbol_with_usdt.upper()  # Garante que o símbolo esteja em maiúsculas
            side = 'BUY' if action == 'CALL' else 'SELL'

            # Ajustar a precisão do preço
            stop_loss_price = round(current_price * (1 - stop_loss_percentage / 100), 2)

            # Ajuste adicional para garantir que o stopPrice não acione imediatamente
            if stopPrice >= price:
                stopPrice = price - tick_size  # Subtrair um tick para garantir uma diferença mínima

            # Ajustar a precisão da quantidade
            #amount = round(amount, 3)
            # Obtenha o preço atual do ativo
            ticker = client.futures_ticker(symbol='BTCUSDT')
            current_price = float(ticker['lastPrice'])

            # Calcule o preço para o trailing stop 10% acima do preço atual
            stop_price_percent_above = 0.1
            stop_price = current_price * (1 + stop_price_percent_above)

            # Calcule o preço de ativação para o trailing stop 10% acima do preço atual
            activation_price_percent_above = 0.1
            activation_price = current_price * (1 + activation_price_percent_above)


            try:
                # Coloca a ordem limitada com trailing stop
                response = client.futures_create_order(
                    symbol=symbol_with_usdt,
                    side=side,
                    type='TRAILING_STOP_MARKET',  # TRAILING_STOP_MARKET ou MARKET
                    quantity=amount,
                    callbackRate=0.1,
                    # callbackRate=0.02,  # Taxa de callback para o trailing stop
                    stopPrice=stop_price,  # Preço de stop loss
                    activationPrice=activation_price,
                    workingType='CONTRACT_PRICE',

                    #activatePrice=None,
                    priceRate=0.2  # Taxa de callback para o trailing stop (2%)
                )

                # Configuração do Stop Loss fixo
                response_stop_loss = client.futures_create_order(
                    symbol=symbol_with_usdt,
                    side=side,
                    type='STOP_MARKET_TRIGGER',  # Ou outro tipo de ordem, dependendo do seu caso
                    quantity=0.01,
                    stopPrice=stopPrice
                )

                print(f"Ordem colocada com trailing stop: {response}")
                print(f"Stop Loss configurado: {stop_loss_order}")

            except Exception as e:
                print(f"Erro ao colocar a ordem: {e}")

        except ccxt.NetworkError as e:
            print(f"Erro de rede ao conectar à API da Binance: {e}")

        except ccxt.ExchangeError as e:
            print(f"Erro de câmbio ao conectar à API da Binance: {e}")

        except ccxt.BaseError as e:
            print(f"Erro genérico ao conectar à API da Binance: {e}")

    except Exception as e:
        print(f"Erro ao conectar à API da Binance: {e}")

Restante do código

def main():
token = ‘####’ # Substitua pelo seu token
chat_id = -#### # Substitua pelo chat_id do seu grupo

updater = Updater(token, use_context=True)
dp = updater.dispatcher

# Adiciona o manipulador de mensagens para todas as mensagens de texto
dp.add_handler(MessageHandler(Filters.text, message_handler))

# Inicia o bot
updater.start_polling()
updater.idle()

if name == ‘main’:
main()

Hi,
I’m sorry but it’s hard for us to identify your issue(s) as this is mostly a programming question mixed with knowledge of the trailing type of order. It’s better if you could test isolated sections/scenarios of your code and debug locally.

If helpful, there’s Futures Testnet available at https://testnet.binancefuture.com/en/futures/BTCUSDT, which you can register and obtain the API keys from the “API Key” tab to test your code without actual losses.

For specific API questions, please feel free to comment here. If it’s knowledge about how the Trailing Order works, you can also publish here as well, we can see how far we can help. Another option, would be the customer support.

1 Like

hello ,
Thank you very much for taking care of my code, have a merry Christmas.
I think it’s better to tell you about my project.
1 I receive a message on Telegram
2 The Bot extracts the information from the Telegram message, Asset / Direction / Price.
3 the Bot sends the order to binance,
the Order must be in the futures market, at trailingStop, with a stoploss of 10% and the trailingstop follows the price every 10%

my code is about that.