@@ -16,6 +16,77 @@ def __init__(
1616 self .headers = headers
1717 self .account = account
1818
19+ ########################################################
20+ # \\\\\\\\\\\\\\\\ Close All Positions ////////////////#
21+ ########################################################
22+ def close_all (self , cancel_orders : bool = False ) -> str :
23+ """
24+ Close all positions.
25+
26+ Args:
27+ cancel_orders (bool, optional): Whether to cancel open orders associated with the positions.
28+ Defaults to False.
29+
30+ Returns:
31+ str: A message indicating the number of positions that have been closed.
32+
33+ Raises:
34+ Exception: If the request to close positions is not successful, an exception is raised with
35+ the error message from the API response.
36+ """
37+
38+ url = f"{ self .base_url } /positions"
39+ params = {"cancel_orders" : cancel_orders }
40+
41+ response = json .loads (
42+ Requests ()
43+ .request (method = "DELETE" , url = url , headers = self .headers , params = params )
44+ .text
45+ )
46+ return f"{ len (response )} positions have been closed"
47+
48+ ########################################################
49+ # \\\\\\\\\\\\\\\\\\ Close Position ///////////////////#
50+ ########################################################
51+ def close (
52+ self , symbol_or_id : str , qty : float = None , percentage : int = None
53+ ) -> str :
54+ """
55+ Closes a position for a given symbol or asset ID.
56+
57+ Args:
58+ symbol_or_id (str): The symbol or asset ID of the position to be closed.
59+ qty (float, optional): The quantity of the position to be closed. Defaults to None.
60+ percentage (int, optional): The percentage of the position to be closed. Defaults to None.
61+
62+ Returns:
63+ str: A message indicating the success or failure of closing the position.
64+
65+ Raises:
66+ ValueError: If neither quantity nor percentage is provided.
67+ ValueError: If both quantity and percentage are provided.
68+ ValueError: If the percentage is not between 0 and 100.
69+ ValueError: If symbol_or_id is not provided.
70+ Exception: If the request to close the position fails.
71+ """
72+
73+ if not qty and not percentage :
74+ raise ValueError ("Quantity or percentage is required." )
75+ if qty and percentage :
76+ raise ValueError ("Quantity or percentage is required, not both." )
77+ if percentage and (percentage < 0 or percentage > 100 ):
78+ raise ValueError ("Percentage must be between 0 and 100." )
79+ if not symbol_or_id :
80+ raise ValueError ("Symbol or asset_id is required." )
81+
82+ url = f"{ self .base_url } /positions/{ symbol_or_id } "
83+ params = {"qty" : qty , "percentage" : percentage }
84+ Requests ().request (
85+ method = "DELETE" , url = url , headers = self .headers , params = params
86+ )
87+
88+ return f"Position { symbol_or_id } has been closed"
89+
1990 def get (self , symbol : str ) -> PositionModel :
2091 """
2192 Retrieves the position for the specified symbol.
0 commit comments