Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

I used this code: import time from binance.client import Client from binance.enums…

  1. User

    I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException from binance.helpers import round_step_size import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import ccxt

    Get the current time and timestamp

    now = dt.datetime.now() date = now.strftime("%m/%d/%Y %H:%M:%S") print(date)

    timestamp = int(time.time() * 1000)

    API keys and other configuration

    API_KEY = '' API_SECRET = ''

    client = Client(API_KEY, API_SECRET)

    STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' quantity = 1 symbol = 'BTC/USDT' order_type = 'market' leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ 'apiKey': '', 'secret': '', 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True },'future': { 'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc… } })

    binance_futures = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True } })

    Load the market symbols

    try: markets = binance_futures.fetch_markets() except ccxt.BaseError as e: print(f'Error fetching markets: {e}') markets = []

    if symbol in markets: print(f"{symbol} found in the market") else: print(f"{symbol} not found in the market")

    Get server time and time difference

    def get_server_time(exchange): server_time = exchange.fetch_currencies() return server_time['timestamp']

    def get_time_difference(): server_time = get_server_time(binance_futures) local_time = int(time.time() * 1000) time_difference = local_time - server_time return time_difference time.sleep(1)

    def get_klines(symbol, interval, lookback): url = "https://fapi.binance.com/fapi/v1/klines" end_time = int(time.time() * 1000) # end time is now start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago symbol = symbol.replace("/", "") # remove slash from symbol query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } try: response = requests.get(url + query_params, headers=headers) response.raise_for_status() data = response.json() if not data: # if data is empty, return None print('No data found for the given timeframe and symbol') return None ohlc = [] for d in data: timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S') ohlc.append({ 'Open time': timestamp, 'Open': float(d[1]), 'High': float(d[2]), 'Low': float(d[3]), 'Close': float(d[4]), 'Volume': float(d[5]) }) df = pd.DataFrame(ohlc) df.set_index('Open time', inplace=True) return df except requests.exceptions.RequestException as e: print(f'Error in get_klines: {e}') return None df = get_klines(symbol, '1m', 89280)

    def signal_generator(df): if df is None: return "" open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2]

    # Bearish pattern
    if (open>close and
    previous_open<previous_close and
    close<previous_open and
    open>=previous_close):
        return 'sell'
    
    # Bullish pattern
    elif (open<close and
    previous_open>previous_close and
    close>previous_open and
    open<=previous_close):
        return 'buy'
    
    # No clear pattern
    else:
        return ""
    

    df = get_klines(symbol, '1m', 89280) def order_execution(symbol, signal, step_size, leverage, order_type): # Close any existing positions leverage = '100x' current_position = None positions = binance_futures.fapiPrivateGetPositionRisk() for position in positions: if position["symbol"] == symbol: current_position = position if current_position is not None and current_position["positionAmt"] != 0: binance_futures.fapiPrivatePostOrder( symbol=symbol, side='SELL' if current_position["positionSide"] == "LONG" else 'BUY', type='MARKET', quantity=abs(float(current_position["positionAmt"])), positionSide=current_position["positionSide"], reduceOnly=True ) time.sleep(1)

    # Calculate appropriate order quantity and price based on signal
    opposite_position = None
    quantity = step_size
    position_side = None #initialze to None
    price = None
    
    # Set default take profit price
    take_profit_price = None
    stop_loss_price = None
    
    if signal == 'buy':
        position_side = 'BOTH'
        opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
        order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
        ticker = binance_futures.fetch_ticker(symbol)
        price = 0 # default price
        if 'askPrice' in ticker:
            price = ticker['askPrice']
            # perform rounding and other operations on price
        else:
            # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
            take_profit_percentage = TAKE_PROFIT_PERCENTAGE
            stop_loss_percentage = STOP_LOSS_PERCENTAGE
    
    elif signal == 'sell':
        position_side = 'BOTH'
        opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
        order_type = FUTURE_ORDER_TYPE_STOP_MARKET
        ticker = binance_futures.fetch_ticker(symbol)
        price = 0 # default price
        if 'askPrice' in ticker:
            price = ticker['askPrice']
            # perform rounding and other operations on price
        else:
        # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
            take_profit_percentage = TAKE_PROFIT_PERCENTAGE
            stop_loss_percentage = STOP_LOSS_PERCENTAGE
    
        # Set stop loss price
        stop_loss_price = None
        if price is not None:
            try:
                price = round_step_size(price, step_size=step_size)
                if signal == 'buy':
                    # Calculate take profit and stop loss prices for a buy signal
                    take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
                    stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
                elif signal == 'sell':
                    # Calculate take profit and stop loss prices for a sell signal
                    take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
                    stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
            except Exception as e:
                print(f"Error rounding price: {e}")
    
    # Reduce quantity if opposite position exists
    if opposite_position is not None:
        if abs(opposite_position['positionAmt']) < quantity:
            quantity = abs(opposite_position['positionAmt'])
    
    # Update position_side based on opposite_position and current_position
    if opposite_position is not None:
        position_side = opposite_position['positionSide']
    elif current_position is not None:
        position_side = current_position['positionSide']
    
    # Place order
    order_params = {
        "type": "MARKET" if signal == "buy" else "MARKET",
        "side": "BUY" if signal == "buy" else "SELL",
        "amount": quantity,
        "price": price,
        "params": {
            "leverage": leverage
        }
    }
    
    try:
        order_params['symbol'] = symbol
        response = binance_futures.create_order(**order_params)
        print(f"Order details: {response}")
    except BinanceAPIException as e:
        print(f"Error in order_execution: {e}")
        time.sleep(1)
        return
    

    signal = signal_generator(df) while True: df = get_klines(symbol, '1m', 89280) # await the coroutine function here if df is not None: signal = signal_generator(df) if signal is not None: print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}") if signal: order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type) time.sleep(0.1) But I getting ERROR: The signal time is: 2023-06-07 18:18:02 :sell Traceback (most recent call last): File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 560, in fetch response.raise_for_status() File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://fapi.binance.com/fapi/v1/order

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 257, in order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type) File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 243, in order_execution response = binance_futures.create_order(**order_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 4215, in create_order response = getattr(self, method)(self.extend(request, requestParams)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method return _self.request(self.path, self.api, self.method, params, config=self.config) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7409, in request response = self.fetch2(path, api, method, params, headers, body, config) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2819, in fetch2 return self.fetch(request['url'], request['method'], request['headers'], request['body']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 576, in fetch skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7386, in handle_errors self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback) File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3169, in throw_exactly_matched_exception raise exactstring ccxt.base.errors.InvalidOrder: binance {"code":-2027,"msg":"Exceeded the maximum allowable position at current leverage."} , please if it possible give me right code

  2. Assistant

    Based on the error message, it seems like you are trying to exceed the maximum allowable position at the current leverage. You can try reducing the position size or leverage to resolve this issue. Here are a few other things you can try:

    1. Check your API keys and ensure that they are correct and have the required permissions for the actions you are trying to perform.
    2. Double-check the symbol you are trading. Make sure it is spelled correctly and is valid for the exchange.
    3. Review the order parameters and ensure they are correctly set.
    4. Check your account balance and ensure you have enough funds to place the order.
    5. Consider adding error handling and logging to your code to make it easier to debug issues like these.
  3. User

    I think this ERROR is comming of order_parameters, how my order_parameters need to seem ?

  4. Assistant

    Your order parameters should be set correctly according to the Binance API documentation. Here is an example of what your order parameters might look like:

    order_params = {
        'symbol': 'BTC/USDT',
        'side': 'BUY',
        'type': 'LIMIT',
        'timeInForce': 'GTC',
        'quantity': '0.001',
        'price': '50000',
    }
    

    Note that the parameters will differ depending on the order type you are using (e.g. market, limit, stop-loss, etc.), the symbol you are trading, and other factors. You can refer to the Binance API documentation for more information on specific parameters.

    Additionally, you may need to adjust the leverage parameter in your order_execution function to ensure that you are not exceeding your maximum allowable position size. You may need to reduce the leverage value or adjust your position size accordingly.

  5. User

    And leverage ?

  6. Assistant

    The leverage parameter in your order_execution function can range from 1 to 125 depending on the specific trading pair and your account's maximum leverage limit.

    For example, if your maximum leverage limit for a specific trading pair is 25, you can set the leverage parameter in your order_execution function to a value between 1 and 25.

    Here's an example of how you can set the leverage parameter:

    leverage = 10  # set leverage to 10x
    order_params['params']['leverage'] = leverage
    

    Make sure to double-check the allowed leverage for the specific trading pair before setting the leverage parameter. Setting the leverage too high can result in losses that exceed your account balance.

  7. User

    Is it right code? order_params = { "type": "MARKET", "side": "BUY" if signal == "buy" else "SELL", "quantity": quantity, "params": { "leverage": leverage } }

  8. Assistant

    Yes, this code looks correct assuming quantity and leverage are set correctly and the order type you want to use is a market order.

    This code will create the order_params dictionary with the following information:

    • Order type: MARKET
    • Order side: BUY if the signal is "buy", otherwise SELL
    • Order quantity: quantity set earlier in your code
    • Additional parameters: "leverage" with the value of leverage from your function argument.

    Make sure to double-check that your other parameters, such as the symbol and timeInForce, are set correctly based on the specific order type and trading pair you are using.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.