本文整理汇总了Python中swigibpy.EPosixClientSocket.placeOrder方法的典型用法代码示例。如果您正苦于以下问题:Python EPosixClientSocket.placeOrder方法的具体用法?Python EPosixClientSocket.placeOrder怎么用?Python EPosixClientSocket.placeOrder使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类swigibpy.EPosixClientSocket
的用法示例。
在下文中一共展示了EPosixClientSocket.placeOrder方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: print
# 需要导入模块: from swigibpy import EPosixClientSocket [as 别名]
# 或者: from swigibpy.EPosixClientSocket import placeOrder [as 别名]
order.action = 'BUY'
order.lmtPrice = 140
order.orderType = 'LMT'
order.totalQuantity = 10
order.algoStrategy = "AD"
order.tif = 'DAT'
order.algoParams = algoParams
#order.transmit = False
print("Placing order for %d %s's (id: %d)" % (order.totalQuantity,
contract.symbol, orderId))
# Place the order
tws.placeOrder(
orderId, # orderId,
contract, # contract,
order # order
)
print("\n=====================================================================")
print(" Order placed, waiting for TWS responses")
print("=====================================================================\n")
print("******************* Press ENTER to quit when done *******************\n")
input()
print("\nDisconnecting...")
tws.eDisconnect()
示例2: enterPositions
# 需要导入模块: from swigibpy import EPosixClientSocket [as 别名]
# 或者: from swigibpy.EPosixClientSocket import placeOrder [as 别名]
def enterPositions(self, weights, execution_sleep=True):
print "----------------------MAKING TRADES ON IB---------------------------"
# Instantiate our callback object
callback = self.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)
# account updates
tws.reqAccountUpdates(True, self.accountNumber)
sleep(1)
print "available funds: %s" % (self.availableFunds)
print "net liquidation value: %s" % (self.netLiquidationValue)
###DELAY UNTIL MARKET HOURS
if execution_sleep:
day_of_week = datetime.now().isoweekday()
# if weekday, and we scanned after midnight, set execution time to this morning at 10:30 am
time_now = datetime.now()
if (
day_of_week in range(1, 6)
and (time_now.hour >= 0 and time_now.hour < 10)
and (time_now.minute >= 0 and time_now.minute < 30)
):
execution_time = datetime(
year=time_now.year, month=time_now.month, day=time_now.day, hour=10, minute=30
)
# otherwise, set to next trading day, morning at 10:30am
else:
execution_time = datetime.now()
execution_time = execution_time + dt.timedelta(days=1)
while execution_time.isoweekday() > 5:
execution_time = execution_time + dt.timedelta(days=1)
execution_time = datetime(
year=execution_time.year, month=execution_time.month, day=execution_time.day, hour=10, minute=30
)
to_sleep = (execution_time - datetime.now()).total_seconds()
print "----------sleeping until execution time of %s---------------" % (execution_time)
# sleep until that time
sleep(to_sleep)
for stock in weights:
print ("\n=====================================================================")
print (" Trading " + stock)
print ("=====================================================================\n")
stock_price = Trader.get_quote([stock])[0][self.QUOTE_LAST]
print "%s last stock price: %s" % (stock, stock_price)
contract = Contract()
contract.symbol = stock
contract.secType = "STK"
contract.exchange = "SMART"
contract.currency = "USD"
if self.orderId is None:
print ("Waiting for valid order id")
sleep(1)
while self.orderId is None:
print ("Still waiting for valid order id...")
sleep(1)
# Order details
order = Order()
order.action = "BUY"
# order.lmtPrice = 140
order.orderType = "MKT"
dollar_value = self.availableFunds * weights[stock]
order.totalQuantity = int(round(dollar_value / stock_price, 0))
# order.algoStrategy = "AD"
order.tif = "DAY"
# order.algoParams = algoParams
order.transmit = True
print (
"Placing order for %d %s's, dollar value $%s (id: %d)"
% (order.totalQuantity, contract.symbol, dollar_value, self.orderId)
)
# Place the order
tws.placeOrder(self.orderId, contract, order) # orderId, # contract, # order
print ("\n=====================================================================")
print (" Order placed, waiting for TWS responses")
print ("=====================================================================\n")
sleep(3)
#.........这里部分代码省略.........
示例3: IBBroker
# 需要导入模块: from swigibpy import EPosixClientSocket [as 别名]
# 或者: from swigibpy.EPosixClientSocket import placeOrder [as 别名]
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
#.........这里部分代码省略.........
示例4: SwigIBClient
# 需要导入模块: from swigibpy import EPosixClientSocket [as 别名]
# 或者: from swigibpy.EPosixClientSocket import placeOrder [as 别名]
#.........这里部分代码省略.........
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 request_hist_data(self, contract):
today = datetime.today()
print("Requesting historical data for %s" % contract.symbol)
# Request some historical data.
self.tws.reqHistoricalData(
2, # tickerId,
contract, # contract,
today.strftime("%Y%m%d %H:%M:%S %Z"), # endDateTime,
"1 W", # durationStr,
"1 day", # barSizeSetting,
"TRADES", # whatToShow,
0, # useRTH,
1 # formatDate
)
print("\n====================================================================")
print(" History requested, waiting %ds for TWS responses" % WAIT_TIME)
print(" History requested, waiting %ds for TWS responses" % WAIT_TIME)
print("====================================================================\n")
try:
self.got_history.wait(timeout=WAIT_TIME)
except KeyboardInterrupt:
pass
finally:
if not self.got_history.is_set():
print('Failed to get history within %d seconds' % WAIT_TIME)
def subscribe_market_data(self, contract):
pass
def unsubscribe_market_data(self, contract):
pass
def place_order(self, contract):
print('Waiting for valid order id')
order_id = self.order_ids.get(timeout=WAIT_TIME)
if not order_id:
raise RuntimeError('Failed to receive order id after %ds' % WAIT_TIME)
# Order details
algoParams = TagValueList()
algoParams.append(TagValue("componentSize", "3"))
algoParams.append(TagValue("timeBetweenOrders", "60"))
algoParams.append(TagValue("randomizeTime20", "1"))
algoParams.append(TagValue("randomizeSize55", "1"))
algoParams.append(TagValue("giveUp", "1"))
algoParams.append(TagValue("catchUp", "1"))
algoParams.append(TagValue("waitForFill", "1"))
algoParams.append(TagValue("startTime", "20110302-14:30:00 GMT"))
algoParams.append(TagValue("endTime", "20110302-21:00:00 GMT"))
order = Order()
order.action = 'BUY'
order.lmtPrice = 140
order.orderType = 'LMT'
order.totalQuantity = 10
order.algoStrategy = "AD"
order.tif = 'DAT'
order.algoParams = algoParams
# order.transmit = False
print("Placing order for %d %s's (id: %d)" % (order.totalQuantity,
contract.symbol, order_id))
# Place the order
self.tws.placeOrder(
order_id, # orderId,
contract, # contract,
order # order
)
print("\n====================================================================")
print(" Order placed, waiting %ds for TWS responses" % WAIT_TIME)
print("====================================================================\n")
print("Waiting for order to be filled..")
try:
self.order_filled.wait(WAIT_TIME)
except KeyboardInterrupt:
pass
finally:
if not self.order_filled.is_set():
print('Failed to fill order')