-3

I have a problem running the code properly.. From what I have checked and referenced... I set TP and SL at 0.5% compared to the entry price. Instead, he does not send them to me, receiving the following message:

Successfully executed BUY market order for BTC. Order ID: 180671918942 Error placing stop loss order: APIError(code=-2021): Order would immediately trigger. Error placing take profit order: APIError(code=-2021): Order would immediately trigger.

The code places my market buy but without TP and SL

The telegram message is in the form:

LONG BTC SHORT BTC

etc.

My code is:

from typing import Final
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
from binance.client import Client
from binance.exceptions import BinanceAPIException

TOKEN: Final = '....'
BOT_USERNAME: Final = '....'
BINANCE_API_KEY = '...'
BINANCE_API_SECRET = '...'

client = Client(BINANCE_API_KEY, BINANCE_API_SECRET)

def execute_stop_loss_order(direction: str, coin: str, stop_price: str) -> str:
    side = 'SELL' if direction == 'SHORT' else 'BUY'
    symbol = f'{coin}USDT'
    try:
        order = client.futures_create_order(
            symbol=symbol,  
            side=side,
            type='STOP_MARKET',
            stopPrice=stop_price,
            closePosition='true'
        )
        return f'Successfully placed stop loss order for {coin}.\nOrder ID: {order["orderId"]}'
    except Exception as e:
        return f'Error placing stop loss order: {str(e)}'

def execute_take_profit_order(direction: str, coin: str, take_profit_price: str) -> str:
    side = 'SELL' if direction == 'SHORT' else 'BUY'
    symbol = f'{coin}USDT'
    try:
        order = client.futures_create_order(
            symbol=symbol,
            side=side,
            type='TAKE_PROFIT_MARKET',
            stopPrice=take_profit_price,
            closePosition='true'
        )
        return f'Successfully placed take profit order for {coin}.\nOrder ID: {order["orderId"]}'
    except Exception as e:
        return f'Error placing take profit order: {str(e)}'

def get_quantity_precision(symbol: str) -> int:
    exchange_info = client.futures_exchange_info()
    for symbol_info in exchange_info['symbols']:
        if symbol_info['symbol'] == symbol:
            return symbol_info['quantityPrecision']
    return 0  # Dacă nu găsim simbolul, folosim o precizie implicită de 0

def execute_market_order_with_tp_sl(direction: str, coin: str, usd_amount: float, leverage: int) -> str:
    side = 'SELL' if direction == 'SHORT' else 'BUY'
    symbol = f'{coin}USDT'

    ticker = client.get_ticker(symbol=symbol)
    entry_price = float(ticker['lastPrice'])

    coin_amount = usd_amount / entry_price

    quantity_precision = get_quantity_precision(symbol)
    coin_amount = round(coin_amount, quantity_precision)

    try:
        order = client.futures_create_order(
            symbol=symbol,
            side=side,
            type='MARKET',
            quantity=coin_amount,
            leverage=leverage
        )

        # Calculează prețurile pentru stop loss și take profit (0.5% față de entry price)
        stop_loss_price = round(entry_price * 0.995, 2)  # Rotunjire la 2 zecimale
        take_profit_price = round(entry_price * 1.005, 2)  # Rotunjire la 2 zecimale
    
        # Plasează ordinele de stop loss și take profit
        stop_loss_response = execute_stop_loss_order(direction, coin, stop_price=str(stop_loss_price))
        take_profit_response = execute_take_profit_order(direction, coin, take_profit_price=str(take_profit_price))
        
        # Returnează un răspuns care include confirmările pentru toate comenzile
        response = f'Successfully executed {side} market order for {coin}.\nOrder ID: {order["orderId"]}\n{stop_loss_response}\n{take_profit_response}'
        return response
    except Exception as e:
        return f'Error executing order: {str(e)}'

async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('Welcome! I am our automated trading bot for Binance Futures. With me, you can automate trades based on signals from your Telegram group. I will guide you through settings and features. To get started, choose one of the options below. ')

async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('Display this list of available instructions.')

def handle_response(text: str) -> str:
    processed: str = text.lower()

    if 'hello' in processed:
        return 'Hei there!'
    
    if 'how are you' in processed:
        return 'I am good'
    
    if 'i love python' in processed:
        return 'Remember to subscribe'
    
    return "I do not understand what you wrote..."

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    text: str = update.message.text
    processed_text = text.strip().upper()

    print(f'User ({update.message.chat.id}) in {update.message.chat.type}: "{text}"')

    if processed_text.startswith('SHORT') or processed_text.startswith('LONG'):
        parts = processed_text.split()
        direction = parts[0]
        coin = parts[1]

        if direction in ['SHORT', 'LONG'] and coin in ['BTC', 'ETH','SOL','EGLD']:
            response = execute_market_order_with_tp_sl(direction, coin, usd_amount=50, leverage=9)
        else:
            response = "Invalid direction or coin."
    else:
        response = handle_response(text)

    print('Bot:', response)
    await update.message.reply_text(response)

async def error(update: Update, context: ContextTypes.DEFAULT_TYPE):
    print(f'Update {update} caused error {context.error}')

if __name__ == '__main__':
    print('Starting bot...')
    app = Application.builder().token(TOKEN).build()

    app.add_handler(CommandHandler('start', start_command))
    app.add_handler(CommandHandler('help', help_command))
    
    app.add_handler(MessageHandler(filters.TEXT, handle_message))

    app.add_error_handler(error)

    print('Polling...')
    app.run_polling(poll_interval=3)


I tried everything possible. I can't really manage to read the API documentation as it should.

Do you have any solution for my error? Please a lot

Thank you!

0 Answers0