### I couldn’t able to set stop loss and take profit while I am making a new bot to automate the BTC buy and sell function in Binance. However, when I make the buy or sell the order is set but it doesn’t set the stop loss and take profit. I set the stop loss and take profit
`from binance.client import Client
import time
API_KEY =
API_SECRET =
client = Client(API_KEY, API_SECRET)
def get_current_price(symbol):
ticker = client.get_symbol_ticker(symbol=symbol)
if 'price' in ticker:
return float(ticker['price'])
else:
return None
def calculate_required_margin(quantity, price, leverage):
return (quantity * price) / leverage
def get_account_balance():
account_info = client.futures_account()
if 'totalWalletBalance' in account_info:
total_wallet_balance = float(account_info['totalWalletBalance'])
return total_wallet_balance
else:
return None
def get_symbol_precision(symbol):
symbol_info = client.get_symbol_info(symbol)
base_precision = int(symbol_info.get('baseAssetPrecision', 0))
price_precision = int(symbol_info.get('pricePrecision', 0))
return base_precision, price_precision
def format_price(price, symbol):
base_precision, price_precision = get_symbol_precision(symbol)
return round(price, price_precision)
def format_quantity(quantity, symbol):
base_precision, _ = get_symbol_precision(symbol)
return round(quantity, base_precision)
def create_cross_order(
symbol,
side,
quantity,
leverage,
position_side,
take_profit_percent,
stop_loss_percent,
stop_price=None,
trailing_stop=None,
iceberg_qty=None
):
current_price = get_current_price(symbol)
if current_price is None:
print('Failed to fetch current price.')
return
required_margin = calculate_required_margin(quantity, current_price, leverage)
total_wallet_balance = get_account_balance()
if total_wallet_balance is None:
print("Failed to fetch account balance.")
return
if total_wallet_balance < required_margin:
print("Insufficient balance for required margin.")
return
take_profit_price = format_price(current_price * (1 + take_profit_percent / 100), symbol)
stop_loss_price = format_price(current_price * (1 - stop_loss_percent / 100), symbol)
order_params = {
'symbol': symbol,
'side': side,
'positionSide': position_side,
'quantity': format_quantity(quantity, symbol),
'price': format_price(current_price, symbol),
'type': 'LIMIT',
'timeInForce': 'GTC',
'leverage': leverage,
'stopPrice': format_price(stop_price, symbol) if stop_price else None,
'closePosition': False, # Ensure closePosition is set to False
'stopLimitPrice': format_price(stop_price, symbol) if stop_price else None,
'activationPrice': format_price(stop_price, symbol) if stop_price else None,
'activationPriceType': 'LAST_PRICE',
'stopPriceType': 'LIMIT',
'workingType': 'MARK_PRICE',
'priceProtect': False,
'newOrderRespType': 'RESULT',
'timestamp': int(time.time() * 1000),
}
if trailing_stop is not None:
order_params['activationPriceType'] = 'TRIGGER'
order_params['stopPriceType'] = 'TRAILING_STOP_MARKET'
order_params['activationPrice'] = None
order_params['stopPrice'] = None
order = client.futures_create_order(**order_params)
if 'orderId' in order:
print("Order Details:")
print(f"Symbol: {order['symbol']}")
print(f"Side: {order['side']}")
print(f"Quantity: {order['origQty']} {order['symbol']}")
print(f"Price: {order['price']}")
print(f"Take Profit Price: {take_profit_price}")
print(f"Stop Loss Price: {stop_loss_price}")
return order
else:
print("Failed to create order.")
return None
# Show account balance
total_wallet_balance = get_account_balance()
if total_wallet_balance is not None:
print(f"Total Wallet Balance: {total_wallet_balance} USDT")
else:
print("Failed to fetch account balance.")
# Create order with take profit of 1.5% and stop loss of 2%, and optional parameters
symbol = 'BTCUSDT'
side = 'BUY' # Change this to 'SELL' if you're opening a short position
quantity = 0.001
leverage = 10 # Leverage x10
position_side = 'LONG' # Change this to 'SHORT' if opening a short position
take_profit_percent = 1.5
stop_loss_percent = 2.0
stop_price_value = None # Replace with your desired stopPrice value if needed
trailing_stop_value = None # Replace with your desired trailing stop value if needed
iceberg_qty_value = None # Replace with your desired icebergQty value if needed
response = create_cross_order(
symbol,
side,
quantity,
leverage,
position_side,
take_profit_percent,
stop_loss_percent,
stop_price=stop_price_value,
trailing_stop=trailing_stop_value,
iceberg_qty=iceberg_qty_value
)
if response is not None:
print(response)
the output
root@localhost:~# python3 1.py
Total Wallet Balance: 10.19490266 USDT
Order Details:
Symbol: BTCUSDT
Side: BUY
Quantity: 0.001 BTCUSDT
Price: 25836.00
Take Profit Price: 26223.0
Stop Loss Price: 25319.0
{‘orderId’: 186876312282, ‘symbol’: ‘BTCUSDT’, ‘status’: ‘FILLED’, ‘clientOrderId’: ‘kY27wVpixbnXj0BamAxDSD’, ‘price’: ‘25836.00’, ‘avgPrice’: ‘25821.70000’, ‘origQty’: ‘0.001’, ‘executedQty’: ‘0.001’, ‘cumQty’: ‘0.001’, ‘cumQuote’: ‘25.82170’, ‘timeInForce’: ‘GTC’, ‘type’: ‘LIMIT’, ‘reduceOnly’: False, ‘closePosition’: False, ‘side’: ‘BUY’, ‘positionSide’: ‘LONG’, ‘stopPrice’: ‘0.00’, ‘workingType’: ‘CONTRACT_PRICE’, ‘priceProtect’: False, ‘origType’: ‘LIMIT’, ‘updateTime’: 1693832035870}
root@localhost
@2pd @chusri @elidioxg @AlfonsoAgAr @bnbot