|
| 1 | +from datetime import datetime |
| 2 | +from decimal import ROUND_HALF_UP, Decimal |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +import httpx |
| 6 | +import typer |
| 7 | + |
| 8 | +from ctenex.domain import OrderSide, OrderType |
| 9 | +from ctenex.domain.order_book.contract.schemas import ContractGetResponse |
| 10 | +from ctenex.exchange_client.db.connection import get_db_connection |
| 11 | +from ctenex.exchange_client.db.init import init_db |
| 12 | + |
| 13 | + |
| 14 | +# TODO: Move to settings |
| 15 | +def get_api_url() -> str: |
| 16 | + """Get the API URL from environment or default to localhost.""" |
| 17 | + return "http://0.0.0.0:8000" # Default to localhost, can be overridden |
| 18 | + |
| 19 | + |
| 20 | +app = typer.Typer() |
| 21 | + |
| 22 | + |
| 23 | +@app.command() |
| 24 | +def place_order( |
| 25 | + contract_id: str = typer.Argument(..., help="Contract identifier"), |
| 26 | + side: OrderSide = typer.Argument(..., help="Order side (BUY/SELL)"), |
| 27 | + type: OrderType = typer.Argument(..., help="Order type (LIMIT/MARKET)"), |
| 28 | + quantity: float = typer.Argument(..., help="Order quantity"), |
| 29 | + price: float = typer.Argument(..., help="Order price (2 decimal places precision)"), |
| 30 | +): |
| 31 | + """Place a new order through the exchange API.""" |
| 32 | + base_url = get_api_url() |
| 33 | + |
| 34 | + # Validate contract ID exists |
| 35 | + try: |
| 36 | + with httpx.Client() as client: |
| 37 | + response = client.get(f"{base_url}/v1/stateless/supported-contracts") |
| 38 | + response.raise_for_status() |
| 39 | + supported_contracts = response.json() |
| 40 | + |
| 41 | + if contract_id not in [c["contract_id"] for c in supported_contracts]: |
| 42 | + typer.echo(f"Error: Contract ID '{contract_id}' is not supported") |
| 43 | + raise typer.Exit(1) |
| 44 | + except httpx.HTTPError as e: |
| 45 | + typer.echo(f"Error validating contract ID: {str(e)}") |
| 46 | + raise typer.Exit(1) |
| 47 | + |
| 48 | + # supported_contracts. |
| 49 | + contracts = [ContractGetResponse(**c) for c in supported_contracts] |
| 50 | + tick_size = next( |
| 51 | + (c.tick_size for c in contracts if c.contract_id == contract_id), None |
| 52 | + ) |
| 53 | + |
| 54 | + if tick_size is None: |
| 55 | + typer.echo(f"Error: Contract ID '{contract_id}' is not supported") |
| 56 | + raise typer.Exit(1) |
| 57 | + |
| 58 | + # Convert float price to Decimal with 2 decimal places precision |
| 59 | + price_decimal = Decimal(str(price)).quantize( |
| 60 | + Decimal(tick_size), rounding=ROUND_HALF_UP |
| 61 | + ) |
| 62 | + quantity_decimal = Decimal(str(quantity)).quantize( |
| 63 | + Decimal("0.01"), rounding=ROUND_HALF_UP |
| 64 | + ) |
| 65 | + |
| 66 | + typer.echo(f"Contract ID: {contract_id}") |
| 67 | + typer.echo(f"Side: {side}") |
| 68 | + typer.echo(f"Quantity: {quantity_decimal}") |
| 69 | + typer.echo(f"Price: {price_decimal}") |
| 70 | + |
| 71 | + # Prepare order data |
| 72 | + order_data = { |
| 73 | + "contract_id": contract_id, |
| 74 | + "trader_id": "1e1590fd-f479-4bd4-ad03-56f2e265ec33", # TODO: Load from local DB |
| 75 | + "side": side, |
| 76 | + "type": type, |
| 77 | + "quantity": str(quantity_decimal), |
| 78 | + "price": str(price_decimal), # Convert Decimal to string for JSON serialization |
| 79 | + } |
| 80 | + |
| 81 | + try: |
| 82 | + with httpx.Client() as client: |
| 83 | + response = client.post(f"{base_url}/v1/stateless/orders", json=order_data) |
| 84 | + response.raise_for_status() |
| 85 | + order_response = response.json() |
| 86 | + |
| 87 | + # Store in DuckDB |
| 88 | + with get_db_connection() as conn: |
| 89 | + conn.execute( |
| 90 | + """ |
| 91 | + INSERT INTO orders (id, contract_id, side, quantity, price, status, created_at) |
| 92 | + VALUES (?, ?, ?, ?, ?, ?, ?) |
| 93 | + """, |
| 94 | + ( |
| 95 | + order_response["id"], |
| 96 | + order_response["contract_id"], |
| 97 | + order_response["side"], |
| 98 | + str(quantity_decimal), |
| 99 | + str(price_decimal), |
| 100 | + order_response["status"], |
| 101 | + datetime.now(), |
| 102 | + ), |
| 103 | + ) |
| 104 | + |
| 105 | + typer.echo(f"Order placed successfully! Order ID: {order_response['id']}") |
| 106 | + |
| 107 | + except httpx.HTTPError as e: |
| 108 | + typer.echo(f"Error placing order: {str(e)}", err=True) |
| 109 | + raise typer.Exit(1) |
| 110 | + |
| 111 | + |
| 112 | +@app.command() |
| 113 | +def list_orders( |
| 114 | + contract_id: Optional[str] = typer.Option(None, help="Filter by contract ID"), |
| 115 | +): |
| 116 | + """List all stored orders, optionally filtered by contract ID.""" |
| 117 | + query = "SELECT * FROM orders" |
| 118 | + params = [] |
| 119 | + |
| 120 | + if contract_id: |
| 121 | + query += " WHERE contract_id = ?" |
| 122 | + params.append(contract_id) |
| 123 | + |
| 124 | + query += " ORDER BY created_at DESC" |
| 125 | + |
| 126 | + with get_db_connection() as conn: |
| 127 | + results = conn.execute(query, params).fetchall() |
| 128 | + |
| 129 | + if not results: |
| 130 | + typer.echo("No orders found.") |
| 131 | + return |
| 132 | + |
| 133 | + # Print results in a table format |
| 134 | + typer.echo("\nStored Orders:") |
| 135 | + typer.echo("-" * 120) |
| 136 | + typer.echo( |
| 137 | + f"{'ID':<40} {'Contract':<15} {'Side':<6} {'Quantity':<10} {'Price':<8} {'Status':<8} {'Created At'}" |
| 138 | + ) |
| 139 | + typer.echo("-" * 120) |
| 140 | + |
| 141 | + for row in results: |
| 142 | + typer.echo( |
| 143 | + f"{row[0]:<40} {row[1]:<15} {row[2]:<6} {row[3]:<10} {row[4]:<8} {row[5]:<8} {row[6]}" |
| 144 | + ) |
| 145 | + |
| 146 | + |
| 147 | +if __name__ == "__main__": |
| 148 | + init_db() |
| 149 | + app() |
0 commit comments