Exemple #1
0
def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497,
                988)  # LFX comment - this needs to be host, port, client ID

    contracts = [
        ContractSamples.EurGbpFx(),
        ContractSamples.AudChfFx(),
        ContractSamples.ChfJpyFx(),
        ContractSamples.EurChfFx(),
        ContractSamples.EurJpyFx(),
        ContractSamples.EurUsdFx(),
        ContractSamples.GbpChfFx(),
        ContractSamples.GbpJpyFx(),
        ContractSamples.NzdUsdFx(),
        ContractSamples.UsdJpyFx()
    ]

    JSONContent = requests.get(contracts).json()
    content = json.dumps(JSONContent, indent=4, sort_keys=True)

    print(content)

    for i in contracts:
        app.reqContractDetails(1, i)

    app.run()
Exemple #2
0
def historicalData_req(self):
    # Requesting historical data
    query_time = (datetime.datetime.today() -
                  datetime.timedelta(days=180)).strftime("%Y%m%d %H:%M:%S")
    self.reqHistoricalData(4102, ContractSamples.EurGbpFx(), query_time, "1 M",
                           "1 day", "MIDPOINT", 1, 1, False, [])
    self.reqHistoricalData(4103, ContractSamples.EurGbpFx(), query_time,
                           "10 D", "1 hour", "MIDPOINT", 1, 1, False, [])
    def opt_tick_req_single_code(self,index,option_code,queryTime):
        self.client.opt_req_next_code = False
        order_id = index*100000 + 1
        while not self.client.opt_req_next_code and not self.client.process_done:
            time_recorder = 0
            self.client.reqHistoricalTicks(order_id, ContractSamples.OptionWithLocalSymbol(option_code),
                                           queryTime.strftime("%Y%m%d %H:%M:%S"), "", 1000, "TRADES", 1, True, [])
            time.sleep(10)
            while not self.client.process_done:
                if self.client.opt_req_next_code:
                    print('next code...............')
                    break
                elif self.client.opt_req_continue:
                    queryTime = self.client.lasttime
                    order_id += 1
                    self.client.opt_req_continue = False
                    print('continue...............')
                    break
                else:
                    time.sleep(2)
                    time_recorder += 1
                    if time_recorder > 90:  #3分钟内没有返回内容,则重新提交请求
                        fw = open('data.txt', 'a')
                        fw.write(option_code+' '+str(order_id)+' '+str(queryTime)+'\n')
                        fw.close()
                        self.client.opt_req_next_code = True
                        self.client.tick_num = 1
                        break
                    print(datetime.datetime.now(), 'sleeping.................')

        print(datetime.datetime.now())
    def option_tikc_req(self):
        index_continue = -1
        if index_continue == -1:
            index_continue = 0
            for index in self.stock_code_map.keys():
                if self.client.process_done:
                    break
                else:
                    stock_code = self.stock_code_map[index]
                    self.client.reqContractDetails(index, ContractSamples.OptionForQuery(stock_code))
                    time.sleep(30)
                    print('Asked for ', str(stock_code))

            while not self.client.req_opt_contract_end and not self.client.process_done:
                print('waiting for req_opt_contract_end Done')
                time.sleep(2)
            print(self.client.option_code_map)
        else:
            temp = pd.read_csv('option_code_map.csv')
            self.client.option_code_map = temp['option_code'].values.tolist()

        option_code_map = self.client.option_code_map
        for index in range(index_continue, len(option_code_map)):
            if self.client.process_done:
                break
            else:
                option_code = option_code_map[index]
                self.client.opt_req_next_code = False
                queryTime = datetime.datetime(2018, 3, 20, 9, 30)
                self.opt_tick_req_single_code(index, option_code, queryTime)

        print('request option tick data done!')
 def persistData(self, reqId: int, time: int, price: float, size: int,
                 tickAttribLast: TickAttribLast):
     #print(" inside persistData")
     contract = ContractSamples.SimpleFuture()
     values = (1, contract.symbol, reqId, time, price, size)
     db = DBHelper()
     db.insertData(values)
    def historicalDataRequests_req_Seconds(self):
        flag = 0
        for queryTime in date_list:
            if flag == 1:
                queryTime += timedelta(hours=16)
            else:
                queryTime = datetime.datetime(2017,12,8,10,30)
                flag = 1

            if self.client.process_done:
                break

            while queryTime.hour > 9:
                for index in self.stock_code_map.keys():
                    if self.client.process_done:
                        break
                    else:
                        stock_code = self.stock_code_map[index]
                        print('Start to get', stock_code, str(index), str(queryTime))
                        self.client.reqHistoricalData(index, ContractSamples.USStockAtSmart(stock_code),
                                               queryTime.strftime("%Y%m%d %H:%M:%S"),
                                               "1800 S", "1 secs", "TRADES", 1, 1, False, [])
                        time.sleep(10)
                        print('Finish query', stock_code + str(queryTime))
#                print(xx)
                queryTime -= timedelta(seconds=1800)

        print('request done')
    def historicalDataRequests_req_opt_Seconds(self):
        for index in self.stock_code_map.keys():
            queryTime = datetime.datetime(2018, 1, 16, 16, 00)
            endday = queryTime - timedelta(days=180)

            while queryTime > endday:
                if self.client.process_done:
                    break
                else:
                    stock_code = self.stock_code_map[index]
                    print('Start to get', stock_code, str(index), str(queryTime))
                    self.client.reqHistoricalData(index, ContractSamples.OptionWithLocalSymbol(stock_code),
                                           queryTime.strftime("%Y%m%d %H:%M:%S"),
                                           "1800 S", "1 secs", "TRADES", 1, 1, False, [])
                    time.sleep(11)
                    print('Finish query', stock_code + str(queryTime))

                if queryTime.hour == 10 and queryTime.minute == 0:
                    if queryTime.isoweekday() == 1:
                        queryTime -= timedelta(days=2,hours=18)
                    else:
                        queryTime -= timedelta(hours=18)
                else:
                    queryTime -= timedelta(seconds=1800)

        print('request done')
Exemple #8
0
 def opt_tick_req_single_code(self,index,option_code,query_Time):
     queryTime = query_Time
     while not self.client.opt_req_next_code and not self.client.process_done:
         self.client.reqHistoricalTicks(index, ContractSamples.OptionWithLocalSymbol(option_code),
                                        queryTime.strftime("%Y%m%d %H:%M:%S"), "", 1000, "TRADES", 1, True, [])
         time.sleep(15)
         while not self.client.process_done:
             if self.client.opt_req_next_time:
                 if queryTime.isoweekday() == 1:
                     queryTime -= timedelta(days=3)
                 else:
                     queryTime -= timedelta(days=1)
                 queryTime = datetime.datetime.combine(queryTime.date(),query_Time.time())
                 print(queryTime)
                 self.client.opt_req_next_time = False
                 print('next time...............')
                 break
             elif self.client.opt_req_continue:
                 queryTime = self.client.lasttime
                 self.client.opt_req_continue = False
                 print('continue...............')
                 break
             else:
                 time.sleep(0.5)
                 print('sleeping.................')
    def marketDepthOperations_req(self):
        # Requesting the Deep Book
        # ! [reqmarketdepth]
        #self.reqMktDepth(2001, ContractSamples.EurGbpFx(), 5, False, [])

        #self.reqMktDepth(2001, ContractSamples.USStock(), 5, True, [])
        self.reqMktDepth(2002, ContractSamples.SimpleFuture(), 5, True, [])
    def tickDataOperations_req(self):
        self.reqMarketDataType(MarketDataTypeEnum.DELAYED_FROZEN)

        #self.reqMktData(1015, ContractSamples.SimpleFuture(), "", False, False, [])
        #self.reqMktData(1999, ContractSamples.USSPYStockAtSmart(), "233,236,258", False, False, [])
        #self.reqHistoricalData(2, ContractSamples.ContFut(), "", "1 Y", "1 hour", "BID_ASK", 0, 1, False, []);
        self.reqTickByTickData(19002, ContractSamples.SimpleFuture(),
                               "AllLast", 0, False)
    def mktData_req_opt(self):
        for index in self.stock_code_map.keys():
            stock_code = self.stock_code_map[index]
            print('Start to get', stock_code, str(index))
            self.client.reqMktData(index, ContractSamples.OptionWithLocalSymbol(stock_code), "100,101,104,106,233,236,258", False, False, [])
            print('Finish query', stock_code)

        print('request done')
 def persistData(self, reqId: int, time: int, price: float, size: int,
                 tickAttribLast: TickAttribLast):
     #print(" inside persistData")
     contract = ContractSamples.USStock()
     converted_time = datetime.datetime.fromtimestamp(time).strftime(
         "%Y%m%d %H:%M:%S")
     values = (1, contract.symbol, contract.secType, reqId, time, price,
               size)
     db = DBHelper()
     db.insertData(values)
