Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

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

  1. User

    I used your 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 json import numpy as np import pytz import datetime as dt import ccxt from decimal import Decimal import requests import hmac import hashlib API_KEY = '' API_SECRET = ''

    client = Client(API_KEY, API_SECRET)

    Set the endpoint and parameters for the request

    url = "https://fapi.binance.com/fapi/v2/account" timestamp = int(time.time() * 1000) recv_window = 5000

    params = { "timestamp": timestamp, "recvWindow": recv_window }

    Sign the message using the Client’s secret key

    message = '&'.join([f"{k}={v}" for k, v in params.items()]) signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() params['signature'] = signature leverage = 100

    Send the request using the requests library

    response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY}) account_info = response.json()

    Get the USDT balance and calculate the max trade size based on the leverage

    usdt_balance = next((item for item in account_info['assets'] if item["asset"] == "USDT"), {"balance": 0}) max_trade_size = float(usdt_balance.get("balance", 0)) * leverage

    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)

    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': API_KEY, 'secret': API_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.load_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 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 #initialise 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 = '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 = '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
    try:
        response = binance_futures.create_order(
            symbol=symbol,
            type=order_type,
            side='BUY' if signal == 'buy' else 'SELL',
            quantity=quantity,
            positionSide=position_side,
            price=price
        )
        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 22:37:00 : The signal time is: 2023-06-07 22:37:01 :sell Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 277, 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 256, in order_execution response = binance_futures.create_order( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: binance.create_order() got an unexpected keyword argument 'quantity'

  2. Assistant

    The issue might be with the argument name used in the binance_futures.create_order() function call. Instead of using quantity, it should be using amount as the argument name. Try changing the line:

    response = binance_futures.create_order(
                symbol=symbol,
                type=order_type,
                side='BUY' if signal == 'buy' else 'SELL',
                quantity=quantity,
                positionSide=position_side,
                price=price
            )
    

    to:

    response = binance_futures.create_order(
                symbol=symbol,
                type=order_type,
                side='BUY' if signal == 'buy' else 'SELL',
                amount=quantity,
                positionSide=position_side,
                price=price
            )
    

    This should resolve the error.

  3. User

    New ERROR: File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 277, 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 256, in order_execution response = binance_futures.create_order( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: binance.create_order() got an unexpected keyword argument 'positionSide'

  4. Assistant

    The error message indicates that the positionSide parameter is not supported by the create_order method for Binance futures, causing a TypeError. The parameter appears to be taken from the Binance spot API method for creating orders, where it is allowed but not for futures trading.

    Try removing the positionSide parameter from the create_order method, since this parameter is not allowed for Binance futures. Edit the order_execution function call to remove that parameter, like so:

    response = binance_futures.create_order(
        symbol=symbol,
        type=order_type,
        side='BUY' if signal == 'buy' else 'SELL',
        amount=quantity,
        price=price
    )
    

    This should help resolve the TypeError caused by the use of the positionSide parameter.

  5. User

    ERROR: File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 276, 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 256, in order_execution response = binance_futures.create_order( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 4204, in create_order raise InvalidOrder(self.id + ' createOrder() requires a stopPrice extra param for a ' + type + ' order') ccxt.base.errors.InvalidOrder: binance createOrder() requires a stopPrice extra param for a STOP_MARKET order

  6. Assistant

    The error message indicates that in the create_order() method, the stopPrice parameter is required when placing a STOP_MARKET order on Binance Futures. A STOP_MARKET order is intended to be executed at the next available market price after the stop price is triggered. The stop price is the price at which the order will become a market order. Therefore, it is important to provide a stopPrice value for this order type.

    To fix the error, include the stopPrice parameter in the create_order() function call. You can add it conditionally based on the order_type. For example, you can modify the order_execution() function to include something like the following code before the create_order() call:

    # Set stop loss price for stop market orders
    if order_type == 'STOP_MARKET':
        stop_price = stop_loss_price
    else:
        stop_price = None
    
    # Place order
    try:
        response = binance_futures.create_order(
            symbol=symbol,
            type=order_type,
            side='BUY' if signal == 'buy' else 'SELL',
            amount=quantity,
            price=price,
            stopPrice=stop_price
        )
        print(f"Order details: {response}")
    except BinanceAPIException as e:
        print(f"Error in order_execution: {e}")
        time.sleep(1)
        return
    

    This code sets the stopPrice value to the stop_loss_price if the order_type is STOP_MARKET, or sets it to None otherwise. This should help fix the error you are seeing.

  7. User

    I used your code, but I getting ERROR: BTC/USDT found in the market The signal time is: 2023-06-07 22:45:23 :buy Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 283, 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 262, in order_execution response = binance_futures.create_order( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: binance.create_order() got an unexpected keyword argument 'stopPrice'

  8. Assistant

    It seems that the stopPrice parameter is not supported in the create_order method for ccxt's Binance Futures. To place a STOP_MARKET order and include a stop price value, you can instead use the fapiPrivatePostOrder method with the additional parameters that are needed.

    To do that, you can replace the create_order method with the following code:

    # Place stop market order
    if order_type == 'STOP_MARKET':
        try:
            response = binance_futures.fapiPrivatePostOrder(
                symbol=symbol,
                side='BUY' if signal == 'buy' else 'SELL',
                type='STOP_MARKET',
                quantity=quantity,
                stopPrice=stop_loss_price,
                reduceOnly=True
            )
            print(f"Order details: {response}")
        except BinanceAPIException as e:
            print(f"Error in order_execution: {e}")
            time.sleep(1)
            return
    
    # Place market or take profit order
    elif order_type == 'market':
        try:
            response = binance_futures.create_order(
                symbol=symbol,
                type=order_type,
                side='BUY' if signal == 'buy' else 'SELL',
                amount=quantity,
                price=price
            )
            print(f"Order details: {response}")
        except BinanceAPIException as e:
            print(f"Error in order_execution: {e}")
            time.sleep(1)
            return
    

    This code first checks if the order_type is STOP_MARKET. If it is, the function uses the fapiPrivatePostOrder method with the stopPrice parameter set to the stop_loss_price. It also sets the reduceOnly parameter to True to ensure that the order will only reduce an existing position and will