Exemplo n.º 1
0
def main():
    json_file = open("config.json")
    config = json.load(json_file)
    json_file.close()

    print(config)

    investor_id = config["investor_id"]
    broker_id = config["broker_id"]
    password = config["password"]
    server = config["trader_server"]
    app_id = config["app_id"]
    auth_code = config["auth_code"]

    if check_address_port(server):

        user_trader = Trader(broker_id=broker_id,
                             app_id=app_id,
                             auth_code=auth_code,
                             investor_id=investor_id,
                             password=password)

        user_trader.Create()
        user_trader.RegisterFront(server)
        user_trader.SubscribePrivateTopic(2)  # 只传送登录后的流内容
        user_trader.SubscribePrivateTopic(2)  # 只传送登录后的流内容

        user_trader.Init()

        print("trader api started")
        print("trading day:", user_trader.GetTradingDay())

        if user_trader.login:
            investor = ApiStructure.QryInvestorField(broker_id, investor_id)

            user_trader.ReqQryInvestor(investor, user_trader.request_id)

            # position = ApiStructure.QryInvestorPositionField.from_dict({"BrokerID": broker_id,
            #                                                             "InvestorID": investor_id})
            # user_trader.ReqQryInvestorPosition(position, user_trader.request_id)

            settlement_info = ApiStructure.SettlementInfoConfirmField.from_dict(
                {
                    "BrokerID": broker_id,
                    "InvestorID": investor_id
                })

            user_trader.ReqSettlementInfoConfirm(settlement_info,
                                                 user_trader.request_id)

            trader_account = ApiStructure.QryTradingAccountField(
                BrokerID=broker_id, InvestorID=investor_id)
            user_trader.ReqQryTradingAccount(trader_account,
                                             user_trader.request_id)

            user_trader.Join()

    else:
        print("trader server down")
Exemplo n.º 2
0
 def OnRspAuthenticate(self, pRspAuthenticateField, pRspInfo, nRequestID,
                       bIsLast):
     logger.info('OnRspAuthenticate')
     req = ApiStructure.ReqUserLoginField(BrokerID=self.broker_id,
                                          UserID=self.investor_id,
                                          Password=self.passwd)
     self.ReqUserLogin(req, self.inc_request_id())
Exemplo n.º 3
0
    def OnFrontConnected(self):

        req = ApiStructure.ReqUserLoginField(BrokerID=self.broker_id,
                                             UserID=self.investor_id,
                                             Password=self.password)
        self.ReqUserLogin(req, self.request_id)
        print("trader on front connection")
Exemplo n.º 4
0
 def reqQryInvestorPosition(self, event):  # 可用
     """查询持仓请求"""
     pQryInvestorPosition = ApiStructure.QryInvestorPositionDetailField(
         BrokerID=self.broker_id, InvestorID=self.investor_id)
     reqID = self.inc_request_id()
     if reqID % 2 == 0:  # 每秒只支持一次查询,故和资金查询错开.
         self.ReqQryInvestorPosition(pQryInvestorPosition, reqID)
Exemplo n.º 5
0
 def get_ins_list(self, ):
     self.td = td = Trader(self.broker_id, self.investor_id, self.password)
     td.Create()
     td.RegisterFront(self.td_front)
     td.SubscribePublicTopic(2)
     td.SubscribePrivateTopic(2)
     td.Init()
     col = self._db.get_collection('Instruments')
     col.create_index([('InstrumentID', pm.ASCENDING)], unique=True)
     while True:
         ins = td._ins_queue.get(timeout=10)
         if ins:
             ins_ = ins.to_dict()
             ins_['CreateDate'] = parser.parse(ins_['CreateDate'])
             ins_['OpenDate'] = parser.parse(ins_['OpenDate'])
             ins_['ExpireDate'] = parser.parse(ins_['ExpireDate'])
             ins_['StartDelivDate'] = parser.parse(ins_['StartDelivDate'])
             ins_['EndDelivDate'] = parser.parse(ins_['EndDelivDate'])
             col.replace_one({'InstrumentID': ins_['InstrumentID']},
                             ins_,
                             upsert=True)
             self._sub_list[ins.InstrumentID] = ins
         else:
             userlogout = ApiStructure.UserLogoutField(
                 self.broker_id, self.investor_id)
             td.ReqUserLogout(userlogout, td.inc_request_id())
             break
     return self._sub_list
