Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/powertrader/core/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def load(cls, base_dir: Path | None = None) -> BinanceCredentials:
return cls(api_key=key, api_secret=secret)
except ImportError:
logger.debug("keyring package not installed, skipping keyring lookup.")
except Exception as exc:
except (OSError, RuntimeError, ValueError) as exc:
logger.debug("Keyring lookup failed: %s", exc)

# 3. Legacy plaintext files
Expand Down
28 changes: 12 additions & 16 deletions src/powertrader/core/trading_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,12 @@ def get_current_prices(self, coins: list[str]) -> dict[str, float]:
mid = (ask + bid) / 2.0 if ask > 0 and bid > 0 else 0.0
if mid > 0:
result[coin] = mid
except (OSError, ConnectionError, ValueError, TypeError) as exc:
except (OSError, ConnectionError, ValueError, TypeError, KeyError) as exc:
logger.debug("Price fetch failed for %s: %s", coin, exc)
except ExchangeError:
raise
except Exception as exc:
logger.warning("Unexpected price fetch error for %s: %s", coin, exc)
raise ExchangeError(f"Unexpected price fetch error for {coin}: {exc}") from exc
return result

# -- order execution (private) -------------------------------------------
Expand Down Expand Up @@ -234,11 +236,12 @@ def _place_order(
except (OSError, ConnectionError) as exc:
logger.error("Order %s %s %s network error: %s", side, quantity, coin, exc)
return None
except (ExchangeError, OrderError):
raise
except Exception as exc:
logger.error(
"Order %s %s %s unexpected error: %s", side, quantity, coin, exc, exc_info=True
)
return None
raise OrderError(
f"Order {side} {quantity} {coin} unexpected error: {exc}"
) from exc

adapted = self._adapt_order(raw)
order_id = str(adapted.get("id", ""))
Expand Down Expand Up @@ -273,10 +276,8 @@ def _wait_terminal(self, symbol: str, order_id: str, timeout: float = 30.0) -> d
state = str(adapted.get("state", "")).lower()
if state in _TERMINAL_STATES:
return adapted
except (OSError, ConnectionError, ValueError, TypeError) as exc:
except (OSError, ConnectionError, ValueError, TypeError, KeyError) as exc:
logger.debug("Order poll for %s/%s failed: %s", symbol, order_id, exc)
except Exception as exc:
logger.debug("Order poll for %s/%s unexpected error: %s", symbol, order_id, exc)
time.sleep(1)
logger.warning("Order %s/%s: timeout waiting for terminal state", symbol, order_id)
return None
Expand All @@ -301,10 +302,8 @@ def _get_lot_size(self, symbol: str) -> dict[str, str]:
"minQty": f.get("minQty", "0.00000001"),
}
break
except (OSError, ConnectionError, ValueError, TypeError, KeyError) as exc:
except (OSError, ConnectionError, ValueError, TypeError, KeyError, AttributeError) as exc:
logger.debug("get_symbol_info(%s) failed: %s", symbol, exc)
except Exception as exc:
logger.warning("get_symbol_info(%s) unexpected error: %s", symbol, exc)

self._lot_size_cache[symbol] = default
return default
Expand All @@ -329,12 +328,9 @@ def _get_ask_price(self, symbol: str) -> float:
self._rate_limiter.acquire()
ticker = self._client.get_orderbook_ticker(symbol=symbol) # type: ignore[union-attr]
return float(ticker.get("askPrice", 0.0) or 0.0)
except (OSError, ConnectionError, ValueError, TypeError) as exc:
except (OSError, ConnectionError, ValueError, TypeError, KeyError) as exc:
logger.debug("Ask price fetch failed for %s: %s", symbol, exc)
return 0.0
except Exception as exc:
logger.warning("Ask price fetch unexpected error for %s: %s", symbol, exc)
return 0.0

# -- response adaptation --------------------------------------------------

Expand Down
150 changes: 75 additions & 75 deletions src/powertrader/hub/app.py

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions src/powertrader/hub/components/account_chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def _on_canvas_configure(e: Any) -> None:
except (ValueError, tk.TclError):
pass
self._resize_after_id = self.after_idle(self.canvas.draw_idle)
except Exception as exc:
except (tk.TclError, ValueError, TypeError, AttributeError) as exc:
logger.debug("Account chart configure error: %s", exc)

canvas_w.bind("<Configure>", _on_canvas_configure, add="+")
Expand All @@ -91,7 +91,7 @@ def _apply_dark_chart_style(self) -> None:
for spine in self.ax.spines.values():
spine.set_color(DARK_BORDER)
self.ax.grid(True, color=DARK_BORDER, linewidth=0.6, alpha=0.35)
except Exception as exc:
except (ValueError, TypeError, AttributeError) as exc:
logger.debug("Failed to apply dark chart style: %s", exc)

