Skip to content

Martingale42/nautilus-dev / skills/nt-adapters

nt-adapters

Verified

Use when working with exchange or data provider adapters, HTTP/WebSocket clients, instrument providers, or venue integration in NautilusTrader.

FileKindSize
SKILL.mdskill md8.5 KB
references/api/.gitkeepother0 B
references/api/adapters/betfair.mdmarkdown1.9 KB
references/api/adapters/binance.mdmarkdown2.4 KB
references/api/adapters/bybit.mdmarkdown1.2 KB
references/api/adapters/databento.mdmarkdown1.4 KB
references/api/adapters/dydx.mdmarkdown1011 B
references/api/adapters/index.mdmarkdown291 B
references/api/adapters/interactive_brokers.mdmarkdown2.2 KB
references/api/adapters/okx.mdmarkdown1004 B
references/api/adapters/polymarket.mdmarkdown1.2 KB
references/api/adapters/tardis.mdmarkdown1021 B
references/api/live.mdmarkdown1.1 KB
references/concepts/.gitkeepother0 B
references/concepts/adapters.mdmarkdown5.9 KB
references/concepts/live.mdmarkdown44.3 KB
references/examples/.gitkeepother0 B
references/examples/architect_ax/ax_book_imbalance.pyscript4.0 KB
references/examples/architect_ax/ax_data_tester.pyexecutablescript3.7 KB
references/examples/architect_ax/ax_exec_tester.pyexecutablescript4.6 KB
references/examples/architect_ax/ax_mean_reversion.pyscript4.0 KB
references/examples/betfair/betfair.pyscript6.8 KB
references/examples/binance/binance_data_tester.pyscript3.6 KB
references/examples/binance/binance_futures_demo_exec_tester.pyscript6.5 KB
references/examples/binance/binance_futures_testnet_exec_tester.pyscript6.8 KB
references/examples/binance/binance_spot_and_futures_market_maker.pyscript6.8 KB
references/examples/binance/binance_spot_demo_exec_tester.pyscript4.3 KB
references/examples/binance/binance_spot_ema_cross_bracket_algo.pyscript4.4 KB
references/examples/binance/binance_spot_exec_tester.pyscript4.9 KB
references/examples/binance/binance_spot_testnet_exec_tester.pyscript4.3 KB
references/examples/bitmex/bitmex_data_tester.pyscript4.0 KB
references/examples/bitmex/bitmex_exec_tester.pyscript5.9 KB
references/examples/bybit/README_options_data_collector.mdmarkdown6.3 KB
references/examples/bybit/bybit_data_tester.pyscript4.1 KB
references/examples/bybit/bybit_ema_cross.pyscript4.9 KB
references/examples/bybit/bybit_ema_cross_bracket_algo.pyscript5.3 KB
references/examples/bybit/bybit_ema_cross_stop_entry.pyscript4.7 KB
references/examples/bybit/bybit_ema_cross_with_trailing_stop.pyscript4.7 KB
references/examples/bybit/bybit_exec_tester.pyscript8.9 KB
references/examples/bybit/bybit_options_data_collector.pyscript32.5 KB
references/examples/bybit/bybit_request_custom_endpoint.pyscript4.9 KB
references/examples/databento/databento_data_tester.pyscript4.3 KB
references/examples/databento/notebooks/databento_historical_data.pyscript6.9 KB
references/examples/deribit/deribit_data_tester.pyscript5.0 KB
references/examples/deribit/deribit_exec_tester.pyscript5.3 KB
references/examples/dydx/dydx_data_tester.pyscript4.0 KB
references/examples/dydx/dydx_exec_tester.pyscript6.9 KB
references/examples/dydx/dydx_market_maker.pyscript4.8 KB
references/examples/hyperliquid/hyperliquid_data_tester.pyscript4.4 KB
references/examples/hyperliquid/hyperliquid_exec_tester.pyscript6.6 KB
references/examples/interactive_brokers/connect_with_dockerized_gateway.pyscript5.7 KB
references/examples/interactive_brokers/connect_with_tws.pyscript4.9 KB
references/examples/interactive_brokers/contract_download.pyscript1.2 KB
references/examples/interactive_brokers/historical_download.pyscript4.3 KB
references/examples/interactive_brokers/notebooks/bracket_order_example.pyscript8.6 KB
references/examples/interactive_brokers/notebooks/oca_group_example.pyscript9.0 KB
references/examples/interactive_brokers/notebooks/simple_conditions_example.pyscript14.2 KB
references/examples/interactive_brokers/notebooks/spread_example.pyscript14.5 KB
references/examples/interactive_brokers/notebooks/with_databento_instrument_id_example.pyscript13.4 KB
references/examples/interactive_brokers/with_databento_client.pyscript4.5 KB
references/examples/kraken/kraken_data_tester.pyscript4.6 KB
references/examples/kraken/kraken_exec_tester.pyscript6.6 KB
references/examples/okx/okx_data_tester.pyscript6.1 KB
references/examples/okx/okx_exec_tester.pyscript11.2 KB
references/examples/okx/okx_spot_swap_quoter.pyscript19.2 KB
references/examples/polymarket/polymarket_data_tester.pyscript4.5 KB
references/examples/polymarket/polymarket_exec_tester.pyscript8.3 KB
references/examples/polymarket/polymarket_slug_builder_tester.pyscript4.0 KB
references/examples/polymarket/slug_builders.pyscript4.0 KB
references/examples/rust_adapters/architect_ax/node_data_tester.rsscript3.3 KB
references/examples/rust_adapters/architect_ax/node_exec_tester.rsscript3.6 KB
references/examples/rust_adapters/binance/futures/node_data_tester.rsscript2.8 KB
references/examples/rust_adapters/binance/futures/node_exec_tester.rsscript3.9 KB
references/examples/rust_adapters/binance/spot/node_data_tester.rsscript2.8 KB
references/examples/rust_adapters/binance/spot/node_exec_tester.rsscript3.7 KB
references/examples/rust_adapters/bitmex/node_data_tester.rsscript2.9 KB
references/examples/rust_adapters/bitmex/node_exec_tester.rsscript3.4 KB
references/examples/rust_adapters/bitmex/node_grid_mm.rsscript3.5 KB
references/examples/rust_adapters/blockchain/node_data_tester.rsscript11.0 KB
references/examples/rust_adapters/bybit/node_data_tester.rsscript2.7 KB
references/examples/rust_adapters/bybit/node_exec_tester.rsscript3.4 KB
references/examples/rust_adapters/databento/node_data_tester.rsscript7.1 KB
references/examples/rust_adapters/deribit/node_data_tester.rsscript3.2 KB
references/examples/rust_adapters/deribit/node_exec_tester.rsscript4.0 KB
references/examples/rust_adapters/dydx/node_data_tester.rsscript2.8 KB
references/examples/rust_adapters/dydx/node_exec_tester.rsscript3.8 KB
references/examples/rust_adapters/dydx/node_grid_mm.rsscript3.4 KB
references/examples/rust_adapters/hyperliquid/node_data_tester.rsscript3.0 KB
references/examples/rust_adapters/hyperliquid/node_exec_tester.rsscript3.9 KB
references/examples/rust_adapters/kraken/node_data_tester.rsscript4.2 KB
references/examples/rust_adapters/kraken/node_exec_tester.rsscript4.8 KB
references/examples/rust_adapters/okx/node_data_tester.rsscript2.9 KB
references/examples/rust_adapters/okx/node_exec_tester.rsscript4.1 KB
references/examples/rust_adapters/sandbox/databento_cme.rsscript4.8 KB
references/examples/rust_adapters/tardis/node_data_tester.rsscript3.0 KB
references/examples/shioaji/__init__.pyscript0 B
references/examples/shioaji/shioaji_data_tester.pyscript2.1 KB
references/examples/shioaji/shioaji_exec_tester.pyscript3.8 KB
references/examples/tardis/tardis_data_tester.pyscript4.8 KB
references/guides/.gitkeepother0 B
references/guides/adapters.mdmarkdown91.6 KB
references/guides/coding_standards.mdmarkdown6.8 KB
references/guides/ffi.mdmarkdown6.1 KB
references/guides/rust.mdmarkdown41.1 KB
references/guides/spec_data_testing.mdmarkdown34.6 KB
references/guides/spec_exec_testing.mdmarkdown79.2 KB
references/integrations/.gitkeepother0 B
references/integrations/architect_ax.mdmarkdown19.3 KB
references/integrations/betfair.mdmarkdown26.3 KB
references/integrations/binance.mdmarkdown40.6 KB
references/integrations/bitmex.mdmarkdown45.0 KB
references/integrations/blockchain.mdmarkdown4.9 KB
references/integrations/bybit.mdmarkdown30.6 KB
references/integrations/databento.mdmarkdown36.5 KB
references/integrations/deribit.mdmarkdown26.0 KB
references/integrations/dydx.mdmarkdown35.4 KB
references/integrations/hyperliquid.mdmarkdown19.9 KB
references/integrations/ib.mdmarkdown73.2 KB
references/integrations/index.mdmarkdown5.7 KB
references/integrations/kraken.mdmarkdown24.0 KB
references/integrations/okx.mdmarkdown32.1 KB
references/integrations/polymarket.mdmarkdown36.9 KB
references/integrations/tardis.mdmarkdown33.6 KB
templates/.gitkeepother0 B
templates/data_provider.pyscript5.2 KB
templates/exchange.pyscript7.6 KB

references/examples/interactive_brokers/notebooks/oca_group_example.py

View on GitHub
# ---
# jupyter:
#   jupytext:
#     formats: py:percent
#     text_representation:
#       extension: .py
#       format_name: percent
#       format_version: '1.3'
#       jupytext_version: 1.17.3
#   kernelspec:
#     display_name: Python 3 (ipykernel)
#     language: python
#     name: python3
# ---

# %% [markdown]
# Note: Use the jupytext python package to be able to open this python file in jupyter as a notebook.
# Also run `jupytext-config set-default-viewer` to open jupytext python files as notebooks by default.

# %%
import datetime
import os
import sys

import pandas as pd

from nautilus_trader.adapters.interactive_brokers.common import IB
from nautilus_trader.adapters.interactive_brokers.common import IBContract
from nautilus_trader.adapters.interactive_brokers.common import IBOrderTags
from nautilus_trader.adapters.interactive_brokers.config import IBMarketDataTypeEnum
from nautilus_trader.adapters.interactive_brokers.config import InteractiveBrokersDataClientConfig
from nautilus_trader.adapters.interactive_brokers.config import InteractiveBrokersExecClientConfig
from nautilus_trader.adapters.interactive_brokers.config import (
    InteractiveBrokersInstrumentProviderConfig,
)
from nautilus_trader.adapters.interactive_brokers.config import SymbologyMethod
from nautilus_trader.adapters.interactive_brokers.factories import (
    InteractiveBrokersLiveDataClientFactory,
)
from nautilus_trader.adapters.interactive_brokers.factories import (
    InteractiveBrokersLiveExecClientFactory,
)
from nautilus_trader.common.config import LoggingConfig
from nautilus_trader.config import TradingNodeConfig

# from nautilus_trader.core.datetime import unix_nanos_to_dt
from nautilus_trader.live.config import LiveDataEngineConfig
from nautilus_trader.live.config import RoutingConfig
from nautilus_trader.live.node import TradingNode
from nautilus_trader.model import BarType
from nautilus_trader.model import TraderId
from nautilus_trader.model.enums import OrderSide
from nautilus_trader.model.enums import OrderType
from nautilus_trader.model.enums import TimeInForce
from nautilus_trader.model.identifiers import InstrumentId
from nautilus_trader.trading import Strategy
from nautilus_trader.trading.config import StrategyConfig


# %%
class Strat_oca_test_config(StrategyConfig, frozen=True):
    tradable_instrument_id: str | None = "ESZ5.CME"


class Strat_oca_test(Strategy):
    def __init__(self, config: Strat_oca_test_config) -> None:
        super().__init__(config)
        self.bar_type_m1: dict[InstrumentId, BarType] = {}
        self.tradable_instrument_id = config.tradable_instrument_id

    def on_start(self) -> None:
        self.log.info(f"instrument_id in cache : {self.cache.instrument_ids()}")
        self.log.info(f"instruments in cache : {self.cache.instruments()}")

        for instrument in self.cache.instruments():
            if str(instrument.id) == self.tradable_instrument_id:
                self.log.info(
                    f"instrument {instrument.info['contract']['tradingClass']}: \n{instrument}",
                )
                self.bar_type_m1[instrument.id] = BarType.from_str(
                    str(instrument.id) + "-1-MINUTE-LAST-EXTERNAL",
                )
                self.log.info(f"subscribing to : {self.bar_type_m1[instrument.id]}")
                # self.subscribe_bars(self.bar_type_m1[instrument.id])

                # Test explicit OCA groups - create two separate orders with explicit OCA group
                self.create_oca_orders(instrument.id)

                self.clock.set_time_alert(
                    "modify_test",
                    self.clock.utc_now() + pd.Timedelta(seconds=10),
                    lambda event, instrument=instrument: self.test_oca_modification(instrument.id),
                )

    def create_oca_orders(self, instrument_id):
        """
        Create two separate orders with explicit OCA group to test OCA functionality.
        """
        instrument = self.cache.instrument(instrument_id)

        if not instrument:
            self.log.error(f"No instrument loaded for instrument id : {instrument_id}")
            sys.exit(1)

        # Create explicit OCA group name
        oca_group_name = f"TEST_OCA_{self.clock.utc_now().strftime('%H%M%S')}"

        # Create first order with explicit OCA group
        order1 = self.order_factory.stop_market(
            instrument_id=instrument_id,
            order_side=OrderSide.SELL,
            quantity=instrument.make_qty(1),
            trigger_price=instrument.make_price(6600),
            time_in_force=TimeInForce.GTC,
            tags=[
                IBOrderTags(ocaGroup=oca_group_name, ocaType=1).value,
            ],  # ocaType=1 means cancel all others
        )

        # Create second order with same OCA group
        order2 = self.order_factory.limit(
            instrument_id=instrument_id,
            order_side=OrderSide.SELL,
            quantity=instrument.make_qty(1),
            price=instrument.make_price(6800),
            time_in_force=TimeInForce.GTC,
            tags=[IBOrderTags(ocaGroup=oca_group_name, ocaType=1).value],  # Same OCA group
        )

        self.log.info(f"Creating OCA orders with group: {oca_group_name}")
        self.log.info(f"Order 1 (Stop): {order1}")
        self.log.info(f"Order 2 (Limit): {order2}")

        # Submit both orders
        self.submit_order(order1)
        self.submit_order(order2)

    def test_oca_modification(self, instrument_id):
        """
        Test if we can modify orders that are part of explicit OCA groups.
        """
        instrument = self.cache.instrument(instrument_id)
        list_orders_for_instrument = self.cache.orders(instrument_id=instrument_id)

        self.log.info(f"Testing OCA modification for {instrument_id}")
        self.log.info(f"Found {len(list_orders_for_instrument)} orders")

        # Find the stop order to modify
        stop_order = None
        for order in list_orders_for_instrument:
            if order.is_open and order.order_type == OrderType.STOP_MARKET:
                stop_order = order
                break

        if stop_order:
            new_trigger_price = instrument.make_price(6550)
            self.log.info(
                f"Attempting to modify OCA stop order from {stop_order.trigger_price} to {new_trigger_price}",
            )
            try:
                self.modify_order(stop_order, trigger_price=new_trigger_price)
                self.log.info("OCA order modification command sent successfully")
            except Exception as e:
                self.log.error(f"Failed to modify OCA order: {e}")
        else:
            self.log.error("No stop order found to modify")


