Example #1
0
def main():
    app = DemoApp()
    
    app.connect("127.0.0.1", 4001, 0)  # 7496
    print("serverVersion:%s connectionTime:%s" % (app.serverVersion(), app.twsConnectionTime()))
    # id = app.reqIds(0)
    
    contract1 = Contract()
    contract1.symbol = "MER PRK"
    contract1.secType = "STK"
    contract1.exchange = "SMART"
    contract1.currency = "USD"
    
    contract2 = Contract()
    contract2.symbol = "FRC PRG"
    contract2.secType = "STK"
    contract2.exchange = "SMART"
    contract2.currency = "USD"
    
    app.reqHistoricalData(1, contract1, endDateTime="", durationStr="10 Y", barSizeSetting="1 day", whatToShow="TRADES",
                          useRTH=1, formatDate=1, keepUpToDate=False, chartOptions=[])
    # app.reqHistoricalData(2, contract2, "", "5 W", "1 day", "TRADES", 0, 1, False, [])
    # app.reqContractDetails(1, contract1)
    # app.reqContractDetails(2, contract2)
    
    app.run()
Example #2
0
 def __init__(self):
     #Connect to IB on init
     self.ib = IBApi()
     self.ib.connect("127.0.0.1", 7496, 1)
     ib_thread = threading.Thread(target=self.run_loop, daemon=True)
     ib_thread.start()
     time.sleep(1)
     #Get symbol info
     symbol = input("Enter the symbol you want to trade : ")
     #Create our IB Contract Object
     contract = Contract()
     contract.symbol = symbol.upper()
     contract.secType = "STK"
     contract.exchange = "SMART"
     contract.currency = "USD"
     # Request Market Data
     self.ib.reqRealTimeBars(0, contract, 5, "TRADES", 1, [])
     # TODO Submit ORDER
     # Create Order Object
     order = Order()
     order.orderType = "MKT"  # or LMT ETC....
     order.action = "BUY"  # or SELL ETC...
     quantity = 1
     order.totalQuantity = quantity
     # Create Contract Object
     contract = Contract()
     contract.symbol = symbol
     contract.secType = "STK"  # or FUT ETC....
     contract.exchange = "SMART"
     contract.primaryExchange = "ISLAND"
     contract.currency = "USD"
     # Place the order
     self.ib.placeOrder(2, contract, order)
 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
Example #4
0
    def __init__(self):
        self.ib = IBapi()
        self.ib.connect("127.0.0.1", 7497, 1)
        ib_thread = threading.Thread(target=self.run_loop, daemon=True)
        ib_thread.start()
        time.sleep(1)
        symbol = input("Enter the symbol you want to trade: ")
        contract = Contract()
        contract.symbol = symbol.upper()
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"

        self.ib.reqRealTimeBars(0, contract, 5, "TRADES", 1, [])

        order = Order()
        order.orderType = "MKT"
        order.action = "BUY"
        quantity = 1
        order.totalQuantity = quantity

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

        self.ib.placeOrder(1, contract, order)