Exemplo n.º 6
0
 def OnFrontConnected(self):
     logger.info('OnFrontConnected')
     req = ApiStructure.ReqAuthenticateField(BrokerID=self.broker_id,
                                             UserID=self.investor_id,
                                             AuthCode=self.auth_code,
                                             AppID=self.app_id)
     self.ReqAuthenticate(req, self.inc_request_id())
Exemplo n.º 7
0
def get_investor_position(instrument_id):
    structure = ApiStructure.QryInvestorPositionField(
        BrokerID=CONST.BORDKER_ID,
        InvestorID=CONST.INVESTOR_ID,
        InstrumentID=instrument_id)
    req_id, future = create_trader_future()
    ctp_handle(trader.ReqQryInvestorPosition(structure, req_id))
    return future
Exemplo n.º 8
0
 def OnFrontConnected(self):
     """
     :return:
     """
     user_login = ApiStructure.ReqUserLoginField(BrokerID=self.broker_id,
                                                 UserID=self.investor_id,
                                                 Password=self.password)
     self.ReqUserLogin(user_login, self.request_id)
Exemplo n.º 9
0
 def OnFrontConnected(self):
     """
     当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。
     :return:
     """
     logger.info('OnFrontConnected')
     req = ApiStructure.ReqUserLoginField(BrokerID=self.broker_id, UserID=self.investor_id, Password=self.passwd)
     self.requestid += 1
     r = self.ReqUserLogin(req, self.requestid)
Exemplo n.º 10
0
    def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):

        if pRspInfo.ErrorID != 0:
            print("td OnRspUserLogin failed error_id=%s msg:%s",
                  pRspInfo.ErrorID, pRspInfo.ErrorMsg.decode('gbk'))
        else:
            print("td user login successfully")
            qryinstrument = ApiStructure.QryInstrumentField()
            self.ReqQryInstrument(qryinstrument, self.inc_request_id())
Exemplo n.º 11
0
    def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):

        if pRspInfo.ErrorID != 0:
            print("Trader OnRspUserLogin failed error_id=%s msg:%s",
                  pRspInfo.ErrorID, pRspInfo.ErrorMsg.decode('gbk'))
        else:
            print("Trader user login successfully")

            inv = ApiStructure.QryInvestorField(BrokerID=self.broker_id,
                                                InvestorID=self.investor_id)

            self.ReqQryInvestor(inv, self.inc_request_id())
            req = ApiStructure.SettlementInfoConfirmField(
                BrokerID=self.broker_id, InvestorID=self.investor_id)

            self.ReqSettlementInfoConfirm(req, self.inc_request_id())

            self.Join()
Exemplo n.º 12
0
    def OnFrontConnected(self):
        print("OnFrontConnected")
        authenticate = ApiStructure.ReqAuthenticateField(
            BrokerID=self.broker_id,
            UserID=self.investor_id,
            AppID=self.app_id,
            AuthCode=self.auth_code)

        self.ReqAuthenticate(authenticate, self.request_id)
Exemplo n.º 13
0
    def test_struct_missing_parameter(self):
        result = {
            "BrokerID": "45544",
            "FromCurrencyID": "",
            "FromCurrencyUnit": 0.0,
            "ToCurrencyID": "4334",
            "ExchangeRate": 11.0
        }

        field = ApiStructure.ExchangeRateField(BrokerID="45544",
                                               ToCurrencyID="4334",
                                               ExchangeRate=11.0)
        result_dict = field.to_dict()
        self.assertDictEqual(result_dict, result)
Exemplo n.º 14
0
    def OnRspAuthenticate(self, pRspAuthenticateField, pRspInfo, nRequestID,
                          bIsLast):

        print("OnRspAuthenticate")
        print("pRspInfo:", pRspInfo)
        print("nRequestID:", nRequestID)
        print("bIsLast:", bIsLast)

        if pRspInfo.ErrorID == 0:
            req = ApiStructure.ReqUserLoginField(BrokerID=self.broker_id,
                                                 UserID=self.investor_id,
                                                 Password=self.password)
            self.ReqUserLogin(req, self.request_id)
        else:
            print("auth failed")
Exemplo n.º 15
0
 def test_to_dict(self):
     result = {
         "BrokerID": "45544",
         "FromCurrencyID": "4343",
         "FromCurrencyUnit": 19.0,
         "ToCurrencyID": "4334",
         "ExchangeRate": 11.0
     }
     field = ApiStructure.ExchangeRateField(BrokerID="45544",
                                            FromCurrencyID="4343",
                                            FromCurrencyUnit=19.0,
                                            ToCurrencyID="4334",
                                            ExchangeRate=11.0)
     result_dict = field.to_dict()
     self.assertDictEqual(result, result_dict)
Exemplo n.º 16
0
    def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):
        """用户登录响应"""
        if pRspInfo.ErrorID != 0:
            print("交易端 OnRspUserLogin failed error_id=%s msg:%s",
                  pRspInfo.ErrorID, pRspInfo.ErrorMsg.decode('gbk'))
        else:
            print("交易端 user login successfully", nRequestID)

            inv = ApiStructure.QryInvestorField(BrokerID=self.broker_id,
                                                InvestorID=self.investor_id)

            self.ReqQryInvestor(inv, self.inc_request_id())
            print("查询投资者信息.", "请求编号:", self.request_id)
            req = ApiStructure.SettlementInfoConfirmField.from_dict({
                "BrokerID":
                self.broker_id,
                "InvestorID":
                self.investor_id
            })

            self.ReqSettlementInfoConfirm(req, self.inc_request_id())
Exemplo n.º 17
0
    def formatOrder(self, inst, direc, open_close, volume, price):
        return ApiStructure.InputOrderField(
            InstrumentID=inst,
            BrokerID=Strategy.traderSpi.broker_id,
            Direction=direc, # D_Buy or D_Sell
            OrderRef=str(Strategy.traderSpi.inc_request_id()),
            LimitPrice=price,
            VolumeTotalOriginal=volume,
            OrderPriceType=OPT_LimitPrice,

            InvestorID=Strategy.traderSpi.investor_id,
            CombOffsetFlag=open_close, # OF_Open, OF_Close, OF_CloseToday
            CombHedgeFlag=HF_Speculation,
            ExchangeID=exchange_id[inst],
            VolumeCondition=VC_AV,
            MinVolume=1,
            ForceCloseReason=FCC_NotForceClose,
            IsAutoSuspend=1,
            UserForceClose=0,
            TimeCondition=TC_GFD,
            ContingentCondition=CC_Immediately
        )
Exemplo n.º 18
0
 def reqQryInstrument(self):
     """查询合约"""
     req = ApiStructure.QryInstrumentField()
     self.ReqQryInstrument(req, self.inc_request_id())
Exemplo n.º 19
0
 def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):
     if bIsLast and not self.isErrorRspInfo(pRspInfo):
         logger.info('OnRspUserLogin %s' % bIsLast)
         req = ApiStructure.SettlementInfoConfirmField(
             BrokerID=self.broker_id, InvestorID=self.investor_id)
         self.ReqSettlementInfoConfirm(req, self.inc_request_id())
Exemplo n.º 20
0
 def OnFrontConnected(self):
     print('Td 前置机已连接')
     req = ApiStructure.ReqUserLoginField(BrokerID=self.broker_id,
                                          UserID=self.investor_id,
                                          Password=self.password)
     self.ReqUserLogin(req, self.request_id)