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 import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import asyncio

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

    url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content)

    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' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1

    client = Client(API_KEY, API_SECRET)

    def getminutedata(symbol, interval, lookback): klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000)) # Cast tuples to lists klines = [list(map(str, kline)) for kline in klines] frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match']) frame = frame[['Open time', 'Price', 'Qty']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched return frame

    df = getminutedata('BTCUSDT', '1m', 44640)

    def signal_generator(df): open = df.Price.iloc[-1] close = df.Price.iloc[-1] previous_open = df.Price.iloc[-2] previous_close = df.Price.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 ''
    

    def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): signal = signal_generator(df) max_trade_quantity = None account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100

    # Close long position if signal is opposite
    long_position = None
    short_position = None
    positions = client.futures_position_information(symbol=symbol)
    for p in positions:
        if p['positionSide'] == 'LONG':
            long_position = p
        elif p['positionSide'] == 'SHORT':
            short_position = p
        if long_position is not None and short_position is not None:
            print("Multiple positions found. Closing both positions.")
        if long_position is not None:
            client.futures_create_order(
                symbol=symbol,
                side=SIDE_SELL,
                type=ORDER_TYPE_MARKET,
                quantity=long_position['positionAmt'],
                reduceOnly=True
            )
        time.sleep(1)
    if short_position is not None:
        client.futures_create_order(
            symbol=symbol,
            side=SIDE_BUY,
            type=ORDER_TYPE_MARKET,
            quantity=short_position['positionAmt'],
            reduceOnly=True
        )
    time.sleep(1)
    print("Both positions closed.")
    
    if signal == 'buy':
        position_side = POSITION_SIDE_LONG
        opposite_position = short_position
    elif signal == 'sell':
        position_side = POSITION_SIDE_SHORT
        opposite_position = long_position
    else:
        print("Invalid signal. No order placed.")
        return
    order_quantity = 0
    if opposite_position is not None:
        order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
    if opposite_position is not None and opposite_position['positionSide'] != position_side:
        print("Opposite position found. Closing position before placing order.")
    client.futures_create_order(
        symbol=symbol,
        side=SIDE_SELL if
            opposite_position['positionSide'] == POSITION_SIDE_LONG
    else
        SIDE_BUY,
        type=ORDER_TYPE_MARKET,
        quantity=order_quantity,
        reduceOnly=True,
        positionSide=opposite_position['positionSide']
    )
    time.sleep(1)
    
    order = client.futures_create_order(
        symbol=symbol,
        side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
        type=ORDER_TYPE_MARKET,
        quantity=order_quantity,
        reduceOnly=False,
        timeInForce=TIME_IN_FORCE_GTC,
        positionSide=position_side, # add position side parameter
        leverage=leverage
    )
    if order is None:
        print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
        return
    order_id = order['orderId']
    print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
    time.sleep(1)
    
    # Set stop loss and take profit orders
    # Get the order details to determine the order price
    order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
    if order_info is None:
        print("Error getting order information. Skipping setting stop loss and take profit orders.")
        return
    order_price = float(order_info['avgPrice'])
    
    # Set stop loss and take profit orders
    stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
    take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
    stop_loss_order = client.futures_create_order(
        symbol=symbol,
        side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
        type=ORDER_TYPE_STOP_LOSS,
        quantity=order_quantity,
        stopPrice=stop_loss_price,
        reduceOnly=True,
        timeInForce=TIME_IN_FORCE_GTC,
        positionSide=position_side # add position side parameter
    )
    take_profit_order = client.futures_create_order(
        symbol=symbol,
        side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
        type=ORDER_TYPE_LIMIT,
        quantity=order_quantity,
        price=take_profit_price,
        reduceOnly=True,
        timeInForce=TIME_IN_FORCE_GTC,
        positionSide=position_side # add position side parameter
    )
    # Print order creation confirmation messages
    print(f"Placed stop loss order with stop loss price {stop_loss_price}")
    print(f"Placed take profit order with take profit price {take_profit_price}")
    time.sleep(1)
    

    async def main(): while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") df = getminutedata('BTCUSDT', '1m', 44640) # Get minute data each loop if df is None: continue current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage) await asyncio.sleep(1) # Await execution with asyncio in an async function time.sleep(1) But I getting ERROR:05/31/2023 11:22:56 Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 51, in df = getminutedata('BTCUSDT', '1m', 44640) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 43, in getminutedata klines = [list(map(str, kline)) for kline in klines] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: 'coroutine' object is not iterable sys:1: RuntimeWarning: coroutine 'ClientBase._request' was never awaited

  2. Assistant

    The error message suggests that the get_historical_trades method in the getminutedata function is a coroutine object and needs to be awaited. To fix this, we can use the await keyword before calling the get_historical_trades method.

    Here's an updated getminutedata function:

    async def getminutedata(symbol, interval, lookback):
        klines = await client.futures_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000))
        # Cast tuples to lists
        klines = [list(map(str, kline)) for kline in klines]
        frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match'])
        frame = frame[['Open time', 'Price', 'Qty']]
        frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
        frame.set_index('Open time', inplace=True)
        frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched
        return frame
    

    We also need to update the main function to be an async function and use await when calling order_execution.

    Here's an updated main function:

    async def main():
        while True:
            current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            df = await getminutedata('BTCUSDT', '1m', 44640) # Get minute data each loop
            if df is None:
                continue
            current_signal = signal_generator(df)
            print(f"The signal time is: {current_time} :{current_signal}")
            if current_signal:
                await order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage)
                await asyncio.sleep(1) # Await execution with asyncio in an async function
    

    We also need to update the last line of the code to actually run the main function with the asyncio.run function.

    Here's the updated last line of the code:

    if __name__ == '__main__':
        asyncio.run(main())
    

    With these updates, the code should now work without errors.

  3. User

    It need to seem like that ? Code: async def getminutedata(symbol, interval, lookback): klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000)) # Cast tuples to lists klines = [list(map(str, kline)) for kline in klines] frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match']) frame = frame[['Open time', 'Price', 'Qty']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched return frame

  4. Assistant

    No, it should still be an async function and use the await keyword before calling the get_historical_trades method. Here's the updated getminutedata function:

    async def getminutedata(symbol, interval, lookback):
        klines = await client.futures_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000))
        # Cast tuples to lists
        klines = [list(map(str, kline)) for kline in klines]
        frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match'])
        frame = frame[['Open time', 'Price', 'Qty']]
        frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
        frame.set_index('Open time', inplace=True)
        frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched
        return frame
    
  5. User

    I used your code: async def getminutedata(symbol, interval, lookback): klines = await client.futures_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000)) # Cast tuples to lists klines = [list(map(str, kline)) for kline in klines] frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match']) frame = frame[['Open time', 'Price', 'Qty']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched return frame

    df = getminutedata('BTCUSDT', '1m', 44640) But I getting ERROR:05/31/2023 11:56:52 sys:1: RuntimeWarning: coroutine 'getminutedata' was never awaited

  6. Assistant

    The error message suggests that you need to await the getminutedata function, since it is an async function now. Here's an updated version of the code with the await keyword before calling the getminutedata function:

    async def main():
        while True:
            current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            df = await getminutedata('BTCUSDT', '1m', 44640) # await call to getminutedata
            if df is None:
                continue
            current_signal = signal_generator(df)
            print(f"The signal time is: {current_time} :{current_signal}")
            if current_signal:
                await order_execution('BTCUSDT', current_signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage) # await call to order_execution
                await asyncio.sleep(1)
    

    Also make sure that the last line of your code is asyncio.run(main()) to properly run the main function as an async function.

  7. User

    It need to seem like that ? Code: async def main(): while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") df = await getminutedata('BTCUSDT', '1m', 44640) # Get minute data each loop if df is None: continue current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: await order_execution('BTCUSDT', current_signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage) await asyncio.sleep(1) # Await execution with asyncio in an async function

  8. Assistant

    Yes, that code looks correct. The await keyword is used before calling both the getminutedata and order_execution functions. Additionally, the asyncio.sleep function is also awaited inside the if statement, since it is an async function.

  9. User

    But I still getting ERROR: RuntimeWarning: coroutine 'getminutedata' was never awaited

  10. Assistant

    It seems like you are still calling the getminutedata function without using the await keyword. Here's an example of how to properly call the getminutedata function:

    df = await getminutedata('BTCUSDT', '1m', 44640)
    

    Make sure you are using the await keyword before calling the getminutedata function.

  11. User

    Am I need to wright df = await getminutedata('BTCUSDT', '1m', 44640) ?

  12. Assistant

    Yes, you need to include the await keyword when calling the getminutedata function if you made it an async function. Here's an example of how it should look:

    df = await getminutedata('BTCUSDT', '1m', 44640)
    

    By using the await keyword before calling getminutedata as shown above, you are indicating to Python that you are waiting for getminutedata to complete before continuing with the next line of code.

  13. User

    Am I need to wirght it in line 51 ?

  14. Assistant

    Yes, on line 51 you need to change the line:

    df = getminutedata('BTCUSDT', '1m', 44640)
    

    To:

    df = await getminutedata('BTCUSDT', '1m', 44640)
    

    This is because you made the getminutedata function into an async function, so you need to include the await keyword when calling it in an async function like main().

  15. User

    But I getting ERROR: File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 51 df = await getminutedata('BTCUSDT', '1m', 44640) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: 'await' outside function

  16. Assistant

    This error indicates that you are using the await keyword outside of an async function. Make sure that the