Ejemplo n.º 1
0
def data_feed():
    app = TestApp("0.0.0.0", 4001, 9)
    for com in Configuration().GetData()['CompanyList']:
        ibcontract = IBcontract()
        ibcontract.secType = "STK"
        ibcontract.lastTradeDateOrContractMonth = "201809"
        ibcontract.symbol = com
        ibcontract.exchange = "SMART"
        resolved_ibcontract = app.resolve_ib_contract(ibcontract)
        durationstr = "1 D"
        for bar in barSize:
            historic_data = app.get_IB_historical_data(resolved_ibcontract,
                                                       durationstr, bar)
            signal = 1
            dataset = pd.DataFrame(historic_data)
            dataset['signal'] = signal
            for index, row in dataset.iterrows():
                if dataset['open'][index] > dataset['close'][index]:
                    signal = 1
                else:
                    signal = 0
                print(signal)
                dataset['signal'][index] = signal
                print(com)
            print(bar)
            Feed_IntraDay(com, bar, dataset)
            print(dataset)
Ejemplo n.º 2
0
    def processPositionDataMsg(self, fields):
        sMsgId = next(fields)
        version = decode(int, fields)

        account = decode(str, fields)

        # decode contract fields
        contract = Contract()
        contract.conId = decode(int, fields)
        contract.symbol = decode(str, fields)
        contract.secType = decode(str, fields)
        contract.lastTradeDateOrContractMonth = decode(str, fields)
        contract.strike = decode(float, fields)
        contract.right = decode(str, fields)
        contract.multiplier = decode(str, fields)
        contract.exchange = decode(str, fields)
        contract.currency = decode(str, fields)
        contract.localSymbol = decode(str, fields)
        if version >= 2:
            contract.tradingClass = decode(str, fields)

        if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS:
            position = decode(float, fields)
        else:
            position = decode(int, fields)

        avgCost = 0.
        if version >= 3:
            avgCost = decode(float, fields)

        self.wrapper.position(account, contract, position, avgCost)
Ejemplo n.º 3
0
    def basic_order(self, order_id: int):
        contract_aapl = self.contract_aapl()

        parent = Order()
        parent.orderId = order_id
        parent.action = "buy"
        parent.orderType = "LMT"
        parent.totalQuantity = 1
        parent.lmtPrice = 8
        parent.transmit = False

        option_contract = Contract()
        option_contract.symbol = 'TSLA'
        option_contract.secType = "OPT"
        option_contract.exchange = "SMART"
        option_contract.primaryExchange = "SMART"
        option_contract.currency = "USD"
        option_contract.strike = 310.0
        option_contract.lastTradeDateOrContractMonth = "20190315"
        option_contract.right = "P"

        pp33_order_builder = PP33BracketOrderBuilder(order_id, parent)

        for order_in_bracket in pp33_order_builder.bracket_order_list():
            self.placeOrder(order_in_bracket.orderId, option_contract,
                            order_in_bracket)
Ejemplo n.º 4
0
def generate_ib_contract(symbol: str,
                         exchange: Exchange) -> Optional[Contract]:
    """"""
    try:
        fields = symbol.split(JOIN_SYMBOL)

        ib_contract = Contract()
        ib_contract.exchange = EXCHANGE_VT2IB[exchange]
        ib_contract.secType = fields[-1]
        ib_contract.currency = fields[-2]
        ib_contract.symbol = fields[0]

        if ib_contract.secType in ["FUT", "OPT", "FOP"]:
            ib_contract.lastTradeDateOrContractMonth = fields[1]

        if ib_contract.secType == "FUT":
            if len(fields) == 5:
                ib_contract.multiplier = int(fields[2])

        if ib_contract.secType in ["OPT", "FOP"]:
            ib_contract.right = fields[2]
            ib_contract.strike = float(fields[3])
            ib_contract.multiplier = int(fields[4])
    except IndexError:
        ib_contract = None

    return ib_contract
