簡體   English   中英

無法使用python連接到Interactive Brokers

[英]Can't connect to Interactive Brokers with python

我想用python連接到IB,這是我的代碼:

from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message


def error_handler(msg):

   print "Server Error: %s" % msg

def reply_handler(msg):

   print "Server Response: %s, %s" % (msg.typeName, msg)



if __name__ == "__main__":
 tws_conn = Connection.create(port=7496, clientId=100)
 tws_conn.connect()
 tws_conn.register(error_handler, 'Error')  
 tws_conn.registerAll(reply_handler)

每當我使用此代碼時,我收到此錯誤,表示我無法連接到服務器:

Server Error: <error id=-1, errorCode=504, errorMsg=Not connected>
Server Response: error, <error id=-1, errorCode=504, errorMsg=Not connected>

為什么我無法連接到IB?

三件事:

  1. 確保TWS java應用程序正在運行且您已登錄。
  2. 在TWS中,轉到全局配置> API,並確保選中“啟用活動和套接字客戶端”。
  3. 在Global Configuration> API中,確保添加“127.0.0.1”作為可信IP地址(這假設您的py代碼在運行TWS java應用程序的同一台機器上運行。

嘿所以你需要做的是幾件事。 首先,您需要Python 3.5或更高版本。 所以你的print語句應該使用()。 其次,您需要指定一個設置為本地計算機的IP地址。 第三,享受。 我用過這個並得到了:

服務器版本:76

交流時間:20170613 21:10:55 MST

from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message


def error_handler(msg):

   print("Server Error: %s" % msg)

def reply_handler(msg):

  print("Server Response: %s, %s" % (msg.typeName, msg))



if __name__ == "__main__":
  tws_conn = Connection.create("127.0.0.1", port=7496, clientId=100)
  tws_conn.connect()
  tws_conn.register(error_handler, 'Error')  
  tws_conn.registerAll(reply_handler)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM