Bitunix

How to Use Bitunix

Bitunix integration in Lumibot supports only perpetual futures trading. Spot trading is not supported.

Account Funding and Cash Calculation:

  • You must transfer funds to the Futures section of your Bitunix account. Money in the spot wallet will not be available for trading.

  • For accurate calculation of available cash, it is strongly recommended to deposit USDT into your Bitunix Futures account. If you deposit crypto (e.g., BTC), it will not register as available cash for order sizing, though it can still be used as margin by Bitunix.

Environment Variables

Set the following environment variables in your .env file or system environment:

BITUNIX_API_KEY=your_bitunix_api_key
BITUNIX_API_SECRET=your_bitunix_api_secret

Setting Leverage for Bitunix Orders

You can specify the leverage for a Bitunix futures order by setting the leverage attribute on the Asset object before creating the order. If not set, the default leverage configured at the broker will be used.

Example: Setting Leverage on a Bitunix Futures Order

from lumibot.entities import Asset, Order

asset = Asset("HBARUSDT", Asset.AssetType.CRYPTO_FUTURE, leverage=10)
order = self.create_order(
    asset=asset,
    quantity=100,
    side=Order.OrderSide.BUY,
    order_type=Order.OrderType.LIMIT,
    limit_price=0.18
)
submitted_order = self.submit_order(order)
if submitted_order:
    self.log_message(f"Placed order: ID={submitted_order.identifier}, Status={submitted_order.status}")

Example Usage

Below are practical examples using the Bitunix broker in Lumibot, based on the bitunix_futures_example.py strategy.

Placing a Limit Order for a Futures Contract

from lumibot.entities import Asset, Order

asset = Asset("HBARUSDT", Asset.AssetType.CRYPTO_FUTURE)
asset.leverage = 5  # Example: set leverage to 5x
order = self.create_order(
    asset=asset,
    quantity=100,
    side=Order.OrderSide.BUY,
    order_type=Order.OrderType.LIMIT,
    limit_price=0.18
)
submitted_order = self.submit_order(order)
if submitted_order:
    self.log_message(f"Placed order: ID={submitted_order.identifier}, Status={submitted_order.status}")

Closing a Position

# Wait for a few seconds if needed
import time
time.sleep(10)
self.close_position(asset)

Cancelling Open Orders

orders = self.get_orders()
for order in orders:
    if order.asset.symbol == "HBARUSDT" and order.asset.asset_type == Asset.AssetType.CRYPTO_FUTURE and order.status in [
        Order.OrderStatus.NEW, Order.OrderStatus.SUBMITTED, Order.OrderStatus.OPEN, Order.OrderStatus.PARTIALLY_FILLED
    ]:
        self.cancel_order(order)
        self.log_message(f"Order {order.identifier} cancellation submitted.")

Checking Available Cash

cash = self.get_cash()
self.log_message(f"Current cash {cash}")

Note

For best results, ensure all funds in your Bitunix Futures account are in USDT. Crypto balances may not be counted as available cash for order sizing.

Documentation

class lumibot.brokers.bitunix.Bitunix(config, max_workers: int = 1, chunk_size: int = 100, connect_stream: bool = True, poll_interval: float | None = None, data_source=None)

Bases: Broker

A broker class that connects to the Bitunix exchange for crypto futures trading.

This broker is designed specifically for Bitunix’s perpetual futures API. It supports submitting, tracking, and closing positions for crypto futures contracts (e.g., BTCUSDT perpetual). The broker uses Bitunix’s REST API for all trading operations.

Key Features: - Only supports crypto futures (TRADING_MODE must be “FUTURES”). - Uses Bitunix’s “flash close” endpoint to close open futures positions instantly at market price. - All positions and orders are managed using Bitunix’s API conventions. - Not suitable for spot trading or non-futures assets.