Example #5
0
def main():
    SetupLogger()
    logging.info("now is %s", datetime.datetime.now())
    openPosition = getOpenPosition()
    print(openPosition)
    app = TestApp(ib_api_include.ip, ib_api_include.port,
                  ib_api_include.clientId)
    time.sleep(ib_api_include.sleeptime_trading)
    summary = DataFrame(portfolio,
                        columns=[
                            'symbol', 'secType', 'exchange', 'position',
                            'marketPrice', 'marketValue', 'averageCost',
                            'unrealizedPNL', 'realizedPNL', 'accountName'
                        ])
    reqId = 1000
    #watchlist_stock_treshold = pd.read_excel('my_ib_threshold.xlsx', sheet_name = 'watchlist_stock_treshold')
    #watchlist_stock_treshold = DataFrame(watchlist_stock_treshold)
    for i in range(0, len(openPosition)):
        record = openPosition.iloc[i]
        ibcontract = IBcontract()
        ibcontract.secType = record.AssetClass
        ibcontract.symbol = record.UnderlyingSymbol
        ibcontract.exchange = "SMART"
        ibcontract.currency = record.CurrencyPrimary
        ibcontract.lastTradeDateOrContractMonth = record.Expiry
        ibcontract.strike = record.Strike
        ibcontract.multiplier = record.Multiplier
        ibcontract.right = record["Put/Call"]
        app.reqMktData(reqId, ibcontract)

        ibcontract = IBcontract()
        ibcontract.symbol = "MU"
        ibcontract.exchange = "SMART"
        ibcontract.secType = "STK"
        app.reqMktNews(reqId, ibcontract)
        time.sleep(30)
        print(
            DataFrame(marketdataPrice,
                      columns=[
                          "reqId", "tickType", "tickPrice",
                          "CanAutoExecuteOrNot"
                      ]))
        print(
            DataFrame(marketdataSize,
                      columns=["reqId", "tickType", "tickSize"]))
        reqId += 1

    app.disconnect()
Example #6
0
def getCcyPairContract():
    contract = Contract()
    contract.symbol = 'EUR'
    contract.secType = 'CASH'
    contract.exchange = 'IDEALPRO'
    contract.currency = 'USD'
    return contract
Example #7
0
File: df.py Project: ajmal017/DF
def place_order(symbol, action, last_price, limit_price):
    global app, order_id, dollars
    if not app.open_order_end:
        return

    if check_order_existed(symbol, action):
        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 = "GTC"
    order.orderType = "LMT"
    order.totalQuantity = int(round(dollars / last_price))
    order.lmtPrice = limit_price
    app.placeOrder(order_id, contract, order)
    order_id += 1
    time.sleep(1)
Example #8
0
File: df.py Project: ajmal017/DF
def request_market_data():
    global id_equity_info_mp, total_requests, id, symbols
    while True:
        time.sleep(sleep_interval)

        requested_symbols = [
            value.symbol for value in id_equity_info_mp.values()
        ]
        symbols_valid_last = [
            value.symbol for value in id_equity_info_mp.values()
            if value.last > 0
        ]

        if id <= len(symbols):

            symbol = symbols[id - 1]
            if symbol not in requested_symbols:  # and len(id_equity_info_mp) <= 80:
                contract = Contract()
                contract.symbol = symbol
                contract.secType = 'STK'
                contract.exchange = 'SMART'
                if symbol == 'CSCO':
                    contract.exchange = 'NASDAQ'

                contract.currency = 'USD'
                app.reqHistoricalData(id, contract, '', '2 D', '1 day',
                                      'TRADES', 1, 1, False, [])

                app.reqMktData(id, contract, '', False, False, [])
                total_requests += 1
                id_equity_info_mp[id] = equity_info(symbol)
                id += 1
    def start(self):#Esta funcion genera un contrato  y objeto order
        
        # # contract = Contract()
        # # contract.symbol = varcSym #"AMZN"
        # # contract.secType = "STK"
        # # contract.exchange = "SMART" # Tengo inconveniente con esta
        # # contract.currency = "USD"
        # # contract.primaryExchange = varcMer #"NASDAQ"##Con el NASDAQ tipo string no funciona como debe

        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("Mercado donde se ejecuta la orden: " + contract.exchange)    

        order = Order()
        order.action = varoOp #"BUY" #"SELL"
        order.totalQuantity = varoVo #100
        order.orderType = "LMT"
        order.lmtPrice = varoMax #347.02
   
        self.placeOrder(self.nextOrderId,contract,order)#places or modifies an order. #id,contract, order
Example #10
0
 def forex(ticker):
     contract = Contract()
     contract.symbol = ticker["symbol"]
     contract.secType = ticker["secType"]
     contract.currency = ticker["currency"]
     contract.exchange = ticker["exchange"]
     return contract
