本文整理汇总了Python中swigibpy.EPosixClientSocket类的典型用法代码示例。如果您正苦于以下问题:Python EPosixClientSocket类的具体用法?Python EPosixClientSocket怎么用?Python EPosixClientSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了EPosixClientSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, callback):
tws = EPosixClientSocket(callback)
(host, port, clientid) = return_IB_connection_info()
tws.eConnect(host, port, clientid)
self.tws = tws
self.cb = callback
示例2: __init__
def __init__(self, callback):
"""
Create like this
callback = IBWrapper()
client = IBclient(callback)
"""
client_socket = EPosixClientSocket(callback)
(host, port, clientid) = return_IB_connection_info()
client_socket.eConnect(host, port, clientid)
self.client_socket = client_socket
self.callback = callback
示例3: __init__
def __init__(self, callback):
"""
Create like this
callback = IBWrapper()
client=IBclient(callback)
"""
tws = EPosixClientSocket(callback)
(host, port, clientid) = return_IB_connection_info()
tws.eConnect(host, port, clientid)
self.tws = tws
self.cb = callback
示例4: __init__
def __init__(self, callback, clientid=None, accountid="DU202715"):
"""
Create like this
callback = IBWrapper()
client=IBclient(callback)
"""
tws = EPosixClientSocket(callback)
(host, port, clientid)=return_IB_connection_info(clientid)
tws.eConnect(host, port, clientid)
self.tws=tws
self.cb=callback
self.accountid = accountid
self.clientid = clientid
示例5: __init__
def __init__(self):
self.accountNumber = ''
self.optionExpiry = '20121221' # This needs manual updating!
self.maxAskBidRatio = 1.25
self.maxAskLastPriceRatio = 1.02
self.maxOrderQueueLength = 3
# Create a file for TWS logging
self.twslog_fh = open('/home/mchan/git/Artemis/twslog.txt', 'a', 0)
self.twslog_fh.write("Session Started " + str(datetime.datetime.now()) + "\n")
self.callback = ArtemisIBWrapperSilent.ArtemisIBWrapper()
self.tws = EPosixClientSocket(self.callback)
self.orderIdCount = 1 # This will be updated automatically
self.requestIdCount = 1
self.invested = False
self.maxLimitPriceFactor = 1.02 # No limit orders above 2% of current ask price
# Connect the socket
self.socketnum = 30
self.tws.eConnect("", 7496, self.socketnum, poll_interval=1)
# Strategy Generic object, has methods for interpreting consensus out/under performance
self.Strat = strategy.Strategy()
# Queue for orders
self.orderQueue = []
# Setup DB connector
self.db = dbutil.db(h='127.0.0.1', schema='mchan')
# Query Cash Account Balance
self.updateBuyingPowerNextId()
示例6: __init__
def __init__(self, port=4001, client_id=12):
super(SwigIBClientForInstrument, self).__init__()
self.tws = EPosixClientSocket(self)
self.port = port
self.client_id = client_id
self.got_history = Event()
self.got_contract = Event()
self.got_err = Event()
self.order_filled = Event()
self.order_ids = Queue()
示例7: testTWS
class testTWS(object):
def __init__(self):
self.callback = ArtemisIBWrapper()
self.tws = EPosixClientSocket(self.callback)
self.tws.eConnect("", 7496, 44, poll_interval=1)
def run(self):
# Simple contract for GOOG
contract = Contract()
#contract.conId = 114376112
contract.exchange = "SMART"
contract.symbol = "ATK"
contract.secType = "STK"
#contract.right = "PUT"
contract.currency = "USD"
#contract.secType = 'OPT'
#contract.strike = 24
#contract.expiry = '20121116'
today = datetime.today()
order = Order()
order.orderId = 89
order.clientId = 44
order.action = "BUY"
order.totalQuantity = 1 # may have to calculate a smarter number
order.orderType = "MKT"
order.tif = "DAY"
order.transmit = True
order.sweepToFill = True
order.outsideRth = True
contract.symbol = "alkjdf"
self.callback.askPrice = None
self.tws.reqMktData(2, contract, "", 1)
max_wait = timedelta(seconds=30) + datetime.now()
while self.callback.askPrice is None:
if datetime.now() > max_wait:
print "max wait giving up"
break
print self.callback.askPrice
示例8: IBBroker
class IBBroker(Broker):
cid = 0 # connection id
oid = 0 # order id
tid = 0 # tick id (for fetching quotes)
tws = None # Trader WorkStation
wrapper = None # instance of EWrapper
sid_to_tid = {} # map of security id to tick id
def __init__(self, wrapper=None):
Broker.__init__(self)
# initialize a default wrapper
if wrapper:
self.wrapper = wrapper
else:
self.wrapper = WrapperDefault()
# initialize the wrapper's portfolio object
self.wrapper.portfolio = IBPortfolio()
# get next order id
def get_next_oid(self):
IBBroker.oid += 1
return IBBroker.oid
# get next connection id
def get_next_cid(self):
IBBroker.cid += 1
return IBBroker.cid
# get next tick request id (for getting quotes)
def get_next_tid(self):
self.tid += 1
return self.tid
# connect to TWS
def connect(self, port=7496):
if self.is_connected():
self.disconnect()
cid = self.get_next_cid()
self.tws = EPosixClientSocket(self.wrapper)
self.tws.eConnect('', port, cid)
# disconnect from TWS
def disconnect(self):
self.tws.eDisconnect()
# check if TWS is connected
def is_connected(self):
if self.tws is None:
return False
return self.tws.isConnected()
# Convert Zipline order signs into IB action strings
def order_action(self, iSign):
if iSign > 0:
return 'BUY'
elif iSign < 0:
return 'SELL'
raise Exception('Order of zero shares has no IB side: %i' % iSign)
# get an IB contract by ticker
def get_contract_by_sid(self, sid):
contract = Contract()
contract.symbol = sid
contract.secType = 'STK'
contract.exchange = 'SMART'
contract.currency = 'USD'
return contract
# get a default IB market order
def get_market_order(self, sid, amt):
order = Order();
order.action = self.order_action(amt)
order.totalQuantity = abs(amt)
order.orderType = 'MKT'
order.tif = 'DAY'
order.outsideRth = False
return order
# get a default IB limit order
def get_limit_order(self, sid, amt, lmtPrice):
order = Order();
order.action = self.order_action(amt)
order.totalQuantity = abs(amt)
order.orderType = 'LMT'
order.tif = 'DAY'
order.outsideRth = False
order.lmtPrice = lmtPrice
return order
# send the IB (contract, order) order to TWS
def place_order(self, contract, order):
oid = self.get_next_oid()
self.tws.placeOrder(oid, contract, order)
return oid
# send order with Zipline style order arguments
# <TODO> stop_price is not implemented
#.........这里部分代码省略.........
示例9: SwigIBClientForInstrument
class SwigIBClientForInstrument(EWrapper):
'''Callback object passed to TWS, these functions will be called directly
by TWS.
'''
def __init__(self, port=4001, client_id=12):
super(SwigIBClientForInstrument, self).__init__()
self.tws = EPosixClientSocket(self)
self.port = port
self.client_id = client_id
self.got_history = Event()
self.got_contract = Event()
self.got_err = Event()
self.order_filled = Event()
self.order_ids = Queue()
def execDetails(self, id, contract, execution):
pass
def managedAccounts(self, openOrderEnd):
pass
### Order
def nextValidId(self, validOrderId):
'''Capture the next order id'''
self.order_ids.put(validOrderId)
def request_contract_details(self, contract):
today = datetime.today()
print("Requesting contract details...")
# Perform the request
self.tws.reqContractDetails(
43, # reqId,
contract, # contract,
)
print("\n====================================================================")
print(" Contract details requested, waiting %ds for TWS responses" % WAIT_TIME)
print("====================================================================\n")
try:
self.got_contract.wait(timeout=WAIT_TIME)
except KeyboardInterrupt:
pass
finally:
if not self.got_contract.is_set():
print('Failed to get contract within %d seconds' % WAIT_TIME)
def contractDetails(self, reqId, contractDetails):
print("Contract details received (request id %i):" % reqId)
print("callable: %s" % contractDetails.callable)
print("category: %s" % contractDetails.category)
print("contractMonth: %s" % contractDetails.contractMonth)
print("convertible: %s" % contractDetails.convertible)
print("coupon: %s" % contractDetails.coupon)
print("industry: %s" % contractDetails.industry)
print("liquidHours: %s" % contractDetails.liquidHours)
print("longName: %s" % contractDetails.longName)
print("marketName: %s" % contractDetails.marketName)
print("minTick: %s" % contractDetails.minTick)
print("nextOptionPartial: %s" % contractDetails.nextOptionPartial)
print("orderTypes: %s" % contractDetails.orderTypes)
print("priceMagnifier: %s" % contractDetails.priceMagnifier)
print("putable: %s" % contractDetails.putable)
if contractDetails.secIdList is not None:
for secId in contractDetails.secIdList:
print("secIdList: %s" % secId)
else:
print("secIdList: None")
print("subcategory: %s" % contractDetails.subcategory)
print("tradingHours: %s" % contractDetails.tradingHours)
print("timeZoneId: %s" % contractDetails.timeZoneId)
print("underConId: %s" % contractDetails.underConId)
print("evRule: %s" % contractDetails.evRule)
print("evMultiplier: %s" % contractDetails.evMultiplier)
contract = contractDetails.summary
print("\nContract Summary:")
print("exchange: %s" % contract.exchange)
print("symbol: %s" % contract.symbol)
print("secType: %s" % contract.secType)
print("currency: %s" % contract.currency)
print("tradingClass: %s" % contract.tradingClass)
if contract.comboLegs is not None:
for comboLeg in contract.comboLegs:
print("comboLegs: %s - %s" %
(comboLeg.action, comboLeg.exchange))
else:
print("comboLegs: None")
# inst_id = seq_mgr.get_next_sequence("instruments")
print("\nBond Values:")
print("bondType: %s" % contractDetails.bondType)
#.........这里部分代码省略.........
示例10: TradeManager
class TradeManager(object):
def __init__(self):
self.accountNumber = ''
self.optionExpiry = '20121221' # This needs manual updating!
self.maxAskBidRatio = 1.25
self.maxAskLastPriceRatio = 1.02
self.maxOrderQueueLength = 3
# Create a file for TWS logging
self.twslog_fh = open('/home/mchan/git/Artemis/twslog.txt', 'a', 0)
self.twslog_fh.write("Session Started " + str(datetime.datetime.now()) + "\n")
self.callback = ArtemisIBWrapperSilent.ArtemisIBWrapper()
self.tws = EPosixClientSocket(self.callback)
self.orderIdCount = 1 # This will be updated automatically
self.requestIdCount = 1
self.invested = False
self.maxLimitPriceFactor = 1.02 # No limit orders above 2% of current ask price
# Connect the socket
self.socketnum = 30
self.tws.eConnect("", 7496, self.socketnum, poll_interval=1)
# Strategy Generic object, has methods for interpreting consensus out/under performance
self.Strat = strategy.Strategy()
# Queue for orders
self.orderQueue = []
# Setup DB connector
self.db = dbutil.db(h='127.0.0.1', schema='mchan')
# Query Cash Account Balance
self.updateBuyingPowerNextId()
def updateBuyingPowerNextId(self):
self.callback.myNextValidId = None
self.callback.buyingPower = None
self.tws.reqAccountUpdates(1, self.accountNumber)
while (self.callback.buyingPower is None or self.callback.myNextValidId is None):
pass
self.buyingPower = float(self.callback.buyingPower)
self.orderIdCount = int(self.callback.myNextValidId)
print "Buying Power recognized: ", self.buyingPower, " Next valid id recognized: ", self.orderIdCount
self.tws.reqAccountUpdates(0, self.accountNumber)
def calcInvSize(self):
'''
Calculates proper investment size
'''
# We take the total size of the portfolio, cash plus stock, and we divide by four
# The reasoning is that we want to avoid the day pattern trader restriction
# Dividing our portfolio size by four ensures that we have enough capital
# to trade for the four trading opportunities that will happen until we can
# finally sell our positions
# This also allows for diversification
self.updateBuyingPowerNextId()
portfolioList = self.getPortfolio()
secMarketPositions = 0
for myContract, myPosition, myMarketValue in portfolioList:
secMarketPositions += myMarketValue
totalPortfolioSize = secMarketPositions + self.buyingPower
investmentSize = min(self.buyingPower, (totalPortfolioSize/4.0))
print "CALCULATE INVESTMENT SIZE: ", str(investmentSize)
return investmentSize
def twsReconnect(self):
print "Reconnecting TWS"
self.twslog_fh.write("Reconnecting TWS" + str(datetime.datetime.now()) + '\n')
self.tws.eDisconnect()
try:
self.tws.eConnect("", 7496, self.socketnum, poll_interval=1)
except TWSError, e:
print e
print "Attempting to reconnect:"
for i in range(0,5):
time.sleep(5)
print "Try ", i
try:
self.tws.eConnect("", 7496, self.socketnum, poll_interval=1)
break
except TWSError, e:
print e
示例11: __init__
def __init__(self):
self.callback = ArtemisIBWrapper()
self.tws = EPosixClientSocket(self.callback)
self.tws.eConnect("", 7496, 44, poll_interval=1)
示例12: ArtemisIBWrapper
import strategy
import fowscanner
import datetime
import multiprocessing
import time
import sys
from swigibpy import EWrapper, EPosixClientSocket, Contract
sys.path.append('/home/mchan/git/Artemis/SwigIbPy')
from ArtemisIBWrapper import ArtemisIBWrapper
callback = ArtemisIBWrapper()
tws = EPosixClientSocket(callback)
# Connect the socket
socketnum = 10
tws.eConnect("", 7496, socketnum, poll_interval=1)
for i in range(0,4):
socketnum += 1
tws.eDisconnect()
print "Socket number: ", socketnum
tws.eConnect("", 7496, socketnum, poll_interval=1)
time.sleep(3)
示例13: SwigIBClient
class SwigIBClient(EWrapper):
'''Callback object passed to TWS, these functions will be called directly
by TWS.
'''
def __init__(self, port=4001, client_id=12):
super(SwigIBClient, self).__init__()
self.tws = EPosixClientSocket(self)
self.port = port
self.client_id = client_id
self.got_history = Event()
self.got_contract = Event()
self.got_err = Event()
self.order_filled = Event()
self.order_ids = Queue()
def execDetails(self, id, contract, execution):
pass
def managedAccounts(self, openOrderEnd):
pass
### Order
def nextValidId(self, validOrderId):
'''Capture the next order id'''
self.order_ids.put(validOrderId)
def orderStatus(self, id, status, filled, remaining, avgFillPrice, permId,
parentId, lastFilledPrice, clientId, whyHeld):
print(("Order #%s - %s (filled %d, remaining %d, avgFillPrice %f,"
"last fill price %f)") %
(id, status, filled, remaining, avgFillPrice, lastFilledPrice))
if remaining <= 0:
self.order_filled.set()
def openOrder(self, orderID, contract, order, orderState):
print("Order opened for %s" % contract.symbol)
def openOrderEnd(self):
pass
def commissionReport(self, commissionReport):
print 'Commission %s %s P&L: %s' % (commissionReport.currency,
commissionReport.commission,
commissionReport.realizedPNL)
### Historical data
def historicalData(self, reqId, date, open, high,
low, close, volume,
barCount, WAP, hasGaps):
if date[:8] == 'finished':
print("History request complete")
self.got_history.set()
else:
date = datetime.strptime(date, "%Y%m%d").strftime("%d %b %Y")
print(("History %s - Open: %s, High: %s, Low: %s, Close: "
"%s, Volume: %d") % (date, open, high, low, close, volume))
### Contract details
def contractDetailsEnd(self, reqId):
print("Contract details request complete, (request id %i)" % reqId)
def contractDetails(self, reqId, contractDetails):
print("Contract details received (request id %i):" % reqId)
print("callable: %s" % contractDetails.callable)
print("category: %s" % contractDetails.category)
print("contractMonth: %s" % contractDetails.contractMonth)
print("convertible: %s" % contractDetails.convertible)
print("coupon: %s" % contractDetails.coupon)
print("industry: %s" % contractDetails.industry)
print("liquidHours: %s" % contractDetails.liquidHours)
print("longName: %s" % contractDetails.longName)
print("marketName: %s" % contractDetails.marketName)
print("minTick: %s" % contractDetails.minTick)
print("nextOptionPartial: %s" % contractDetails.nextOptionPartial)
print("orderTypes: %s" % contractDetails.orderTypes)
print("priceMagnifier: %s" % contractDetails.priceMagnifier)
print("putable: %s" % contractDetails.putable)
if contractDetails.secIdList is not None:
for secId in contractDetails.secIdList:
print("secIdList: %s" % secId)
else:
print("secIdList: None")
print("subcategory: %s" % contractDetails.subcategory)
print("tradingHours: %s" % contractDetails.tradingHours)
print("timeZoneId: %s" % contractDetails.timeZoneId)
print("underConId: %s" % contractDetails.underConId)
print("evRule: %s" % contractDetails.evRule)
print("evMultiplier: %s" % contractDetails.evMultiplier)
contract = contractDetails.summary
print("\nContract Summary:")
print("exchange: %s" % contract.exchange)
print("symbol: %s" % contract.symbol)
print("secType: %s" % contract.secType)
#.........这里部分代码省略.........
示例14: openOrder
def openOrder(self, orderID, contract, order, orderState):
print("Order opened for %s" % contract.symbol)
prompt = input("WARNING: This example will place an order on your IB "
"account, are you sure? (Type yes to continue): ")
if prompt.lower() != 'yes':
sys.exit()
# Instantiate our callback object
callback = PlaceOrderExample()
# Instantiate a socket object, allowing us to call TWS directly. Pass our
# callback object so TWS can respond.
tws = EPosixClientSocket(callback)
# Connect to tws running on localhost
tws.eConnect("", 7496, 42)
# Simple contract for GOOG
contract = Contract()
contract.symbol = "IBM"
contract.secType = "STK"
contract.exchange = "SMART"
contract.currency = "USD"
if orderId is None:
print('Waiting for valid order id')
sleep(1)
while orderId is None:
示例15: print
if date[:8] == 'finished':
print("History request complete")
self.got_history.set()
else:
date = datetime.strptime(date, "%Y%m%d").strftime("%d %b %Y")
print(("reqId: %d, History %s - Open: %s, High: %s, Low: %s, Close: "
"%s, Volume: %d") % (reqId, date, open, high, low, close, volume))
'''
# Instantiate our callback object
callback = HistoricalDataExample()
# Instantiate a socket object, allowing us to call TWS directly. Pass our
# callback object so TWS can respond.
tws = EPosixClientSocket(callback, reconnect_auto=True)
# Connect to tws running on localhost
if not tws.eConnect("", 7496, 42):
raise RuntimeError('Failed to connect to TWS')
today = datetime.today()
for index, row in contractlist.iterrows():
print 'Index:', index, ', Sym:', row['sym']
#self.reqMktData(index, create_contract(row['sym']), '233', False)
# Request some historical data.
tws.reqHistoricalData(
index, # tickerId,
create_contract(row['sym']), # contract,
today.strftime("%Y%m%d %H:%M:%S %Z"), # endDateTime,