I am trying to build a python application for automated trading using ES/MES, I have subscribed to the live CME data however this code is not successful. I get this error message, any help is greatly appreciated. API is enabled and NinjaTrader 8 is running on Windows 11.
“Not connected to NinjaTrader. Ensure NinjaTrader is running and ATI is enabled”
import clr
import sys
import os
from time import sleep
import logging
from datetime import datetime
import pytz
# Configuration
DLL_PATH = r"c:\progra~1\ninjat~1\bin" # NinjaTrader bin directory
# Logging configuration
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('trading.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Add path to NinjaTrader.Client.dll
if not os.path.exists(DLL_PATH):
logger.error(f"DLL path not found: {DLL_PATH}")
raise FileNotFoundError(f"DLL path not found: {DLL_PATH}")
sys.path.append(DLL_PATH)
# Ensure dependencies are accessible
dependency_dlls = ["NinjaTrader.Core.dll", "NinjaTrader.Client.dll"]
for dll in dependency_dlls:
if not os.path.exists(os.path.join(DLL_PATH, dll)):
logger.error(f"Required DLL not found: {dll}")
raise FileNotFoundError(f"Required DLL not found: {dll}")
try:
clr.AddReference("NinjaTrader.Client")
except Exception as e:
logger.error(f"Failed to load NinjaTrader.Client.dll: {e}")
raise ImportError(f"Failed to load NinjaTrader.Client.dll: {e}")
# Import NinjaTrader Client
try:
from NinjaTrader.Client import Client
except ImportError as e:
logger.error(f"Failed to import Client from NinjaTrader.Client: {e}")
raise ImportError(f"Failed to import Client from NinjaTrader.Client: {e}")
def is_market_open():
"""
Check if CME futures market is open (Sun 6:00 PM – Fri 5:00 PM EDT).
Returns:
bool: True if market is open, False otherwise.
"""
now = datetime.now(pytz.timezone('US/Eastern'))
day = now.weekday() # 0 = Monday, 6 = Sunday
hour = now.hour
minute = now.minute
# Market is open Sun 6:00 PM – Fri 5:00 PM EDT
if day == 6: # Sunday
return hour >= 18 # Open after 6:00 PM
elif day == 5: # Friday
return hour < 17 # Closed after 5:00 PM
elif 0 <= day <= 4: # Monday–Thursday
return True # Open all day (with daily maintenance 5:00–6:00 PM)
return False
def get_market_data(instrument: str, data_type: int) -> float:
"""
Retrieve market data from NinjaTrader for the specified instrument.
Args:
instrument (str): Instrument symbol (e.g., 'ES 06-25').
data_type (int): Data type (1 = Last, 2 = Bid, 3 = Ask).
Returns:
float: Market data price, or None if an error occurs.
"""
try:
# Check market hours
if not is_market_open():
logger.warning(f"Market is closed for {instrument}. Skipping data retrieval.")
return None
# Initialize NinjaTrader client
logger.info(f"Connecting to NinjaTrader ATI for {instrument}")
client = Client()
# Check connection
connection_status = client.Connected(0) # 0 = no message popup
if connection_status != 1:
logger.error("Not connected to NinjaTrader. Ensure NinjaTrader is running and ATI is enabled.")
raise ConnectionError("Not connected to NinjaTrader. Ensure NinjaTrader is running and ATI is enabled.")
# Subscribe to market data
subscribe_result = client.SubscribeMarketData(instrument)
if subscribe_result != 0:
logger.error(f"Failed to subscribe to {instrument}. Error code: {subscribe_result}")
raise RuntimeError(f"Failed to subscribe to {instrument}. Error code: {subscribe_result}")
# Wait for data
sleep(1)
# Retrieve market data
price = client.MarketData(instrument, data_type)
if price == 0.0:
logger.error(f"No valid data for {instrument}. Ensure market is open and data feed is active.")
raise ValueError(f"No valid data for {instrument}. Ensure market is open and data feed is active.")
logger.info(f"Market data for {instrument} (type {data_type}): {price}")
return price
except Exception as e:
logger.error(f"Error retrieving market data: {e}")
return None
finally:
# Unsubscribe
try:
client.UnsubscribeMarketData(instrument)
logger.info(f"Unsubscribed from {instrument}")
except Exception as e:
logger.warning(f"Failed to unsubscribe from {instrument}: {e}")
# Example usage
if __name__ == "__main__":
instrument = "ES 06-25" # E-mini S&P 500 June 2025 futures
data_type = 1 # 1 = Last price
price = get_market_data(instrument, data_type)
Also here’s a simple conn.py to check connectivity, it returns 0 when NT 8 is running
import clr
import sys
import os
dll_path = r"c:\progra~1\ninjat~1\bin"
# Configuration
# HOST = "localhost" # NinjaTrader ATI host
# PORT = 36973 # NinjaTrader ATI port (default)
if not os.path.exists(dll_path):
raise FileNotFoundError(f"DLL path not found: {dll_path}")
sys.path.append(dll_path)
clr.AddReference("NinjaTrader.Client")
from NinjaTrader.Client import Client
client = Client()
#client.SetHost(HOST, PORT)
# Explicitly set host and port
print(f"Connection status: {client.Connected(0)}")