### Install PyKalshi and Plotly Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Installs the necessary libraries for PyKalshi and Plotly. Use '-q' for quiet installation. ```python %pip install --upgrade pykalshi plotly -q ``` -------------------------------- ### Run Example Scripts Source: https://github.com/arshka/pykalshi/blob/main/examples/README.md Execute the provided example Python scripts to test different functionalities of the pykalshi library. ```bash python examples/basic_usage.py python examples/stream_orderbook.py python examples/place_order.py ``` -------------------------------- ### Install Pykalshi Source: https://github.com/arshka/pykalshi/blob/main/examples/README.md Install the pykalshi library using pip. ```bash pip install pykalshi ``` -------------------------------- ### Install pykalshi from source with web dependencies Source: https://github.com/arshka/pykalshi/blob/main/web/README.md Install pykalshi from source, including web dependencies, using pip. ```bash pip install -e ".[web]" ``` -------------------------------- ### Install pykalshi with web dependencies Source: https://github.com/arshka/pykalshi/blob/main/web/README.md Install the pykalshi library with optional web dependencies using pip. ```bash pip install pykalshi[web] ``` -------------------------------- ### Install PyKalshi Source: https://github.com/arshka/pykalshi/blob/main/README.md Installs the PyKalshi package. Use the `[dataframe]` extra to include pandas support. ```bash pip install pykalshi # With pandas support pip install pykalshi[dataframe] ``` -------------------------------- ### Run the FastAPI application Source: https://github.com/arshka/pykalshi/blob/main/web/README.md Start the FastAPI web server for the Kalshi Dashboard from the project root directory. Use --reload for development. ```bash uvicorn web.backend.main:app --reload ``` -------------------------------- ### Get Series, Events, and Markets (Top-Down) Source: https://github.com/arshka/pykalshi/blob/main/examples/README.md Retrieve hierarchical market data starting from a series ticker. This demonstrates fetching related events and markets. ```python # Top-down series = client.get_series("KXPRESPERSON") events = client.get_events(series_ticker="KXPRESPERSON") event = client.get_event("KXPRESPERSON-28") markets = client.get_markets(event_ticker="KXPRESPERSON-28") ``` -------------------------------- ### Get Portfolio Positions Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Fetches current open positions and converts them to a pandas DataFrame. Ensure 'client' is initialized. ```python positions = client.portfolio.get_positions() positions.to_dataframe() ``` -------------------------------- ### Get Portfolio Balance Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Retrieves the current account balance. Requires an authenticated client instance. ```python client.portfolio.get_balance() ``` -------------------------------- ### Get Series and Events Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Fetches market series and retrieves the first event from the series. Ensure the client is initialized before use. ```python series = client.get_series("kxpresperson") event = series.get_events()[0] event ``` -------------------------------- ### Python: Context Managers (with statement) Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb This Python snippet demonstrates context managers using the 'with' statement. They are useful for managing resources, ensuring setup and teardown operations are performed correctly, like file handling. ```python with open('myfile.txt', 'w') as f: f.write('This is inside the context.') # File is automatically closed here ``` -------------------------------- ### Real-time Data Streaming with PyKalshi Source: https://github.com/arshka/pykalshi/blob/main/README.md Demonstrates how to subscribe to real-time market data feeds (ticker, orderbook, trades) using WebSockets and process incoming messages asynchronously. Includes examples for handling TickerMessage and OrderbookSnapshotMessage. ```python from pykalshi import Feed, TickerMessage, OrderbookSnapshotMessage async with Feed(client) as feed: await feed.subscribe_ticker("KXBTC-25MAR15-B100000") await feed.subscribe_orderbook("KXBTC-25MAR15-B100000") await feed.subscribe_trades("KXBTC-25MAR15-B100000") async for msg in feed: match msg: case TickerMessage(): print(f"Price: ${msg.price_dollars}") case OrderbookSnapshotMessage(): print(f"Book: {len(msg.yes)} yes levels, {len(msg.no)} no levels") ``` -------------------------------- ### Place a Limit Buy Order (Python) Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Places a limit buy order for a specified market and side ('yes') with a defined count and price. The example uses a very low price to ensure the order rests on the book without filling. Requires a client object and a market object. ```python from pykalshi import Action, Side order = client.portfolio.place_order( ticker=market.ticker, action=Action.BUY, side=Side.YES, count_fp="5", yes_price_dollars="0.01", # $0.01 - won't fill ) order ``` -------------------------------- ### Python: File Path Handling Example Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb This Python code snippet illustrates how to handle file paths, including the use of escape characters for special directories. It's essential for file I/O operations. ```python const path = "C:\\Users\\file"; ``` -------------------------------- ### Get Portfolio Balance Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Retrieves the current account balance information. This includes details about available funds and margin. ```python client.portfolio.get_balance() ``` -------------------------------- ### GET /markets Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Retrieve open markets and identify the one with the highest 24-hour volume. ```APIDOC ## GET /markets ### Description Fetches a list of open markets and filters them to find the most active market based on 24-hour volume. ### Method GET ### Endpoint /markets ### Parameters #### Query Parameters - **status** (string) - Required - Filter by market status (e.g., OPEN) - **limit** (integer) - Optional - Number of results to return - **mve_filter** (string) - Optional - Filter for market volume exclusion ### Request Example client.get_markets(status=MarketStatus.OPEN, limit=200, mve_filter="exclude") ### Response #### Success Response (200) - **market** (object) - The market object with the highest volume. #### Response Example { "ticker": "KXPRES-24", "volume_24h_fp": "1500.50", "liquidity_dollars": "500.00" } ``` -------------------------------- ### Mock HTTP Response for Testing Source: https://github.com/arshka/pykalshi/blob/main/tests/README.md Example of mocking an HTTP response using a client fixture and a mock response factory. Used to simulate API responses for testing client logic without making actual network calls. ```python def test_example(client, mock_response): client._session.request.return_value = mock_response({ "data": {"key": "value"} }) result = client.get("/endpoint") assert result["data"]["key"] == "value" ``` -------------------------------- ### Get Portfolio Fills Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Retrieves recent trade fills and converts them to a pandas DataFrame. A limit can be specified for the number of fills. Ensure 'client' is initialized. ```python fills = client.portfolio.get_fills(limit=5) fills.to_dataframe() ``` -------------------------------- ### JavaScript Path Handling Example Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb This JavaScript snippet demonstrates how to handle file paths, including escaping special characters like backslashes. It's crucial for operations involving file system interactions or string manipulation where paths are involved. ```javascript const path = "C:\\Users\\file"; ``` -------------------------------- ### Get First Event and Find Market with Most Volume (Python) Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Fetches a series by its ticker, retrieves the first event associated with that series, and then identifies the market with the highest trading volume within that event. Requires a client object. ```python series = client.get_series("kxpresperson") event = series.get_events()[0] max_volume_market = max(event.get_markets(), key=lambda x: Decimal(x.volume_fp or "0")) market = max_volume_market ``` -------------------------------- ### Get Portfolio Positions Dataframe Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Fetches current open positions in the portfolio and converts them into a pandas DataFrame. This provides a snapshot of all active trades and their details. ```python positions = client.portfolio.get_positions() positions.to_dataframe() ``` -------------------------------- ### Get Market Orderbook Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Fetches the orderbook for a market up to a specified depth and converts it to a Pandas DataFrame. ```python market.get_orderbook(depth=5).to_dataframe() ``` -------------------------------- ### Get Event and Series from Market (Bottom-Up) Source: https://github.com/arshka/pykalshi/blob/main/examples/README.md Retrieve the parent event and series associated with a specific market ticker. This shows how to navigate up the hierarchy. ```python # Bottom-up market = client.get_market("KXPRESPERSON-28-JOSS") event = market.get_event() series = event.get_series() ``` -------------------------------- ### Get Orderbook Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Retrieves an orderbook for a specific market with a specified depth. This is useful for analyzing market liquidity and pricing. ```python ob = market.get_orderbook(depth=7) ob ``` -------------------------------- ### Find Most Active Open Market Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Fetches all open markets for a given series ticker and selects the one with the highest volume. Ensure the 'pykalshi' library is installed and a client is initialized. ```python from decimal import Decimal from pykalshi import MarketStatus markets = client.get_markets(series_ticker="KXPRESPERSON", status=MarketStatus.OPEN, fetch_all=True) market = max(markets, key=lambda m: Decimal(m.volume_fp or "0")) market ``` -------------------------------- ### Get Open Markets Dataframe Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Retrieves open market data and converts it into a pandas DataFrame. It selects specific columns for display, including ticker, title, bid/ask prices, and volume. ```python client.get_markets(status=MarketStatus.OPEN, limit=10).to_dataframe()[ ["ticker", "title", "yes_bid_dollars", "yes_ask_dollars", "volume_fp", "open_interest_fp"] ] ``` -------------------------------- ### Initialize Kalshi Client for Demo Environment Source: https://github.com/arshka/pykalshi/blob/main/examples/README.md Create a Kalshi client instance configured for the demo environment. Use the demo=True argument for this purpose. ```python client = KalshiClient.from_env(demo=True) ``` -------------------------------- ### Configure Demo Environment Credentials Source: https://github.com/arshka/pykalshi/blob/main/examples/README.md Set up .env file for Kalshi's demo environment using demo-specific credentials. This allows testing without using real money. ```dotenv KALSHI_API_KEY_ID=your-demo-key-id KALSHI_PRIVATE_KEY_PATH=/path/to/demo-private-key.pem ``` -------------------------------- ### Set Up and Run Integration Tests Source: https://github.com/arshka/pykalshi/blob/main/tests/README.md Instructions for running integration tests against the real Kalshi API. Requires setting API credentials as environment variables before executing pytest. ```bash # Set environment variables export KALSHI_API_KEY_ID="your_key" export KALSHI_PRIVATE_KEY_PATH="/path/to/key.pem" # Run integration tests pytest tests/test_integration.py -v ``` -------------------------------- ### GET /orderbook Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Retrieve the orderbook for a specific market and perform analytics like VWAP calculation. ```APIDOC ## GET /orderbook ### Description Fetches the orderbook for a given market ticker to analyze spread, mid-price, and depth. ### Method GET ### Endpoint /markets/{ticker}/orderbook ### Parameters #### Path Parameters - **ticker** (string) - Required - The market ticker symbol #### Query Parameters - **depth** (integer) - Optional - Number of levels to return ### Request Example market.get_orderbook(depth=7) ### Response #### Success Response (200) - **spread** (float) - Current market spread - **mid** (float) - Current mid-price - **vwap** (float) - Volume Weighted Average Price #### Response Example { "spread": 0.05, "mid": 0.52, "vwap": 0.55 } ``` -------------------------------- ### Batch Place and Cancel Orders (Python) Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Demonstrates placing multiple orders atomically using batch operations and then canceling them using their IDs. All placed orders will succeed or fail together, and similarly for cancellations. Requires a client object and a market object. ```python orders = client.portfolio.batch_place_orders([ {"ticker": market.ticker, "action": "buy", "side": "yes", "type": "limit", "count_fp": "1", "yes_price_dollars": "0.01"}, {"ticker": market.ticker, "action": "buy", "side": "yes", "type": "limit", "count_fp": "1", "yes_price_dollars": "0.02"}, {"ticker": market.ticker, "action": "buy", "side": "yes", "type": "limit", "count_fp": "1", "yes_price_dollars": "0.03"}, ]) canceled_batch = client.portfolio.batch_cancel_orders([o.order_id for o in orders]) for order in canceled_batch: print(order) print('='*20) ``` -------------------------------- ### Fetch Portfolio and Market Data with Pandas Source: https://github.com/arshka/pykalshi/blob/main/README.md Demonstrates fetching positions, markets, fills, candlesticks, and orderbooks and converting them to pandas DataFrames. Ensure you have initialized the client and market objects. ```python positions_df = client.portfolio.get_positions().to_dataframe() markets_df = client.get_markets(limit=500).to_dataframe() fills_df = client.portfolio.get_fills().to_dataframe() candles_df = market.get_candlesticks(start, end).to_dataframe() orderbook_df = market.get_orderbook().to_dataframe() ``` -------------------------------- ### Automatic Pagination with Pykalshi Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Use `fetch_all=True` to automatically retrieve all available data, useful for comprehensive market data retrieval. ```python client.get_markets(fetch_all=True) ``` -------------------------------- ### Place a Trade with PyKalshi Source: https://github.com/arshka/pykalshi/blob/main/README.md Demonstrates how to place a trade order for a specific market. The order can be blocked until it is filled or canceled. ```python from pykalshi import KalshiClient, Action, Side client = KalshiClient() # Place a trade order = client.portfolio.place_order("KXBTC-25MAR15-B100000", Action.BUY, Side.YES, count_fp="10", yes_price_dollars="0.45") order.wait_until_terminal() # Block until filled/canceled ``` -------------------------------- ### Batch Place and Cancel Orders Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Demonstrates atomic batch operations for placing and canceling multiple orders. All orders in a batch succeed or fail together. The output shows details of canceled orders. ```python orders = client.portfolio.batch_place_orders([ {"ticker": market.ticker, "action": "buy", "side": "yes", "type": "limit", "count_fp": "1", "yes_price_dollars": "0.01"}, {"ticker": market.ticker, "action": "buy", "side": "yes", "type": "limit", "count_fp": "1", "yes_price_dollars": "0.02"}, {"ticker": market.ticker, "action": "buy", "side": "yes", "type": "limit", "count_fp": "1", "yes_price_dollars": "0.03"}, ]) canceled_batch = client.portfolio.batch_cancel_orders([o.order_id for o in orders]) for order in canceled_batch: print(order) print('='*20) ``` -------------------------------- ### Get Recent Fills Dataframe Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Retrieves a limited number of recent trade fills and converts them into a pandas DataFrame. This is useful for reviewing recent transaction history. ```python fills = client.portfolio.get_fills(limit=5) fills.to_dataframe() ``` -------------------------------- ### Authenticate with Kalshi using .env file Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Loads Kalshi API credentials from a .env file using dotenv. Ensure your .env file contains KALSHI_API_KEY_ID and KALSHI_PRIVATE_KEY_PATH. ```python import os from pykalshi import KalshiClient from dotenv import load_dotenv load_dotenv("my.env") client = KalshiClient(demo=False) client.exchange.get_status() ``` -------------------------------- ### Get Market Orderbook Dataframe Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Fetches the order book for a given market up to a specified depth and converts it into a pandas DataFrame. This is useful for analyzing market liquidity and order flow. ```python market.get_orderbook(depth=5).to_dataframe() ``` -------------------------------- ### Local Orderbook Management with PyKalshi Source: https://github.com/arshka/pykalshi/blob/main/README.md Illustrates how to use `OrderbookManager` to maintain a local, up-to-date orderbook by applying incoming WebSocket messages. This allows efficient querying of the best bid and ask prices. ```python from pykalshi import Feed, OrderbookManager manager = OrderbookManager() async with Feed(client) as feed: await feed.subscribe_orderbook(ticker) async for msg in feed: manager.apply(msg) book = manager.get(ticker) best_bid = book["yes_dollars"][0] if book["yes_dollars"] else None ``` -------------------------------- ### Get Candlesticks Dataframe Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Retrieves historical candlestick data for a market over a specified period (e.g., 360 days) and converts it into a pandas DataFrame. It uses predefined candlestick periods for aggregation. ```python from pykalshi import CandlestickPeriod from datetime import datetime, timedelta end = int(datetime.now().timestamp()) start = int((datetime.now() - timedelta(days=360)).timestamp()) candles = market.get_candlesticks(start_ts=start, end_ts=end, period=CandlestickPeriod.ONE_DAY) candles.to_dataframe().tail(5) ``` -------------------------------- ### Python: Working with Sets Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb This Python snippet demonstrates the creation and manipulation of sets, which are unordered collections of unique elements. Sets are useful for membership testing and eliminating duplicates. ```python my_set = {1, 2, 3, 3, 4} print(my_set) # Output: {1, 2, 3, 4} my_set.add(5) print(my_set) print(3 in my_set) ``` -------------------------------- ### Configuring Rate Limiter in Pykalshi Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Instantiate `KalshiClient` with a custom `RateLimiter` to manage request frequency and avoid rate limits. ```python KalshiClient(rate_limiter=RateLimiter(10)) ``` -------------------------------- ### Python: Importing Modules Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb This Python snippet shows how to import modules to use their functionality. Importing allows you to leverage code written by others or organize your own code into reusable modules. ```python import math print(math.sqrt(16)) from os import path print(path.join('folder', 'file.txt')) ``` -------------------------------- ### Real-time Local Orderbook Management with Pykalshi Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb This snippet demonstrates how to maintain a real-time local orderbook using pykalshi's OrderbookManager. It processes WebSocket deltas, applies snapshots and updates, and calculates live metrics like spread, mid, imbalance, and cost-to-fill. It requires the pykalshi library and a WebSocket client connection. ```python from pykalshi import OrderbookManager, OrderbookSnapshotMessage import time # Assuming 'client' and 'market' are pre-defined # book = OrderbookManager(market.ticker) # with client.feed() as feed: # @feed.on("orderbook_delta") # def handle(msg): # if isinstance(msg, OrderbookSnapshotMessage): # book.apply_snapshot(msg.yes_dollars, msg.no_dollars) # print(f" Snapshot: {len(book.yes)} bid levels, {len(book.no)} ask levels") # else: # book.apply_delta(msg.side, msg.price_dollars, msg.delta_fp) # print(f" Delta: {msg.side} ${msg.price_dollars} {msg.delta_fp} \u2192 spread=${book.spread} mid=${book.mid}") # feed.subscribe("orderbook_delta", market_ticker=market.ticker) # print(f"Tracking {market.ticker} orderbook for 10 seconds...\n") # time.sleep(10) # # Final state # print(f"\nFinal: bid=${book.best_bid} ask=${book.best_ask} spread=${book.spread}") # cost = book.cost_to_buy("10") # if cost: # print(f"Cost to buy 10 YES: ${cost[0]} (avg ${cost[1]})") ``` -------------------------------- ### Handle Resource Not Found Error Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Demonstrates catching a specific `ResourceNotFoundError` exception when attempting to access a non-existent market. This pattern helps in debugging and gracefully handling API errors. Ensure 'client' is initialized. ```python from pykalshi.exceptions import ResourceNotFoundError, KalshiAPIError try: client.get_market("DOESNOTEXIST-123") except ResourceNotFoundError as e: print(f"Caught: {type(e).__name__}") print(f"Status: {e.status_code}") print(f"Message: {e.message}") ``` -------------------------------- ### Handle Kalshi API Errors in Python Source: https://github.com/arshka/pykalshi/blob/main/README.md Illustrates how to use a try-except block to catch specific Kalshi API errors such as InsufficientFundsError, RateLimitError, and general KalshiAPIError. The RateLimitError includes an automatic retry mechanism. ```python from pykalshi import InsufficientFundsError, RateLimitError, KalshiAPIError try: order = client.portfolio.place_order(...) except InsufficientFundsError: print("Not enough balance") except RateLimitError: pass # Client auto-retries with backoff except KalshiAPIError as e: print(f"{e.status_code}: {e.error_code}") ``` -------------------------------- ### Find Active Market with Most Volume (Python) Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Retrieves open markets, filters for those with liquidity, and selects the market with the highest 24-hour volume. It uses the pykalshi library and requires a client object. ```python from decimal import Decimal from pykalshi import MarketStatus markets = client.get_markets(status=MarketStatus.OPEN, limit=200, mve_filter="exclude") market = max([m for m in markets if float(m.liquidity_dollars or "0") > 0], key=lambda x: Decimal(x.volume_24h_fp or "0")) market ``` -------------------------------- ### Browse Markets with PyKalshi Source: https://github.com/arshka/pykalshi/blob/main/README.md Shows how to search for markets by status or ticker, retrieve a specific market's details, and fetch its orderbook, trades, and historical candlestick data. ```python from pykalshi import MarketStatus, CandlestickPeriod client = KalshiClient() # Search markets markets = client.get_markets(status=MarketStatus.OPEN, limit=100) btc_markets = client.get_markets(series_ticker="KXBTC") # Get a specific market market = client.get_market("KXBTC-25MAR15-B100000") print(f"{market.title}: ${market.yes_bid_dollars} / ${market.yes_ask_dollars}") # Market data orderbook = market.get_orderbook() trades = market.get_trades(limit=50) candles = market.get_candlesticks(start_ts, end_ts, period=CandlestickPeriod.ONE_HOUR) ``` -------------------------------- ### Set Kalshi API Credentials Directly Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Sets Kalshi API key ID and private key path as environment variables. Ensure these are kept secure. ```python import os os.environ["KALSHI_API_KEY_ID"] = "your-key-id" os.environ["KALSHI_PRIVATE_KEY_PATH"] = "/path/to/your/private_key.pem" ``` -------------------------------- ### Project Information Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Details about the Pykalshi project. ```APIDOC ## Project: /arshka/pykalshi ### Description This section provides general information about the Pykalshi project. ### Endpoint N/A ### Method N/A ### Parameters N/A ### Request Body N/A ### Response N/A ``` -------------------------------- ### Java: Abstract Classes and Methods Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb This Java snippet demonstrates abstract classes and methods. Abstract methods are declared without an implementation and must be implemented by concrete subclasses. Abstract classes cannot be instantiated. ```java abstract class Vehicle { abstract void startEngine(); void stop() { System.out.println("Vehicle stopped."); } } class Car extends Vehicle { @Override void startEngine() { System.out.println("Car engine started."); } } ``` -------------------------------- ### Trading Operations with PyKalshi Source: https://github.com/arshka/pykalshi/blob/main/README.md Covers essential trading functions: checking account balance, placing orders, managing existing orders (modifying price, canceling), and retrieving portfolio information like positions, fills, and active orders. ```python from pykalshi import Action, Side, OrderStatus # Check balance balance = client.portfolio.get_balance() print(f"${balance.balance / 100:.2f} available") # Place an order order = client.portfolio.place_order(market, Action.BUY, Side.YES, count_fp="10", yes_price_dollars="0.50") # Manage orders order.wait_until_terminal() # Block until filled/canceled order.modify(yes_price=45) # Amend price order.cancel() # Cancel # View portfolio positions = client.portfolio.get_positions() fills = client.portfolio.get_fills(limit=100) orders = client.portfolio.get_orders(status=OrderStatus.RESTING) ``` -------------------------------- ### Test API Error Handling Source: https://github.com/arshka/pykalshi/blob/main/tests/README.md Demonstrates how to test for expected exceptions, such as ResourceNotFoundError, when an API endpoint returns an error status code like 404. This ensures proper error handling in the client library. ```python def test_not_found(client, mock_response): client._session.request.return_value = mock_response( {"message": "Not found"}, status_code=404 ) with pytest.raises(ResourceNotFoundError): client.get("/missing") ``` -------------------------------- ### Test Pagination with Mock Responses Source: https://github.com/arshka/pykalshi/blob/main/tests/README.md Tests the client's ability to fetch all items across multiple pages using mocked API responses. Ensures correct handling of pagination cursors and total item count. ```python def test_pagination(client, mock_response): client._session.request.side_effect = [ mock_response({"items": [1], "cursor": "page2"}), mock_response({"items": [2], "cursor": ""}), ] result = client.get_items(fetch_all=True) assert len(result) == 2 assert client._session.request.call_count == 2 ``` -------------------------------- ### Analyze Orderbook Spread, Mid, Imbalance, and Depth (Python) Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb Retrieves an orderbook for a given market up to a specified depth and prints its spread, mid-price, and imbalance. Handles cases where imbalance data might be unavailable. Requires a market object. ```python ob = market.get_orderbook(depth=7) print(f"Spread: ${ob.spread}") print(f"Mid: ${ob.mid}") print(f"Imbalance: {ob.imbalance:+.2f}" if ob.imbalance else "Imbalance: N/A") ``` -------------------------------- ### JavaScript: Modules (import/export) Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb This JavaScript snippet demonstrates the use of ES6 modules for organizing code. The 'export' keyword makes functionality available to other modules, and 'import' brings it in. ```javascript // utils.js export function add(a, b) { return a + b; } // main.js import { add } from './utils.js'; console.log(add(5, 7)); // 12 ``` -------------------------------- ### Run Pytest Commands Source: https://github.com/arshka/pykalshi/blob/main/tests/README.md Commands to execute tests using pytest. Supports running all tests, verbose output, specific files or classes, and coverage analysis. ```bash pytest tests/ ``` ```bash pytest tests/ -v ``` ```bash pytest tests/test_exchange.py ``` ```bash pytest tests/test_exchange.py::TestExchangeStatus ``` ```bash pytest tests/ --cov=pykalshi ``` -------------------------------- ### Java: Inheritance Source: https://github.com/arshka/pykalshi/blob/main/examples/demo.ipynb This Java snippet demonstrates inheritance, a core OOP concept where a class can inherit properties and methods from a parent class. It promotes code reuse. ```java class Animal { void eat() { System.out.println("Eating..."); } } class Dog extends Animal { void bark() { System.out.println("Barking..."); } } ```