Beispiel #1
0
    def newTrade(self, contractSymbol:str, entryPrice:float, stopPrice:float ):
        
        # TEMP
        contractSymbol="EURUSD"
        contract = Contract()
        contract.symbol = "EUR"
        contract.secType = "CASH"
        contract.currency = "GBP"
        contract.exchange = "IDEALPRO"
        contract.tickSize = 0.00005
        contract.lotSize  = 20000
        # TEMP
        
        #if( self.trades[contractSymbol]  )
        
        '''                
        contractDetails = s.getContractDetails( contractSymbol )

        contract = Contract()
        
        contract.exchange = contractDetails.exchange
        contract.secType  = contractDetails.secType
        contract.symbol   = contractSymbol
        contract.lastTradeDateOrContractMonth = contractDetails.expiry
        contract.tickSize = contractDetails.tickSize                # Custom field
        contract.lotSize  = contractDetails.lotSize                 # Custom field
        '''

        diff = abs(entryPrice-stopPrice) 
        qty  = self.capital * s.RiskPerTrade / diff 

        t = trade.Trade( self.ib, contract )
        t.placeNewTrade( qty, entryPrice, stopPrice  )
        
        self.trades[contractSymbol] = t 
Beispiel #2
0
def get_fx_data(symbol,
                currency,
                duration="2 M",
                period="4 hours",
                is_simulated=False):

    config = config_loader.load()

    ip = config.get("ib-gateway", "ip")
    #ip = "127.0.0.1"

    if (is_simulated):
        app = TestApp(ip, 4002, ClientID.HIST_FX.value)
    else:
        app = TestApp(ip, 4001, ClientID.HIST_FX.value)

    ibcontract = IBcontract()
    #ibcontract.lastTradeDateOrContractMonth="201809"
    #ibcontract.secType = "FUT"
    #ibcontract.symbol="GE"
    #ibcontract.exchange="GLOBEX"
    ibcontract.symbol = symbol
    ibcontract.secType = "CASH"
    ibcontract.currency = currency
    ibcontract.exchange = "IDEALPRO"

    resolved_ibcontract = app.resolve_ib_contract(ibcontract)

    historic_data = app.get_IB_historical_data(resolved_ibcontract, duration,
                                               period)
    #print(historic_data)

    out_tup = resample.filter_data("FX", historic_data, period)
    historic_data = out_tup

    try:
        app.disconnect()
    except:
        print("Disconnect with errors (no harm)!")

    return historic_data
Beispiel #3
0
 def get_IB_historical_close(self, historic_close,
                             security_list,
                             endDateTime=datetime.datetime.today(),
                             durationStr="1 Y",
                             barSizeSetting="1 day",
                             whatToShow="Trades",
                             useRTH=0,
                             formatDate=1,
                             KeepUpToDate=False,
                             tickerid=DEFAULT_HISTORIC_DATA_ID
                             ):
     for index, security in security_list.iterrows():
         ibcontract = IBcontract()
         ibcontract.secType = security.secType
         ibcontract.lastTradeDateOrContractMonth = security.lastTradeDateOrContractMonth
         ibcontract.symbol = security.symbol
         ibcontract.exchange = security.exchange
         ibcontract.currency = security.currency
 
         resolved_ibcontract = IBClient.resolve_ib_contract(self,ibcontract)
         historical_data = IBClient.get_IB_historical_data(self,
                                                         resolved_ibcontract,
                                                         endDateTime,
                                                         durationStr,
                                                         barSizeSetting,
                                                         whatToShow,
                                                         useRTH,
                                                         formatDate,
                                                         KeepUpToDate,
                                                         tickerid)
        
         historical_df = pd.DataFrame(historical_data,columns = ["date","open","high","low","close","volume"])
         historical_df.head()
         historical_df = historical_df[["date", "close"]]
         historical_df.rename(columns={'close':security.symbol}, inplace=True)
         
         historical_df["date"] = pd.to_datetime(historical_df['date'])
         historical_df=historical_df.set_index('date')
         #historical_df.sort_index(inplace=True)
         historic_close = historical_df.combine_first(historic_close)
     return historic_close    
