Hi,
Sometimes my test program fails with the following exception:
# Error code
Code : 42210000. Contract <SYM> expires soon. Unable to open new positions.
This is understandable as the relevant contract in question expires soon. However, I do not want my program to die in such a scenario.
How exactly should I deal with it? Will the order status be populated accordingly? And, if that is the case, can I query order status, check for the relevant condition and move accordingly?
Thanks
This was essentially a Python question and @Dan_Whitnable_Alpaca has graciously given the following answer:
You asked about identifying and responding to errors in python. The typical approach is to wrap the parts of your code which could fail with a try-except
statement (see the python docs here). Consider every API call you make, even if it’s simply to fetch positions, as potentially failing for various reasons. As an example
try: position_df = pd.DataFrame(client.get_all_positions()) except Exception as err: # do anything here print(type(err)) # the exception type print(err.args) # the error message is stored in .args
A more general approach is to create a function for each API function and call that. This will make your code a bit more concise but moreover ensures errors are handled consistently. Like this
def my_get_positions(): # define the alpaca-py client globally or it could be passed to the function try: position_df = pd.DataFrame(client.get_all_positions()) except Exception as err: # return an empty dataframe if there's an error position_df = pd.DataFrame() print(type(err)) # the exception type print(err.args) # the error message is stored in .args return position_df
Hope that helps.