Skip to content

Latest commit

 

History

240 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Quality Gate Status

The Sphinx orderbook

Implementation of the sphinx orderbook and The Sphinx API provides a robust platform for trading operations, offering a wide range of endpoints from account management to market data access and order execution. This API is designed for developers looking to integrate their trading applications with Sphinx's trading services.

Orderbook Operations

Basic Operations

  • Add: Adds an order to the order book. The time complexity is O(log M) when placing the first order at a specific limit price, and O(1) for all subsequent orders at the same limit.
  • Cancel: Removes an order from the order book instantly with a time complexity of O(1).
  • GetBestBid/Offer: Retrieves the best available bid or offer from the order book instantly with a time complexity of O(1).
  • GetVolumeAtLimit: Provides the total volume of orders at a specific limit price instantly with a time complexity of O(1).

basic_orderbook_operations

Market and Limit Order Processing

  • ProcessMarketOrder(order *Order): Processes a market order and matches it against the order book. Returns completed orders, any partial order that could not be fully executed, the quantity processed, and any remaining quantity.
  • ProcessLimitOrder(order *Order): Processes a limit order. Similar to market orders, it returns completed orders and any partial order along with the quantity processed.

process_market_limit_orders

Price and Depth Information

  • GetBestPrice(side Side): Fetches the best price available for a given side (buy or sell).
  • Depth(): Returns two lists representing the depth of the market, categorized into asks and bids.
  • CalculateMarketPrice(side Side, quantity decimal.Decimal): Calculates the potential market price for a given quantity on a specified side, useful for estimating market impact.

price_depth_information

Order and Position Management

  • GetOrderSide(side Side): Retrieves orders segregated by the side (buy or sell).
  • MarketDepth(): Provides a view of the market depth including both bids and asks.
  • MarketOverview(): Offers a summary view of the market orders.
  • CreateNewPosition(order *Order): Creates a new trading position based on the order details.
  • GetPosition(accountID string): Fetches a trading position for a specific account ID.
  • UpdatePosition(accountID string, position *Position): Updates a trading position for a specific account.
  • NewOrUpdatedPosition(order *Order): Evaluates an order and creates or updates a position accordingly.

order_position_management

System and Data Management

  • NewProcessResultChan(size int): Initializes a new channel to handle process results with a specified buffer size.
  • GetProcessResultChan(): Retrieves the channel used for processing results.
  • GetStateManager(): Accesses the state manager responsible for maintaining state across the system.

Monitoring and Data Integration

  • StartMonitoringAndLiquidationEngine(): Initiates monitoring processes that handle market conditions and trigger liquidations if necessary.
  • StartMonitoringTriggerPricesLimit(): Begins monitoring for price triggers that affect limit orders.
  • StartMonitoringTriggerPricesMarket(): Starts tracking price triggers for market orders.

Utility Methods

  • Ticker(): Returns the ticker symbol associated with the order book.
  • String(): Provides a string representation of the order book.
  • MarshalJSON(): Serializes the order book into JSON format.
  • UnmarshalJSON(data []byte): Deserializes data from JSON into the order book structure.

Liquidation engine

Key Components for Liquidation Decision

  1. Current and Entry Prices:

    • The system retrieves the best current buy and sell prices from the order book, representing the highest bid (buy) and lowest ask (sell) prices available.
  2. Position Side (Long or Short):

    • Whether the position is long (Buy) or short (Sell) determines how price movements affect the position's risk exposure.
  3. Position Size and Price Update:

    • The size of the position (positive for long, negative for short) and its current price are updated based on the latest market prices.

Calculating Position Health

The ShouldBeLiquidated function implements the logic to determine the need for liquidation:

  • Price Update:

    • For Buy positions, the CurrentPrice updates to bestPriceSell, and for Sell positions, to bestPriceBuy. This reflects the worst-case scenario price for potentially closing the position given the current market liquidity.
  • Market Value and Margin Requirement:

    • Current Value: Calculated as CurrentPrice * abs(Size), representing the market value of the position.
    • Margin Requirement: Calculated as EntryPrice * abs(Size) * MaintenanceMargin. This is the minimum amount required to maintain the position, adjusted by a maintenance margin percentage from the configuration.
  • Equity Consideration:

    • The unrealized profit or loss (UnrealizedPL) of the position is also considered. Positions showing a profit (positive equity) are generally not targeted for liquidation unless they fail to meet other conditions (like sufficient margin coverage).

