Untitled

 avatar
unknown
plain_text
8 days ago
16 kB
8
Indexable
from binance.client import Client
import os
import time

import hmac
import hashlib
import time
import requests
    
def close_futures_position(client,symbol):
    try:
        # Get the current position information
        positions = client.futures_position_information()
        
        # Find the position for the given symbol
        for pos in positions:
            if pos['symbol'] == symbol and float(pos['positionAmt']) != 0:
                position_amt = float(pos['positionAmt'])
                side = Client.SIDE_SELL if position_amt > 0 else Client.SIDE_BUY
                
                # Place an order to close the position
                order = client.futures_create_order(
                    symbol=symbol,
                    side=side,
                    type=Client.ORDER_TYPE_MARKET,
                    quantity=abs(position_amt),
                    reduceOnly=True  # Ensure it's a close order
                )
                
                print(f"Closed position: {order}")
                return order
            
        print("No open position to close.")
    
    except Exception as e:
        print(f"Error: {e}")

def get_pair_pnl(client,symbol, limit=100):    
    trades = client.futures_account_trades(symbol=symbol, limit=limit)
    last_time = trades[-1]['time']
    last_pnl = float(trades[-1]['realizedPnl'])
    for i in range(len(trades)-2,-1,-1):
        if (last_time - trades[i]['time']) < 600:
            last_pnl += float(trades[i]['realizedPnl'])
    last_pnl = round(last_pnl,2)
    return last_pnl

def get_future_balance(client,coin_pair):
    account_info = client.futures_account()
    balances = account_info['assets']
    for balance in balances:
        if balance['asset'] == coin_pair:
            return round(float(balance['walletBalance']),1)


def get_quantity(client,symbol,target_buy):
    price = float(client.futures_mark_price(symbol=symbol)['markPrice'])
    futures_exchange_info = client.futures_exchange_info()  # request info on all futures symbols
    for i in futures_exchange_info['symbols']:
        if i['symbol'] == symbol:
            quantity_in_contracts = round(target_buy / price,i['quantityPrecision'])
    return(quantity_in_contracts)

def create_future_order(client,symbol,leverage,order_type,target_buy,isolated_status):
    # Define the symbol and order parameters
    quantity = get_quantity(client,symbol,target_buy)
    #leverage = 15  # Leverage amount (e.g., 5, 10, 15, etc.)
    if order_type == 'Long':
        side_type = Client.SIDE_BUY
    elif order_type == 'Short':
        side_type = Client.SIDE_SELL

    # Set the leverage
    client.futures_change_leverage(
        symbol=symbol,
        leverage=leverage
    )

    # Create the order
    order = client.futures_create_order(
        symbol=symbol,
        side=side_type,
        type=Client.ORDER_TYPE_MARKET,
        quantity=quantity,
        isIsolated=isolated_status,
    )

    # Print the order details
    print(f"Order created: {order}")

def close_positions(client,symbol,close_side):
    # Get open positions
    positions = client.futures_position_information(symbol=symbol)
    if len(positions) > 0:
        quantity = 0
        for position in positions:
            if position['symbol'] == symbol:
                # Close the position
                if close_side == 'Long':
                    side_type = Client.SIDE_SELL
                    quantity = float(position['positionAmt'])
                else:
                    side_type = Client.SIDE_BUY
                    quantity = -(float(position['positionAmt']))
                if quantity != 0:
                    # Create the order to close the position
                    order = client.futures_create_order(
                        symbol=symbol,
                        side=side_type,
                        type=Client.ORDER_TYPE_MARKET,
                        quantity=quantity
                    )
                    # Print the order details
                    print(f"Order created: {order}")

def get_positions_info(client,symbol,close_side):
    positions = client.futures_position_information(symbol=symbol)
    for position in positions:
        if position['symbol'] == symbol:
            print(position['isolatedWallet'])

