Lab 02: Binance Sandbox IntegrationHands-on: connect to a real exchange test environment and experience live market connectivity
Objectives
- Apply for a Binance Testnet (Futures) API Key.
- Configure a
TradingNodeto connect to the sandbox environment. - Run a simple strategy to execute simulated trading.
- Observe console logs and order statuses.
You will need network access to the Binance Testnet (a VPN may be required in some regions).
You must have Redis installed (via Docker or a local installation).
Step 1: API Provisioning
- Navigate to the Binance Futures Testnet.
- Register or log in to your account.
- Locate the API Key and Secret Key at the bottom of the dashboard.
- Securely store these credentials!
Step 2: Environment Configuration (.env)
For security, do not hard-code API keys in your source code. Put them in a .env file instead:
BINANCE_API_KEY=YOUR_API_KEY
BINANCE_API_SECRET=YOUR_SECRET_KEYInstall python-dotenv:
pip install python-dotenvStep 3: Writing the Startup Script (run_sandbox.py)
import os
from dotenv import load_dotenv
from decimal import Decimal
from nautilus_trader.live.node import TradingNode
from nautilus_trader.live.config import (
TradingNodeConfig,
LiveDataEngineConfig,
LiveExecEngineConfig,
)
from nautilus_trader.adapters.binance.config import (
BinanceLiveDataClientConfig,
BinanceLiveExecClientConfig,
)
from nautilus_trader.model.enums import AccountType, OmsType
from nautilus_trader.model.identifiers import TraderId
# 1. Load environment variables
load_dotenv()
API_KEY = os.getenv("BINANCE_API_KEY")
API_SECRET = os.getenv("BINANCE_API_SECRET")
# 2. Build configurations
node_config = TradingNodeConfig(
trader_id=TraderId("SANDBOX-001"),
# Data clients (receiving market data)
data_clients={
"BINANCE": BinanceLiveDataClientConfig(
api_key=API_KEY,
api_secret=API_SECRET,
usdt_futures=True, # Use U-margined contracts
testnet=True, # CRITICAL: Connect to Testnet
),
},
# Execution clients (order routing)
exec_clients={
"BINANCE": BinanceLiveExecClientConfig(
api_key=API_KEY,
api_secret=API_SECRET,
usdt_futures=True,
testnet=True,
),
},
# Engine configurations
data_engine=LiveDataEngineConfig(time_bars_feed_only=True), # Subscribe only to 1m bars to conserve bandwidth
exec_engine=LiveExecEngineConfig(reconciliation=True), # Enable state reconciliation
)
# 3. Instantiate the node
node = TradingNode(config=node_config)
# 4. Define a simple logging strategy (for connection testing)
from nautilus_trader.trading.strategy import Strategy
from nautilus_trader.config import StrategyConfig
class PrintBarStrategy(Strategy):
def on_bar(self, bar):
self.log.info(f"Received Bar: {bar}")
# 5. Add the strategy
config = StrategyConfig(instrument_id="BTCUSDT-PERP.BINANCE")
node.trader.add_strategy(PrintBarStrategy(config))
# 6. Execute!
if __name__ == "__main__":
node.run()Step 4: Execution Results
After running the script, your console should output a connection lifecycle similar to the following:
[INFO] Node: Starting...
[INFO] TradingNode: Connecting to data clients...
[INFO] BinanceLiveDataClient: Connected to wss://stream.binancefuture.com...
[INFO] TradingNode: Connecting to execution clients...
[INFO] BinanceLiveExecClient: Connected...
[INFO] TradingNode: Starting strategies...
[INFO] PrintBarStrategy: Received Bar: Bar(BTCUSDT-PERP.BINANCE, ...)
...This means your NautilusTrader instance has connected to Binance successfully and is receiving live market data from the test environment. At that point, you have the basic plumbing in place for sandbox trading.
Exercises
1. Migrate the EMA Cross strategy from Lab 01 and configure it within run_sandbox.py.
2. Attempt to modify the trade_size to 0.001 BTC and observe if the order fills (be mindful of Binance’s minimum order quantity rules).
3. Check your account via the Binance Testnet web interface to verify that the orders have been routed and executed.