def refresh(self) -> None:
Expand Down Expand Up @@ -251,12 +251,12 @@ def refresh(self) -> None:
label, (x, y), textcoords="offset points", xytext=(0, 10),
ha="center", fontsize=8, color=DARK_FG, zorder=7,
)
except Exception as exc:
except (OSError, ValueError, TypeError, KeyError, IndexError) as exc:
logger.debug("Failed to draw trade markers on account chart: %s", exc)

try:
self.ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _pos: f"${y:,.2f}"))
except Exception as exc:
except (ValueError, TypeError) as exc:
logger.debug("Failed to set y formatter: %s", exc)

n = len(points)
Expand All @@ -283,7 +283,7 @@ def refresh(self) -> None:
self.ax.set_xticks(tick_x)
self.ax.set_xticklabels(tick_lbl)
self.ax.tick_params(axis="x", labelsize=8)
except Exception as exc:
except (ValueError, TypeError) as exc:
logger.debug("Failed to set account chart x labels: %s", exc)

self.ax.set_xlim(-0.5, (len(points) - 0.5) + 0.6)
Expand Down
10 changes: 5 additions & 5 deletions src/powertrader/hub/components/candle_chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def _on_canvas_configure(e: Any) -> None:
except (ValueError, tk.TclError):
pass
self._resize_after_id = self.after_idle(self.canvas.draw_idle)
except Exception as exc:
except (tk.TclError, ValueError, TypeError, AttributeError) as exc:
logger.debug("Canvas configure error: %s", exc)

canvas_w.bind("<Configure>", _on_canvas_configure, add="+")
Expand All @@ -138,7 +138,7 @@ def _apply_dark_chart_style(self) -> None:
for spine in self.ax.spines.values():
spine.set_color(DARK_BORDER)
self.ax.grid(True, color=DARK_BORDER, linewidth=0.6, alpha=0.35)
except Exception as exc:
except (ValueError, TypeError, AttributeError) as exc:
logger.debug("Failed to apply dark chart style: %s", exc)

def refresh(
Expand Down Expand Up @@ -309,7 +309,7 @@ def _label_right(y: Optional[float], tag: str, color: str) -> None:
_label_right(avg_cost_basis, "AVG", "yellow")
_label_right(dca_line_price, "DCA", "red")
_label_right(trail_line, "SELL", "green")
except Exception as exc:
except (ValueError, TypeError, IndexError) as exc:
logger.debug("Failed to draw chart labels: %s", exc)

try:
Expand Down Expand Up @@ -376,7 +376,7 @@ def _label_right(y: Optional[float], tag: str, color: str) -> None:
label, (x, y), textcoords="offset points", xytext=(0, 10),
ha="center", fontsize=8, color=DARK_FG, zorder=7,
)
except Exception as exc:
except (OSError, ValueError, TypeError, KeyError, IndexError) as exc:
logger.debug("Failed to draw trade markers: %s", exc)

self.ax.set_xlim(-0.5, (len(candles) - 0.5) + 0.6)
Expand Down Expand Up @@ -410,7 +410,7 @@ def _label_right(y: Optional[float], tag: str, color: str) -> None:
self.ax.set_xticks(tick_x)
self.ax.set_xticklabels(tick_lbl)
self.ax.tick_params(axis="x", labelsize=8)
except Exception as exc:
except (ValueError, TypeError) as exc:
logger.debug("Failed to set x tick labels: %s", exc)

self.canvas.draw_idle()
Expand Down
2 changes: 1 addition & 1 deletion src/powertrader/hub/components/candle_fetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def __init__(self) -> None:
logger.debug("kucoin package not installed, using REST fallback")
self._mode = "rest"
self._market = None
except Exception as exc:
except (OSError, ConnectionError, RuntimeError, ValueError) as exc:
logger.debug("KuCoin client init failed: %s", exc)
self._mode = "rest"
self._market = None
Expand Down
2 changes: 1 addition & 1 deletion src/powertrader/hub/components/health_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,5 +146,5 @@ def set_status(self, text: str, color: str) -> None:
try:
self._canvas.itemconfigure(self._dot, fill=color)
self._label.config(text=f"{self._name}: {text}")
except Exception as exc:
except (tk.TclError, AttributeError) as exc:
logger.debug("Failed to update health row %s: %s", self._name, exc)
2 changes: 1 addition & 1 deletion src/powertrader/hub/components/wrap_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def clear(self, destroy_widgets: bool = True) -> None:
if destroy_widgets:
try:
it.w.destroy()
except Exception:
except (tk.TclError, AttributeError):
pass
self._items = []
self._schedule_reflow()
Expand Down
10 changes: 5 additions & 5 deletions src/powertrader/hub/dialogs/settings_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ def save() -> None:
messagebox.showinfo("Saved", "Settings saved.")
win.destroy()

except Exception as e:
except (ValueError, TypeError, OSError, tk.TclError) as e:
messagebox.showerror("Error", f"Failed to save settings:\n{e}")

ttk.Button(btns, text="Save", command=save).pack(side="left")
Expand Down Expand Up @@ -379,7 +379,7 @@ def _open_api_folder() -> None:
subprocess.Popen(["open", folder])
return
subprocess.Popen(["xdg-open", folder])
except Exception as e:
except OSError as e:
messagebox.showerror("Couldn't open folder", f"Tried to open:\n{self.project_dir}\n\nError:\n{e}")

def _clear_api_files() -> None:
Expand All @@ -398,7 +398,7 @@ def _clear_api_files() -> None:
os.remove(key_path)
if os.path.isfile(secret_path):
os.remove(secret_path)
except Exception as e:
except OSError as e:
messagebox.showerror("Delete failed", f"Couldn't delete the files:\n\n{e}")
return
_refresh_api_status()
Expand Down Expand Up @@ -575,7 +575,7 @@ def _test_credentials() -> None:
"Your API Key + Secret Key worked!\n\n"
f"Binance responded successfully.\nUSDT balance: {usdt_balance}\n\nNext: click Save."
)
except Exception as e:
except (OSError, ConnectionError, ValueError, RuntimeError) as e:
err_str = str(e)
hint = ""
if "APIError(code=-2015)" in err_str or "Invalid API-key" in err_str:
Expand Down Expand Up @@ -636,7 +636,7 @@ def do_save() -> None:
f.write(api_key)
with open(secret_path, "w", encoding="utf-8") as f:
f.write(secret_key)
except Exception as e:
except OSError as e:
messagebox.showerror("Save failed", f"Couldn't write the credential files.\n\nError:\n{e}")
return

Expand Down
2 changes: 1 addition & 1 deletion src/powertrader/hub/process_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def _poll_runner_ready_then_start_trader(
if after_cb:
try:
after_cb(250, lambda: self._poll_runner_ready_then_start_trader(after_cb))
except Exception as exc:
except (RuntimeError, ValueError, TypeError) as exc:
logger.debug("Polling schedule failed: %s", exc)

# ---- training ----
Expand Down
2 changes: 1 addition & 1 deletion src/powertrader/thinker/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def step(self) -> dict[str, Signal]:
logger.error("Signal generation I/O error for %s: %s", coin, exc)
if self._health:
self._health.record_error("thinker", exc)
except Exception as exc:
except (RuntimeError, ValueError, TypeError, KeyError, IndexError, ArithmeticError) as exc:
logger.error("Signal generation failed for %s: %s", coin, exc, exc_info=True)
if self._health:
self._health.record_error("thinker", exc)
Expand Down
6 changes: 3 additions & 3 deletions src/powertrader/trader/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def run(self) -> None:
logger.error("Trade management error: %s", exc)
if self._health:
self._health.record_error("trader", exc)
except Exception as exc:
except (RuntimeError, ValueError, TypeError, KeyError, IndexError, ArithmeticError) as exc:
logger.error("Unexpected trade management error: %s", exc, exc_info=True)
if self._health:
self._health.record_error("trader", exc)
Expand Down Expand Up @@ -157,7 +157,7 @@ def _sync_positions(self, prices: dict[str, float]) -> None:
except (ExchangeError, OSError, ConnectionError) as exc:
logger.error("Failed to fetch holdings: %s", exc)
return
except Exception as exc:
except (RuntimeError, ValueError, TypeError, KeyError) as exc:
logger.error("Unexpected error fetching holdings: %s", exc, exc_info=True)
return

Expand Down Expand Up @@ -394,7 +394,7 @@ def _calculate_account_value(self, prices: dict[str, float]) -> float:
except (ExchangeError, OSError, ConnectionError) as exc:
logger.error("Failed to fetch account balance: %s", exc)
return 0.0
except Exception as exc:
except (RuntimeError, ValueError, TypeError, KeyError) as exc:
logger.error("Unexpected error fetching balance: %s", exc, exc_info=True)
return 0.0

Expand Down
2 changes: 1 addition & 1 deletion src/powertrader/trainer/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def _train_coin(
logger.error("Training %s/%s failed: %s", coin, timeframe, exc)
if self._health:
self._health.record_error("trainer", exc)
except Exception as exc:
except (RuntimeError, ValueError, TypeError, KeyError, IndexError, ArithmeticError) as exc:
logger.error(
"Training %s/%s unexpected error: %s", coin, timeframe, exc, exc_info=True
)
Expand Down
Loading