# %%
es_contract = IBContract(
    secType="FUT",
    exchange="CME",
    localSymbol="ESZ5",
    lastTradeDateOrContractMonth="20251219",
)

contracts = [es_contract]
tradable_instrument_id = "ESZ5.CME"


# Configure the trading node
instrument_provider = InteractiveBrokersInstrumentProviderConfig(
    load_contracts=frozenset(contracts),
    symbology_method=SymbologyMethod.IB_SIMPLIFIED,
)

config_node = TradingNodeConfig(
    trader_id=TraderId("TESTER-001"),
    logging=LoggingConfig(
        log_level="INFO",
        log_level_file="INFO",
        log_file_name=datetime.datetime.strftime(
            datetime.datetime.now(tz=datetime.UTC),
            "%Y-%m-%d_%H-%M",
        )
        + "_oca_test.log",
        log_directory="./logs/",
        print_config=True,
    ),
    data_clients={
        IB: InteractiveBrokersDataClientConfig(
            ibg_host="127.0.0.1",
            ibg_port=7497,
            ibg_client_id=9004,  # Different client ID to avoid conflicts
            market_data_type=IBMarketDataTypeEnum.DELAYED_FROZEN,
            instrument_provider=instrument_provider,
            use_regular_trading_hours=False,
        ),
    },
    exec_clients={
        IB: InteractiveBrokersExecClientConfig(
            ibg_host="127.0.0.1",
            ibg_port=7497,
            ibg_client_id=9004,  # Different client ID to avoid conflicts
            account_id=os.environ.get("TWS_ACCOUNT"),
            instrument_provider=instrument_provider,
            routing=RoutingConfig(
                default=True,
            ),
        ),
    },
    data_engine=LiveDataEngineConfig(
        time_bars_timestamp_on_close=False,  # Will use opening time as `ts_event` (same like IB)
        validate_data_sequence=True,  # Will make sure DataEngine discards any Bars received out of sequence
        time_bars_build_with_no_updates=False,
    ),
)
strat_config = Strat_oca_test_config(tradable_instrument_id=tradable_instrument_id)
# Instantiate your strategy
strategy = Strat_oca_test(config=strat_config)

# Instantiate the node with a configuration
node = TradingNode(config=config_node)

# Add your strategies and modules
node.trader.add_strategy(strategy)

# Register your client factories with the node (can take user-defined factories)
node.add_data_client_factory(IB, InteractiveBrokersLiveDataClientFactory)
node.add_exec_client_factory(IB, InteractiveBrokersLiveExecClientFactory)
node.build()

# %%
node.run()

# %%
node.stop()

# %%
node.dispose()

# %%
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 197kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall