This commit is contained in:
1
backend/trading_journal/crud.py
Normal file
1
backend/trading_journal/crud.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
@@ -15,22 +15,43 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
class Database:
|
||||
def __init__(self, database_url: str | None = None, *, echo: bool = False, connect_args: dict | None = None) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
database_url: str | None = None,
|
||||
*,
|
||||
echo: bool = False,
|
||||
connect_args: dict | None = None,
|
||||
) -> None:
|
||||
self._database_url = database_url or "sqlite:///:memory:"
|
||||
|
||||
default_connect = {"check_same_thread": False, "timeout": 30} if self._database_url.startswith("sqlite") else {}
|
||||
default_connect = (
|
||||
{"check_same_thread": False, "timeout": 30}
|
||||
if self._database_url.startswith("sqlite")
|
||||
else {}
|
||||
)
|
||||
merged_connect = {**default_connect, **(connect_args or {})}
|
||||
|
||||
if self._database_url == "sqlite:///:memory:":
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.warning("Using in-memory SQLite database; all data will be lost when the application stops.")
|
||||
self._engine = create_engine(self._database_url, echo=echo, connect_args=merged_connect, poolclass=StaticPool)
|
||||
logger.warning(
|
||||
"Using in-memory SQLite database; all data will be lost when the application stops."
|
||||
)
|
||||
self._engine = create_engine(
|
||||
self._database_url,
|
||||
echo=echo,
|
||||
connect_args=merged_connect,
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
else:
|
||||
self._engine = create_engine(self._database_url, echo=echo, connect_args=merged_connect)
|
||||
self._engine = create_engine(
|
||||
self._database_url, echo=echo, connect_args=merged_connect
|
||||
)
|
||||
|
||||
if self._database_url.startswith("sqlite"):
|
||||
|
||||
def _enable_sqlite_pragmas(dbapi_conn: DBAPIConnection, _connection_record: object) -> None:
|
||||
def _enable_sqlite_pragmas(
|
||||
dbapi_conn: DBAPIConnection, _connection_record: object
|
||||
) -> None:
|
||||
try:
|
||||
cur = dbapi_conn.cursor()
|
||||
cur.execute("PRAGMA journal_mode=WAL;")
|
||||
@@ -62,5 +83,10 @@ class Database:
|
||||
self._engine.dispose()
|
||||
|
||||
|
||||
def create_database(database_url: str | None = None, *, echo: bool = False, connect_args: dict | None = None) -> Database:
|
||||
def create_database(
|
||||
database_url: str | None = None,
|
||||
*,
|
||||
echo: bool = False,
|
||||
connect_args: dict | None = None,
|
||||
) -> Database:
|
||||
return Database(database_url, echo=echo, connect_args=connect_args)
|
||||
|
||||
@@ -18,9 +18,16 @@ def _mig_0_1(engine: Engine) -> None:
|
||||
"""
|
||||
# Ensure all models are imported before this is called (import side-effect registers tables)
|
||||
# e.g. trading_journal.models is imported in the caller / app startup.
|
||||
from trading_journal import models_v1 # noqa: PLC0415, F401
|
||||
from trading_journal import models_v1
|
||||
|
||||
SQLModel.metadata.create_all(bind=engine)
|
||||
SQLModel.metadata.create_all(
|
||||
bind=engine,
|
||||
tables=[
|
||||
models_v1.Trades.__table__,
|
||||
models_v1.Cycles.__table__,
|
||||
models_v1.Users.__table__,
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
# map current_version -> function that migrates from current_version -> current_version+1
|
||||
@@ -51,7 +58,9 @@ def run_migrations(engine: Engine, target_version: int | None = None) -> int:
|
||||
while cur_version < target:
|
||||
fn = MIGRATIONS.get(cur_version)
|
||||
if fn is None:
|
||||
raise RuntimeError(f"No migration from {cur_version} -> {cur_version + 1}")
|
||||
raise RuntimeError(
|
||||
f"No migration from {cur_version} -> {cur_version + 1}"
|
||||
)
|
||||
# call migration with Engine (fn should use transactions)
|
||||
fn(engine)
|
||||
_set_sqlite_user_version(conn, cur_version + 1)
|
||||
|
||||
@@ -3,8 +3,8 @@ from __future__ import annotations
|
||||
from datetime import date, datetime # noqa: TC003
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy import Date, Text, UniqueConstraint
|
||||
from sqlmodel import Column, DateTime, Field, Relationship, SQLModel
|
||||
from sqlmodel import Enum as SQLEnum
|
||||
|
||||
|
||||
class TradeType(str, Enum):
|
||||
@@ -12,6 +12,18 @@ class TradeType(str, Enum):
|
||||
ASSIGNMENT = "ASSIGNMENT"
|
||||
SELL_CALL = "SELL_CALL"
|
||||
EXERCISE_CALL = "EXERCISE_CALL"
|
||||
LONG_SPOT = "LONG_SPOT"
|
||||
CLOSE_LONG_SPOT = "CLOSE_LONG_SPOT"
|
||||
SHORT_SPOT = "SHORT_SPOT"
|
||||
CLOSE_SHORT_SPOT = "CLOSE_SHORT_SPOT"
|
||||
LONG_CFD = "LONG_CFD"
|
||||
CLOSE_LONG_CFD = "CLOSE_LONG_CFD"
|
||||
SHORT_CFD = "SHORT_CFD"
|
||||
CLOSE_SHORT_CFD = "CLOSE_SHORT_CFD"
|
||||
LONG_OTHER = "LONG_OTHER"
|
||||
CLOSE_LONG_OTHER = "CLOSE_LONG_OTHER"
|
||||
SHORT_OTHER = "SHORT_OTHER"
|
||||
CLOSE_SHORT_OTHER = "CLOSE_SHORT_OTHER"
|
||||
|
||||
|
||||
class TradeStrategy(str, Enum):
|
||||
@@ -34,13 +46,25 @@ class FundingSource(str, Enum):
|
||||
|
||||
class Trades(SQLModel, table=True):
|
||||
__tablename__ = "trades"
|
||||
id: str | None = Field(default=None, primary_key=True)
|
||||
user_id: str
|
||||
symbol: str
|
||||
underlying_currency: str
|
||||
trade_type: TradeType = Field(sa_column=Column(SQLEnum(TradeType, name="trade_type_enum"), nullable=False))
|
||||
trade_strategy: TradeStrategy = Field(sa_column=Column(SQLEnum(TradeStrategy, name="trade_strategy_enum"), nullable=False))
|
||||
trade_time_utc: datetime = Field(sa_column=Column(DateTime(timezone=True), nullable=False))
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"user_id", "friendly_name", name="uq_trades_user_friendly_name"
|
||||
),
|
||||
)
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
user_id: int = Field(foreign_key="users.id", nullable=False, index=True)
|
||||
# allow null while user may omit friendly_name; uniqueness enforced per-user by constraint
|
||||
friendly_name: str | None = Field(
|
||||
default=None, sa_column=Column(Text, nullable=True)
|
||||
)
|
||||
symbol: str = Field(sa_column=Column(Text, nullable=False))
|
||||
underlying_currency: str = Field(sa_column=Column(Text, nullable=False))
|
||||
trade_type: TradeType = Field(sa_column=Column(Text, nullable=False))
|
||||
trade_strategy: TradeStrategy = Field(sa_column=Column(Text, nullable=False))
|
||||
trade_time_utc: datetime = Field(
|
||||
sa_column=Column(DateTime(timezone=True), nullable=False)
|
||||
)
|
||||
expiry_date: date | None = Field(default=None, nullable=True)
|
||||
strike_price_cents: int | None = Field(default=None, nullable=True)
|
||||
quantity: int
|
||||
@@ -48,21 +72,41 @@ class Trades(SQLModel, table=True):
|
||||
gross_cash_flow_cents: int
|
||||
commission_cents: int
|
||||
net_cash_flow_cents: int
|
||||
cycle_id: str | None = Field(default=None, foreign_key="cycles.id", nullable=True)
|
||||
cycle_id: int | None = Field(
|
||||
default=None, foreign_key="cycles.id", nullable=True, index=True
|
||||
)
|
||||
cycle: Cycles | None = Relationship(back_populates="trades")
|
||||
|
||||
|
||||
class Cycles(SQLModel, table=True):
|
||||
__tablename__ = "cycles"
|
||||
id: str | None = Field(default=None, primary_key=True)
|
||||
user_id: str
|
||||
symbol: str
|
||||
underlying_currency: str
|
||||
start_date: date
|
||||
end_date: date | None = Field(default=None, nullable=True)
|
||||
status: CycleStatus = Field(sa_column=Column(SQLEnum(CycleStatus, name="cycle_status_enum"), nullable=False))
|
||||
funding_source: FundingSource = Field(sa_column=Column(SQLEnum(FundingSource, name="funding_source_enum"), nullable=False))
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"user_id", "friendly_name", name="uq_cycles_user_friendly_name"
|
||||
),
|
||||
)
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
user_id: int = Field(foreign_key="users.id", nullable=False, index=True)
|
||||
friendly_name: str | None = Field(
|
||||
default=None, sa_column=Column(Text, nullable=True)
|
||||
)
|
||||
symbol: str = Field(sa_column=Column(Text, nullable=False))
|
||||
underlying_currency: str = Field(sa_column=Column(Text, nullable=False))
|
||||
status: CycleStatus = Field(sa_column=Column(Text, nullable=False))
|
||||
funding_source: FundingSource = Field(sa_column=Column(Text, nullable=False))
|
||||
capital_exposure_cents: int
|
||||
loan_amount_cents: int | None = Field(default=None, nullable=True)
|
||||
loan_interest_rate_bps: int | None = Field(default=None, nullable=True)
|
||||
start_date: date = Field(sa_column=Column(Date, nullable=False))
|
||||
end_date: date | None = Field(default=None, sa_column=Column(Date, nullable=True))
|
||||
trades: list[Trades] = Relationship(back_populates="cycle")
|
||||
|
||||
|
||||
class Users(SQLModel, table=True):
|
||||
__tablename__ = "users"
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
# unique=True already creates an index; no need to also set index=True
|
||||
username: str = Field(sa_column=Column(Text, nullable=False, unique=True))
|
||||
password_hash: str = Field(sa_column=Column(Text, nullable=False))
|
||||
is_active: bool = Field(default=True, nullable=False)
|
||||
|
||||
@@ -3,8 +3,8 @@ from __future__ import annotations
|
||||
from datetime import date, datetime # noqa: TC003
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy import Date, Text, UniqueConstraint
|
||||
from sqlmodel import Column, DateTime, Field, Relationship, SQLModel
|
||||
from sqlmodel import Enum as SQLEnum
|
||||
|
||||
|
||||
class TradeType(str, Enum):
|
||||
@@ -12,6 +12,18 @@ class TradeType(str, Enum):
|
||||
ASSIGNMENT = "ASSIGNMENT"
|
||||
SELL_CALL = "SELL_CALL"
|
||||
EXERCISE_CALL = "EXERCISE_CALL"
|
||||
LONG_SPOT = "LONG_SPOT"
|
||||
CLOSE_LONG_SPOT = "CLOSE_LONG_SPOT"
|
||||
SHORT_SPOT = "SHORT_SPOT"
|
||||
CLOSE_SHORT_SPOT = "CLOSE_SHORT_SPOT"
|
||||
LONG_CFD = "LONG_CFD"
|
||||
CLOSE_LONG_CFD = "CLOSE_LONG_CFD"
|
||||
SHORT_CFD = "SHORT_CFD"
|
||||
CLOSE_SHORT_CFD = "CLOSE_SHORT_CFD"
|
||||
LONG_OTHER = "LONG_OTHER"
|
||||
CLOSE_LONG_OTHER = "CLOSE_LONG_OTHER"
|
||||
SHORT_OTHER = "SHORT_OTHER"
|
||||
CLOSE_SHORT_OTHER = "CLOSE_SHORT_OTHER"
|
||||
|
||||
|
||||
class TradeStrategy(str, Enum):
|
||||
@@ -34,13 +46,25 @@ class FundingSource(str, Enum):
|
||||
|
||||
class Trades(SQLModel, table=True):
|
||||
__tablename__ = "trades"
|
||||
id: str | None = Field(default=None, primary_key=True)
|
||||
user_id: str
|
||||
symbol: str
|
||||
underlying_currency: str
|
||||
trade_type: TradeType = Field(sa_column=Column(SQLEnum(TradeType, name="trade_type_enum"), nullable=False))
|
||||
trade_strategy: TradeStrategy = Field(sa_column=Column(SQLEnum(TradeStrategy, name="trade_strategy_enum"), nullable=False))
|
||||
trade_time_utc: datetime = Field(sa_column=Column(DateTime(timezone=True), nullable=False))
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"user_id", "friendly_name", name="uq_trades_user_friendly_name"
|
||||
),
|
||||
)
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
user_id: int = Field(foreign_key="users.id", nullable=False, index=True)
|
||||
# allow null while user may omit friendly_name; uniqueness enforced per-user by constraint
|
||||
friendly_name: str | None = Field(
|
||||
default=None, sa_column=Column(Text, nullable=True)
|
||||
)
|
||||
symbol: str = Field(sa_column=Column(Text, nullable=False))
|
||||
underlying_currency: str = Field(sa_column=Column(Text, nullable=False))
|
||||
trade_type: TradeType = Field(sa_column=Column(Text, nullable=False))
|
||||
trade_strategy: TradeStrategy = Field(sa_column=Column(Text, nullable=False))
|
||||
trade_time_utc: datetime = Field(
|
||||
sa_column=Column(DateTime(timezone=True), nullable=False)
|
||||
)
|
||||
expiry_date: date | None = Field(default=None, nullable=True)
|
||||
strike_price_cents: int | None = Field(default=None, nullable=True)
|
||||
quantity: int
|
||||
@@ -48,21 +72,41 @@ class Trades(SQLModel, table=True):
|
||||
gross_cash_flow_cents: int
|
||||
commission_cents: int
|
||||
net_cash_flow_cents: int
|
||||
cycle_id: str | None = Field(default=None, foreign_key="cycles.id", nullable=True)
|
||||
cycle_id: int | None = Field(
|
||||
default=None, foreign_key="cycles.id", nullable=True, index=True
|
||||
)
|
||||
cycle: Cycles | None = Relationship(back_populates="trades")
|
||||
|
||||
|
||||
class Cycles(SQLModel, table=True):
|
||||
__tablename__ = "cycles"
|
||||
id: str | None = Field(default=None, primary_key=True)
|
||||
user_id: str
|
||||
symbol: str
|
||||
underlying_currency: str
|
||||
start_date: date
|
||||
end_date: date | None = Field(default=None, nullable=True)
|
||||
status: CycleStatus = Field(sa_column=Column(SQLEnum(CycleStatus, name="cycle_status_enum"), nullable=False))
|
||||
funding_source: FundingSource = Field(sa_column=Column(SQLEnum(FundingSource, name="funding_source_enum"), nullable=False))
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"user_id", "friendly_name", name="uq_cycles_user_friendly_name"
|
||||
),
|
||||
)
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
user_id: int = Field(foreign_key="users.id", nullable=False, index=True)
|
||||
friendly_name: str | None = Field(
|
||||
default=None, sa_column=Column(Text, nullable=True)
|
||||
)
|
||||
symbol: str = Field(sa_column=Column(Text, nullable=False))
|
||||
underlying_currency: str = Field(sa_column=Column(Text, nullable=False))
|
||||
status: CycleStatus = Field(sa_column=Column(Text, nullable=False))
|
||||
funding_source: FundingSource = Field(sa_column=Column(Text, nullable=False))
|
||||
capital_exposure_cents: int
|
||||
loan_amount_cents: int | None = Field(default=None, nullable=True)
|
||||
loan_interest_rate_bps: int | None = Field(default=None, nullable=True)
|
||||
start_date: date = Field(sa_column=Column(Date, nullable=False))
|
||||
end_date: date | None = Field(default=None, sa_column=Column(Date, nullable=True))
|
||||
trades: list[Trades] = Relationship(back_populates="cycle")
|
||||
|
||||
|
||||
class Users(SQLModel, table=True):
|
||||
__tablename__ = "users"
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
# unique=True already creates an index; no need to also set index=True
|
||||
username: str = Field(sa_column=Column(Text, nullable=False, unique=True))
|
||||
password_hash: str = Field(sa_column=Column(Text, nullable=False))
|
||||
is_active: bool = Field(default=True, nullable=False)
|
||||
|
||||
Reference in New Issue
Block a user