def buildContract(symbol, currency, exchange, sec_type):
    contract = Contract()
    contract.symbol = symbol
    contract.currency = currency
    contract.exchange = exchange
    contract.secType = sec_type
    return contract
Example #12
0
 def start(self):
     
     contract = Contract()
     contract.symbol = "EUR" 
     contract.secType = "CASH" 
     contract.currency = "USD"
     contract.exchange = "IDEALPRO"         
Example #13
0
def createStk(symbol, sec_type="STK", currency="INR", exchange="NSE"):
    contract = Contract()
    contract.symbol = symbol
    contract.secType = sec_type
    contract.currency = currency
    contract.exchange = exchange
    return contract
Example #14
0
def main():
    global app
    global var1
    global var2
    app = TestApp()
    app.connect("127.0.0.1", 7497, 0)
    print("serverVersion:%s connectionTime:%s" %
          (app.serverVersion(), app.twsConnectionTime()))
    # var1 = 'NASDAQ' #Con estas variables pude generar los contratos
    # var2 = 'AAPL'   #Faltaria ingresar que los capture desde la lectura y regese al contrato

    time.sleep(2)

    contract = Contract()
    contract.symbol = var2  #variable 2
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.primaryExchange = var1  #variable 1

    #Esto son metodos de la clase EClient
    app.reqMarketDataType(4)  # Este 4 es para delayed-frozen data

    #(tickrId, contract, genericTickList(GenericTickTypes), snapshot, regulatorySnaphsot,mkdDataOptions)
    app.reqMktData(0, contract, "", False, False, [])
    app.run()
Example #15
0
def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 0)
    time.sleep(2)

    #Contrato Editado --->Como aparece en el Tutorial Video
    # contract = Contract()
    # contract.symbol = "AAPL"
    # contract.secType = "STK"
    # contract.exchange = "SMART"
    # contract.currency = "USD"
    # contract.primaryExchange = "NASDAQ"

    #Contrato Original ##Si uso este tipo de contratos no funciona ##Error:  0    200   No security definition has been found for the request
    # contract = Contract()
    # contract.symbol = "AAPL"
    # contract.secType = "STK"
    # contract.currency = "USD"
    # contract.primaryExchange = "NASDAQ"##Da error 200 por este atributo

    contract = Contract()
    contract.symbol = "AMZN"
    contract.secType = "STK"
    contract.currency = "USD"
    #In the API side, NASDAQ is always defined as ISLAND in the exchange field
    contract.exchange = "ISLAND"

    #(reqId, contract)
    app.reqContractDetails(
        0, contract
    )  #Esto es una funcion de EClient function, es una clase de EClient

    app.run()
    def subscribe_to_market_data(self,
                                 ib_symbol,
                                 exchange='SMART',
                                 primaryExchange='ISLAND',
                                 secType='STK',
                                 currency='USD'):
        if ib_symbol in self.symbol_to_ticker_id:
            # Already subscribed to market data
            return

        contract = Contract()
        contract.symbol = ib_symbol
        contract.exchange = exchange
        contract.primaryExchange = primaryExchange
        contract.secType = secType
        contract.currency = currency
        ticker_id = self.next_ticker_id

        self.symbol_to_ticker_id[ib_symbol] = ticker_id
        self.ticker_id_to_symbol[ticker_id] = ib_symbol

        # INDEX tickers cannot be requested with market data. The data can,
        # however, be requested with realtimeBars. This change will make
        # sure we can request data from INDEX tickers like SPX, VIX, etc.
        if contract.secType == 'IND':
            self.reqRealTimeBars(ticker_id, contract, 60, 'TRADES', True, [])
        else:
            self.reqMktData(ticker_id, contract, "", True, False, [])
            sleep(11)