Exemple #13
0
def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 988)  # LFX comment - this needs to be host, port, client ID

    contract = ContractSamples.EurUsdFx()

    app.reqHistoricalData(1, contract, "", "1 M", "1 day", "MIDPOINT", 0, 1, False, [])

    app.run()
Exemple #14
0
def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 988)  # LFX comment - this needs to be host, port, client ID

    contract = ContractSamples.EurGbpFx()

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

    app.run()
Exemple #15
0
 def historicalDataRequests_req_HeadTimestamp(self):
     # Requesting historical data
     # ! [reqHeadTimeStamp]
     for index in self.stock_code_map.keys():
         if self.client.process_done:
             break
         else:
             stock_code = self.stock_code_map[index]
             print('Start to get', stock_code, str(index))
             self.client.reqHeadTimeStamp(index, ContractSamples.OptionWithLocalSymbol(stock_code), "TRADES", 0, 1)
             time.sleep(10)
             print('Finish query', stock_code)
Exemple #16
0
    def orderOperations_req(self):
        # If not check - orders will be placed consistently
        if self.started:
            return

        # Will need to set this flag to false somewhere in order to place a new order
        self.started = True

        # The parameter is always ignored.
        self.reqIds(-1)
        self.placeOrder(self.nextOrderId(), ContractSamples.EurGbpFx(),
                        OrderSamples.MarketOrder("SELL", 20000))
Exemple #17
0
    def optionsOperations_req(self):
        # ! [reqsecdefoptparams]
        self.reqSecDefOptParams(0, "IBM", "", "STK", 8314)
        # ! [reqsecdefoptparams]

        # Calculating implied volatility
        # ! [calculateimpliedvolatility]
        self.calculateImpliedVolatility(5001, ContractSamples.OptionAtBOX(), 5,
                                        85, [])
        # ! [calculateimpliedvolatility]

        # Calculating option's price
        # ! [calculateoptionprice]
        self.calculateOptionPrice(5002, ContractSamples.OptionAtBOX(), 0.22,
                                  85, [])
        # ! [calculateoptionprice]

        # Exercising options
        # ! [exercise_options]
        self.exerciseOptions(5003, ContractSamples.OptionWithTradingClass(), 1,
                             1, self.account, 1)
def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497,
                988)  # LFX comment - this needs to be host, port, client ID

    contract = ContractSamples.EurGbpFx()

    app.reqHistoricalData(1, contract, "", "7 D", "1 hour", "MIDPOINT", 0, 1,
                          False, [])
    #app.historicalDataOperations_req()

    app.run()
Exemple #19
0
 def ocaSample(self):
     """One Cancels All. This could come in handy when I'm not picky
     about the particular strike, but care more that I get one of several
     strikes at a reasonable price. For instance place multiple limit orders
     when I only want 1."""
     ocaOrders = [
         OrderSamples.LimitOrder("BUY", 1, 10),
         OrderSamples.LimitOrder("BUY", 1, 11),
         OrderSamples.LimitOrder("BUY", 1, 12)
     ]
     OrderSamples.OneCancelsAll("TestOCA_" + self.nextValidOrderId,
                                ocaOrders, 2)
     for o in ocaOrders:
         self.placeOrder(self.nextOrderId(), ContractSamples.USStock(), o)
