コード例 #1
0
    def req_hist_price(self, security, endtime, goback=None, barSize=None):
        """
        Send request to IB server for real time market data
        """
        #print 'req_hist_price', security.symbol+security.currency
        if goback == None:
            if barSize == '1 day':
                goback = '1 Y'
            elif barSize == '1 min':
                goback = '20000 S'
            elif barSize == '10 mins':
                goback = '1 D'
            elif barSize == '1 hour':
                goback = '30 D'
            elif barSize == '4 hours':
                goback = '20 D'

            else:
                print 'req_hist_price cannot handle', barSize
                exit()
        # Submit request to IB
        if endtime.tzname() == None:
            req = datetime.datetime.strftime(
                endtime, "%Y%m%d %H:%M:%S")  #datatime -> string
        else:
            endtime = endtime.astimezone(tz=pytz.utc)
            req = datetime.datetime.strftime(
                endtime, "%Y%m%d %H:%M:%S %Z")  #datatime -> string
        #print req
        if security.secType == 'STK' or security.secType == 'FUT':
            self.reqHistoricalData(self.nextHistDataId,
                                   create_contract(security), req, goback,
                                   barSize, 'TRADES', 1, 1)
        elif security.secType == 'CASH':
            self.reqHistoricalData(self.nextHistDataId,
                                   create_contract(security), req, goback,
                                   barSize, 'BID', 1, 1)
        # Record requst info
        self.returned_hist[self.nextHistDataId] = HistClass(security, barSize)
        self.returned_hist[
            self.nextHistDataId].status = 'submitted'  # Record status

        # Others
        time.sleep(0.1)
        self.log.info(__name__ + ": " + "requesting hist data for " + security.symbol+'.' \
                                  + security.currency+'.'\
                                  + security.secType+'.'\
                                  + barSize)
        self.nextHistDataId += 1
コード例 #2
0
 def order_quantopian(self, security, amount, style=MarketOrder()):       
     print 'place_order'
     if amount>0:  
         action='BUY'
         totalQuantity=amount
     elif amount<0:
         action='SELL'
         totalQuantity=-amount
     else:
         return -1
     security_order=create_order(action, totalQuantity, style)
     if security_order != None:
         cntrct=create_contract(security)
         self.placeOrder(self.my_next_valid_id, cntrct, security_order)
         print 'Request to',security_order.action,security_order.totalQuantity,'shares', cntrct.symbol+cntrct.currency,'id=',self.my_next_valid_id       
         self.context.portfolio.openOrderBook[self.my_next_valid_id] = \
             OrderClass(orderId=self.my_next_valid_id,
                 created=datetime.datetime.now(),
                 stop=style[1],
                 limit=style[2],
                 amount=security_order.totalQuantity,
                 sid=Security(cntrct.symbol+'.'+cntrct.currency),
                 status='PreSubmitted',
                 contract=cntrct,
                 order=security_order,
                 orderstate=None)
         self.my_next_valid_id=self.my_next_valid_id+1
         return self.my_next_valid_id-1
     else:
         print 'order_quantopian wrong serurity instance',security
         return -1
コード例 #3
0
 def order_quantopian(self, security, amount, style=MarketOrder()):
     print 'place_order'
     if amount > 0:
         action = 'BUY'
         totalQuantity = amount
     elif amount < 0:
         action = 'SELL'
         totalQuantity = -amount
     else:
         return -1
     security_order = create_order(action, totalQuantity, style)
     if security_order != None:
         cntrct = create_contract(security)
         self.placeOrder(self.my_next_valid_id, cntrct, security_order)
         print 'Request to', security_order.action, security_order.totalQuantity, 'shares', cntrct.symbol + cntrct.currency, 'id=', self.my_next_valid_id
         self.context.portfolio.openOrderBook[self.my_next_valid_id] = \
             OrderClass(orderId=self.my_next_valid_id,
                 created=datetime.datetime.now(),
                 stop=style[1],
                 limit=style[2],
                 amount=security_order.totalQuantity,
                 sid=Security(cntrct.symbol+'.'+cntrct.currency),
                 status='PreSubmitted',
                 contract=cntrct,
                 order=security_order,
                 orderstate=None)
         self.my_next_valid_id = self.my_next_valid_id + 1
         return self.my_next_valid_id - 1
     else:
         print 'order_quantopian wrong serurity instance', security
         return -1
