refactor: replace position check error with friendly 'No open positions found' message
This commit is contained in:
1 parent
e21bf3c8dd
commit
b4a645cf01
2 files changed
+11
-2
No files matched your search
@@ -1,7 +1,14 @@
|
|||||||
import time
|
import time
|
||||||
|
import logging
|
||||||
import backoff
|
import backoff
|
||||||
import alpaca_trade_api as tradeapi
|
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:
|
class AlpacaClient:
|
||||||
def __init__(self, api_key_id, api_secret_key, base_url, api_version="v2"):
|
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):
|
def close_all_positions(self):
|
||||||
return self.api.close_all_positions()
|
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):
|
def get_position(self, symbol):
|
||||||
return self.api.get_position(symbol)
|
return self.api.get_position(symbol)
|
||||||
|
|
||||||
|
|||||||
@@ -1327,6 +1327,7 @@ def main():
|
|||||||
max_intraday_drawdown = 0
|
max_intraday_drawdown = 0
|
||||||
last_indicator_log = datetime.now(EASTERN)
|
last_indicator_log = datetime.now(EASTERN)
|
||||||
|
|
||||||
|
logger.info("🔎 Checking for existing positions...")
|
||||||
try:
|
try:
|
||||||
existing_position = api.get_position(SYMBOL)
|
existing_position = api.get_position(SYMBOL)
|
||||||
qty = float(existing_position.qty)
|
qty = float(existing_position.qty)
|
||||||
@@ -1360,7 +1361,8 @@ def main():
|
|||||||
if USE_TRAILING_STOP:
|
if USE_TRAILING_STOP:
|
||||||
position_state.trailing_stop = stop_loss
|
position_state.trailing_stop = stop_loss
|
||||||
except Exception as e:
|
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
|
retry_count = 0
|
||||||
max_retries = 3
|
max_retries = 3
|
||||||
|
|||||||
Reference in new issue
Block a user