本文整理汇总了Python中ib.opt.Connection类的典型用法代码示例。如果您正苦于以下问题:Python Connection类的具体用法?Python Connection怎么用?Python Connection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Connection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, host='localhost', port=4001,
client_id=130, is_use_gateway=False, evaluation_time_secs=20,
resample_interval_secs='30s',
moving_window_period=dt.timedelta(seconds=60)):
self.moving_window_period = moving_window_period
# self.chart = Chart()
self.ib_util = IBUtil()
# Store parameters for this model
# self.strategy_params = StrategyParameters(evaluation_time_secs,
# resample_interval_secs)
self.stocks_data = {} # Dictionary storing StockData objects.
self.symbols = None # List of current symbols
self.account_code = ""
self.prices = None # Store last prices in a DataFrame
self.ohlc = None # I need another store for minute data (I think)
self.trade_qty = 0
self.order_id = 0
self.lock = threading.Lock()
#addition for hdf store
self.data_path = os.path.normpath("/Users/maxime_back/Documents/avocado/data.csv")
self.ohlc_path = os.path.normpath("/Users/maxime_back/Documents/avocado/ohlc.csv")
self.last_trim = dt.datetime.now()
# Use ibConnection() for TWS, or create connection for API Gateway
self.conn = ibConnection() if is_use_gateway else \
Connection.create(host=host, port=port, clientId=client_id)
self.__register_data_handlers(self.__on_tick_event,
self.__event_handler)
示例2: test
def test():
# Connect to the Trader Workstation (TWS) running on the
# usual port of 7496, with a clientId of 100
# (The clientId is chosen by us and we will need
# separate IDs for both the execution connection and
# market data connection)
tws_conn = Connection.create(port=7496, clientId=100)
tws_conn.connect()
# Assign the error handling function defined above
# to the TWS connection
tws_conn.register(error_handler, 'Error')
# Assign all of the server reply messages to the
# reply_handler function defined above
tws_conn.registerAll(reply_handler)
# Create an order ID which is 'global' for this session. This
# will need incrementing once new orders are submitted.
order_id = 1
# Create a contract in GOOG stock via SMART order routing
goog_contract = create_contract('GOOG', 'STK', 'SMART', 'SMART', 'USD')
# Go long 100 shares of Google
goog_order = create_order('MKT', 1000, 'BUY')
# Use the connection to the send the order to IB
tws_conn.placeOrder(order_id, goog_contract, goog_order)
# Disconnect from TWS
tws_conn.disconnect()
示例3: __init__
def __init__(self, host='localhost', port=4001,
client_id=101, is_use_gateway=False, evaluation_time_secs=20,
resample_interval_secs='30s',
moving_window_period=dt.timedelta(hours=1)):
self.moving_window_period = moving_window_period
self.chart = Chart()
self.ib_util = IBUtil()
# Store parameters for this model
self.strategy_params = StrategyParameters(evaluation_time_secs,
resample_interval_secs)
self.stocks_data = {} # Dictionary storing StockData objects.
self.symbols = None # List of current symbols
self.account_code = ""
self.prices = None # Store last prices in a DataFrame
self.trade_qty = 0
self.order_id = 0
self.lock = threading.Lock()
# Use ibConnection() for TWS, or create connection for API Gateway
self.conn = ibConnection() if is_use_gateway else \
Connection.create(host=host, port=port, clientId=client_id)
self.__register_data_handlers(self.__on_tick_event,
self.__event_handler)
示例4: __init__
def __init__(self):
tws = Connection.create(port=7496, clientId=101)
tws.connect()
tws.registerAll(self.reply_handler)
tws.register(self.error_handler, message.Error)
tws.register(self.my_hist_data_handler, message.historicalData)
self.tws=tws
self.histdata = list()
示例5: connect
def connect(self):
self.update_connection_status("Connecting")
api_hostname = environ["TXTRADER_API_HOST"]
api_port = int(environ["TXTRADER_API_PORT"])
api_client_id = int(environ["TXTRADER_API_CLIENT_ID"])
self.output("Connnecting to TWS API at %s:%d with client id %d" % (api_hostname, api_port, api_client_id))
self.tws_conn = Connection.create(host=api_hostname, port=api_port, clientId=api_client_id)
self.tws_conn.registerAll(self.reply_handler)
self.tws_conn.connect()
示例6: main
def main():
conn = Connection.create(port=7497, clientId=999)
conn.connect()
oid = 1
cont = make_contract('SPY', 'STK', 'SMART', 'SMART', 'USD')
offer = make_order('BUY', 1, 200)
conn.placeOrder(oid, cont, offer)
conn.disconnect()
示例7: __init__
def __init__(self, clientId=999):
self.tws_conn = Connection.create(port=7496, clientId=clientId)
self.tws_conn.connect()
self.tws_conn.register(error_handler, 'Error')
self.tws_conn.registerAll(reply_handler)
self.ib_orderid_fname="ib_orderid_fname.p"
if os.path.isfile(self.ib_orderid_fname):
self.order_id = pickle.load(open(self.ib_orderid_fname, 'rb'))
else:
self.order_id = 1
示例8: main
def main():
conn = Connection.create(port=7496, clientId=994)
conn.registerAll(print_message_from_ib)
conn.connect()
#In future blog posts, this is where we'll write code that actually does
#something useful, like place orders, get real-time prices, etc.
import time
time.sleep(1) #Simply to give the program time to print messages sent from IB
conn.disconnect()
示例9: main
def main():
global conn
print "HFT model started."
# Use ibConnection() for TWS, or create connection for API Gateway
#conn = ibConnection()
conn = Connection.create(port=4001, clientId=101)
register_data_handlers()
conn.connect()
# Input your stocks of interest
stocks = ("C", "MS")
setup_stocks_data(stocks)
request_streaming_data(conn)
print "Boot strapping..."
start_time = time.time()
boot_strap_long_term(conn)
wait_for_boot_strap_lt_to_complete()
boot_strap_short_term(conn)
wait_for_boot_strap_st_to_complete()
print_elapsed_time(start_time)
strategy_params.set_bootstrap_completed()
print "Calculating strategy parameters..."
start_time = time.time()
calculate_params(stocks_data)
print_elapsed_time(start_time)
print "Bridging historical data..."
start_time = time.time()
bridge_historical_and_present_ticks(stocks_data, ticks_data, datetime.now())
print_elapsed_time(start_time)
print "Trading started."
try:
plot_stocks(strategy_params)
while True:
update_charts()
time.sleep(1)
except Exception, e:
print "Cancelling...",
cancel_market_data_request()
print "Disconnecting..."
conn.disconnect()
time.sleep(1)
print "Disconnected."
示例10: test_make_order
def test_make_order():
conn = Connection.create(port=7496, clientId=99)
conn.connect()
conn.register(error_handler, 'Error')
conn.registerAll(reply_handler)
print 'connect'
oid = 7;
contract = make_contract('TSLA', 'STK', 'SMART', 'SMART', 'USD')
offer = make_order('BUY', 100, 200)
print contract
print offer
conn.placeOrder(oid, contract, offer)
示例11: main
def main():
conn = Connection.create(port=7497, clientId=88) #Has to be connected to Global settings of TWS
conn.connect()
oid = main.count #Order number
print (oid)
cont = make_contract('anf', 'STK', 'SMART', 'SMART', 'USD') #Check exch name for stock symbol
offer = make_order('BUY',100,16.30)
conn.placeOrder(oid, cont, offer)
print(oid, str(cont), offer)
conn.disconnect()
示例12: main
def main():
# port.main()
# prices.main()
# connects to TWS-- make sure to include your port and clientID here
conn = Connection.create(port='{YOUR PORT}', clientId='{YOUR CLIENT_ID}')
values = contrarian_plays(to_integer(datetime.date.today()))
send_orders(values[0], values[1], conn)
# for some reason if there is no break between transactions it won't work
time.sleep(5)
portfolio = values[2]
# checks if there are any stocks to be sold
check_sells(conn, portfolio)
conn.disconnect()
示例13: get_data_ib
def get_data_ib(self, id, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate):
con = Connection.create(port=7496, clientId=1)
con.connect()
con.register(self.watcher, message.historicalData)
# time.sleep(1)
#con.reqMktData(id, self.contract, '', False)
con.reqHistoricalData(id, self.contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate)
time.sleep(1)
con.cancelHistoricalData(id)
time.sleep(1)
con.disconnect()
return self.data
示例14: __init__
def __init__(self, host='localhost', port=4001,
client_id=101, is_use_gateway=False, evaluation_time_secs=20,
resample_interval_secs='30s',
moving_window_period=dt.timedelta(hours=1)):
self.moving_window_period = moving_window_period
self.chart = Chart()
self.ib_util = IBUtil()
self.strategy_params = StrategyParameters(evaluation_time_secs,
resample_interval_secs)
self.stocks_data = {}
self.symbols = None
self.account_code = ""
self.prices = None
self.trade_qty = 0
self.order_id = 0
self.lock = threading.Lock()
self.conn = ibConnection() if is_use_gateway else \
Connection.create(host=host, port=port, clientId=client_id)
self.__register_data_handlers(self.__on_tick_event,
self.__event_handler)
示例15: connect_to_tws
def connect_to_tws(self):
self.tws_conn = Connection.create(port=self.port,
clientId=self.client_id)
self.tws_conn.connect()