StatArb / StatBot / Execution / func_position_calls.py
func_position_calls.py
Raw
from config_execution_api import session_private
from exceptions import FailedRequestError, InvalidRequestError
from requests.exceptions import ConnectionError, Timeout, RequestException
from json.decoder import JSONDecodeError

# Check for open positions
def open_position_confirmation(ticker):
    try:
        position = session_private.my_position(symbol=ticker)
        if position["ret_msg"] == "OK":
            for item in position["result"]:
                if item["size"] > 0:
                    return True
    except:
        return True
    return False


# Check for active positions
def active_position_confirmation(ticker):
    try:
        active_order = session_private.get_active_order(
            symbol=ticker,
            order_status="Created,New,PartiallyFilled,Active"
        )
        if active_order["ret_msg"] == "OK":
            if active_order["result"]["data"] != None:
                return True
    except:
        return True
    return False


# Get open position price and quantity
def get_open_positions(ticker, direction="Long"):

    # Get position
    position = session_private.my_position(symbol=ticker)

    # Select index to avoid looping through response
    index = 0 if direction == "Long" else 1

    # Construct a response
    if "ret_msg" in position.keys():
        if position["ret_msg"] == "OK":
            if "symbol" in position["result"][index].keys():
                order_price = position["result"][index]["entry_price"]
                order_quantity = position["result"][index]["size"]
                return order_price, order_quantity
            return (0, 0)
    return (0, 0)


# Get active position price and quantity
def get_active_positions(ticker):
    
    exception = True
    try:
        # Get position
        active_order = session_private.get_active_order(
            symbol=ticker,
            order_status="Created,New,PartiallyFilled,Active"
        )

        print("\n")
        print('-------------------------------------------------------------------')
        print("Get Active Positions")
        print(active_order)
        print('-------------------------------------------------------------------')
        print("\n")

        # Construct a response
        if "ret_msg" in active_order.keys():
            if active_order["ret_msg"] == "OK" and len(active_order["result"])>0:
                exception = False
                if active_order["result"]["data"] != None:
                    order_price = active_order["result"]["data"][0]["price"]
                    order_quantity = active_order["result"]["data"][0]["quantity"]    
                    return (order_price,order_quantity,exception)
                return (0, 0, exception)
    except (ConnectionError, Timeout, RequestException, JSONDecodeError, FailedRequestError, InvalidRequestError) as e:
        print(e)
    return (0, 0, exception)


# Query existing order
def query_existing_order(ticker, order_id, direction):

    exception = True
    try:
        # Query order
        order = session_private.query_active_order(symbol=ticker, order_id=order_id)
        
        print("\n")
        print('-------------------------------------------------------------------')
        print("Query Existing Order")
        print(order)
        print('-------------------------------------------------------------------')
        print("\n")
        
        # Construct response
        if "ret_msg" in order.keys():
            if order["ret_msg"] == "OK" and len(order["result"])>0:
                order_price = order["result"]["price"]
                order_quantity = order["result"]["qty"]
                order_status = order["result"]["order_status"]
                
                return order_price, order_quantity, order_status
    except (ConnectionError, Timeout, RequestException, JSONDecodeError, FailedRequestError, InvalidRequestError) as e:
        print(e)
    return (0, 0, "")

def get_closed_pnl_info(ticker,start_time):

    exception = True
    try:
        pnl = session_private.closed_profit_and_loss(symbol=ticker, start_time = start_time) #-28800
        closed_pnl = 0

        print("\n")
        print('-------------------------------------------------------------------')
        print("Get Closed PnL Info")
        print(pnl)
        print('-------------------------------------------------------------------')
        print("\n")

        if "ret_msg" in pnl.keys():
            print("ret_msg in pnl keys")
            if pnl["ret_msg"] == "OK" and len(pnl["result"])>0:
                print("ret_msg = OK")
                print((pnl["result"]))
                if pnl["result"]["data"] != None:
                    print("[result][data] != none")
                    for item in pnl["result"]["data"]:
                        closed_pnl += item["closed_pnl"]
        exception = False
        return (closed_pnl, exception)
    except (ConnectionError, Timeout, RequestException, JSONDecodeError, FailedRequestError, InvalidRequestError) as e:
        print(e)   
    return (0, exception)

# Get position information
def get_position_info(ticker):
    
    exception = True
    try:
        position = session_private.my_position(symbol=ticker)
        side = 0
        size = ""
        pnl_un = 0
        pos_value = 0

        print("\n")
        print('-------------------------------------------------------------------')
        print("Get Position Info")
        print(position)
        print('-------------------------------------------------------------------')
        print("\n")

        if "ret_msg" in position.keys():
            if position["ret_msg"] == "OK" and len(position["result"])>0:
                if len(position["result"]) == 2:
                    if position["result"][0]["size"] > 0:
                        size = position["result"][0]["size"]
                        side = "Buy"
                        pnl_un = position["result"][0]["unrealised_pnl"]
                        pos_value = position["result"][0]["position_value"]
                    else:
                        size = position["result"][1]["size"]
                        side = "Sell"
                        pnl_un = position["result"][1]["unrealised_pnl"]
                        pos_value = position["result"][1]["position_value"]
        
        exception = False
        # Return output
        return (side, size, pnl_un, pos_value, exception)
    except (ConnectionError, Timeout, RequestException, JSONDecodeError, FailedRequestError, InvalidRequestError) as e:
        print(e)   
    # Return output
    return ("", 0, 0, 0, exception)