def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 988)  # LFX comment - this needs to be host, port, client ID

    contract = ContractSamples.EurGbpFx()

    # order = OrderSamples.MarketOrder("buy", 10)

    app.nextValidId(orderId=1)

    Timer(3, app.stop).start()

    app.run()
Exemple #21
0
def main():
    app = TestApp()
    app.connect("127.0.0.1", 7497, 0)
    print("serverVersion:%s connectionTime:%s" %
          (app.serverVersion(), app.twsConnectionTime()))

    # app.reqContractDetails(10, ContractSamples.SI())
    # app.reqMktData(1101,ContractSamples.SI(),"",False,False,[])
    # app.reqMktData(1101, ContractSamples.USStockAtSmart(), "", False, False, [])
    queryTime = (datetime.datetime.today() -
                 datetime.timedelta(days=180)).strftime("%Y%m%d %H:%M:%S")
    SI_data = app.reqHistoricalData(4101, ContractSamples.SI(), queryTime,
                                    "1 M", "1 day", "MIDPOINT", 1, 1, [])
    app.run()
Exemple #22
0
 def __init__(self):
     TestWrapper.__init__(self)
     TestClient.__init__(self, wrapper=self)
     self.nKeybInt = 0
     self.started = False
     self.nextValidOrderId = None
     self.nextRequestId = 5000
     self.historicalDataFrame = pd.DataFrame(columns=[
         "reqID", "Date", "Open", "High", "Low", "Close", "Volume", "Count",
         "WAP"
     ])
     self.permId2ord = {}
     #self.reqId2nErr = collections.defaultdict(int)
     self.globalCancelOnly = False
     self.simplePlaceOid = None
     self.sampleStock = ContractSamples.USStockAtSmart()
     self.historicalDataReceived = False
    def optionsOperations_req(self):
        # ! [reqsecdefoptparams]
        # self.client.reqSecDefOptParams(1, "IBM", "", "STK", 8314)
        # self.client.reqContractDetails(210, ContractSamples.OptionForQuery())
        # self.client.reqMktData(1002, ContractSamples.USStockAtSmart('AAPL'), "", False, False, []) #OptionForQuery()
        # self.client.reqHistoricalData(1, ContractSamples.OptionForQuery(),
        #                               "20180224 16:00:00", "900 S", "1 secs", "TRADES", 1, 1, False, [])

        # self.client.reqHistoricalTicks(0, ContractSamples.OptionWithLocalSymbol("AAPL  180420C00180000"),
        #                         "20171124 09:30:00", "", 1000, "TRADES", 1, True, [])
        # self.opt_tick_req_single_code(0, "AAPL  180420C00180000", datetime.datetime(2017,11,22,9,30))
        self.client.reqHeadTimeStamp(1, ContractSamples.OptionWithLocalSymbol("AAPL  190118C00135000"), "TRADES", 0, 1)

        # self.client.reqMktData(1000, ContractSamples.OptionWithLocalSymbol("AAPL  180420C00180000"), "100,101,104,106,233,236,258", False, False, [])
        # ! [reqsecdefoptparams]

        print('request done!!')
    def paper_trade(self):
        my_client = MongoClient('10.12.0.30', 27017)
        my_db = my_client['research']
        my_col = my_db['optionsonar']
        data = my_col.find({}, {'_id': 0})
        data_pd = pd.DataFrame(list(data))
        start_num = len(data_pd)
        order_done = False
        while not self.client.process_done and not order_done:

            if self.client.nextValidOrderId is not None:
                self.client.placeOrder(self.client.nextOrderId(), ContractSamples.OptionWithLocalSymbol('AAPL  180420C00180000'),
                               OrderSamples.LimitOrder("BUY", 3, 0.1))
                order_done = True
            else:
                time.sleep(1)
                print('wait for placing order')
        print('place order done')
    def historicalDataRequests_req_Days(self):
        queryTime = datetime.datetime(2016, 12, 25)
        while queryTime > datetime.datetime(1980, 1, 1):
            for index in self.stock_code_map.keys():
                if self.client.process_done:
                    break
                stock_code = self.stock_code_map[index]
                headTimestamp = datetime.datetime.strptime(stock_HeadTimestamp[stock_code], '%Y/%m/%d')
                if queryTime > headTimestamp:
                    print('Start to get', stock_code, str(index), str(queryTime))
                    self.client.reqHistoricalData(index, ContractSamples.USStockAtSmart(stock_code),
                                                  queryTime.strftime("%Y%m%d %H:%M:%S"),
                                                  "1 Y", "1 day", "TRADES", 1, 1, False, [])
                    time.sleep(10)
                    print('Finish query', stock_code + str(queryTime))
                    #                print(xx)
            queryTime -= timedelta(days=360)

        print('request done')