Ejemplo n.º 5
0
def make_contract(symbol='',
                  conID=0,
                  secType='STK',
                  currency='USD',
                  exchange='',
                  primaryExchange='',
                  multiplier=100,
                  tradingClass='',
                  localSymbol='',
                  right='',
                  lastTradeDateOrContractMonth='',
                  strike=0):
    contract = Contract()
    contract.symbol = symbol
    contract.conId = conID
    contract.secType = secType
    contract.currency = currency
    contract.exchange = exchange
    contract.primaryExchange = primaryExchange
    contract.multiplier = multiplier
    contract.tradingClass = tradingClass
    if tradingClass == '':
        contract.tradingClass = symbol
    contract.localSymbol = localSymbol
    contract.right = right
    contract.lastTradeDateOrContractMonth = lastTradeDateOrContractMonth
    contract.strike = strike
    return contract
Ejemplo n.º 6
0
 def createContract(self,
                    symbol,
                    secType,
                    currency,
                    exchange,
                    primaryExchange=None,
                    right=None,
                    strike=None,
                    expiry=None):
     contract = Contract()
     if type(symbol) is list:
         # Foreign stocks
         print(symbol[0], symbol[1])
         contract.symbol = symbol[0]
         contract.currency = symbol[1]
     else:
         contract.symbol = symbol
         contract.currency = currency
         if primaryExchange:
             contract.primaryExchange = primaryExchange
     contract.secType = secType
     contract.exchange = exchange
     if right:
         contract.right = right
     if strike:
         contract.strike = strike
     if expiry:
         contract.lastTradeDateOrContractMonth = expiry
     return contract
Ejemplo n.º 7
0
 def getdata(self):
     app = TestApp("0.0.0.0", 4001, 10)
     for com in Configuration().GetData()['CompanyList']:
         ibcontract = IBcontract()
         ibcontract.secType = "STK"
         ibcontract.lastTradeDateOrContractMonth = "201809"
         ibcontract.symbol = com
         ibcontract.exchange = "SMART"
         resolved_ibcontract = app.resolve_ib_contract(ibcontract)
         dataset1 = {
             0: ['20190502  13:30:00', '20190502  16:00:00'],
             1: [209.95, 208.65],
             2: [212.65, 210.29],
             3: [208.13, 208.41],
             4: [208.63, 209.17],
             5: [149612, 100915]
         }
         durationstr = "3600 S"
         # historic_data = app.get_IB_historical_data(resolved_ibcontract, durationstr, bar)
         df = pd.DataFrame(dataset1)
         df.rename(columns={
             0: "date",
             1: "open",
             2: "high",
             3: "low",
             4: "close",
             5: "volume"
         },
                   inplace=True)
         for bar in barSize:
             dataset = self.strategy(df)
             print(com)
             print(bar)
             # MongoStore().Feed_IntraDay(com, bar, dataset)
             print(df)
Ejemplo n.º 8
0
    def contractDetails(self, reqId: int, contractDetails: ContractDetails):
        super(IbApp, self).contractDetails(reqId, contractDetails)
        self.Logger.info('contractDetails received %s ' %
                         contractDetails.summary)
        if reqId not in self.requestedContracts:
            self.Logger.warning('Unknown contractDetails reqId: %s' % reqId)
            return
        contract = self.requestedContracts[reqId]
        if contract.symbol == contractDetails.summary.symbol or contract.symbol == contractDetails.marketName:
            validated = Contract()
            validated.symbol = contractDetails.summary.symbol
            validated.secType = contractDetails.summary.secType
            validated.exchange = contractDetails.summary.exchange
            validated.tradingClass = contractDetails.summary.tradingClass
            validated.lastTradeDateOrContractMonth = contractDetails.summary.lastTradeDateOrContractMonth
            validated.localSymbol = contractDetails.summary.localSymbol

            if self.__subRealMD:
                cId = self.nextReqId()
                self.marketDataLookup[cId] = validated.localSymbol
                self.requestedMarketData[cId] = validated
                self.reqMktData(cId, contract, "", True, False, [])

            if self.__subHistMD:
                hId = self.nextReqId()
                self.historicalLookup[hId] = validated.localSymbol
                self.requestedHistoricalData[hId] = validated
                self.reqHistoricalData(hId, validated, '', "2 D", "1 day",
                                       "TRADES", 1, 1, False, list("XYZ"))

        else:
            self.Logger.warning('Unknown contract received %s' %
                                contractDetails.summary)
Ejemplo n.º 9
0
    def create_contract(self,
                        symbol,
                        secType=None,
                        exchange=None,
                        primary_exchange=None,
                        currency=None,
                        lastTradeDate=None):
        """
        Returns List with Contract. If multiple contracts are possible, a list with all contracts is returned
        :param secType:
        :param lastTradeDate:
        :param symbol:
        :param exchange:
        :return:
        """
        ibcontract = IBcontract()
        ibcontract.symbol = symbol
        if secType is not None:
            ibcontract.secType = secType
        if currency is not None:
            ibcontract.currency = currency
        if exchange is not None:
            ibcontract.exchange = exchange
        if primary_exchange is not None:
            ibcontract.primaryExchange = primary_exchange
        if lastTradeDate is not None:
            ibcontract.lastTradeDateOrContractMonth = lastTradeDate
        resolved_contract = self.resolve_ib_contract(ibcontract)

        return resolved_contract
Ejemplo n.º 10
0
    def processPositionMultiMsg(self, fields):
        sMsgId = next(fields)

        version = decode(int, fields)
        reqId = decode(int, fields)
        account = decode(str, fields)

        # decode contract fields
        contract = Contract()
        contract.conId = decode(int, fields)
        contract.symbol = decode(str, fields)
        contract.secType = decode(str, fields)
        contract.lastTradeDateOrContractMonth = decode(str, fields)
        contract.strike = decode(float, fields)
        contract.right = decode(str, fields)
        contract.multiplier = decode(str, fields)
        contract.exchange = decode(str, fields)
        contract.currency = decode(str, fields)
        contract.localSymbol = decode(str, fields)
        contract.tradingClass = decode(str, fields)
        position = decode(float, fields)
        avgCost = decode(float, fields)
        modelCode = decode(str, fields)
 
        self.wrapper.positionMulti(reqId, account, modelCode, contract, position, avgCost)
Ejemplo n.º 11
0
def make_contract(symbol,
                  secType,
                  exchange,
                  primaryExchange,
                  currency,
                  lastTradeDateOrContractMonth=None,
                  strike=None,
                  right=None,
                  multiplier=None,
                  tradingClass=None):
    contract = Contract()
    contract.symbol = symbol
    contract.secType = secType
    contract.exchange = exchange
    contract.primaryExchange = primaryExchange
    contract.currency = currency
    if lastTradeDateOrContractMonth is not None:
        contract.lastTradeDateOrContractMonth = lastTradeDateOrContractMonth
    if strike is not None:
        contract.strike = strike
    if right is not None:
        contract.right = strike
    if multiplier is not None:
        contract.multiplier = multiplier
    if tradingClass is not None:
        contract.tradingClass = tradingClass

    return contract
Ejemplo n.º 12
0
    def processExecutionDataMsg(self, fields):
        sMsgId = next(fields)
        version = decode(int, fields)

        reqId = -1
        if version >= 7:
            reqId = decode(int, fields)

        orderId = decode(int, fields)

        # decode contract fields
        contract = Contract()
        contract.conId = decode(int, fields) # ver 5 field
        contract.symbol = decode(str, fields)
        contract.secType = decode(str, fields)
        contract.lastTradeDateOrContractMonth = decode(str, fields)
        contract.strike = decode(float, fields)
        contract.right = decode(str, fields)
        if version >= 9:
            contract.multiplier = decode(str, fields)
        contract.exchange = decode(str, fields)
        contract.currency = decode(str, fields)
        contract.localSymbol = decode(str, fields)
        if version >= 10:
            contract.tradingClass = decode(str, fields)

        # decode execution fields
        exec = Execution()
        exec.orderId = orderId
        exec.execId = decode(str, fields)
        exec.time = decode(str, fields)
        exec.acctNumber = decode(str, fields)
        exec.exchange = decode(str, fields)
        exec.side = decode(str, fields)

        if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS:
                exec.shares = decode(float, fields)
        else:
                exec.shares = decode(int, fields)

        exec.price = decode(float, fields)
        exec.permId = decode(int, fields) # ver 2 field
        exec.clientId = decode(int, fields)  # ver 3 field
        exec.liquidation = decode(int, fields) # ver 4 field

        if version >= 6:
            exec.cumQty = decode(float, fields)
            exec.avgPrice = decode(float, fields)

        if version >= 8:
            exec.orderRef = decode(str, fields)

        if version >= 9:
            exec.evRule = decode(str, fields)
            exec.evMultiplier = decode(float, fields)
        if self.serverVersion >= MIN_SERVER_VER_MODELS_SUPPORT:
            exec.modelCode = decode(str, fields)

        self.wrapper.execDetails(reqId, contract, exec)
Ejemplo n.º 13
0
 def SimpleFuture():
     contract = Contract()
     contract.symbol = "ES"
     contract.secType = "FUT"
     contract.exchange = "GLOBEX"
     contract.currency = "USD"
     contract.lastTradeDateOrContractMonth = "201612"
     return contract
Ejemplo n.º 14
0
def makeSimpleContract(ct:OneContract):
    contract = Contract()
    contract.symbol=ct.symbol
    contract.secType=ct.sectype
    contract.currency=ct.currency
    contract.exchange=ct.exchange
    contract.lastTradeDateOrContractMonth=ct.expire
    #contract.conId=ct.contractID can't to this contract ID is different
    return contract
Ejemplo n.º 15
0
 def FutureWithMultiplier():
     contract = Contract()
     contract.symbol = "DAX"
     contract.secType = "FUT"
     contract.exchange = "DTB"
     contract.currency = "EUR"
     contract.lastTradeDateOrContractMonth = "201609"
     contract.multiplier = "5"
     return contract
Ejemplo n.º 16
0
 def contract_amzn_opt(self):
     incomplete_contract = Contract()
     incomplete_contract.symbol = 'AMZN'
     incomplete_contract.secType = "OPT"
     incomplete_contract.exchange = "SMART"
     incomplete_contract.currency = "USD"
     incomplete_contract.strike = 1900
     incomplete_contract.lastTradeDateOrContractMonth = "20190719"
     incomplete_contract.right = "C"
     return incomplete_contract
Ejemplo n.º 17
0
 def contract_spx_option(self):
     contract = Contract()
     contract.symbol = 'SPX'
     contract.secType = "OPT"
     contract.exchange = "SMART"
     contract.primaryExchange = "SMART"
     contract.currency = "USD"
     contract.strike = 2800
     contract.lastTradeDateOrContractMonth = "20190329"
     contract.right = "C"
     return contract
Ejemplo n.º 18
0
 def createOptionContract(self, symbol, currency, exchange):
     contract = Contract()
     contract.symbol = symbol
     contract.secType = "OPT"
     contract.exchange = exchange
     contract.currency = currency
     contract.lastTradeDateOrContractMonth = "201901"
     contract.strike = 150
     contract.right = "C"
     contract.multiplier = "100"
     return contract
Ejemplo n.º 19
0
 def OptionAtIse():
     contract = Contract()
     contract.symbol = "BPX"
     contract.secType = "OPT"
     contract.currency = "USD"
     contract.exchange = "ISE"
     contract.lastTradeDateOrContractMonth = "20160916"
     contract.right = "C"
     contract.strike = 65
     contract.multiplier = "100"
     return contract
Ejemplo n.º 20
0
def create_contract(symbol, secType, currency, exchange, expiry):

    contract = IBcontract()
    contract.symbol = symbol
    contract.secType = secType
    contract.currency = currency
    contract.exchange = exchange
    if expiry is not None:
        contract.lastTradeDateOrContractMonth = expiry

    return contract
Ejemplo n.º 21
0
 def OptionAtBOX():
     contract = Contract()
     contract.symbol = "GOOG"
     contract.secType = "OPT"
     contract.exchange = "BOX"
     contract.currency = "USD"
     contract.lastTradeDateOrContractMonth = "20170120"
     contract.strike = 615
     contract.right = "C"
     contract.multiplier = "100"
     return contract
Ejemplo n.º 22
0
 def FuturesOnOptions():
     contract = Contract()
     contract.symbol = "SPX"
     contract.secType = "FOP"
     contract.exchange = "GLOBEX"
     contract.currency = "USD"
     contract.lastTradeDateOrContractMonth = "20180315"
     contract.strike = 1025
     contract.right = "C"
     contract.multiplier = "250"
     return contract
