1
votes

I currently have a python bot im using to connect to the binance API and make trades with. I am using it with binance(dot)com, but I have a friend who wants to implement it with his binance(dot)us account. I looked into some of the documentation, and it said that the client must be specified to the US version, like so: "client = Client(API_KEY, API_SEC, tld='us')"

Even still, i am getting an error when running the script, like this:

Traceback (most recent call last):
  File "/home/kali/.local/lib/python3.10/site-packages/ccxt/base/exchange.py", line 658, in fetch
    response.raise_for_status()
  File "/usr/lib/python3/dist-packages/requests/models.py", line 960, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error:  for url: https://api.binance.com/sapi/v1/capital/config (...)

And here are the packages I am using currently:

import math
import sys
from binance.client import Client
import websocket
import json
import time
import ccxt
import threading
import decimal

Please let me know what else I have to change in order for this to work, thanks

import math
import sys
from binance.client import Client
import websocket
import json
import time
import ccxt
import threading
import decimal

PER_ORDER_BUY = 25  # ORDER LIMITATON IN TERMS OF $USD$

# Private IDs,Tokens, settings

# websocket.enableTrace(True)
API_KEY = "" # Binance API KEY
API_SEC = "" # Binance API SECRET


# Order Placement Program START

order_queue = []
session_id = ""
last_seq = "null"

global buy_amount
global ponged
ponged = False
global heartbeat_thread

buy_amount = PER_ORDER_BUY
global connection_lost
connection_lost = False

api_key = API_KEY
api_sec = API_SEC

# Setting up exchange Client
exchange = ccxt.binance({
    'enableRateLimit': True,
    'options': {
        # 'defaultType': 'future',
        'adjustForTimeDifference': True
    },
    "apiKey": api_key,
    "secret": api_sec
})

# To test in sandbox mode
# exchange.set_sandbox_mode(True)

# Loading market data
markets = exchange.load_markets()


# To Open Market Order
def open_market_order(order):
    current_price = fetch_current_price(order['ticker'])
    global buy_amount
    if current_price is not None:
        if order['ticker'][-4:] == "USDT":
            volume = buy_amount / current_price
        else:
            volume = calculate_buy_amount() / float(current_price)

        # print(volume)
        # change_leverage(order['ticker'], order['leverage'])
        # change_leverage_type(order['ticker'], 'ISOLATED')

        for i in range(3):

            try:

                place_order = exchange.create_market_buy_order(order['ticker'], volume)

                if place_order['info']['status'] == 'FILLED':
                    # print("New Order Placed --> ", place_order)
                    volume_filled = place_order['info']['executedQty']
                    # print("Volume Filled was --> ", volume_filled)
                    # Place limit sell orders
                    return open_limit_sell_order(order, volume_filled)
                break

            except Exception as e:
                print(e)
                print(f"An Error Occured while opening BUY position for {order['ticker']}")
                print("Trying Againg in 15 seconds...")
                time.sleep(15)

        else:
            return False

    else:
        return False


# To open Limit orders for Takeprofit positions


def open_limit_sell_order(order, volume):
    tp_target = (order['exit']['tp1'] + order['exit']['tp2']) / 2
    for i in range(3):
        try:
            client = Client(API_KEY, API_SEC, tld='us')
            client.order_oco_sell(symbol=order['ticker'].replace("/", ""), quantity=volume, price=normalize_float(tp_target), stopPrice=normalize_float(order['stoploss'])
                                  , stopLimitPrice=normalize_float(order['stoploss']), stopLimitTimeInForce="GTC")
            #open_order = exchange.create_limit_sell_order(order['ticker'], volume, tp_target)
            #return set_stoploss(order, volume)
            client.close_connection()
            del client
            return True
        except Exception as e:
            print("Error: ", e)
            print("Price: ", normalize_float(volume))
            print("Quantity : " ,volume, "AND", normalize_float(volume))
            print("Stop-Loss: ", normalize_float(order['stoploss']))
            print(f"An Error Occured while opening SELL position for {order['ticker']}")
            print("Trying Againg in 15 seconds...")
            time.sleep(15)

    else:
        return False


# To open Stoploss Order
def set_stoploss(order, volume):
    for i in range(3):

        try:
            stop_loss_params = {'stopPrice': order['stoploss']}
            place_stoploss = exchange.create_order(order['ticker'], 'STOP_LOSS_LIMIT', 'sell', volume, order['stoploss']
                                                   , stop_loss_params)
            return True

        except Exception as e:
            print(e)
            print("Error Occured while placing Stoploss order trying again in 15 secs")
            time.sleep(15)
    else:

        return False


# To fetch current price of the Pair/symbol


def fetch_current_price(ticker):
    for i in range(3):

        try:

            current_price = exchange.fetch_ticker(ticker)

            return current_price["last"]

        except Exception as e:
            print(f"Error occured while fetching price data for : {ticker}")
            time.sleep(3)

    else:
        return None


# To Check weather the coin is available on Binance and add order in pending orders array


def check_coin(new_order):
    exchange.load_markets()

    avail_markets = exchange.markets
    coin_name = (new_order['ticker']).replace("/", '')

    symbols = [avail_markets[x]['id'] for x in avail_markets]

    # print("Symbol: ", symbols)

    if coin_name in symbols:

        if len(order_queue) < 10:

            order_queue.append(new_order)
            print(f"Trade for {coin_name} has been added to Pending Order List")

        else:
            print("New order can't be accepted 10 orders are already in the queue")

    else:
        print(f"Coin {coin_name} is not availble to trade on binance")


# Check Price of the order to execute


def check_price(order):
    entry_price = max(order['entry'])
    other_price = match_precision(entry_price, 1)
    entry_price += other_price
    current_price = fetch_current_price(order['ticker'])
    #print("Entry: %s, %s, %s\nCurrent Price: %s, %s, %s" % (entry_price, normalize_float(entry_price), match_precision(current_price, entry_price),
    #                                                        current_price, normalize_float(current_price), match_precision(current_price, entry_price)))
    if current_price is not None:
        if current_price <= entry_price:
            print("market order")
            return open_market_order(order)
        else:
            return None

    else:
        return None


# Main thread to continuously checking the pending orders
def start_order_placement_thread():
    while True:
        try:
            if len(order_queue) > 0:
                for order in range(len(order_queue)):
                    p_order = check_price(order_queue[order])

                    if p_order:

                        print("A new order successfully placed --> ", order_queue[order])
                        order_queue.pop(order)

                    elif not p_order:

                        print("Error Occured while placing order --> ", order_queue[order])
                        order_queue.pop(order)

            else:
                print("No Pending orders")
        except:
            pass
        finally:
            time.sleep(8)

Shouldn't you be hitting api.binance.us instead of api.binance.com?wkl
How do I change that, I wasnt able to find it on the binance documentation page, but that was something i noticed. I thought maybe they designed it to see 'tld=us' and redirect to the binance.us urlCryptomogul
it's hard to give you feedback w/out sharing codeSchalton
i can add the binance api portion of itCryptomogul