binance / binance-futures-connector-python

Simple python connector to Binance Futures API
MIT License
863 stars 238 forks source link

Can not set stop loss / take profit, error ‘Order does not exist’ #137

Closed Najmulhaq1997 closed 1 year ago

Najmulhaq1997 commented 1 year ago

I have an issue is the TP/SL function not reading the Binance side could you please help me to resolve this issues

import requests
import hashlib
import hmac
import time

API_KEY = 'g'
API_SECRET = 'h'

def get_current_price(symbol):
    base_url = 'https://fapi.binance.com'
    endpoint = '/fapi/v1/ticker/price'

    params = {
        'symbol': symbol
    }

    response = requests.get(f'{base_url}{endpoint}', params=params)
    data = response.json()

    if 'price' in data:
        return float(data['price'])
    else:
        return None

def calculate_required_margin(quantity, price, leverage):
    return (quantity * price) / leverage

def get_account_balance():
    base_url = 'https://fapi.binance.com'
    endpoint = '/fapi/v2/account'

    params = {
        'timestamp': int(time.time() * 1000)
    }

    signature = hmac.new(API_SECRET.encode('utf-8'), '&'.join([f'{k}={v}' for k, v in params.items()]).encode('utf-8'), hashlib.sha256).hexdigest()

    headers = {
        'X-MBX-APIKEY': API_KEY
    }

    url = f'{base_url}{endpoint}?timestamp={params["timestamp"]}&signature={signature}'

    response = requests.get(url, headers=headers)
    return response.json()

def create_cross_order(symbol, side, quantity, leverage, position_side, take_profit_percent, stop_loss_percent):
    base_url = 'https://fapi.binance.com'
    endpoint = '/fapi/v1/order'

    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)

    # Fetch account information to check available balance
    account_info = get_account_balance()
    if 'totalWalletBalance' in account_info:
        total_wallet_balance = float(account_info['totalWalletBalance'])
        if total_wallet_balance < required_margin:
            print("Insufficient balance for required margin.")
            return
    else:
        print("Failed to fetch account balance.")
        return

    # Calculate take profit and stop loss prices
    take_profit_price = current_price * (1 + take_profit_percent / 100)
    stop_loss_price = current_price * (1 - stop_loss_percent / 100)

    params = {
        'symbol': symbol,
        'side': side,
        'positionSide': position_side,
        'quantity': quantity,
        'price': current_price,
        'type': 'LIMIT',
        'timeInForce': 'GTC',
        'leverage': leverage,
        'timestamp': int(time.time() * 1000),
        'takeProfit': take_profit_price,
        'stopLoss': stop_loss_price
    }

    query_string = '&'.join([f'{k}={v}' for k, v in params.items()])
    signature = hmac.new(API_SECRET.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

    headers = {
        'X-MBX-APIKEY': API_KEY
    }

    url = f'{base_url}{endpoint}?{query_string}&signature={signature}'

    response = requests.post(url, headers=headers)
    return response.json()

# Show account balance
balance_response = get_account_balance()
if 'totalWalletBalance' in balance_response:
    print(f"Total Wallet Balance: {balance_response['totalWalletBalance']} USDT")
else:
    print("Failed to fetch account balance.")

# Create order with take profit of 1.5% and stop loss of 2%
symbol = 'BTCUSDT'
side = 'BUY'  # Change this to 'SELL' if you're opening a short position
quantity = 0.01
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
response = create_cross_order(symbol, side, quantity, leverage, position_side, take_profit_percent, stop_loss_percent)
if response is not None:
    print(response)

image

root@localhost:

root@localhost:-# ls

cron.sh. Ex test test2.py test.py

root@localhost:-# vi test2.py

root@localhost:-# python3 test2.py

Total Wallet Balance: 10.37452555 USDT

Order Details:

Symbol: BTCUSDT

Side: BUY

Quantity: 0.001 BTCUSDT

Price: 25882.18

Take Profit Price: 26278.331499999997

Stop Loss Price: 25364.458

{'orderId': 186536328011, symbol': 'BTCUSDT, 'status': 'NEW', 'clientOrderId: 87qlv5fгUAFCvShHsYbCz1', 'price': '25882.18, avgPrice': '0.00', 'origQty': '0.801', 'executedQty: 8.888', 'cumoty: 8.000' 'cumQuote': '0.00000', 'timeInForce': 'GTC', 'type': 'LIMIT', 'reduceonly': False, 'closePosition': False, 'side': 'BUY', 'positionSide': 'LONG', 'stopPrice': '0.00', 'workingType': 'CONTRACT PRICE, pricep rotect: False, 'origType': 'LIMIT, 'updateTime: 1693718623738} root@localhost:-# image image

@2pd @chusri @elidioxg @AlfonsoAgAr @bnbot

2pd commented 1 year ago

Unfortunately TP/SL is not supported by API.