refactor: replace position check error with friendly 'No open positions found' message
This commit is contained in:
@@ -1,7 +1,14 @@
|
||||
import time
|
||||
import logging
|
||||
import backoff
|
||||
import alpaca_trade_api as tradeapi
|
||||
|
||||
logging.getLogger('backoff').setLevel(logging.CRITICAL)
|
||||
|
||||
|
||||
def _is_position_not_found(e):
|
||||
return isinstance(e, tradeapi.rest.APIError) and "position does not exist" in str(e)
|
||||
|
||||
|
||||
class AlpacaClient:
|
||||
def __init__(self, api_key_id, api_secret_key, base_url, api_version="v2"):
|
||||
@@ -50,7 +57,7 @@ class AlpacaClient:
|
||||
def close_all_positions(self):
|
||||
return self.api.close_all_positions()
|
||||
|
||||
@backoff.on_exception(backoff.expo, (tradeapi.rest.APIError, ConnectionError), max_tries=5, jitter=backoff.full_jitter)
|
||||
@backoff.on_exception(backoff.expo, (tradeapi.rest.APIError, ConnectionError), max_tries=5, jitter=backoff.full_jitter, giveup=_is_position_not_found)
|
||||
def get_position(self, symbol):
|
||||
return self.api.get_position(symbol)
|
||||
|
||||
|
||||
@@ -1327,6 +1327,7 @@ def main():
|
||||
max_intraday_drawdown = 0
|
||||
last_indicator_log = datetime.now(EASTERN)
|
||||
|
||||
logger.info("🔎 Checking for existing positions...")
|
||||
try:
|
||||
existing_position = api.get_position(SYMBOL)
|
||||
qty = float(existing_position.qty)
|
||||
@@ -1360,7 +1361,8 @@ def main():
|
||||
if USE_TRAILING_STOP:
|
||||
position_state.trailing_stop = stop_loss
|
||||
except Exception as e:
|
||||
debug_print(f"No existing position found or error during recovery: {e}")
|
||||
logger.info("🔎 No open positions found")
|
||||
debug_logger.debug(f"Position check exception: {e}")
|
||||
|
||||
retry_count = 0
|
||||
max_retries = 3
|
||||
|
||||
Reference in New Issue
Block a user