Exemple #26
0
    def run(self):
        i = 1
        while i == 1:
            records = Signal.objects.all()
            for record in records:
                if record.status == "new":
                    print(f"new record id: {record.id}")
                    rec = json.loads(record.request_payload)  # Parse json

                    if rec['url'] == 'placeorder':
                        self.app.nextOrderId()
                        # STK
                        #contract = ContractSamples.USStock()
                        #contract.symbol = rec['symbol']
                        #self.app.placeOrder(self.app.nextOrderId(), contract, OrderSamples.MarketOrder(rec['direction'], rec['volume']))

                        #contract = ContractSamples.EurGbpFx()
                        contract = ContractSamples.USStock()
                        contract.symbol = rec['symbol']
                        self.app.placeOrder(
                            self.app.nextValidOrderId, contract,
                            OrderSamples.MarketOrder(rec['direction'],
                                                     rec['volume']))

                        #print("next trading.py:" + str(self.app.nextValidOrderId))

                        print("Request payload(Trading.py):" + str(rec))

                        record.status = "processed"
                        #record.url = rec['url']
                        record.req_id = self.app.nextValidOrderId
                        record.save()

                    if rec['url'] == 'botstatus':
                        record.status = "processed"
                        #record.req_id = self.app.nextValidOrderId
                        record.save()

            time.sleep(1)
Exemple #27
0
    def option_tikc_req(self):
        for index in self.stock_code_map.keys():
            if self.client.process_done:
                break
            else:
                stock_code = self.stock_code_map[index]
                self.client.reqContractDetails(index, ContractSamples.OptionForQuery(stock_code))
                time.sleep(11)

        while not self.client.req_opt_contract_end and not self.client.process_done:
            print('waiting for req_opt_contract_end Done')
            time.sleep(0.5)

        option_code_map = self.client.option_code_map
        for index in option_code_map:
            if self.client.process_done:
                break
            else:
                option_code = option_code_map[index]
                self.client.opt_req_next_code = False
                queryTime = datetime.datetime(2018, 3, 9, 9, 30)
                self.opt_tick_req_single_code(index, option_code, queryTime)

        print('request option tick data done!')
 def historicalDataOperations_req(self):
     self.reqHistoricalData(10, ContractSamples.EurGbpFx(), "", "1 D",
                            "1 hour", "MIDPOINT", 1, 1, True, [])
     self.reqHistoricalData(20, ContractSamples.EurUsdFx(), "", "1 D",
                            "1 hour", "MIDPOINT", 1, 1, False, [])
 def historicalDataOperations_req(self):
     self.reqHistoricalData(1, ContractSamples.EurGbpFx(), "",
                            "1 M", "1 day", "MIDPOINT", 1, 1, False, [])