Beispiel #4
0
def ib_stock_api(stocks, stock_index):
    # app.connect("127.0.0.1", 4004, clientId=0) # REAL ACCOUNT

    # TEST 1
    app = TestApp()
    # app.connect("127.0.0.1", 7497, clientId=17)
    app.connect("127.0.0.1", 4004, clientId=0)  # REAL ACCOUNT

    # TEST 2
    # app = TestApp1("127.0.0.1", 7497, 17)

    contract = Contract()

    for i in range(len(stocks)):
        contract.symbol = stocks[i]
        # contract.symbol = stock
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"
        contract.primaryExchange = "NASDAQ"

        # resolved_ibcontract = app.resolve_ib_contract(contract)

        # print(f"*************** Start Stream {stocks[i]} ****************")
        # tickerid = app.start_getting_IB_market_data(resolved_ibcontract, i)

        # time.sleep(5)

        # print(f"*************** Get data {stocks[i]}****************")
        # market_data1 = app.get_IB_market_data(tickerid)
        # print(market_data1)

        app.reqMarketDataType(4)
        app.reqMktData(i, contract, "", False, False, [])

    t = threading.Thread(target=lambda app: worker(app), args=([app]))
    t.start()
    app.run()
    reqId = app.reqId
    price = app.price
    print(f'kaka and pipi {reqId} {price}')
Beispiel #5
0
    def query_contracts(self):
        """Gets the contracts from the contract table of the MySQL database"""

        # Queries the MySQL database to get the attributes of the contract table that are necessary to define each
        # contract in the IB API.
        self.cursor.execute(
            '''SELECT id, exchange_id, symbol, security_type, currency FROM contract'''
        )

        #  Appends self.contract_objects with tuples containing the contract ids and corresponding IB Contract objects.
        for contract_info in self.cursor:
            contract = Contract()
            # NASDAQ is called ISLAND in the API so define the contract's exchange based on the exchange_id
            if contract_info[1] == 1:
                contract.exchange = 'ISLAND'
            elif contract_info[1] == 2:
                contract.exchange = 'NYSE'
            contract.symbol = contract_info[2]
            contract.secType = contract_info[3]
            contract.currency = contract_info[4]
            self.contract_objects.append((contract_info[0], contract))
def main():
    app = TestApp()
    app.connect("127.0.0.1", 7497, 0)

    contract = Contract()
    contract.symbol = "TGP"
    contract.secType = "INDUSTRIAL"
    contract.exchange = "SMART"
    contract.currency = "USD"

    Dividend_Pershare=app.reqMktData(1,contract,'258',True,False,['TTMDIVSHR'])
    Asset=app.reqMktData(1,contract,'258',False,False,['AATCA'])
    EBITDA=app.reqMktData(1,contract,'258',False,False,['QEBITDA'])
    NetDebt=app.reqMktData(1,contract,'258',False,False,['AFPRD'])
    ShortDebt=app.reqMktData(1,contract,'258',False,False,['ALSTD'])


    LongDebt = NetDebt - ShortDebt
    

    app.run()
    def start(self):#Esta funcion genera un contrato  y objeto order
        
        contract = Contract()
        contract.symbol = varcSym #"AMZN"
        contract.secType = "STK"
        contract.currency = "USD"
        #In the API side, NASDAQ is always defined as ISLAND in the exchange field
        contract.exchange = varcMer #"ISLAND"

        print("DATOS DE LA ORDEN A EJCUTAR: " )    
        print(contract.symbol)
        print(contract.exchange)    

        order = Order()
        order.action = varoOp #"BUY" #"SELL"
        order.totalQuantity = varoVoSo #100
        order.orderType = "LMT"
        order.lmtPrice = varoMax #347.02
        print(varoVoSo)
   
        self.placeOrder(self.nextOrderId,contract,order)#places or modifies an order. #id,contract, order
