Coder Social home page Coder Social logo

binance-toolbox-python's People

Contributors

2pd avatar aisling11 avatar chairz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

binance-toolbox-python's Issues

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

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



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
image
image

@2pd @aisling11 @chairz @bnbot

SSL verification failing

Hey I wanted to use some of this code to compare to mine and see if the issue I'm having lies in my implementation. I just installed binance-connector on a new conda enviroment and I cant seem to connect to any of binance's servers. My code uses the standard requests library for the REST endpoint and websocket-client library for handling websockets and I don't get any of these issues.
Anyway I keep getting this error (theres a refrence to it here : ccxt/ccxt#882 with even more refrencing it but no solutions that worked at least for me):
WARNING:root:WebSocket connection closed: connection was closed uncleanly (SSL error: certificate verify failed (in tls_process_server_certificate)), code: 1006, clean: False, reason: connection was closed uncleanly (SSL error: certificate verify failed (in tls_process_server_certificate))
ERROR:root:Lost connection to Server. Reason: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionDone'>: Connection was closed cleanly.]. Retrying: 1

Any help would be greatly appreciated as after searching around and googling I went so far as to uninstall anaconda, remove any left over files including my previous environments, reinstall anaconda and all necessary packages and previous environments and still nothing.

Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.