def create_limit_long_order(client,symbol,target_buy,order_deep,sleep_time,timeout,leverage):
    target_buy = int(target_buy)*int(leverage)
    # Set the leverage
    client.futures_change_leverage(
        symbol=symbol,
        leverage=leverage
    )
    min_quantity = 0.001
    total_try = int(timeout/sleep_time)
    try_count = 0
    while True:
        open_orders = client.futures_get_open_orders(symbol=symbol)
        #print(open_orders)
        try:
            if len(open_orders) > 0:
                for order in open_orders:
                    if order['symbol'] == symbol:
                        result = client.futures_cancel_order(
                        symbol=symbol,
                        orderId=order['orderId'])
        except: #when api error
            continue

        try:
            open_positions = client.futures_position_information(symbol=symbol)
        except:
            try:
                time.sleep(3)
                open_positions = client.futures_position_information(symbol=symbol)
            except:
                continue
            
        current_quantity = 0
        if len(open_positions) > 0:
            for position in open_positions:
                if position['symbol'] == symbol:
                    current_quantity = float(position['positionAmt'])
        order_book = client.futures_order_book(symbol=symbol)
        if float(order_book['bids'][0][1]) < 15:
            maker_price = float(order_book['bids'][order_deep][0])
        else:
            maker_price = float(order_book['bids'][2][0])
        if try_count > total_try*1/5:
            maker_price = float(order_book['bids'][1][0])
        if try_count > total_try*2/5:
            maker_price = float(order_book['bids'][0][0])
        target_buy2 = target_buy - current_quantity*maker_price
        quantity = get_quantity(client,symbol,target_buy2)
        #quantity =  round(target_buy2  / maker_price,3)
        if quantity <= 0:
            break
        try:
            if try_count >= total_try:
                order = client.futures_create_order(
                    symbol=symbol,
                    side=Client.SIDE_BUY,
                    type=Client.ORDER_TYPE_MARKET,
                    quantity=quantity,
                    isIsolated=True,)
            else:
                order = client.futures_create_order(
                    symbol=symbol,
                    side=Client.SIDE_BUY,
                    type=Client.ORDER_TYPE_LIMIT,
                    timeInForce=Client.TIME_IN_FORCE_GTC,
                    quantity=quantity,
                    price=maker_price,
                    isIsolated=True,)
        except:
            try_count += 1
            time.sleep(sleep_time)
            continue
        try_count += 1
        time.sleep(sleep_time)
        
def create_limit_long_sell(client,symbol,order_deep,sleep_time,timeout):
    #client.futures_change_leverage(
    #    symbol=symbol,
    #    leverage=leverage
    #)
    min_quantity = 0.001
    total_try = int(timeout/sleep_time)
    try_count = 0
    while True:
        open_orders = client.futures_get_open_orders(symbol=symbol)
        try:
            if len(open_orders) > 0:
                for order in open_orders:
                    if order['symbol'] == symbol:
                        result = client.futures_cancel_order(
                        symbol=symbol,
                        orderId=order['orderId'])
        except: #when api error
            continue

        try:
            open_positions = client.futures_position_information(symbol=symbol)
        except:
            time.sleep(3)
            open_positions = client.futures_position_information(symbol=symbol)
        current_quantity = 0
        if len(open_positions) > 0:
            for position in open_positions:
                if position['symbol'] == symbol:
                    current_quantity = float(position['positionAmt'])
        order_book = client.futures_order_book(symbol=symbol)
        if float(order_book['asks'][0][1]) < 15:
            maker_price = float(order_book['asks'][order_deep][0])
        else:
            maker_price = float(order_book['asks'][2][0])

        if try_count > total_try*1/5:
            maker_price = float(order_book['asks'][1][0])
        if try_count > total_try*2/5:
            maker_price = float(order_book['asks'][0][0])
        target_sell = current_quantity*maker_price
        #quantity =  round(target_sell  / maker_price,3)
        quantity = get_quantity(client,symbol,target_sell)
        if quantity <= 0:
            break
        try:
            if try_count >= total_try:
                order = client.futures_create_order(
                    symbol=symbol,
                    side=Client.SIDE_SELL,
                    type=Client.ORDER_TYPE_MARKET,
                    quantity=quantity,
                    isIsolated=True,
                    )
            else:
                order = client.futures_create_order(
                    symbol=symbol,
                    side=Client.SIDE_SELL,
                    type=Client.ORDER_TYPE_LIMIT,
                    timeInForce=Client.TIME_IN_FORCE_GTC,
                    quantity=quantity,
                    price=maker_price,
                    isIsolated=True,
                    )
        except:
            continue
        try_count += 1
        time.sleep(sleep_time)