Beispiel #8
0
def main():
    app = TestApp()

    # cause API running on same computer as TWS, host is localhost = 127.0.0.1
    app.connect("127.0.0.1", 7497, clientId=4)
    time.sleep(1)

    contract = Contract()
    contract.symbol = "AAPL"
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.primaryExchange = "NASDAQ"

    # app.reqContractDetails(10, contract)
    # app.run()

    app.reqContractDetails(10, contract)
    app.reqMarketDataType(4)
    app.reqMktData(1, contract, "", False, False, [])
    app.run()
Beispiel #9
0
 def _get_option_contract(ticker: str,
                          expiration: str,
                          strike: float,
                          right: str,
                          exchange="SMART",
                          currency="USD",
                          **_):
     """ Helper function for creating a contract object for use in querying
     data for options
     """
     if right not in ["C", "P"]:
         raise ValueError(f"Invalid right: {right}")
     contract = Contract()
     contract.secType = "OPT"
     contract.symbol = ticker
     contract.exchange = exchange
     contract.currency = currency
     contract.lastTradeDateOrContractMonth = expiration
     contract.strike = strike
     contract.right = right
     return contract
Beispiel #10
0
    def buy_stock(self):
        print(self.bidPrice)
        global buyCount

        contract = Contract()
        contract.symbol = "TSLA"
        contract.secType = "STK"
        contract.currency = "USD"
        contract.exchange = "ISLAND"

        order = Order()
        order.action = "BUY"
        order.orderType = "LMT"
        order.totalQuantity = buyCount
        order.lmtPrice = self.bidPrice + 0.01
        #order.orderType = "MTL"
        #order.totalQuantity = 10
        print("place an order", self.oID)
        self.placeOrder(self.oID, contract, order)
        self.playBuyOrderTime = datetime.now()
        self.oID = self.oID + 1
Beispiel #11
0
def main():

    # Create the client and connect to TWS
    print ('Inicio conexion con el servidor')
    client = GrowiiClient('127.0.0.1', 7497, 0)
    print ('Conexion con el servidor completa\n')

    time.sleep(3)

    # Request the current time
    print ('Comprobación tiempo del servidor')
    current_time = client.getCurrentTime()
    print ('El momento actual es {}\n'.format(current_time))

    time.sleep(3)

    #Request data
    con = Contract()
    con.symbol = "EUR"
    con.secType = "CASH"
    con.exchange = "IDEALPRO"
    con.currency = "USD"

    endDateTime = datetime.now().strftime("%Y%m%d, %H:%M:%S")
    durationStr = str(10*60) + " S"
    barSizeSetting = "1 min"
    whatToShow = "MIDPOINT"

    delay = 1

    print('Comprobacion de descarga de datos')
    historical_date, historical_open, historical_high, historical_low, historical_close, historical_volume  = client.getHistoricalData(delay, con, endDateTime, durationStr, barSizeSetting, whatToShow)  
    print('\n')

    time.sleep(3)

    # Disconnect from TWS
    print('Procedo a la desconexión')
    client.disconnect()
    print('Desconexión realizada')
Beispiel #12
0
def close_order(acc):
    # закрыть счёт конкретного аккаунта
    global baseOrder
    app = IBapi()
    app.connect('127.0.0.1', 7497, clientId)
    time.sleep(5)

    with open('positions.txt', 'r') as root:
        positions = [line.split() for line in root.readlines()]

    print(positions)

    used = list()
    for position in positions:
        if position[1] not in used:
            contract = Contract()
            contract.secType = 'STK'
            contract.symbol = position[1]
            contract.currency = 'USD'
            contract.exchange = 'SMART'
            used.append(position[1])

            if float(position[2]) >= 0.0:
                baseOrder.action = 'SELL'
            else:
                baseOrder.action = 'BUY'

            ordId = app.nextOrderId()
            app.FillAdaptiveParams(baseOrder, 'Normal')
            app.placeOrder(ordId, contract, baseOrder)

    thread = threading.Thread(target=app.run)
    thread.start()
    time.sleep(3)

    try:
        thread._stop()
    except Exception as stop_marker:
        print(f'Stop error: {type(stop_marker).__name__}')
        return
    def start(self):
        contract = Contract()
        contract.symbol = "BA"
        contract.secType = "OPT"
        contract.strike = 380
        contract.right = "C"
        contract.Multiplier = "100"
        contract.exchange = "BOX"
        contract.currency = "USD"
        contract.primaryExchange = "BOX"
        contract.lastTradeDateOrContractMonth = "20200214"

        order = Order()
        order.action = "BUY"
        order.totalQuantity = 200
        order.orderType = "MKT"
        order.lmtPrice = 400
        order.right = "C"
        order.strike = 180
        order.expiry = "20200214"

        self.placeOrder(self.nextOrderId, contract, order)
Beispiel #14
0
def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 0)

    #contract = Contract()     #Con este tipo de contrato no funciona
    #contract.symbol = "AAPL"
    #contract.secType = "STK"
    #contract.exchange = "SMART"
    #contract.currency = "USD"
    #contract.primaryExchange = "NASDAQ"

    contract = Contract()
    contract.symbol = "EUR"
    contract.secType = "CASH"
    contract.exchange = "IDEALPRO" #Este contrato no corre si estoy en la sesion de tfm2020le, pero si corre en la sesion "demo TWS"
    contract.currency = "USD"
    
#idRequest,contract,EndDay(Se puede especificar el dia que queremos data)",Duration,Bar(size),typeData(BID,ASK,etc),0(trading hours),1(format data), Bool,Attribute
    app.reqHistoricalData(1,contract,"","1 D","1 min","MIDPOINT",0,1,False,[])
         
    app.run()
    def getContracts(self):

        self.got_contracts = True
        #remove already current tickers
        to_remove = []
        for reqId, info in self.newTickers.items():
            if info['symbol'] in self.allCurrentTickers:
                print(info["symbol"])
                to_remove.append(reqId)

        for reqId in to_remove:
            self.newTickers.pop(reqId)
        if self.newTickers == {}:
            print("No new tickers")
            app.disconnect()
        for reqId, info in self.newTickers.items():
            contract = Contract()
            contract.symbol = info["symbol"]
            contract.currency = "USD"
            contract.secType = "STK"
            contract.exchange = "SMART"
            self.reqContractDetails(reqId, contract)
Beispiel #16
0
def init_req_market_data():
    global app, id_equity_info_mp, total_requests, market_data_id, symbols
    global requested_symbols
    while True:
        time.sleep(sleep_interval)

        for symbol in symbols:
            if symbol not in requested_symbols:
                contract = Contract()
                contract.symbol = symbol
                contract.secType = 'STK'
                contract.exchange = 'SMART'
                if symbol == 'CSCO':
                    contract.exchange = 'NASDAQ'

                contract.currency = 'USD'
                app.reqHistoricalData(market_data_id, contract, '', '2 D',
                                      '1 day', 'TRADES', 1, 1, False, [])
                app.reqMktData(market_data_id, contract, '', False, False, [])
                id_equity_info_mp[market_data_id] = equity_info(symbol)
                market_data_id += 1
                total_requests += 1
Beispiel #17
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 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
Beispiel #18
0
def place_order(symbol, action, last_price, limit_price, position=None):
    global app, order_id, dollars
    print(f'order to be placed symbol {symbol}')

    if last_price < 0 or limit_price < 0:
        print('last or limit price <0')
        return

    if check_order_existed(symbol, action):
        print('order already existed')
        return

    contract = Contract()
    contract.symbol = symbol

    contract.exchange = 'SMART'
    if symbol == 'CSCO':
        contract.exchange = 'NASDAQ'
    contract.secType = 'STK'

    contract.currency = 'USD'
    order = Order()
    order.action = action
    order.tif = "DAY"
    order.orderType = "LMT"
    order.lmtPrice = limit_price
    if position is None:
        order.totalQuantity = int(round(dollars / last_price))
    else:
        order.totalQuantity = abs(position)
    order.account = account
    app.placeOrder(order_id, contract, order)
    order_id += 1
    app.position_end = False
    app.reqPositions()
    app.open_order_end = False
    app.reqOpenOrders()
    time.sleep(2)
Beispiel #19
0
def main():
    # Create the client and Connect to TWS API
    client = TestTradingData('127.0.0.1', 7497, 7)
    time.sleep(3)  #Sleep interval to allow time for connection to server
    client.orderId = None

    # Define a Contract
    # contract = Contract()
    # contract.symbol = 'AAPL'
    # contract.secType = 'STK'
    # contract.exchange = 'SMART'
    # contract.currency = 'USD'
    contract = Contract()
    contract.symbol = 'INFY'
    contract.secType = 'STK'
    contract.exchange = 'SMART'
    contract.currency = 'INR'
    contract.primaryExchange = "NSE"

    # Define 10 Ticks containing midpoint data
    client.reqTickByTickData(1, contract, 'MidPoint', 10, True)

    # Request market data
    client.reqMarketDataType(
        4)  # Switch to live (1) frozen (2) delayed (3) delayed frozen (4).
    client.reqMktData(2, contract, '', False, False, [])

    # Request Real Time Bars of 5 seconds
    client.reqRealTimeBars(3, contract, 5, 'MIDPOINT', False, [])

    # Request Historical Bars
    now = datetime.datetime.now().strftime("%Y%m%d, %H:%M:%S")
    client.reqHistoricalData(4, contract, now, '2 D', '5 mins', 'BID', False,
                             1, False, [])

    # Disconnect from TWS
    time.sleep(10)
    client.disconnect()
def main1():
    global app1
    global var1
    global var2 
    global myList
    print("Se supone que elimine conexion del objeto anterior de la clase TestApp que es global")
    myList.remove(myList[0])
    myList.remove(myList[0])
    
    if len(myList) == 0:
        print("Termine todos los contratos")
        #app.disconnect()
        return
    var1 = myList[0]
    var2 = myList[1]
    
    print(myList)
    print("La lista que se muestra en pantalla ya tiene menos dos elementos")
    # if len(myList) == 0:
    #     print("Termine")
    #     app.disconnect()
    #     return 
    
    print("Se supone que voy a crear un nuevo contrato, por eso vuelvo a llamar a la clase,Inicio nueva conexion")
    app1 = TestApp()
    app1.connect("127.0.0.1", 7497, 0)
    time.sleep(3)
    contract = Contract()
    contract.symbol = var2                #variable 2
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.primaryExchange = var1 

    app1.reqMarketDataType(4)
    app1.reqMktData(0,contract,"",False,False,[])
    app1.run()
    print("Termino el objeto de la clase")# Pasa por aqui luego de que termino todos los contratos, No deberia
Beispiel #21
0
def make_combo_Box(call_H: Contract, put_H: Contract, call_L: Contract, put_L: Contract):

    Pleg_H = ComboLeg()
    Pleg_H.ratio = 1
    Pleg_H.action = 'SELL'
    Pleg_H.exchange = 'SMART'
    Pleg_H.conId = put_H.conId

    Cleg_H = ComboLeg()
    Cleg_H.ratio = 1
    Cleg_H.action = 'BUY'
    Cleg_H.exchange = 'SMART'
    Cleg_H.conId = call_H.conId

    Pleg_L = ComboLeg()
    Pleg_L.ratio = 1
    Pleg_L.action = 'BUY'
    Pleg_L.exchange = 'SMART'
    Pleg_L.conId = put_L.conId

    Cleg_L = ComboLeg()
    Cleg_L.ratio = 1
    Cleg_L.action = 'SELL'
    Cleg_L.exchange = 'SMART'
    Cleg_L.conId = call_L.conId

    contract = Contract()
    contract.symbol = call_H.symbol
    contract.secType = 'BAG'
    contract.currency = 'USD'
    contract.exchange = 'SMART'
    contract.comboLegs = []
    contract.comboLegs.append(Cleg_H)
    contract.comboLegs.append(Pleg_H)
    contract.comboLegs.append(Cleg_L)
    contract.comboLegs.append(Pleg_L)

    return contract
Beispiel #22
0
    def orderStatus(self, orderId: OrderId, status: str, filled: float,
                    remaining: float, avgFillPrice: float, permId: int,
                    parentId: int, lastFillPrice: float, clientId: int,
                    whyHeld: str, mktCapPrice: float):
        print("OrderStatus. Id: ", orderId, ", Status: ", status, ", Filled: ",
              filled)
        #print(time.time()-self.playBuyOrderTime)

        if (filled == 10.0 and self.hasBuy == True):
            self.oID = self.oID + 1

            contract = Contract()
            contract.symbol = "TSLA"
            contract.secType = "STK"
            contract.currency = "USD"
            contract.exchange = "ISLAND"

            order = Order()
            order.action = "SELL"
            order.orderType = "LMT"
            order.totalQuantity = 10

            order.lmtPrice = avgFillPrice + 0.5
Beispiel #23
0
    def InterCmdtyFuturesContract():
        contract = Contract()
        contract.symbol = "CL.BZ"  # symbol is 'local symbol' of intercommodity spread.
        contract.secType = "BAG"
        contract.currency = "USD"
        contract.exchange = "NYMEX"

        leg1 = ComboLeg()
        leg1.conId = 47207310  # CL Dec'16 @NYMEX
        leg1.ratio = 1
        leg1.action = "BUY"
        leg1.exchange = "NYMEX"

        leg2 = ComboLeg()
        leg2.conId = 47195961  # BZ Dec'16 @NYMEX
        leg2.ratio = 1
        leg2.action = "SELL"
        leg2.exchange = "NYMEX"

        contract.comboLegs = []
        contract.comboLegs.append(leg1)
        contract.comboLegs.append(leg2)
        return contract
Beispiel #24
0
    def SmartFutureComboContract():
        contract = Contract()
        contract.symbol = "WTI"  # WTI,COIL spread. Symbol can be defined as first leg symbol ("WTI") or currency ("USD")
        contract.secType = "BAG"
        contract.currency = "USD"
        contract.exchange = "SMART"

        leg1 = ComboLeg()
        leg1.conId = 55928698  # WTI future June 2017
        leg1.ratio = 1
        leg1.action = "BUY"
        leg1.exchange = "IPE"

        leg2 = ComboLeg()
        leg2.conId = 55850663  # COIL future June 2017
        leg2.ratio = 1
        leg2.action = "SELL"
        leg2.exchange = "IPE"

        contract.comboLegs = []
        contract.comboLegs.append(leg1)
        contract.comboLegs.append(leg2)
        return contract
Beispiel #25
0
    def FutureComboContract():
        contract = Contract()
        contract.symbol = "VIX"
        contract.secType = "BAG"
        contract.currency = "USD"
        contract.exchange = "CFE"

        leg1 = ComboLeg()
        leg1.conId = 256038899  # VIX FUT 201708
        leg1.ratio = 1
        leg1.action = "BUY"
        leg1.exchange = "CFE"

        leg2 = ComboLeg()
        leg2.conId = 260564703  # VIX FUT 201709
        leg2.ratio = 1
        leg2.action = "SELL"
        leg2.exchange = "CFE"

        contract.comboLegs = []
        contract.comboLegs.append(leg1)
        contract.comboLegs.append(leg2)
        return contract
Beispiel #26
0
    def StockComboContract():
        contract = Contract()
        contract.symbol = "IBKR,MCD"
        contract.secType = "BAG"
        contract.currency = "USD"
        contract.exchange = "SMART"

        leg1 = ComboLeg()
        leg1.conId = 43645865  # IBKR STK
        leg1.ratio = 1
        leg1.action = "BUY"
        leg1.exchange = "SMART"

        leg2 = ComboLeg()
        leg2.conId = 9408  # MCD STK
        leg2.ratio = 1
        leg2.action = "SELL"
        leg2.exchange = "SMART"

        contract.comboLegs = []
        contract.comboLegs.append(leg1)
        contract.comboLegs.append(leg2)
        return contract
Beispiel #27
0
    def OptionComboContract():
        contract = Contract()
        contract.symbol = "DBK"
        contract.secType = "BAG"
        contract.currency = "EUR"
        contract.exchange = "DTB"

        leg1 = ComboLeg()
        leg1.conId = 197397509  # DBK JUN 15 2018 C
        leg1.ratio = 1
        leg1.action = "BUY"
        leg1.exchange = "DTB"

        leg2 = ComboLeg()
        leg2.conId = 197397584  # DBK JUN 15 2018 P
        leg2.ratio = 1
        leg2.action = "SELL"
        leg2.exchange = "DTB"

        contract.comboLegs = []
        contract.comboLegs.append(leg1)
        contract.comboLegs.append(leg2)
        return contract
Beispiel #28
0
def main():
    global data_collected, column
    data_collected = []
    app = TestApp()
    
    app.connect("127.0.0.1", 7496, 0)
    
    #create a contract object
    contract = Contract()

    contract.symbol = "EUR"
    contract.secType = "CASH"
    contract.exchange = "IDEALPRO"   #if you use smart, the API look through all available exchanges
    contract.currency = "USD"
    
    #http://interactivebrokers.github.io/tws-api/historical_bars.html
    app.reqHistoricalData(1, contract, "20200127 23:59:59", "1 D", "1 min", "MIDPOINT", 1, 1, False, [])
    #3rd parameter is "end day", if empty space, it means current day, duration,bar size, regular trading hour, format of date, keep_up_the_date, always [] reserved for internal use
    
    app.run()
    df = pd.DataFrame(data_collected, columns = column)
    df.to_csv("historical_data")
    print (df)
Beispiel #29
0
	def new_stock(self, symbol, data):

		if symbol in self.stocks.keys():
			return

		if data["last"] > 0.9 * data["open"]:
			return

		if data["ask"] > 0.9 * data["open"]:
			return

		overnight = (data["open"] - data["close"]) / data["close"]
		if abs(overnight) > 0.1:
			return 

		self.stocks[symbol] = data

		contract = Contract()
		contract.symbol = symbol
		contract.currency = "USD"
		contract.secType = "STK"
		contract.exchange = "SMART"
		self.reqContractDetails(0, contract)
Beispiel #30
0
 def request_option_chain(self,
                          ticker: str,
                          exchange: str,
                          expiration: str,
                          currency="USD"):
     """ Request a list of all the options available for a given ticker and expiration.
     :param ticker: stock ticker with available options
     :param exchange: exchange of the options contracts
     :param expiration: expiration of the options contracts, in YYYYMMDD format
     :param currency: currency to report information in
     """
     response = OptionDetailsResponse()
     request_id = self._start_request(response)
     # do not use _get_option_contract shortcut because we are leaving right and strike blank
     contract = Contract()
     contract.secType = "OPT"
     contract.symbol = ticker
     contract.exchange = exchange
     contract.currency = currency
     contract.lastTradeDateOrContractMonth = expiration
     self._app.reqContractDetails(request_id, contract)
     response.finished.wait(timeout=self.timeout)
     return response.table
Beispiel #31
0
    def nextValidId(self, orderId: int):

        print("sss")
        print("setting nextValidOrderId: %d", orderId)
        self.oID = orderId
        # here is where you start using api

        contract = Contract()
        contract.symbol = "TSLA"
        contract.secType = "STK"
        contract.currency = "USD"
        contract.exchange = "ISLAND"

        print("sdfsdf")
        self.reqMarketDataType(1)
        # self.reqMktData(19003, contract, "" ,False, False, [])
        # self.reqTickByTickData(19004, contract, "BidAsk")

        # queryTime = (datetime.datetime.today() - datetime.timedelta(days=180)).strftime("%Y%m%d %H:%M:%S")
        self.reqHistoricalData(4101, contract, "", "4 M", "5 mins", "TRADES",
                               1, 1, True, [])

        print("sss")