Ejemplo n.º 23
0
def optContract():
    contract = Contract()
    contract.symbol = 'GOOG'
    contract.secType = 'OPT'
    contract.exchange = 'SMART'
    contract.currency = 'USD'
    contract.lastTradeDateOrContractMonth = '20190823'
    contract.strike = 1190
    contract.right = 'C'
    contract.multiplier = '100'
    return contract
Ejemplo n.º 24
0
def futures(symbol="ES",
            sec_type="FUT",
            currency="USD",
            exchange="GLOBEX",
            lastTradeDateOrContractMonth="202103"):
    contract = Contract()
    contract.symbol = symbol
    contract.secType = sec_type
    contract.currency = currency
    contract.exchange = exchange
    contract.lastTradeDateOrContractMonth = lastTradeDateOrContractMonth
    return contract
Ejemplo n.º 25
0
def contract(symbol="ES",
             secType="FUT",
             exchange="GLOBEX",
             lastTradeDateOrContractMonth="202103"):
    contract = Contract()
    contract.symbol = symbol
    contract.secType = secType
    contract.currency = "USD"
    contract.exchange = exchange
    contract.lastTradeDateOrContractMonth = lastTradeDateOrContractMonth
    print('Contract details are retrieved', contract)
    return contract
Ejemplo n.º 26
0
def OptionAtBOX():
    #! [optcontract]
    contract = Contract()
    contract.symbol = "AMZN"
    contract.secType = "OPT"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.lastTradeDateOrContractMonth = "20190125"
    contract.strike = 1570
    contract.right = "C"
    contract.multiplier = "100"
    #! [optcontract]
    return contract
Ejemplo n.º 27
0
def generalStk(symbol="ES",
               sec_type="FUT",
               currency="USD",
               exchange="GLOBEX",
               lastTradeDateOrContractMonth="202103"):
    contract = Contract()
    contract.symbol = symbol
    contract.secType = sec_type
    contract.currency = currency
    contract.exchange = exchange
    contract.lastTradeDateOrContractMonth = lastTradeDateOrContractMonth
    log(f'Contract details extracted {contract}')
    return contract
Ejemplo n.º 28
0
def form_option_contract(symbol, strike, type):
    contract1 = Contract()  # Creates a contract object from the import
    contract1.symbol = symbol  # Sets the ticker symbol
    contract1.secType = "OPT"  # Defines the security type as stock
    contract1.currency = "USD"  # Currency is US dollars
    contract1.exchange = "SMART"
    contract1.strike = strike
    contract1.right = type  # call not put
    contract1.expiry = "20200717"
    contract1.lastTradeDateOrContractMonth = "20200717"
    # contract1.PrimaryExch = "NYSE"

    return contract1  # Returns the contract object
Ejemplo n.º 29
0
    def getRolledOption(self, r):
        option = Contract()
        option.symbol = self.statData.buyWrite["underlyer"]["@tickerSymbol"]
        option.avPrice = r["sellprice"]
        option.secType = "OPT"
        option.exchange = "SMART"
        option.currency = "USD"
        option.lastTradeDateOrContractMonth = r['to']
        option.strike = r['strike']
        option.right = "Call"
        option.multiplier = "100"

        return option
Ejemplo n.º 30
0
    def option(self):
        option = Contract()
        option.symbol = self.statData.buyWrite["underlyer"]["@tickerSymbol"]
        option.avPrice = self.statData.inioptprice
        option.secType = "OPT"
        option.exchange = "SMART"
        option.currency = "USD"
        option.lastTradeDateOrContractMonth = self.statData.expiry
        option.strike = self.statData.strike
        option.right = "Call"
        option.multiplier = "100"

        return option
Ejemplo n.º 31
0
    def _fetchFutureMonth(self):
        contract = Contract()
        
        '''
        contract.secType = "CONTFUT"
        #contract.lastTradeDateOrContractMonth="201812"     # CONTFUT can be used to get details of contract from which we can get month for order
        contract.symbol="SBIN"
        contract.exchange="NSE"
        '''
        
        contract.secType = "FUT"
        contract.lastTradeDateOrContractMonth="201805"
        contract.symbol="SBIN"
        contract.exchange="NSE"

        ## resolve the contract
        self.ib.reqContractDetails(213, contract)