def create_limit_short_order(client,symbol,target_buy,order_deep,sleep_time,timeout,leverage):
    target_buy = int(target_buy)*int(leverage)
    # Set the leverage
    client.futures_change_leverage(
        symbol=symbol,
        leverage=leverage
    )
    min_quantity = 0.001
    total_try = int(timeout/sleep_time)
    try_count = 0
    while True:
        open_orders = client.futures_get_open_orders(symbol=symbol)
        try:
            if len(open_orders) > 0:
                for order in open_orders:
                    if order['symbol'] == symbol:
                        result = client.futures_cancel_order(
                        symbol=symbol,
                        orderId=order['orderId'])
        except: #when api error
            continue

        try:
            open_positions = client.futures_position_information(symbol=symbol)
        except:
            try:
                time.sleep(3)
                open_positions = client.futures_position_information(symbol=symbol)
            except:
                continue

        current_quantity = 0
        if len(open_positions) > 0:
            for position in open_positions:
                if position['symbol'] == symbol:
                    current_quantity = float(position['positionAmt'])
        order_book = client.futures_order_book(symbol=symbol)
        if float(order_book['asks'][0][1]) < 15:
            maker_price = float(order_book['asks'][order_deep][0])
        else:
            maker_price = float(order_book['asks'][2][0])
        if try_count > total_try*1/3:
            maker_price = float(order_book['asks'][1][0])
        if try_count > total_try*2/3:
            maker_price = float(order_book['asks'][0][0])
        target_buy2 = target_buy + current_quantity*maker_price
        #quantity =  round(target_buy2  / maker_price,3)
        quantity = -(get_quantity(client,symbol,target_buy2))
        
        if quantity >= 0:
            break

        try:
            if try_count >= total_try:
                order = client.futures_create_order(
                    symbol=symbol,
                    side=Client.SIDE_SELL,
                    type=Client.ORDER_TYPE_MARKET,
                    quantity=abs(quantity),
                    isIsolated=True,)
            else:
                order = client.futures_create_order(
                    symbol=symbol,
                    side=Client.SIDE_SELL,
                    type=Client.ORDER_TYPE_LIMIT,
                    timeInForce=Client.TIME_IN_FORCE_GTC,
                    quantity=abs(quantity),
                    price=maker_price,
                    isIsolated=True,)

        except:
            time.sleep(sleep_time)
            try_count += 1
            continue
        try_count += 1
        time.sleep(sleep_time)

def create_limit_short_sell(client,symbol,order_deep,sleep_time,timeout):
    # client.futures_change_leverage(
    #     symbol=symbol,
    #     leverage=leverage
    # )
    min_quantity = 0.001
    total_try = int(timeout/sleep_time)
    try_count = 0
    while True:
        open_orders = client.futures_get_open_orders(symbol=symbol)
        try:
            if len(open_orders) > 0:
                for order in open_orders:
                    if order['symbol'] == symbol:
                        result = client.futures_cancel_order(
                        symbol=symbol,
                        orderId=order['orderId'])
        except: #when api error
            continue

        try:
            open_positions = client.futures_position_information(symbol=symbol)
        except:
            time.sleep(3)
            open_positions = client.futures_position_information(symbol=symbol)
        current_quantity = 0
        if len(open_positions) > 0:
            for position in open_positions:
                if position['symbol'] == symbol:
                    current_quantity = float(position['positionAmt'])
        order_book = client.futures_order_book(symbol=symbol)
        if float(order_book['bids'][0][1]) < 15:
            maker_price = float(order_book['bids'][order_deep][0])
        else:
            maker_price = float(order_book['bids'][2][0])

        if try_count > total_try*1/3:
            maker_price = float(order_book['bids'][1][0])
        if try_count > total_try*2/3:
            maker_price = float(order_book['bids'][0][0])
        target_sell = current_quantity*maker_price
        #quantity =  round(target_sell  / maker_price,3)
        quantity = get_quantity(client,symbol,target_sell)
        if quantity >= 0:
            break

        try:
            if try_count >= total_try:
                order = client.futures_create_order(
                    symbol=symbol,
                    side=Client.SIDE_BUY,
                    type=Client.ORDER_TYPE_MARKET,
                    quantity=abs(quantity),
                    isIsolated=True,
                    )
            else:
                order = client.futures_create_order(
                    symbol=symbol,
                    side=Client.SIDE_BUY,
                    type=Client.ORDER_TYPE_LIMIT,
                    timeInForce=Client.TIME_IN_FORCE_GTC,
                    quantity=abs(quantity),
                    price=maker_price,
                    isIsolated=True,
                    )
        except:
            continue
        try_count += 1
        time.sleep(sleep_time)


if __name__ == "__main__":
    client = Client(api_key="", api_secret="",tld ='com')
    #create_limit_long_order(client,"ETHUSDT",20,2,5,90,5)
    #create_limit_long_sell(client,"ETHUSDT",2,5,90)
    #create_limit_short_order(client,"BNBBUSD",30,2,4,180,1)
    #create_limit_short_sell(client,"BNBBUSD",2,4,180)
Editor is loading...
Leave a Comment