Пример #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 
Пример #2
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
Пример #3
0
    def setup(self):
        # contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate, keepUpToDate, chartOptions
        # Create a contract object
        for symbol in self.symbols:
            contract = Contract()
            contract.symbol = symbol
            contract.secType = "STK"

            # Make a data request
            self.reqHistoricalData(contract, "", f"{self.days_required} D",
                                   "5 min", "BID_ASK", 0, 1, True, [])
Пример #4
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
def makeStkContract(contractTuple):
    newContract = Contract()
    newContract.symbol = contractTuple[0]
    newContract.secType = contractTuple[1]
    newContract.exchange = contractTuple[2]
    newContract.currency = contractTuple[3]
    #newContract.expiry = contractTuple[4]
    #newContract.strike = contractTuple[5]
    #newContract.right = contractTuple[6]
    print('Contract Values:%s,%s,%s,%s,%s,%s,%s:' % contractTuple)
    return newContract
Пример #6
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
Пример #7
0
def makeSimpleContract(symbol,
                       secType="STK",
                       currency="USD",
                       exchange="SMART"):
    contract = Contract()
    contract.symbol = symbol
    contract.secType = secType
    contract.currency = currency
    contract.exchange = exchange

    return contract
Пример #8
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
Пример #9
0
    def __init__(self):
        self.ids = []
        self.lots = 5
        self.params = pd.read_csv(r'C:/Users/JD/Google Drive/Quantitative Trading/Trading Params/UsoXle Params.csv', header=0, index_col=0)

        xleC, usoC = Contract(), Contract()
        xleC.secType, usoC.secType = 'STK', 'STK'
        xleC.symbol, usoC.symbol = 'XLE', 'USO'
        xleC.currency, usoC.currency = 'USD', 'USD'
        xleC.exchange, usoC.exchange = 'ARCA', 'ARCA'
        self.contracts = (xleC, usoC)
Пример #10
0
def main():
    app = TestApp()
    app.connect("127.0.0.1", 4002, 0)  # 7497 live

    # Crete a contract
    contract = Contract()
    contract.symbol = "AAPL"
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.primaryExchange = "NASDAQ"
Пример #11
0
    def closePosition(self, symbol, volume):
        contract = Contract()
        contract.symbol = symbol
        contract.secType = "STK"

        order = Order()
        order.action = "SELL"
        order.totalQuantity = volume
        order.orderType = "MKT"

        self.placeOrder(contract, order)
Пример #12
0
    def start(self):
        contract = Contract()
        contract.symbol = 'TGP'

        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"
        contract.primaryExchange = "NASDAQ"

        self.reqHistoricalData(1, contract, "", "26 W", "1 day", "MIDPOINT", 0,
                               1, False, [])
Пример #13
0
    def defineContract(self, symbol, secType, exchange, currency,
                       primaryExchange):

        contract = IBcontract()
        contract.symbol = symbol
        contract.secType = secType
        contract.exchange = exchange
        contract.currency = currency
        contract.primaryExchange = primaryExchange

        return contract
Пример #14
0
 def Stock_contract(symbol,
                    secType='STK',
                    exchange='SMART',
                    currency='USD'):
     ''' custom function to create stock contract '''
     contract = Contract()
     contract.symbol = symbol
     contract.secType = secType
     contract.exchange = exchange
     contract.currency = currency
     return contract
Пример #15
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
Пример #16
0
 def contract(self) -> Contract:
     out = Contract()
     out.symbol = self.symbol
     out.secType = "STK"
     out.currency = "USD"
     out.exchange = "SMART"
     if self.pex == "NASDAQ":
         out.primaryExchange = "ISLAND"
     else:
         out.primaryExchange = self.pex
     return out
Пример #17
0
 def stock_contract(self,
                    symbol,
                    secType='STK',
                    exchange='ISLAND',
                    currency='USD'):
     contract = Contract()
     contract.symbol = symbol
     contract.secType = secType
     contract.exchange = exchange
     contract.currency = currency
     return contract
Пример #18
0
def createContract(symbol,
                   sec_type='STK',
                   exch='SMART',
                   prim_exch='ISLAND',
                   currency='USD'):
    contract = Contract()
    contract.symbol = symbol
    contract.secType = sec_type
    contract.exchange = exch
    contract.primaryExch = prim_exch
    contract.currency = currency
    return contract
Пример #19
0
    def test_req_pnl_single_blocking(self):
        contract = Contract()
        contract.symbol = "AAPL"
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = 'USD'

        result = self.app.req_contract_details(contract)
        contract_id = result[0]['contract']['conId']
        contract_pnl = self.app.req_pnl_single_blocking(
            self.account_id, '', contract_id)
        print(contract_pnl)