Liquidation Conditions

  • For Long Positions (Buy):

    • Liquidation is triggered if the current value of the position falls below the margin requirement, indicating that the position's market value can no longer cover the required margin.
  • For Short Positions (Sell):

    • Liquidation occurs if the equity (loss) plus the margin requirement turns negative, showing that the position's losses exceed the margin held, thus increasing the risk to the trading platform if the market moves further against the expected direction.

Liquidation Criteria Formula

The liquidation decision for a position is determined by the following conditions based on the side of the position (Long or Short):

For Long Positions (Buy)

  1. Current Market Value Calculation:
    • CurrentValue = CurrentPrice × |Size|
    • CurrentPrice: The lowest price at which the position could be sold (best ask price).
    • Size: The absolute size of the position.
  2. Margin Requirement Calculation:
  • MarginRequirement = EntryPrice × |Size| × MaintenanceMargin
  • EntryPrice: The price at which the position was originally entered.
  • MaintenanceMargin: The minimum margin ratio required to keep the position open, specified in the configuration.
  1. Liquidation Condition:
  • ShouldLiquidate = CurrentValue < MarginRequirement
  • This checks if the current market value of the position is less than the margin requirement. If true, the position is considered unhealthy and is marked for liquidation.

For Short Positions (Sell)

  1. Equity Calculation: Equity = UnrealizedPL

    • UnrealizedPL: The unrealized profit or loss of the position.
  2. Adjusted Margin Requirement Calculation:

    • AdjustedMarginRequirement = MarginRequirement + Equity
  3. Liquidation Condition: ShouldLiquidate = AdjustedMarginRequirement < 0

    • This checks if the loss on the position (negative equity) plus the margin requirement is negative, indicating that the losses exceed the margin held. This condition flags the position for potential liquidation.

General Considerations

  • Positions will not be liquidated if they are currently profitable (Equity >= 0).
  • Positions where the market price does not significantly deviate from the entry price as per the set thresholds (bestPriceBuy <= EntryPrice for Sell, bestPriceSell >= EntryPrice for Buy) will not trigger liquidation.

Interfaces

Account Management

The IAccountManager interface manages accounts and their associated transactions and orders. Key functionalities include:

  • GetAccountByID(string): Retrieves account details by ID.
  • GetAccounts(): Returns a list of all accounts.
  • NewAccount(decimal.Decimal): Creates a new account with an initial balance.
  • NewAccountWithID(decimal.Decimal, string): Creates a new account with a specified ID and initial balance.
  • AddOrder(accountID string, order *Order, isOpen bool): Adds an order to the account.
  • RemoveOrder(accountID string, orderID string, isOpen bool): Removes an order from the account.
  • Deposit(tx *Transaction): Handles deposits into accounts.
  • GetDeposit(accountID string, txID string): Retrieves a specific deposit transaction.
  • Withdraw(tx *Transaction): Handles withdrawals from accounts.
  • GetWithdraw(accountID string, txID string): Retrieves a specific withdrawal transaction. account_management

Additional IAccount interface methods include:

  • CheckAccountBalance(amount decimal.Decimal): Verifies if the account balance is sufficient for a transaction.
  • GetOrderByID(orderID string, isOpen bool): Retrieves an order by ID from the account.
  • RemoveOrderByID(orderID string, isOpen bool): Removes an order by ID from the account.
  • GetID(): Returns the account ID.
  • GetBalance(): Provides the current account balance.
  • GetOrders(isOpen bool): Lists all open or closed orders.
  • GetTransactions(isDeposit bool): Lists all transactions, filtered by deposit or withdrawal.
  • MarshalJSON(), UnmarshalJSON(data []byte): Serialization and deserialization of account data. iaccount

Order and Position Management