コード例 #4
0
    def req_hist_price(self, security, endtime, goback=None, barSize=None): 
        """
        Send request to IB server for real time market data
        """           
        #print 'req_hist_price', security.symbol+security.currency
        if goback==None:
            if barSize=='1 day':
                goback='1 Y'
            elif barSize=='1 min':
                goback='20000 S'
            elif barSize=='10 mins':
                goback='1 D'
            elif barSize=='1 hour':
                goback='30 D'
            elif barSize=='4 hours':
                goback='20 D'

            else:
                print 'req_hist_price cannot handle',barSize
                exit()
        # Submit request to IB
        if endtime.tzname()==None:
            req = datetime.datetime.strftime(endtime,"%Y%m%d %H:%M:%S") #datatime -> string
        else:
            endtime=endtime.astimezone(tz=pytz.utc)
            req = datetime.datetime.strftime(endtime,"%Y%m%d %H:%M:%S %Z") #datatime -> string
        #print req
        if security.secType=='STK' or security.secType=='FUT':
            self.reqHistoricalData(self.nextHistDataId, create_contract(security),
                                   req, goback, barSize, 'TRADES', 1, 1)
        elif security.secType=='CASH':
            self.reqHistoricalData(self.nextHistDataId, create_contract(security),
                                   req, goback, barSize, 'BID', 1, 1)
        # Record requst info
        self.returned_hist[self.nextHistDataId] = HistClass(security, barSize)
        self.returned_hist[self.nextHistDataId].status='submitted'# Record status

        # Others
        time.sleep(0.1)
        self.log.info(__name__ + ": " + "requesting hist data for " + security.symbol+'.' \
                                  + security.currency+'.'\
                                  + security.secType+'.'\
                                  + barSize)                    
        self.nextHistDataId += 1
コード例 #5
0
 def req_real_time_price(self):
     """
     Send request to IB server for real time market data
     """
     for security in self.data: 
         self.reqMktData(self.nextReqMktDataId, create_contract(security),
         '233',False) # Send market data requet to IB server
         time.sleep(0.1)
         security.req_real_time_price_id = self.nextReqMktDataId
         self.nextReqMktDataId += 1  # Prepare for next request
コード例 #6
0
 def req_real_time_price(self):
     """
     Send request to IB server for real time market data
     """
     for security in self.data:
         self.reqMktData(self.nextReqMktDataId, create_contract(security),
                         '233',
                         False)  # Send market data requet to IB server
         time.sleep(0.1)
         security.req_real_time_price_id = self.nextReqMktDataId
         self.nextReqMktDataId += 1  # Prepare for next request
コード例 #7
0
"""
Created on Sat Jan 03 08:35:42 2015

@author: Huapu (Peter) Pan
"""
import datetime
from IBridgePy.IBridgePyBasicLib.IBAccountManager import IBAccountManager, MSG_TABLE
import IBridgePy.IBridgePyBasicLib.quantopian as qtopian
import BasicPyLib.simpleLogger as simpleLogger

if __name__ == "__main__":
    port = 7496
    clientID = 1
    c = IBAccountManager()  # create a client object
    c.setup(logLevel=simpleLogger.NOTSET)
    # additional setup. It's optional.
    c.connect(
        "", port,
        clientID)  # you need to connect to the server before you do anything.
    c.reqCurrentTime()
    symbs = ['IBM', 'BMA']
    for ii, s in enumerate(symbs):
        c.reqMktData(ii, qtopian.create_contract(qtopian.symbol(s)), '233',
                     False)
    while (True):
        if (c.stime is not None and c.stime_previous is None):
            c.stime_previous = c.stime
            print "current system time: ", c.stime, datetime.datetime.now(
                tz=c.USeasternTimeZone)
        c.processMessages(
        )  # put this function into infinit loop. A better way is to put it into a new thread.
コード例 #8
0
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 03 08:35:42 2015