Example #17
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 
Example #18
0
def main():
    app = TestApp()

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

    contract = Contract()
    #contract.symbol = "ABBV"
    #contract.symbol = "JNJ"
    contract.symbol = "SAN1"
    #contract.symbol = "KHC"
    contract.secType = "STK"
    contract.exchange = "SMART"
    #contract.currency = "USD"
    contract.currency = "EUR"
    contract.primaryExchange = "BM"

    time.sleep(3)
    #Esto son metodos de la clase EClient
    app.reqMarketDataType(4)  # Este 4 es para delayed-frozen data

    #(tickrId, contract, genericTickList(GenericTickTypes), snapshot, regulatorySnaphsot,mkdDataOptions)
    app.reqMktData(0, contract, "", False, False, [])
    app.run()
    print("Elimino Conexion")
    app.disconnect()  #Como que no funciona
Example #19
0
def FX_order(symbol):
    contract = Contract()
    contract.symbol = symbol[:3]
    contract.secType = 'CASH'
    contract.exchange = 'IDEALPRO'
    contract.currency = symbol[3:]
    return contract
Example #20
0
 def MutualFund():
     contract = Contract()
     contract.symbol = "VINIX"
     contract.secType = "FUND"
     contract.exchange = "FUNDSERV"
     contract.currency = "USD"
     return contract
Example #21
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
Example #22
0
 def CSFBContract():
     contract = Contract()
     contract.symbol = "IBKR"
     contract.secType = "STK"
     contract.exchange = "CSFBALGO"
     contract.currency = "USD"
     return contract
Example #23
0
 def EuropeanStock():
     contract = Contract()
     contract.symbol = "SIE"
     contract.secType = "STK"
     contract.currency = "EUR"
     contract.exchange = "SMART"
     return contract
Example #24
0
 def CFD():
     contract = Contract()
     contract.symbol = "IBDE30"
     contract.secType = "CFD"
     contract.currency = "EUR"
     contract.exchange = "SMART"
     return contract
Example #25
0
 def JefferiesContract():
     contract = Contract()
     contract.symbol = "AAPL"
     contract.secType = "STK"
     contract.exchange = "JEFFALGO"
     contract.currency = "USD"
     return contract
Example #26
0
 def OptionForQuery():
     contract = Contract()
     contract.symbol = "FISV"
     contract.secType = "OPT"
     contract.exchange = "SMART"
     contract.currency = "USD"
     return contract
Example #27
0
 def Index():
     contract = Contract()
     contract.symbol = "DAX"
     contract.secType = "IND"
     contract.currency = "EUR"
     contract.exchange = "DTB"
     return contract
Example #28
0
 def EurGbpFx():
     contract = Contract()
     contract.symbol = "EUR"
     contract.secType = "CASH"
     contract.currency = "GBP"
     contract.exchange = "IDEALPRO"
     return contract
Example #29
0
 def USStockAtSmart():
     contract = Contract()
     contract.symbol = "IBKR"
     contract.secType = "STK"
     contract.currency = "USD"
     contract.exchange = "SMART"
     return contract
Example #30
0
 def Commodity():
     contract = Contract()
     contract.symbol = "XAUUSD"
     contract.secType = "CMDTY"
     contract.exchange = "SMART"
     contract.currency = "USD"
     return contract
Example #31
0
def main():
    # setup postgreSQL
    sqlLink = pgCode.sqlLink()
    sqlLink.connect("DATA_IB_TWS")

    #setup TWS
    twsApp = TestApp(sqlLink)
    twsApp.connect("127.0.0.1", 7496, 1)

    contract2 = Contract()
    contract2.symbol = "USD"
    contract2.secType = "CASH"
    contract2.exchange = "IDEALPRO"
    contract2.currency = "JPY"

    #setupfile for writing
    #twsApp.setupFile("USD.CAD")

    #setup request type
    twsApp.reqMarketDataType(1)
    uniqueId = 2
    twsApp.reqMktData(uniqueId, contract2, "", False, False, [])
    twsApp.reqContractDetails(uniqueId, contract2)

    #final Run
    print("Run")

    twsApp.run()  # process's the return
Example #32
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)