IOrderBook extends its functionalities to include advanced trading and order handling:

  • ProcessMarketOrder(order *Order), ProcessLimitOrder(order *Order): Process market and limit orders respectively.
  • GetBestPrice(side Side), Depth(), CalculateMarketPrice(side Side, quantity decimal.Decimal): Methods to retrieve price and market depth.
  • GetOrderSide(side Side), MarketDepth(), MarketOverview(): Retrieve orders by side, market depth, and market overview.
  • CreateNewPosition(order *Order), GetPosition(accountID string), UpdatePosition(accountID string, position *Position), NewOrUpdatedPosition(order *Order): Manage trading positions.
  • NewProcessResultChan(size int), GetProcessResultChan(): Management of process results via channels.
  • GetStateManager(): Accesses the state manager.
  • StartMonitoringAndLiquidationEngine(), StartMonitoringTriggerPricesLimit(), StartMonitoringTriggerPricesMarket(): Monitoring functions for market conditions and price triggers. iorderbook

System and Data Management

IStateManager interface ensures data integrity and manages the state of the order book:

  • IsOrderExist(orderID string), GetOrderByID(orderID string), CancelOrder(orderID string): Check if an order exists, retrieve it, or cancel it.
  • AddOrder(order *Order, sideToAdd *OrderSide), UpdateOrder(orderID string, o *Order): Add or update orders in the order book.
  • GetAsks(), GetBids(), SetAsks(asks *OrderSide), SetBids(bids *OrderSide): Manage ask and bid sides of the order book.
  • MarshalJSON(), UnmarshalJSON(data []byte): Serialization and deserialization of state.
  • SetSnapshot(snapshot []byte), GetSnapshot(): Manage snapshots of the order book state for recovery and backup.

istatemanager

API Authentication

The API uses Basic Authentication to secure endpoints. Ensure that your API requests include the appropriate authorization headers.

API Content-Type

All requests should be made with the Content-Type header set to application/json.

API Endpoints

processing_limit_order

API Accounts

For full API documentation, please visit our Swagger UI.

Accounts

  • GET /accounts/: Retrieve all accounts with details like account ID, balance, and lists of open and closed orders.
  • GET /accounts/:id: Fetch a single account by its ID.
  • GET /accounts/current: Get the currently authenticated account's details.
  • GET /accounts/current/positions: Retrieve positions for the current account.
  • POST /accounts/deposit: Deposit funds into an account.
  • GET /accounts/deposit/:id/status: Check the status of a specific deposit.
  • POST /accounts/withdraw: Withdraw funds from an account.
  • GET /accounts/withdraw/:id/status: Check the status of a specific withdrawal.

API Order Management

  • POST /order/limit: Place a limit order with specified order parameters.
  • POST /order/market: Execute a market order.
  • GET /order/{id}: Retrieve details about a specific order using its ID.
  • DELETE /order/{id}: Cancel a specific order.

API Market Data

  • GET /orderbook/: Access the complete order book, including asks and bids.
  • GET /orderbook/depth: Get market depth information from the order book.
  • GET /orderbook/ws: Establish a WebSocket connection for real-time order book updates.
  • POST /order/price: Request the market price for a specified order and OrderBook.

API TradingView Integration

  • GET /tradingview/config: Fetch configuration data for the TradingView integration.
  • GET /tradingview/history: Obtain historical market data based on symbol and resolution.
  • GET /tradingview/groups: List all symbol groups available for TradingView.
  • GET /tradingview/search: Search for TradingView symbols based on various criteria.
  • GET /tradingview/symbol_info: Retrieve detailed information about trading instruments.
  • GET /tradingview/symbols: Request resolution data for a specific symbol.

API General

  • GET /healthcheck: Perform a health check of the API.

Response Structures

Responses will follow the structure defined in the Swagger documentation provided, including objects for accounts, orders, positions, and various responses specific to TradingView integration.

Error Handling

Responses for erroneous requests will contain an error message and, when applicable, details about the validation errors encountered.

Sequence diagram that illustrates SPHX system's trading flow

processing_limit_order

Installing PostgreSQL with Docker locally:

docker pull postgres:16
docker volume create postgres_data
docker run --name postgres_container -e POSTGRES_PASSWORD=test123 -d -p 5432:5432 -v postgres_data:/var/lib/postgresql/data postgres:16
docker ps

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages