pyokx.rest_handling

pyokx.rest_handling.REDIS_STREAM_MAX_LEN = 1000

THE MODULE NEEDS TO BE UPDATED WITH ENUMS AND STRUCTURED DATA TYPES WHERE APPLICABLE

Type:

NOTE

async pyokx.rest_handling.assert_okx_account_level(account_level: [1, 2, 3, 4])[source]

Validates and sets the OKX account level, ensuring it is one of the acceptable levels.

Parameters:

account_level (list[int]) – The account level to be validated and set. Acceptable levels are 1, 2, 3, and 4.

Raises:

AssertionError – If the account level is not one of the acceptable levels or if the account level could not be set.

async pyokx.rest_handling.cancel_all_algo_orders_with_params(algo_orders_list: List[Algo_Order] | None = None, instId=None, ordType=None) List[Cancelled_Algo_Order][source]
async pyokx.rest_handling.cancel_all_orders(orders_list: List[Order] | None = None, instType: InstType | None = None, instId: str | None = None) List[Cancelled_Order][source]

Cancels all or specific orders based on the provided parameters.

Parameters:
  • orders_list (List[Order], optional) – A list of specific orders to cancel. If not provided, all orders are cancelled.

  • instType (InstType, optional) – The type of instrument to cancel orders for.

  • instId (str, optional) – The specific instrument ID to cancel orders for.

Returns:

A list of the orders that were successfully cancelled.

Return type:

List[Cancelled_Order]

async pyokx.rest_handling.close_positions(positions_list: List[Position] | None = None, instType: InstType | None = None, instId: str | None = None) List[Closed_Position][source]

Closes all or specific positions based on the provided parameters.

Parameters:
  • positions_list (List[Position], optional) – A list of specific positions to close. If not provided, all positions are closed.

  • instType (InstType, optional) – The type of instrument to close positions for.

  • instId (str, optional) – The specific instrument ID to close positions for.

Returns:

A list of the positions that were successfully closed.

async pyokx.rest_handling.fetch_fill_history(start_timestamp, end_timestamp, instType=None)[source]

Fetches the fill history for a specific period and instrument type.

Parameters:
  • start_timestamp (int) – The starting timestamp for the fill history.

  • end_timestamp (int) – The ending timestamp for the fill history.

  • instType (str, optional) – The type of instrument for the fill history, defaults to

Returns:

A list of fill entries.

Raises:

AssertionError – If the requested period is outside the allowed range based on the instrument type.

async pyokx.rest_handling.fetch_incomplete_algo_orders(instId=None, ordType=None)[source]
async pyokx.rest_handling.fetch_incomplete_orders(instId: str | None = None, instType: str | None = None)[source]
async pyokx.rest_handling.fetch_initial_data(TD_MODE, instId=None)[source]

Fetches initial data including account balance, account configuration, and instrument status.

Parameters:
  • TD_MODE (str) – The trade mode (e.g., ‘cash’, ‘margin’).

  • instId (str, optional) – The instrument ID for which to fetch the data, defaults to

Returns:

A tuple containing simplified balance details, account configuration data, and instrument status report.

async pyokx.rest_handling.fetch_status_report_for_instrument(instId, TD_MODE)[source]

Fetches a comprehensive status report for a specific instrument.

Parameters:
  • instId (str) – The instrument ID for which to fetch the status report.

  • TD_MODE (str) – The trade mode (e.g., ‘cash’, ‘margin’).

Returns:

A status report for the instrument, structured according to the InstrumentStatusReport class.

pyokx.rest_handling.generate_random_string(length, char_type='alphanumeric')[source]

Generates a random string of the specified length and character type.

Parameters:
  • length (int) – The length of the random string to generate.

  • char_type (str, optional) – The type of characters to include in the string (‘alphanumeric’, ‘numeric’, or ‘alphabetic’). Defaults to ‘alphanumeric’.

Returns:

A random string of the specified length and character type.

Raises:

ValueError – If the length exceeds 32 or if an invalid char_type is specified.

async pyokx.rest_handling.get_account_balance()[source]

Retrieves the account balance details.

Returns:

The account balance data, structured according to the AccountBalanceData class.

async pyokx.rest_handling.get_account_config()[source]

Retrieves the account configuration details.

Returns:

The account configuration data, structured according to the AccountConfigData class.

async pyokx.rest_handling.get_algo_orders(instId=None, ordType=None) List[Algo_Order][source]
async pyokx.rest_handling.get_leverage(instId, mgnMode)[source]
async pyokx.rest_handling.get_max_avail_size(instId, tdMode)[source]

Retrieves the maximum available size for trading a specific instrument in a specific trade mode.

Parameters:
  • instId (str) – The instrument ID for which to get the maximum available size.

  • tdMode (str) – The trade mode (e.g., ‘cash’, ‘margin’).

Returns:

The maximum available size data, structured according to the MaxAvailSizeData class.

async pyokx.rest_handling.get_max_order_size(instId, tdMode)[source]

Retrieves the maximum order size for a specific instrument and trade mode.

Parameters:
  • instId (str) – The instrument ID for which to get the maximum order size.

  • tdMode (str) – The trade mode (e.g., ‘cash’, ‘margin’).

Returns:

The maximum order size data, structured according to the MaxOrderSizeData class.

async pyokx.rest_handling.get_order_book(instId, depth)[source]

Fetches the order book for a specific instrument.

Parameters:
  • instId (str) – The instrument ID for which to get the order book.

  • depth (int) – The depth of the order book to fetch.

Returns:

The order book snapshot, structured according to the Orderbook_Snapshot class.

Raises:

ValueError – If the order book could not be fetched for the specified instrument ID.

async pyokx.rest_handling.get_orders(instType: str | None = None, instId: str | None = None, ordType: str | None = None, state: str | None = None, instFamily: str | None = None) List[Order][source]
async pyokx.rest_handling.get_positions(instType: InstType | None = None, instId: str | None = None) List[WSPosition][source]

Fetches all positions matching the given criteria from the account API.

Parameters:
  • instType (InstType, optional) – The type of instrument to fetch positions for (e.g., ‘FUTURES’).

  • instId (str, optional) – The specific instrument ID to fetch positions for.

Returns:

A list of positions that match the given criteria.

async pyokx.rest_handling.get_request_data(returned_data, target_data_structure)[source]

Processes the returned data from an API call, mapping it to the specified data structure.

Parameters:
  • returned_data (dict) – The raw data returned from the API call.

  • target_data_structure (class) – The class to which the returned data items will be mapped.

Returns:

A list of instances of the target data structure class, populated with the returned data.

Return type:

List[Any]

async pyokx.rest_handling.get_ticker(instId)[source]

Retrieves the latest ticker information for a specified instrument.

Parameters:

instId (str) – The instrument ID for which to get the ticker information.

Returns:

The latest ticker information for the specified instrument.

async pyokx.rest_handling.get_ticker_with_higher_volume(seed_symbol_name, instrument_type='FUTURES', top_n=1)[source]

Retrieves the ticker(s) with the highest trading volume for a given seed symbol and instrument type. Optionally, returns the top N tickers sorted by volume.

Parameters:
  • seed_symbol_name (str) – The base symbol to search for.

  • instrument_type (str, optional) – The type of instrument (e.g., “FUTURES”). Defaults to “FUTURES”.

  • top_n (int, optional) – The number of top-volume tickers to return. Defaults to 1.

Returns:

A list of tickers, sorted by volume, up to the specified top_n number.

Return type:

List[Ticker]

async pyokx.rest_handling.is_valid_alphanumeric(string, max_length)[source]

Validates if the input string is alphanumeric and conforms to the specified maximum length.

Parameters:
  • string (str) – The string to validate.

  • max_length (int) – The maximum allowable length for the string.

Returns:

True if the string is alphanumeric and does not exceed the max_length, False otherwise.

Return type:

bool

async pyokx.rest_handling.okx_premium_indicator_handler(indicator_input: OKXPremiumIndicatorSignalRequestForm | dict)[source]

Handles incoming premium indicator signals for trading on the OKX platform. It processes the signals, interprets the trading instructions, manages positions based on the received signals, and executes trading actions.

Parameters:

indicator_input (OKXPremiumIndicatorSignalRequestForm or dict) – The input containing the signals and parameters from the premium indicator. This can be an instance of PremiumIndicatorSignalRequestForm or a dictionary that corresponds to the structure of PremiumIndicatorSignalRequestForm.

Returns:

A dictionary detailing the outcome of the signal processing. If the processing is successful, it includes the ‘instrument_status_report’ which is a comprehensive status report of the instrument after handling the signal. In case of an error, it returns a message detailing the issue.