Exemple #30
0
    def run(self):
        i = 1
        while i == 1:
            records = Signal.objects.all()
            for record in records:
                if record.status == "new":
                    print(f"Watch loop: new record id: {record.id}")
                    rec = json.loads(record.request_payload)  # Parse json

                    if rec['url'] == 'placeorder':
                        self.app.nextOrderId()
                        contract = ContractSamples.USStock()
                        contract.exchange = rec['exchange']
                        contract.symbol = rec['symbol']
                        contract.currency = rec['currency']

                        if rec['order_type'] == 'market':
                            # Place market orders
                            self.app.placeOrder(
                                self.app.nextValidOrderId, contract,
                                OrderSamples.MarketOrder(
                                    rec['direction'], rec['volume']))
                        else:
                            self.app.placeOrder(
                                self.app.nextValidOrderId, contract,
                                OrderSamples.LimitOrder(
                                    rec['direction'], rec['volume'],
                                    rec['price']))

                        print("Request payload (Trading.py placeorder):" +
                              str(rec))
                        try:
                            record.status = "pending"
                            record.req_id = self.app.nextValidOrderId
                            record.save()
                        except:
                            error = 'Trading.py. Update Model query error. Most likely - no MYSQL connection. Code: 99oozz4'
                            print(error)
                            self.log.error(error)

                    if rec['url'] == 'botstatus' and record.status != 'pending':
                        self.app.timeStamp()
                        print('Entered bot status: ' + str(i) + ' ' +
                              str(self.app.timestamp))
                        contract = ContractSamples.USStock()
                        contract.exchange = 'nyse'
                        contract.symbol = 'aapl'
                        self.app.reqContractDetails(self.app.timestamp,
                                                    contract)
                        #self.app.reqPositionsMulti(self.app.timestamp, "", "")
                        try:
                            record.status = "pending"
                            record.req_id = self.app.timestamp
                            record.save()
                        except:
                            error = 'Trading.py. Update Model query error. Most likely - no MYSQL connection. Code: 99oozz5'
                            print(error)
                            self.log.error(error)

                    # Get all positions. Can be executed with symbol as an optional parameter
                    # Response will be returned to positionMulti. positionMultiEnd - will be the finalizing event
                    # https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClient.html#a4fa2744c3459f9f6cf695980267608c3
                    if rec['url'] == 'getpositions' and record.status != 'pending':
                        self.app.timeStamp()
                        print('Entered bot getpositions:' + str(i) + ' ' +
                              str(self.app.timestamp))
                        self.app.reqPositionsMulti(self.app.timestamp, "", "")
                        TestApp.positionSymbol = rec['symbol'].upper()

                        try:
                            record.status = "pending"
                            record.req_id = self.app.timestamp
                            record.save()
                        except:
                            error = 'Trading.py. Update Model query error. Most likely - no MYSQL connection. Code: 26ooutt'
                            print(error)
                            self.log.error(error)

                    if rec['url'] == 'getquote' and record.status != 'pending':
                        self.app.timeStamp()
                        print('Entered bot get quote:' + str(i) + ' ' +
                              str(self.app.timestamp))
                        contract = ContractSamples.USStock()
                        contract.exchange = rec['exchange']
                        contract.symbol = rec['symbol']
                        contract.currency = rec['currency']
                        # self.app.reqContractDetails(self.app.timestamp, contract)
                        # Tick types
                        self.app.reqMktData(self.app.timestamp, contract, "",
                                            False, False, [])
                        try:
                            record.status = "pending"
                            record.req_id = self.app.timestamp
                            record.save()
                        except:
                            error = 'Trading.py. Update Model query error. Most likely - no MYSQL connection. Code: 99oozz6'
                            print(error)
                            self.log.error(error)

                        # https://github.com/dacoders77/tbr/blob/master/!%D1%81%23/TBR_noform/Classes/ApiManager.cs
                        # iBClient.ClientSocket.reqMktData(requestId, contract, "", true, false, null);

                        # https://github.com/dacoders77/tbr/blob/master/!%D1%81%23/TBR_noform/Form1.cs
                        # ibClient.TickPrice += IbClient_TickPrice; // reqMarketData. EWrapper Interface

                    if rec['url'] == 'cancelall' and record.status != 'pending':
                        self.app.timeStamp()
                        print('Entered cancel all:' + str(i) + ' ' +
                              str(self.app.timestamp))
                        self.app.reqGlobalCancel()
                        try:
                            record.status = 'processed'
                            record.req_id = self.app.timestamp
                            record.response_payload = 'cancel all ok'
                            record.save()
                        except:
                            error = 'Trading.py. Update Model query error. Most likely - no MYSQL connection. Code: 99oozz7'
                            print(error)
                            self.log.error(error)

            time.sleep(1)