Пример #20
0
def subscribe_to_asset(ticker):
    logger = logging.getLogger(__name__)
    try:
        contract = Contract()
        contract.symbol = ticker
        contract.secType = 'STK'
        contract.exchange = 'SMART'
        contract.currency = 'USD'
        app_ib.req_mkt_data(contract)
    except Exception as e:
        logger.error(e)
    return jsonify('success')
Пример #21
0
def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 2)
    time.sleep(2)
    # contract = Contract()
    # contract.symbol = "IBEX35"  # No market data permissions for NYSE STK -->>  For Live TWS
    # contract.secType = "IND"
    # contract.exchange = "MEFFRV"
    # contract.currency = "EUR"

    #contract = Contract()
    #contract.symbol = "MGM"  # No market data permissions for NYSE STK -->>  For Live TWS
    #contract.secType = "STK"
    #contract.exchange = "SMART"
    #contract.currency = "USD"

    #contract = Contract()
    #contract.symbol = "UAVS" #No market data permissions for AMEX STK-->> For Live TWS
    #contract.secType = "STK"
    #contract.exchange = "SMART"  # Este contrato no corre si estoy en la sesion de tfm2020le, pero si corre en la sesion "demo TWS"
    #contract.currency = "USD"

    #contract = Contract()
    #contract.symbol = "IBKR"
    #contract.secType = "STK"
    #contract.exchange = "SMART"  # Este contrato no corre si estoy en la sesion de tfm2020le, pero si corre en la sesion "demo TWS"
    #contract.currency = "USD"

    #contract = Contract()
    #contract.symbol = "GBP"
    #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"

    #contract = Contract()     #Con este tipo de contrato no funciona
    #contract.symbol = "AAPL"  #No market data permissions for ISLAND STK en version DEMO
    #contract.secType = "STK"  #No market data permissions for ISLAND STK en version tfm2020le
    #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()
Пример #22
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
Пример #23
0
def streaming():
    app = TestApp("0.0.0.0", 4001, 9)
    contract = IBcontract()
    contract.symbol = 'AAPL'
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.primaryExchange = "NASDAQ"

    app.reqMarketDataType(4)
    req = app.reqMktData(1, contract, "", False, False, [])
    print(req)
Пример #24
0
def create_contract(mysymbol, sec_type, exch, prim_exch, currency):
    """
    亲测可用
    全局使用。按照标准的自带的Contract()格式制作,没啥可调的,按规矩做就是了。
    """
    contract = Contract()  # 自己的
    contract.symbol = mysymbol
    contract.secType = sec_type
    contract.exchange = exch
    contract.primaryExch = prim_exch
    contract.currency = currency
    return contract
Пример #25
0
    def start(self):
        contract = Contract()
        contract.symbol = "TGP"
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"
        contract.primaryExchange = "NASDAQ"

        wb = Workbook.load_workbook(
            'D:\\TWS API\\source\\pythonclient\\ibapi\\Accounting Info TGP.xlsx'
        )
        range = wb['Accounting Info']

        wb_1 = Workbook.load_workbook(
            'D:\\TWS API\\source\\pythonclient\\ibapi\\StockPrice TGP.xlsx')
        range_1 = wb_1['stock yield TGP']

        wb_2 = Workbook.load_workbook(
            'D:\\TWS API\\source\\pythonclient\\ibapi\\Dividend Info TGP.xlsx')
        range_2 = wb_2['Dividend Info']

        wb_3 = Workbook.load_workbook(
            'D:\\TWS API\\source\\pythonclient\\ibapi\\StockPrice TGP PRa.xlsx'
        )
        range_3 = wb_3['stock yield TGP PRa']

        wb_4 = Workbook.load_workbook(
            'D:\\TWS API\\source\\pythonclient\\ibapi\\YTC TGP.xlsx')
        range_4 = wb_4['YTC TGP']
        TGP_Dividend_PRa = float(input('please enter Dividend of TGP PRa'))
        TGP_Dividend_PRb = float(input('please enter Dividend of TGP PRb'))
        Outstanding_share = float(
            input('please enter Outstanding share of PRa'))
        condition_1 = TGP_Dividend_PRa > TGP_Dividend_PRb
        condition_2 = float(str(range_4['A1'].value)) > 0.7
        condition_3 = float(str(range_3['A1'].value)) < float(
            str(range_1['A1'].value))
        condition_4 = (float(str(range['A1'].value)) -
                       float(str(range_2['B1'].value)) * Outstanding_share) / (
                           TGP_Dividend_PRa + TGP_Dividend_PRb) > 2.0

        if condition_1:
            if condition_2 and condition_3 and condition_4:
                order = Order()
                order.action = "BUY"
                order.orderType = "LMT"
                order.totalQuantity = 400
                order.lmtPrice = 210

        if not (condition_1 and condition_2 and condition_3 and condition_4):
            print('doesnt meet criteria cant place order')
        else:
            self.placeOrder(self.nextOrderId, contract, order)
Пример #26
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
    def get_contract_object(symbol: str,
                            security_type: "SecurityType") -> Contract:
        contract = Contract()
        contract.symbol = symbol
        contract.secType = security_type.value
        contract.exchange = "SMART"
        contract.currency = "USD"

        from ibkr.models import SecurityType
        if security_type == SecurityType.STOCK:
            contract.primaryExchange = "NASDAQ"
        return contract
Пример #28
0
def main():
    app = DemoApp()

    app.connect("127.0.0.1", 4001, 0)  # 7496 4001
    print("serverVersion:%s connectionTime:%s" %
          (app.serverVersion(), app.twsConnectionTime()))
    # id = app.reqIds(0)

    contract1 = Contract()
    contract1.symbol = "OXLC"
    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="1 Y", barSizeSetting="1 day",
    #                       whatToShow="TRADES", useRTH=1, formatDate=1, keepUpToDate=False, chartOptions=[]) # TRADES ADJUSTED_LAST
    # app.reqHistoricalData(2, contract2, "", "5 W", "1 day", "TRADES", 0, 1, False, [])
    # app.reqContractDetails(1, contract1)
    # app.reqContractDetails(2, contract2)

    # ReportsFinSummary
    # ReportsOwnership
    # ReportSnapshot
    # ReportsFinStatements
    # RESC
    # CalendarReport
    # app.reqFundamentalData(11, contract1, "ReportsFinSummary", [])

    # genericTickList:
    #   - Fundamental Ratios - 258
    #   - IB Dividends - 456
    app.reqMktData(1, contract1, "258, 456", False, False, [])

    app.run()
Пример #29
0
def update(config, symbol):

    conn_cred = config['conn_cred']

    app = TestApp("127.0.0.1", 7497, 1)
    ibcontract = IBcontract()
    ibcontract.secType = "STK"
    # ibcontract.lastTradeDateOrContractMonth="202011"
    ibcontract.symbol = symbol
    ibcontract.exchange = "SMART"
    ibcontract.currency = "USD"
    ibcontract.primaryExchange = "NASDAQ"
    resolved_ibcontract = app.resolve_ib_contract(ibcontract)
    # print(resolved_ibcontract)
    historic_data = app.get_IB_historical_data(resolved_ibcontract,
                                               durationStr="1 W",
                                               barSizeSetting="5 secs")
    print('pulled historical data. converting data to something mysql expects')
    df = pd.DataFrame(
        historic_data,
        columns=['datetime', 'open', 'high', 'low', 'close', 'volume'])
    df['symbol'] = symbol
    df['datetime'] = pd.to_datetime(df['datetime'], format='%Y%m%d  %H:%M:%S')

    df['epoch'] = (df['datetime'] -
                   datetime(1970, 1, 1)).dt.total_seconds() + (480 * 60)
    list_vals = df[[
        'symbol', 'epoch', 'open', 'high', 'low', 'close', 'volume'
    ]].values.tolist()
    # list_vals = (tuple(i) for i in list_vals) # for executemany()

    print('inserting to sql database')
    ## robust one-by-one insertion
    for i in range(len(list_vals)):
        query = "INSERT INTO {dbname}.bar_data (symbol, epoch,\
					open, high,low, close, volume\
					) VALUES ({csv})".format(dbname=conn_cred['dbname'],
                              csv=','.join(
                                  map(lambda x: "'" + str(x) + "'",
                                      list_vals[i])))
        run_query(conn_cred, query)
    ## executemany (supposed to be a gajillion times faster)
    ## dunno how to make this work tho
    # query = "INSERT INTO {dbname}.bar_data (symbol, epoch,\
    #  				open, high,low, close, volume\
    #  				) VALUES (%s)".format(dbname=conn_cred['dbname'],
    #  												symbol=symbol)
    # dbconn, cursor = mysql_conn(conn_cred['dbname'])
    # cursor.executemany(query, list_vals)
    # db_conn_close()
    print('done updating')
    quit()
Пример #30
0
 def gen_contract(self,
                  symbol,
                  secType="STK",
                  currency="USD",
                  exchange="ISLAND"):
     contract = Contract()
     contract.symbol = symbol
     contract.secType = secType
     contract.currency = currency
     # In the API side, NASDAQ is always defined as ISLAND in the exchange
     # field
     contract.exchange = exchange
     return contract
Пример #31
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
Пример #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)