Notes: - The close_position method will use Bitunix’s flash close endpoint, which is faster and more reliable for closing futures positions than submitting a regular market order. - All asset symbols should be the full Bitunix symbol (e.g., “BTCUSDT”). - Leverage and margin settings are managed per-symbol as needed.

ASSET_TYPE_MAP = {'crypto': ['crypto'], 'crypto_future': ['future'], 'forex': [], 'future': ['future'], 'option': [], 'stock': []}
DEFAULT_POLL_INTERVAL = 5
LUMIBOT_DEFAULT_QUOTE_ASSET = USDT
cancel_order(order: Order)

Cancels a FUTURES order.

close_position(strategy_name: str, asset: Asset)

Close one open crypto futures position via Bitunix’s flash_close_position endpoint.

This method finds the open position for the given asset and, if found, uses Bitunix’s “flash close” API to close the position at market price. This is the recommended way to close positions on Bitunix, as it is faster and more reliable than submitting a regular market order.

Parameters:
  • strategy_name (str) – The name of the strategy requesting the close (not used for Bitunix, but required by interface).

  • asset (Asset) – The Asset object representing the futures contract to close (e.g., Asset(“BTCUSDT”, Asset.AssetType.CRYPTO_FUTURE)).

Returns:

None

Notes

  • Only works for open crypto futures positions.

  • If no open position is found, or if the position cannot be closed, this method does nothing.

  • For spot or non-futures assets, this method is not applicable.

do_polling()

Polls Bitunix for order status updates and dispatches events.

get_historical_account_value(start_date=None, end_date=None, frequency=None) dict

Not implemented: Bitunix does not support historical account value retrieval.

get_quote_asset()
get_time_to_close()

Return the remaining time for the market to close in seconds

get_time_to_open()

Return the remaining time for the market to open in seconds

get_timestamp()
is_market_open()

Determines if the market is open.

Parameters:

None

Returns:

True if market is open, false if the market is closed.

Return type:

boolean

Examples

>>> self.is_market_open()
True
sell_all(strategy_name, cancel_open_orders: bool = True, strategy=None, is_multileg: bool = False)

Override sell_all to use flash_close_position for futures.

ws_url

# Set default futures position mode to hedge try:

response = self.api.change_position_mode(“HEDGE”) # Check response code for success if response and response.get(“code”) == 0:

logger.info(

f”Default position mode set to {response.get(‘data’, [{}])[0].get(‘positionMode’)}”

)

else:

# Log specific error if code is not 0 logger.warning(

f”Failed to set default position mode to HEDGE. API Response: {response}”

)

except Exception as e:

# Log exception details logger.warning(f”Failed to set default position mode to HEDGE due to an exception: {e}”) logger.debug(traceback.format_exc()) # Add debug level traceback for more detail if needed

Bitunix.get_time_to_close()

Return the remaining time for the market to close in seconds

Bitunix.get_time_to_open()

Return the remaining time for the market to open in seconds

Bitunix.get_timestamp()
Bitunix.is_market_open()

Determines if the market is open.

Parameters:

None

Returns:

True if market is open, false if the market is closed.

Return type:

boolean

Examples

>>> self.is_market_open()
True
Bitunix.close_position(strategy_name: str, asset: Asset)

Close one open crypto futures position via Bitunix’s flash_close_position endpoint.

This method finds the open position for the given asset and, if found, uses Bitunix’s “flash close” API to close the position at market price. This is the recommended way to close positions on Bitunix, as it is faster and more reliable than submitting a regular market order.

Parameters:
  • strategy_name (str) – The name of the strategy requesting the close (not used for Bitunix, but required by interface).

  • asset (Asset) – The Asset object representing the futures contract to close (e.g., Asset(“BTCUSDT”, Asset.AssetType.CRYPTO_FUTURE)).

Returns:

None

Notes

  • Only works for open crypto futures positions.

  • If no open position is found, or if the position cannot be closed, this method does nothing.

  • For spot or non-futures assets, this method is not applicable.