@author: Huapu (Peter) Pan
"""
import datetime
from IBridgePy.IBridgePyBasicLib.IBAccountManager import IBAccountManager, MSG_TABLE
import IBridgePy.IBridgePyBasicLib.quantopian as qtopian
import BasicPyLib.simpleLogger as simpleLogger

if __name__ == "__main__":
    port = 7496; clientID = 1
    c = IBAccountManager()  # create a client object
    c.setup(logLevel = simpleLogger.NOTSET);      # additional setup. It's optional.
    c.connect("", port, clientID) # you need to connect to the server before you do anything.
    c.reqCurrentTime()
    symbs = ['IBM', 'BMA']
    for ii, s in enumerate(symbs):
        c.reqMktData(ii, qtopian.create_contract(qtopian.symbol(s)), '233',False)
    while (True):
        if (c.stime is not None and c.stime_previous is None):
            c.stime_previous = c.stime
            print "current system time: ", c.stime, datetime.datetime.now(tz = c.USeasternTimeZone)
        c.processMessages()       # put this function into infinit loop. A better way is to put it into a new thread.     
コード例 #9
0
 def order_with_SL_TP(self, sec, amount, orderId = None, 
                      stopLossPrice = None, takeProfitPrice = None):
     '''
     This function make orders. When amount > 0 it is BUY and when amount < 0 it is SELL
     '''
     # fill order info
     if amount > 0:
         orderAction = 'BUY'
         orderReverseAction = 'SELL'
         amount = int(amount)
     elif amount < 0:
         orderAction = 'SELL'
         orderReverseAction = 'BUY'
         amount = int(np.abs(amount))
     else:
         self.log.warning("order amount is 0!")
         return
         
     if (stopLossPrice is None):
         self.log.warning("can not place an order without stop loss!")
         return
     # fill contract info
     contract = create_contract(sec)
     ### place order
     # market order
     marketOrder = IBCpp.Order()
     marketOrder.action = orderAction
     marketOrder.totalQuantity = amount
     marketOrder.orderType = 'MKT'
     marketOrder.transmit = False
     marketOrder.account = self.accountCode
     parentOrderId = self.nextOrderId
     self.placeOrder(parentOrderId, contract, marketOrder)
     if not (parentOrderId in self.context.portfolio.openOrderBook):
         self.context.portfolio.openOrderBook[parentOrderId] = \
             OrderClass(orderId = parentOrderId, parentOrderId = None,
                 created=datetime.datetime.now(),
                 stop = None,
                 limit = None,
                 amount = marketOrder.totalQuantity,
                 sid = Security(contract.symbol+'.'+contract.currency),
                 status = 'PreSubmitted',
                 contract = contract,
                 order = marketOrder,
                 orderstate = None)
     self.nextOrderId += 1
     # stop sell order: stop loss
     childOrder = IBCpp.Order()
     childOrder.action = orderReverseAction
     childOrder.totalQuantity = amount
     childOrder.orderType = 'STP'
     childOrder.auxPrice = self.roundToMinTick(stopLossPrice)
     childOrder.parentId = parentOrderId
     if (takeProfitPrice is None):
         childOrder.transmit = True # if not limit order transmit STP order
     else:
         childOrder.transmit = False
     childOrder.account = self.accountCode
     childOrderId = self.nextOrderId
     childOrder.ocaGroup = str(parentOrderId)
     self.placeOrder(childOrderId, contract, childOrder)
     if not (childOrderId in self.context.portfolio.openOrderBook):
         self.context.portfolio.openOrderBook[childOrderId] = \
             OrderClass(orderId = childOrderId, parentOrderId = parentOrderId,
                 created=datetime.datetime.now(),
                 stop = stopLossPrice,
                 limit = None,
                 amount = childOrder.totalQuantity,
                 sid = Security(contract.symbol+'.'+contract.currency),
                 status = 'PreSubmitted',
                 contract = contract,
                 order = childOrder,
                 orderstate = None)
     self.nextOrderId += 1
     # limit sell order: take profit
     # Limit order: an order to buy or sell at a specified price or better.
     if (takeProfitPrice is not None):
         childOrder = IBCpp.Order()
         childOrder.action = orderReverseAction
         childOrder.totalQuantity = amount
         childOrder.orderType = 'LMT'
         childOrder.lmtPrice = self.roundToMinTick(takeProfitPrice)
         childOrder.parentId = parentOrderId
         childOrder.transmit = True
         childOrder.account = self.accountCode
         childOrderId = self.nextOrderId
         childOrder.ocaGroup = str(parentOrderId)
         self.placeOrder(childOrderId, contract, childOrder)
         if not (childOrderId in self.context.portfolio.openOrderBook):
             self.context.portfolio.openOrderBook[childOrder] = \
                 OrderClass(orderId = childOrderId, parentOrderId = parentOrderId,
                     created=datetime.datetime.now(),
                     stop = None,
                     limit = takeProfitPrice,
                     amount = childOrder.totalQuantity,
                     sid = Security(contract.symbol+'.'+contract.currency),
                     status = 'PreSubmitted',
                     contract = contract,
                     order = childOrder,
                     orderstate = None)   
         self.nextOrderId += 1
     # print order placement time    
     self.log.info(__name__ + ": " + 'order placed at: ' + str(datetime.datetime.now(self.USeasternTimeZone)))
     self.log.info(sec.symbol + ": " + orderAction + " " + str(amount))
 
     return self.nextOrderId
コード例 #10
0
    def order_with_SL_TP(self,
                         sec,
                         amount,
                         orderId=None,
                         stopLossPrice=None,
                         takeProfitPrice=None):
        '''
        This function make orders. When amount > 0 it is BUY and when amount < 0 it is SELL
        '''
        # fill order info
        if amount > 0:
            orderAction = 'BUY'
            orderReverseAction = 'SELL'
            amount = int(amount)
        elif amount < 0:
            orderAction = 'SELL'
            orderReverseAction = 'BUY'
            amount = int(np.abs(amount))
        else:
            self.log.warning("order amount is 0!")
            return

        if (stopLossPrice is None):
            self.log.warning("can not place an order without stop loss!")
            return
        # fill contract info
        contract = create_contract(sec)
        ### place order
        # market order
        marketOrder = IBCpp.Order()
        marketOrder.action = orderAction
        marketOrder.totalQuantity = amount
        marketOrder.orderType = 'MKT'
        marketOrder.transmit = False
        marketOrder.account = self.accountCode
        parentOrderId = self.nextOrderId
        self.placeOrder(parentOrderId, contract, marketOrder)
        if not (parentOrderId in self.context.portfolio.openOrderBook):
            self.context.portfolio.openOrderBook[parentOrderId] = \
                OrderClass(orderId = parentOrderId, parentOrderId = None,
                    created=datetime.datetime.now(),
                    stop = None,
                    limit = None,
                    amount = marketOrder.totalQuantity,
                    sid = Security(contract.symbol+'.'+contract.currency),
                    status = 'PreSubmitted',
                    contract = contract,
                    order = marketOrder,
                    orderstate = None)
        self.nextOrderId += 1
        # stop sell order: stop loss
        childOrder = IBCpp.Order()
        childOrder.action = orderReverseAction
        childOrder.totalQuantity = amount
        childOrder.orderType = 'STP'
        childOrder.auxPrice = self.roundToMinTick(stopLossPrice)
        childOrder.parentId = parentOrderId
        if (takeProfitPrice is None):
            childOrder.transmit = True  # if not limit order transmit STP order
        else:
            childOrder.transmit = False
        childOrder.account = self.accountCode
        childOrderId = self.nextOrderId
        childOrder.ocaGroup = str(parentOrderId)
        self.placeOrder(childOrderId, contract, childOrder)
        if not (childOrderId in self.context.portfolio.openOrderBook):
            self.context.portfolio.openOrderBook[childOrderId] = \
                OrderClass(orderId = childOrderId, parentOrderId = parentOrderId,
                    created=datetime.datetime.now(),
                    stop = stopLossPrice,
                    limit = None,
                    amount = childOrder.totalQuantity,
                    sid = Security(contract.symbol+'.'+contract.currency),
                    status = 'PreSubmitted',
                    contract = contract,
                    order = childOrder,
                    orderstate = None)
        self.nextOrderId += 1
        # limit sell order: take profit
        # Limit order: an order to buy or sell at a specified price or better.
        if (takeProfitPrice is not None):
            childOrder = IBCpp.Order()
            childOrder.action = orderReverseAction
            childOrder.totalQuantity = amount
            childOrder.orderType = 'LMT'
            childOrder.lmtPrice = self.roundToMinTick(takeProfitPrice)
            childOrder.parentId = parentOrderId
            childOrder.transmit = True
            childOrder.account = self.accountCode
            childOrderId = self.nextOrderId
            childOrder.ocaGroup = str(parentOrderId)
            self.placeOrder(childOrderId, contract, childOrder)
            if not (childOrderId in self.context.portfolio.openOrderBook):
                self.context.portfolio.openOrderBook[childOrder] = \
                    OrderClass(orderId = childOrderId, parentOrderId = parentOrderId,
                        created=datetime.datetime.now(),
                        stop = None,
                        limit = takeProfitPrice,
                        amount = childOrder.totalQuantity,
                        sid = Security(contract.symbol+'.'+contract.currency),
                        status = 'PreSubmitted',
                        contract = contract,
                        order = childOrder,
                        orderstate = None)
            self.nextOrderId += 1
        # print order placement time
        self.log.info(__name__ + ": " + 'order placed at: ' +
                      str(datetime.datetime.now(self.USeasternTimeZone)))
        self.log.info(sec.symbol + ": " + orderAction + " " + str(amount))

        return self.nextOrderId