diff --git a/artifacts/exchanges/base_exchange.yaml b/artifacts/exchanges/base_exchange.yaml new file mode 100644 index 0000000..e69de29 diff --git a/artifacts/exchanges/binance.yaml b/artifacts/exchanges/binance.yaml new file mode 100644 index 0000000..e69de29 diff --git a/artifacts/exchanges/btcc.yaml b/artifacts/exchanges/btcc.yaml new file mode 100644 index 0000000..e69de29 diff --git a/artifacts/exchanges/bullish.yaml b/artifacts/exchanges/bullish.yaml new file mode 100644 index 0000000..e69de29 diff --git a/artifacts/exchanges/bybit.yaml b/artifacts/exchanges/bybit.yaml new file mode 100644 index 0000000..e69de29 diff --git a/artifacts/exchanges/mexc.yaml b/artifacts/exchanges/mexc.yaml new file mode 100644 index 0000000..e69de29 diff --git a/artifacts/execution/live.yaml b/artifacts/execution/live.yaml new file mode 100644 index 0000000..e69de29 diff --git a/artifacts/execution/trader.yaml b/artifacts/execution/trader.yaml new file mode 100644 index 0000000..f3465e7 --- /dev/null +++ b/artifacts/execution/trader.yaml @@ -0,0 +1,149 @@ +source_file: ./trader.py +schema_version: v1.1 + +factual_summary: > + Implements the execution component responsible for placing and managing + long and short trades, including associated hedge operations, across + supported exchanges. Maintains order book state, open positions, fees, + and profit and loss tracking while supporting both live trading and + backtesting modes. + +methods: + _getBracket(exch: str, sym: str) -> List[]: + description: > + Retrieves the current bid and ask information for a given symbol + on a specified exchange using maintained order book state. + + startBidding(exch: str, sym: str, ts: float, entryPrice: float or None) -> None: + description: > + Used in the Strat class to update the entry price of a symbol on a particular exchange. Logic for updating the + entry price is contained there. + + stopBidding(exch: str, sym: str, ts: float) -> None: + description: > + Halts the bidding by removing the order from the limitBuy dictionary. + + updateBracket(exch: str, sym: str, bidQuote: float, askQuote: float) -> None: + description: > + Updates the bracketed strings in our brackets dictionary. + + startOffering(exch: str, sym: str, ts: float, entryPrice: float or None) -> None: + description: > + Executes the trades when we are going short. + + stopOffering(exch: str, sym: str, ts: float) -> None: + description: > + Stops the short position. + + logIntradayPnl(val: float) -> None: + description: > + Updates the value of our account to our pnl database + + fpnl() -> None: + description: > + Returns a list of floating profit and loss summaries + + posCounts() -> dict: + description: > + Returns a python dictionary of the total positions we have on each exchange. + + logFee(fee: float) -> None: + description: > + Updates our fees in our database + + posValueAtExchOld(exch: str, sym: str) -> int: + description: > + Calculates the values of the long and short positions. + + fpnlnotional() -> int: + description: > + This method calculates the profit/loss (P&L) based on the notional value of long and short positions for each + unique symbol across different exchanges. It computes the average price of long positions, sums the notional + values of both long and short positions, and then uses these to compute the P&L. + + fillLong(exch: str, sym: str, price: float, quan: float, ts: int, tag: str, feeType: str) -> None: + description: > + The fillLong method handles the process of filling a buy order for a specified asset on an exchange. It updates + the trader's position with the new quantity and calculates the average price if necessary. If there was a short + position, it also calculates the profit/loss from buying back some or all of the shorted amount. Additionally, + it logs the trade, applies fees, and ensures data integrity by asserting non-negative values. + + fillShort(exch: str, sym: str, price: float, quan: float, ts: int, tag: str, feeType: str) -> None: + description: > + The fillShort method handles the process of filling a sell order for a specified asset on an exchange. It updates + the trader's position with the new quantity and calculates the average price if necessary. If there was a long + position, it also calculates the profit/loss from selling some or all of the held amount. Additionally, it logs + the trade, applies fees, and ensures data integrity by asserting non-negative values. + + hedgeLong(exch: str, sym: str, price: float, quan: float, ts: int, force: bool) -> Exchange: + description: > + The hedgeLong method finds an appropriate exchange to hedge a long position by executing a corresponding sell + order. It iterates over possible exchanges, calculates adjusted bid prices based on offsets, and selects the + highest bid price for execution. If no suitable exchange is found without forcing, it forces hedging. The method + ensures that the hedge does not exceed maximum allowed positions and logs relevant information throughout the + process. + + hedgeShort(exch: str, sym: str, price: float, quan: float, ts: int, force: bool) -> Exchange: + description: > + The hedgeShort method finds an appropriate exchange to hedge a short position by executing a corresponding buy + order. It iterates over possible exchanges, calculates adjusted ask prices based on offsets, and selects the + lowest ask price for execution. If no suitable exchange is found without forcing, it forces hedging. The method + ensures that the hedge does not exceed maximum allowed positions and logs relevant information throughout the + process. + + processTrade(exch: str, sym: str, price: float, tradeDir: list) -> None: + description: > + The first half of the processTrade method handles the scenario where a market sell order results in hitting a + limit buy order. It processes the fill, hedges the position, and logs various portfolio and holdings-related + details. The second half of the processTrade method handles the scenario where a market buy order results in + hitting a limit sell order. It processes the fill, hedges the position, and logs various portfolio and + holdings-related details. + + +interpretive_summary: > + Acts as the execution boundary between strategy decision logic and + exchange interaction, encapsulating trade placement, position tracking, + and operational mode handling. Designed to centralize execution-side + concerns such as fee application, position state, and environment-aware + behavior for live and simulated trading. + +invariants: + - Trades must only be executed when trading is explicitly enabled. + - Exchange-specific state must be initialized before order execution. + - Position and profit tracking must remain consistent with executed trades. + - Execution behavior must respect live versus backtest operating modes. + +tags: + domain: + - order_execution + - exchange_integration + - pnl_accounting + + trading_function: + - entry_logic + - exit_logic + + strategy_layer: + - execution + + system_layer: + - service + + intent: + - abstraction + - safety + - isolation + + data_type: + - orders + - positions + - pnl + - exchanges + + risk: + - capital_loss + - latency + - data_corruption + + maturity: + - production \ No newline at end of file diff --git a/artifacts/risk/manhole.yaml b/artifacts/risk/manhole.yaml new file mode 100644 index 0000000..e69de29 diff --git a/artifacts/strategies/strat.yaml b/artifacts/strategies/strat.yaml new file mode 100644 index 0000000..0c3b94c --- /dev/null +++ b/artifacts/strategies/strat.yaml @@ -0,0 +1,95 @@ +source_file: ./strat.py +schema_version: v1.1 + +factual_summary: > + Implements a market making strategy module responsible for maintaining + top-of-book state, calculating bid and ask prices using threshold-based + logic, validating tradable assets, and coordinating trade logging. + Manages exchange instances, symbol discovery across exchanges, and + runtime strategy state used for order placement and monitoring. + +methods: + registerExchange(exch: str, exchInst: Exchange) -> None: + description: > + Registers an exchange instance under a named key for use by the + strategy during execution. + + setMinQty(exch: str, qtyMap: dict) -> None: + description: > + Updates minimum and maximum trade quantity constraints for a given + exchange using a provided quantity mapping. + + printFloating(ts: float) -> None: + description: > + Emits a formatted runtime summary of strategy activity for logging + and monitoring purposes. + + bestEdgeBid(exch: str, sym: str) -> List[bool, float, bool, str, float]: + description: > + This method is designed to determine whether and where a bid should be placed based on several factors + related to market conditions and strategy rules. Its primary goal of is to calculate the optimal bid price for a + given symbol on a specific exchange, taking into account market positions, hedging strategies, trading limits, + price precision, and fee structures. Returns a collection of decision outputs including bid eligibility status, + relative pricing divergence, long-position participation, selected hedge exchange, and the computed bid price. + + bestEdgeOffer(exch: str, sym: str) -> list: + description: > + The primary goal of bestEdgeOffer is to calculate the optimal offer (ask) price for a given symbol on a specific + exchange, considering market positions, hedging strategies, trading limits, price precision, fee structures. + Returns almost identical items as bestEdgeBid, but on the other side of the order book + + updateTob(exch: str, sym: str, tob: dict, ts: float, force: bool) -> None: + description: > + The primary goal of the updateTob function is to update the top of the order book for quick access to perform + market making operations (bidding and selling) using the highest bid and lowest ask prices. + +interpretive_summary: > + Serves as the central coordination unit for the market making strategy, + maintaining shared runtime state across exchanges and assets while + enforcing eligibility rules and operational constraints. Designed to + balance responsiveness with safety through internal validation, + rate limiting counters, and symbol qualification logic. + +invariants: + - Only assets validated by runtime eligibility checks may be traded. + - Exchange instances must be registered before strategy execution. + - Top-of-book data must exist before bid or ask calculations occur. + - Rate limiting counters must accurately reflect order activity. + +tags: + domain: + - market_data + - strategy_execution + - order_execution + - exchange_integration + + trading_function: + - position_sizing + - entry_logic + - exit_logic + + strategy_layer: + - execution + - decision + + system_layer: + - engine + + intent: + - orchestration + - validation + - safety + + data_type: + - signals + - orders + - positions + - exchanges + + risk: + - capital_loss + - latency + - data_corruption + + maturity: + - production \ No newline at end of file diff --git a/schemas/artifact_schema.yaml b/schemas/artifact_schema.yaml new file mode 100644 index 0000000..3e1f0c7 --- /dev/null +++ b/schemas/artifact_schema.yaml @@ -0,0 +1,102 @@ +# artifact_schema.yaml +schema_name: trading_code_artifact +schema_version: v1.1 +description: > + Defines the structure for derived knowledge artifacts generated from + trading system source code. Artifacts capture factual structure, + interpretive intent, invariants, and validated tags for reasoning + and retrieval by the AI backend. + +required_fields: + - source_file + - schema_version + - factual_summary + - tags + +optional_fields: + - methods + - interpretive_summary + - invariants + - provenance + +field_definitions: + + source_file: + type: string + description: Relative path to the source file in the trading repository. + constraints: + - non_empty + - relative_path + + schema_version: + type: string + description: Version of the artifact schema used to generate this artifact. + + factual_summary: + type: text + description: > + Objective description of what the file or module does. + Focuses on responsibilities and structure, not rationale. + constraints: + - min_length: 40 + - max_length: 500 + - no_interpretive_language + + methods: + type: object + optional: true + description: > + Optional method-level descriptions for classes or modules where + fine-grained behavioral understanding is useful. + method_definition: + signature: + type: string + description: + type: text + constraints: + - no_implementation_details + - max_length: 200 + + interpretive_summary: + type: text + optional: true + description: > + High-level explanation of why the file exists, what architectural + role it plays, and what tradeoffs or risks it is designed to manage. + constraints: + - min_length: 40 + - max_length: 500 + - no_code_identifiers + + invariants: + type: list + optional: true + description: > + Conditions that must always hold true for correct behavior. + item_constraints: + - type: string + - min_length: 10 + + tags: + type: object + description: > + Classification metadata for the artifact. All tag dimensions + and values must conform to the backend tag schema. + constraints: + - validated_against_tag_schema + + provenance: + type: object + optional: true + fields: + generated_at: + type: datetime + generated_by: + type: string + source_commit: + type: string + confidence_score: + type: float + constraints: + - min: 0.0 + - max: 1.0 diff --git a/schemas/tag_schema.yaml b/schemas/tag_schema.yaml new file mode 100644 index 0000000..f63b2eb --- /dev/null +++ b/schemas/tag_schema.yaml @@ -0,0 +1,60 @@ +# tag_schema.yaml +schema_version: v1 + +dimensions: + domain: + - market_data + - signal_generation + - strategy_execution + - risk_management + - order_execution + - exchange_integration + - pnl_accounting + + trading_function: + - data_ingest + - alpha_generation + - position_sizing + - entry_logic + - exit_logic + + strategy_layer: + - signal + - decision + - execution + - evaluation + + system_layer: + - api + - service + - engine + - worker + - persistence + + intent: + - orchestration + - abstraction + - isolation + - validation + - optimization + - safety + + data_type: + - signals + - orders + - positions + - pnl + - configs + - exchanges + + risk: + - capital_loss + - liquidation + - latency + - data_corruption + - security + - hedging + + maturity: + - experimental + - production \ No newline at end of file