|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# ------------------------------------------------------------------------------------------------- |
| 3 | +# Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved. |
| 4 | +# https://nautechsystems.io |
| 5 | +# |
| 6 | +# Licensed under the GNU Lesser General Public License Version 3.0 (the "License"); |
| 7 | +# You may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# ------------------------------------------------------------------------------------------------- |
| 16 | + |
| 17 | +import asyncio |
| 18 | +import json |
| 19 | +from decimal import Decimal |
| 20 | + |
| 21 | +from nautilus_trader.adapters.binance.common.enums import BinanceAccountType |
| 22 | +from nautilus_trader.adapters.binance.config import BinanceDataClientConfig |
| 23 | +from nautilus_trader.adapters.binance.factories import BinanceLiveDataClientFactory |
| 24 | +from nautilus_trader.adapters.binance.futures.types import BinanceFuturesMarkPriceUpdate |
| 25 | +from nautilus_trader.adapters.sandbox.config import SandboxExecutionClientConfig |
| 26 | +from nautilus_trader.adapters.sandbox.factory import SandboxLiveExecClientFactory |
| 27 | +from nautilus_trader.common.enums import LogColor |
| 28 | +from nautilus_trader.config import CacheConfig |
| 29 | +from nautilus_trader.config import InstrumentProviderConfig |
| 30 | +from nautilus_trader.config import LiveExecEngineConfig |
| 31 | +from nautilus_trader.config import LoggingConfig |
| 32 | +from nautilus_trader.config import TradingNodeConfig |
| 33 | +from nautilus_trader.core.data import Data |
| 34 | +from nautilus_trader.live.node import TradingNode |
| 35 | +from nautilus_trader.model.data import Bar |
| 36 | +from nautilus_trader.model.data import DataType |
| 37 | +from nautilus_trader.model.data import QuoteTick |
| 38 | +from nautilus_trader.model.data import TradeTick |
| 39 | +from nautilus_trader.model.identifiers import ClientId |
| 40 | +from nautilus_trader.model.identifiers import InstrumentId |
| 41 | +from nautilus_trader.model.identifiers import TraderId |
| 42 | +from nautilus_trader.model.identifiers import Venue |
| 43 | +from nautilus_trader.model.instruments import Instrument |
| 44 | +from nautilus_trader.trading import Strategy |
| 45 | +from nautilus_trader.trading.config import StrategyConfig |
| 46 | + |
| 47 | + |
| 48 | +# *** THIS IS A TEST STRATEGY WITH NO ALPHA ADVANTAGE WHATSOEVER. *** |
| 49 | +# *** IT IS NOT INTENDED TO BE USED TO TRADE LIVE WITH REAL MONEY. *** |
| 50 | + |
| 51 | + |
| 52 | +class TestStrategyConfig(StrategyConfig, frozen=True): |
| 53 | + futures_client_id: ClientId |
| 54 | + futures_instrument_id: InstrumentId |
| 55 | + spot_instrument_id: InstrumentId |
| 56 | + |
| 57 | + |
| 58 | +class TestStrategy(Strategy): |
| 59 | + def __init__(self, config: TestStrategyConfig) -> None: |
| 60 | + super().__init__(config) |
| 61 | + |
| 62 | + self.futures_instrument: Instrument | None = None # Initialized in on_start |
| 63 | + self.spot_instrument: Instrument | None = None # Initialized in on_start |
| 64 | + self.futures_client_id = config.futures_client_id |
| 65 | + |
| 66 | + def on_start(self) -> None: |
| 67 | + self.futures_instrument = self.cache.instrument(self.config.futures_instrument_id) |
| 68 | + if self.futures_instrument is None: |
| 69 | + self.log.error( |
| 70 | + f"Could not find instrument for {self.config.futures_instrument_id}" |
| 71 | + f"\nPossible instruments: {self.cache.instrument_ids()}", |
| 72 | + ) |
| 73 | + self.stop() |
| 74 | + return |
| 75 | + self.spot_instrument = self.cache.instrument(self.config.spot_instrument_id) |
| 76 | + if self.spot_instrument is None: |
| 77 | + self.log.error( |
| 78 | + f"Could not find futures instrument for {self.config.spot_instrument_id}" |
| 79 | + f"\nPossible instruments: {self.cache.instrument_ids()}", |
| 80 | + ) |
| 81 | + self.stop() |
| 82 | + return |
| 83 | + |
| 84 | + account = self.portfolio.account(venue=self.futures_instrument.venue) |
| 85 | + balances = {str(currency): str(balance) for currency, balance in account.balances().items()} |
| 86 | + self.log.info(f"Futures balances\n{json.dumps(balances, indent=4)}", LogColor.GREEN) |
| 87 | + account = self.portfolio.account(venue=self.spot_instrument.venue) |
| 88 | + balances = {str(currency): str(balance) for currency, balance in account.balances().items()} |
| 89 | + self.log.info(f"Spot balances\n{json.dumps(balances, indent=4)}", LogColor.GREEN) |
| 90 | + |
| 91 | + # Subscribe to live data |
| 92 | + self.subscribe_quote_ticks(self.config.futures_instrument_id) |
| 93 | + self.subscribe_quote_ticks(self.config.spot_instrument_id) |
| 94 | + self.subscribe_data( |
| 95 | + data_type=DataType( |
| 96 | + BinanceFuturesMarkPriceUpdate, |
| 97 | + metadata={"instrument_id": self.futures_instrument.id}, |
| 98 | + ), |
| 99 | + client_id=self.futures_client_id, |
| 100 | + ) |
| 101 | + |
| 102 | + def on_data(self, data: Data) -> None: |
| 103 | + self.log.info(repr(data), LogColor.CYAN) |
| 104 | + |
| 105 | + def on_quote_tick(self, tick: QuoteTick) -> None: |
| 106 | + self.log.info(repr(tick), LogColor.CYAN) |
| 107 | + |
| 108 | + def on_trade_tick(self, tick: TradeTick) -> None: |
| 109 | + self.log.info(repr(tick), LogColor.CYAN) |
| 110 | + |
| 111 | + def on_bar(self, bar: Bar) -> None: |
| 112 | + self.log.info(repr(bar), LogColor.CYAN) |
| 113 | + |
| 114 | + def on_stop(self) -> None: |
| 115 | + # Unsubscribe from data |
| 116 | + self.unsubscribe_quote_ticks(self.config.futures_instrument_id) |
| 117 | + self.unsubscribe_quote_ticks(self.config.spot_instrument_id) |
| 118 | + |
| 119 | + |
| 120 | +async def main(): |
| 121 | + """ |
| 122 | + Show how to run a strategy in a sandbox for the Binance venue. |
| 123 | + """ |
| 124 | + # Configure the trading node |
| 125 | + config_node = TradingNodeConfig( |
| 126 | + trader_id=TraderId("TESTER-001"), |
| 127 | + logging=LoggingConfig( |
| 128 | + log_level="INFO", |
| 129 | + log_colors=True, |
| 130 | + use_pyo3=True, |
| 131 | + ), |
| 132 | + exec_engine=LiveExecEngineConfig( |
| 133 | + reconciliation=True, |
| 134 | + reconciliation_lookback_mins=1440, |
| 135 | + filter_position_reports=True, |
| 136 | + ), |
| 137 | + cache=CacheConfig( |
| 138 | + timestamps_as_iso8601=True, |
| 139 | + flush_on_start=False, |
| 140 | + ), |
| 141 | + data_clients={ |
| 142 | + "BINANCE_FUTURES": BinanceDataClientConfig( |
| 143 | + venue=Venue("BINANCE_FUTURES"), |
| 144 | + api_key=None, # 'BINANCE_API_KEY' env var |
| 145 | + api_secret=None, # 'BINANCE_API_SECRET' env var |
| 146 | + account_type=BinanceAccountType.USDT_FUTURE, |
| 147 | + base_url_http=None, # Override with custom endpoint |
| 148 | + base_url_ws=None, # Override with custom endpoint |
| 149 | + us=False, # If client is for Binance US |
| 150 | + testnet=False, # If client uses the testnet |
| 151 | + instrument_provider=InstrumentProviderConfig(load_all=True), |
| 152 | + ), |
| 153 | + "BINANCE_SPOT": BinanceDataClientConfig( |
| 154 | + venue=Venue("BINANCE_SPOT"), |
| 155 | + api_key=None, # 'BINANCE_API_KEY' env var |
| 156 | + api_secret=None, # 'BINANCE_API_SECRET' env var |
| 157 | + account_type=BinanceAccountType.SPOT, |
| 158 | + base_url_http=None, # Override with custom endpoint |
| 159 | + base_url_ws=None, # Override with custom endpoint |
| 160 | + us=False, # If client is for Binance US |
| 161 | + testnet=False, # If client uses the testnet |
| 162 | + instrument_provider=InstrumentProviderConfig(load_all=True), |
| 163 | + ), |
| 164 | + }, |
| 165 | + exec_clients={ |
| 166 | + "BINANCE_FUTURES": SandboxExecutionClientConfig( |
| 167 | + venue="BINANCE_FUTURES", |
| 168 | + account_type="MARGIN", |
| 169 | + starting_balances=["10_000 USDC", "0.005 BTC"], |
| 170 | + default_leverage=Decimal("5"), |
| 171 | + ), |
| 172 | + "BINANCE_SPOT": SandboxExecutionClientConfig( |
| 173 | + venue="BINANCE_SPOT", |
| 174 | + account_type="CASH", |
| 175 | + starting_balances=["1_000 USDC", "0.001 BTC"], |
| 176 | + ), |
| 177 | + }, |
| 178 | + timeout_connection=30.0, |
| 179 | + timeout_reconciliation=10.0, |
| 180 | + timeout_portfolio=10.0, |
| 181 | + timeout_disconnection=10.0, |
| 182 | + timeout_post_stop=5.0, |
| 183 | + ) |
| 184 | + |
| 185 | + # Instantiate the node with a configuration |
| 186 | + node = TradingNode(config=config_node) |
| 187 | + |
| 188 | + # Configure your strategy |
| 189 | + strat_config = TestStrategyConfig( |
| 190 | + futures_client_id=ClientId("BINANCE_FUTURES"), |
| 191 | + futures_instrument_id=InstrumentId.from_str("BTCUSDT-PERP.BINANCE_FUTURES"), |
| 192 | + spot_instrument_id=InstrumentId.from_str("BTCUSDC.BINANCE_SPOT"), |
| 193 | + ) |
| 194 | + # Instantiate your strategy |
| 195 | + strategy = TestStrategy(config=strat_config) |
| 196 | + |
| 197 | + # Add your strategies and modules |
| 198 | + node.trader.add_strategy(strategy) |
| 199 | + |
| 200 | + # Register your client factories with the node (can take user-defined factories) |
| 201 | + node.add_data_client_factory("BINANCE_FUTURES", BinanceLiveDataClientFactory) |
| 202 | + node.add_data_client_factory("BINANCE_SPOT", BinanceLiveDataClientFactory) |
| 203 | + node.add_exec_client_factory("BINANCE_FUTURES", SandboxLiveExecClientFactory) |
| 204 | + node.add_exec_client_factory("BINANCE_SPOT", SandboxLiveExecClientFactory) |
| 205 | + node.build() |
| 206 | + |
| 207 | + try: |
| 208 | + await node.run_async() |
| 209 | + finally: |
| 210 | + await node.stop_async() |
| 211 | + await asyncio.sleep(1) |
| 212 | + node.dispose() |
| 213 | + |
| 214 | + |
| 215 | +# Stop and dispose of the node with SIGINT/CTRL+C |
| 216 | +if __name__ == "__main__": |
| 217 | + asyncio.run(main()) |
0 commit comments