Process Flow: 1. Validates the input type and converts it into PremiumIndicatorSignalRequestForm if necessary. 2. Extracts and processes trading signals (like Bearish, Bullish, and their respective exit signals) from the input. 3. Determines the trading action (buy/sell) based on the processed signals. 4. Fetches the current positions for the given instrument ID and aligns them with the received signals. 5. Prepares the trading action by setting order sides, clearing prior orders if needed, and handling the ‘red_button’ emergency stop. 6. Passes the processed signal to okx_signal_handler for executing the trading operations on the OKX platform. 7. Returns a success message with the ‘instrument_status_report’ or an error message in case of an exception.

Raises:

Exception – Catches and logs any exceptions that occur during the processing of the signal, returning a detailed error message.

Note: The major difference between the okx_signal_handler and okx_premium_indicator is that the latter is specifically designed to handle premium indicator signals (TV), and it includes additional processing steps for interpreting the signals and aligning them with the current positions.

async pyokx.rest_handling.okx_signal_handler(instID: str = '', usd_order_size: int | None = None, leverage: int | None = None, order_side: str | None = None, order_type: str | None = None, max_orderbook_limit_price_offset: float | None = None, min_orderbook_limit_price_offset: float | None = None, flip_position_if_opposite_side: bool = False, clear_prior_to_new_order: bool = False, red_button: bool = False, sl_trigger_price_offset: float | None = None, tp_trigger_price_offset: float | None = None, tp_trigger_price_type: str | None = None, sl_execution_price_offset: float | None = None, tp_execution_price_offset: float | None = None, sl_trigger_price_type: str | None = None, trailing_stop_activation_price_offset: float | None = None, trailing_stop_callback_offset: float | None = None, dca_parameters: List[DCAInputParameters] | None = None)[source]

Handles trading signals for the OKX platform, executing trades based on the specified parameters and current market conditions.

Overview: 1. Validates and processes input parameters, preparing the trading signal. 2. Checks and manages current positions based on new signal, potentially flipping positions or clearing orders as configured. 3. Calculates and sets order parameters such as price and size, leveraging current market data and user preferences. 4. Executes the trading actions (placing/canceling orders, opening/closing positions) on the OKX platform. 5. Fetches and returns an updated status report of the instrument, reflecting the changes made by the executed signal.

Process Flow: The okx_signal_handler function is a complex asynchronous function designed to handle trading signals for the OKX platform, covering a wide range of trading strategies and actions. Here is a step-by-step structural and behavioral walkthrough of the main activities within the function, highlighting how it interacts with other helper functions:

1. Initialize OKX Signal Input: It creates an instance of OKXSignalInput with all the provided parameters. This step is crucial for collecting all user inputs regarding the trading signal they wish to execute.

2. Pre-validation and Setup: - Validates trading mode (TD_MODE) and position type (POSSIDETYPE) to ensure they are within acceptable parameters. - If the red_button parameter is true, the function triggers emergency actions to close all positions, cancel all orders, and return the status of these actions.

3. Validate Parameters: Calls validate_okx_signal_params to validate and process input parameters comprehensively. This includes instrument ID validation, leverage checks, and configuration of additional parameters like order size, type, and various trading strategies (e.g., stop loss, take profit).

4. Initial Data Fetching: Retrieves necessary initial data related to the trading account and the specific instrument being traded. This might include balance details, account configurations, and the current status report of the instrument.

5. Set Leverage: If leverage is specified, it sets the leverage for the trading account according to the provided value.

6. Order and Position Management: - Checks for existing positions and manages them based on the new signal. This includes closing positions, canceling orders, or flipping positions if configured to do so by the user. - If there are no conflicting positions or if the user has opted to clear previous orders and positions, it proceeds to calculate and set new order parameters.

7. Order Execution: - Retrieves current market data (e.g., ticker information) to determine reference prices for order placement. - Calls prepare_limit_price to calculate the appropriate limit price for the order based on current market conditions and user specifications. - Constructs and sends order requests, including handling of special order types like take profit, stop loss, and trailing stop losses.

8. Dollar-Cost Averaging (DCA) Orders: - If DCA parameters are provided, it prepares and sends multiple DCA orders based on the specified strategies and market conditions. - Each DCA order is configured with trigger prices, execution prices, and optional stop loss/take profit parameters.

9. Final Actions: - After all trading actions have been attempted, it fetches and returns an updated status report for the instrument, reflecting the changes made by the executed signal. - Handles exceptions and errors throughout the process, ensuring that any issues are caught and logged, with appropriate cleanup actions taken if necessary.

This function encapsulates a comprehensive set of trading strategies and operations, leveraging asynchronous programming to handle market data fetching, order preparation, and execution in a non-blocking manner. It demonstrates a complex integration of trading logic, error handling, and user input validation to manage trading signals on the OKX platform effectively.

raises Exception:

Catches and logs any exceptions that occur during signal handling, providing detailed

error information.

async pyokx.rest_handling.place_algo_order(instId: str = '', tdMode: str = '', side: str = '', ordType: str = '', sz: str = '', ccy: str = '', posSide: str = '', reduceOnly: str = '', tpTriggerPx: str = '', tpOrdPx: str = '', slTriggerPx: str = '', slOrdPx: str = '', triggerPx: str = '', orderPx: str = '', tgtCcy: str = '', pxVar: str = '', pxSpread: str = '', szLimit: str = '', pxLimit: str = '', timeInterval: str = '', tpTriggerPxType: str = '', slTriggerPxType: str = '', callbackRatio: str = '', callbackSpread: str = '', activePx: str = '', tag: str = '', triggerPxType: str = '', closeFraction: str = '', quickMgnType: str = '', algoClOrdId: str = '', cxlOnClosePos: str = '')[source]

Places an algorithmic order with detailed parameters. (as defined by the OKX API documentation, see Orders vs Algo Orders for more details)

Parameters:
  • instId (str) – The instrument ID for the order.

  • tdMode (str) – The trade mode for the order (e.g., ‘cash’, ‘margin’).

… (and so on for other parameters) :returns: The response from the algorithmic order placement request.

async pyokx.rest_handling.place_algo_trailing_stop_loss(instId: str = '', tdMode: str = '', ordType: str = '', side: str = '', sz: str = '', activePx: str = '', posSide: str = '', callbackRatio: str = '', reduceOnly: str = '', algoClOrdId: str = '', cxlOnClosePos: str = '')[source]

Places a trailing stop-loss order with detailed parameters.

Parameters:
  • instId (str) – The instrument ID for the order.

  • tdMode (str) – The trade mode for the order (e.g., ‘cash’, ‘margin’).

… (and so on for other parameters) :returns: The response from the trailing stop-loss order placement request.

async pyokx.rest_handling.place_order(instId: Any, tdMode: Any, side: Any, ordType: Any, sz: Any, ccy: str = '', clOrdId: str = '', tag: str = '', posSide: str = '', px: str = '', reduceOnly: str = '', tgtCcy: str = '', tpTriggerPx: str = '', tpOrdPx: str = '', slTriggerPx: str = '', slOrdPx: str = '', tpTriggerPxType: str = '', slTriggerPxType: str = '', quickMgnType: str = '', stpId: str = '', stpMode: str = '', algoClOrdId: str = '')[source]

Places an order with the specified parameters.

Parameters:
  • instId (Any) – The instrument ID for the order.

  • tdMode (Any) – The trade mode for the order (e.g., ‘cash’, ‘margin’).

  • side (Any) – The side of the order (‘buy’ or ‘sell’).

  • ordType (Any) – The type of the order (e.g., ‘limit’, ‘market’).

  • sz (Any) – The size of the order.

… (and so on for other parameters) :returns: The response from the order placement request.

async pyokx.rest_handling.prepare_dca(dca_parameters: List[DCAInputParameters], side: str, reference_price: float, ccy_contract_size: float, ccy_last_price: float, usd_to_base_rate: float, leverage: int, min_order_quantity: int, max_market_order_quantity: int, ctValCcy: str)[source]
async pyokx.rest_handling.prepare_limit_price(order_book: Orderbook_Snapshot, quantity: int | float, side, reference_price: float, max_orderbook_price_offset=None)[source]

Prepares a limit price based on the order book, quantity, side, reference price, and maximum order book price offset.

Parameters:
  • order_book (Orderbook_Snapshot) – The snapshot of the order book.

  • quantity (Union[int, float]) – The quantity for which to prepare the limit price.

  • side (str) – The side of the order (‘buy’ or ‘sell’).

  • reference_price (float) – The reference price to base the limit price on.

  • max_orderbook_price_offset (float, optional) – The maximum allowed offset from the reference price, defaults to

Returns:

The prepared limit price.

Raises:

Exception – If a price in the order book that has enough volume to cover the quantity cannot be found.

async pyokx.rest_handling.validate_okx_signal_params(okx_signal: OKXSignalInput)[source]