Ejemplo n.º 1
0
    def on_query_contract(self, data: List[Dict[str, str]]) -> None:
        """"""
        if not data:
            self.gateway.write_log("合约信息查询失败")
            return

        # Process option contract
        for d in data:
            contract = ContractData(
                symbol=d["option_code"],
                exchange=EXCHANGE_HSOPTION2VT[d["exchange_type"]],
                name=d["option_name"],
                size=int(float(d["amount_per_hand"])),
                pricetick=float(d["opt_price_step"]),
                product=Product.OPTION,
                gateway_name=self.gateway_name)

            contract.option_portfolio = d["stock_code"] + "_O"
            contract.option_underlying = (d["stock_code"] + "-" +
                                          str(d["end_date"]))
            contract.option_type = OPTIONTYPE_HSOPTION2VT[d["option_type"]]
            contract.option_strike = float(d["exercise_price"])
            contract.option_expiry = datetime.strptime(d["end_date"], "%Y%m%d")
            contract.option_index = get_option_index(contract.option_strike,
                                                     d["optcontract_id"])

            self.gateway.on_contract(contract)

            symbol_exchange_map[contract.symbol] = contract.exchange
            symbol_name_map[contract.symbol] = contract.name

        if len(data) == 1000:
            position_str = d["position_str"]
            self.query_contract(position_str)
        else:
            self.gateway.write_log("合约信息查询成功")
            self.query_order()
Ejemplo n.º 2
0
    def OnRspQrySecurity(self, data: dict, error: dict, reqid: int,
                         last: bool) -> None:
        """
        Callback of instrument query.
        """
        if last:
            self.gateway.write_log("合约信息查询成功")
        if not data:
            return

        contract = ContractData(
            gateway_name=self.gateway.gateway_name,
            symbol=data["SecurityID"],
            exchange=EXCHANGE_TORA2VT[bytes.decode(data["ExchangeID"])],
            name=data["SecurityName"],
            product=PRODUCT_TORA2VT[bytes.decode(data["ProductID"])],
            size=data["VolumeMultiple"],
            pricetick=data["PriceTick"],
            min_volume=data["MinLimitOrderBuyVolume"],
            stop_supported=False,
            net_position=True,
            history_data=False,
        )

        contract.option_portfolio = data["UnderlyingSecurityID"] + "_O"
        contract.option_underlying = (data["UnderlyingSecurityID"] + "-" +
                                      str(data["LastDate"]))
        contract.option_type = OPTIONTYPE_TORA2VT[bytes.decode(
            data["OptionsType"])]

        contract.option_strike = data["StrikePrice"]
        contract.option_expiry = datetime.strptime(str(data["LastDate"]),
                                                   "%Y%m%d")
        contract.option_index = get_option_index(contract.option_strike,
                                                 data["ExchSecurityID"])

        self.gateway.on_contract(contract)
Ejemplo n.º 3
0
    def onQueryOptionAuctionInfo(self, data: dict, error: dict, reqid: int, last: bool, session: int) -> None:
        """"""
        if not data or not data["ticker"]:
            return

        contract = ContractData(
            symbol=data["ticker"],
            exchange=MARKET_XTP2VT[data["security_id_source"]],
            name=data["symbol"],
            product=Product.OPTION,
            size=data["contract_unit"],
            min_volume=data["qty_unit"],
            pricetick=data["price_tick"],
            gateway_name=self.gateway_name
        )

        contract.option_portfolio = data["underlying_security_id"] + "_O"
        contract.option_underlying = (
            data["underlying_security_id"]
            + "-"
            + str(data["delivery_month"])
        )
        contract.option_type = OPTIONTYPE_XTP2VT.get(data["call_or_put"], None)

        contract.option_strike = data["exercise_price"]
        contract.option_expiry = datetime.strptime(
            str(data["last_trade_date"]), "%Y%m%d"
        )
        contract.option_index = get_option_index(
            contract.option_strike, data["contract_id"]
        )

        self.gateway.on_contract(contract)
        symbol_pricetick_map[contract.vt_symbol] = contract.pricetick

        if last:
            self.gateway.write_log("期权信息查询成功")
Ejemplo n.º 4
0
    def on_query_contract(self, data: dict, request: Request) -> None:
        """"""
        for d in data["symbols"]:
            base_currency = d["baseAsset"]
            quote_currency = d["quoteAsset"]
            name = f"{base_currency.upper()}/{quote_currency.upper()}"

            pricetick = 1
            min_volume = 1
            symbol = d["symbol"]

            for f in d["filters"]:
                if f["filterType"] == "PRICE_FILTER":
                    pricetick = float(f["tickSize"])
                elif f["filterType"] == "LOT_SIZE":
                    min_volume = float(f["stepSize"])

            # 合约乘数
            symbol_size = 20  # 缺省为20倍的杠杆
            contract_info = self.contracts.get(symbol, {})
            if contract_info:
                symbol_size = int(contract_info.get('leverage', symbol_size))

            contract = ContractData(symbol=symbol,
                                    exchange=Exchange.BINANCE,
                                    name=name,
                                    pricetick=pricetick,
                                    size=symbol_size,
                                    min_volume=min_volume,
                                    margin_rate=1,
                                    product=Product.FUTURES,
                                    history_data=True,
                                    gateway_name=self.gateway_name,
                                    stop_supported=True)
            self.gateway.on_contract(contract)

            symbol_name_map[contract.symbol] = contract.name

        self.gateway.write_log("合约信息查询成功")
Ejemplo n.º 5
0
 def on_query_stock(
     self,
     session_info: SGeneralClientChannelT,
     head: SMsgHeadT,
     body: Any,
     cursor: OesQryCursorT,
 ):
     """"""
     data: OesStockBaseInfoT = caster.toOesStockItemT(body)
     contract = ContractData(
         gateway_name=self.gateway.gateway_name,
         symbol=data.securityId,
         exchange=EXCHANGE_OES2VT[data.mktId],
         name=data.securityName,
         product=PRODUCT_OES2VT[data.mktId],
         size=data.buyQtyUnit,
         min_volume=100,
         net_position=True,
         pricetick=data.priceUnit,
     )
     self.gateway.on_contract(contract)
     return 1
Ejemplo n.º 6
0
    def on_contract(self, d):
        """"""
        if "tickSize" not in d:
            return

        if not d["lotSize"]:
            return

        contract = ContractData(
            symbol=d["symbol"],
            exchange=Exchange.BITMEX,
            name=d["symbol"],
            product=Product.FUTURES,
            pricetick=d["tickSize"],
            size=d["lotSize"],
            stop_supported=True,
            net_position=True,
            history_data=True,
            gateway_name=self.gateway_name,
        )

        self.gateway.on_contract(contract)
Ejemplo n.º 7
0
    def onRspQryInstrument(self, data: dict, error: dict, reqid: int,
                           last: bool):
        """
        Callback of instrument query.
        """
        product = PRODUCT_CTP2VT.get(data["ProductClass"], None)
        if not product:
            return

        contract = ContractData(
            symbol=data["InstrumentID"],
            exchange=EXCHANGE_CTP2VT[data["ExchangeID"]],
            name=data["InstrumentName"],
            product=product,
            size=data["VolumeMultiple"],
            pricetick=data["PriceTick"],
            option_underlying=data["UnderlyingInstrID"],
            option_type=OPTIONTYPE_CTP2VT.get(data["OptionsType"], None),
            option_strike=data["StrikePrice"],
            option_expiry=datetime.strptime(data["ExpireDate"], "%Y%m%d"),
            gateway_name=self.gateway_name)

        self.gateway.on_contract(contract)

        symbol_exchange_map[contract.symbol] = contract.exchange
        symbol_name_map[contract.symbol] = contract.name
        symbol_size_map[contract.symbol] = contract.size

        if last:
            self.gateway.write_log("合约信息查询成功")

            for data in self.order_data:
                self.onRtnOrder(data)
            self.order_data.clear()

            for data in self.trade_data:
                self.onRtnTrade(data)
            self.trade_data.clear()
Ejemplo n.º 8
0
    def on_query_contract(self, data, request):  # type: (dict, Request)->None
        """"""
        for d in data:
            symbol = d["name"]
            self.symbols.append(symbol)

            contract = ContractData(symbol=symbol,
                                    exchange=Exchange.GATEIO,
                                    name=symbol,
                                    pricetick=float(d["order_price_round"]),
                                    size=int(d["leverage_min"]),
                                    min_volume=d["order_size_min"],
                                    product=Product.FUTURES,
                                    gateway_name=self.gateway_name,
                                    history_data=True)
            self.gateway.on_contract(contract)

        self.gateway.write_log("合约信息查询成功")

        # Connect websocket api after account id and contract symbols collected
        self.ws_api.connect(self.key, self.secret, self.server,
                            self.proxy_host, self.proxy_port, self.account_id,
                            self.symbols)
Ejemplo n.º 9
0
    def on_query_contract(self, data, request):
        """"""
        for instrument_data in data:
            symbol = instrument_data["instrument_id"]
            contract = ContractData(
                symbol=symbol,
                exchange=Exchange.OKEX,
                name=symbol,
                product=Product.SPOT,
                size=1,
                pricetick=float(instrument_data["tick_size"]),
                min_volume=float(instrument_data["min_size"]),
                gateway_name=self.gateway_name)
            self.gateway.on_contract(contract)

            instruments.add(instrument_data["instrument_id"])
            currencies.add(instrument_data["base_currency"])
            currencies.add(instrument_data["quote_currency"])

        self.gateway.write_log("合约信息查询成功")

        # Start websocket api after instruments data collected
        self.gateway.ws_api.start()
Ejemplo n.º 10
0
    def on_query_contract(self, data, request):
        """"""
        for symbol in data:
            priceScale = int(data[symbol]["priceScale"])
            amountScale = int(data[symbol]["amountScale"])
            contract = ContractData(
                symbol=symbol,
                exchange=Exchange.ZB,
                name=symbol,
                product=Product.SPOT,
                size=1,
                pricetick=round(0.1 ** priceScale, priceScale),
                min_volume=round(0.1 ** amountScale, amountScale),
                history_data=True,
                gateway_name=self.gateway_name
            )
            self.gateway.on_contract(contract)
            instruments.add(symbol)
            spot1, spot2 = symbol.split("_")
            currencies.add(spot1)
            currencies.add(spot2)

        self.gateway.write_log("ZB 现货信息查询成功")
Ejemplo n.º 11
0
    def query_contract(self) -> None:
        """"""
        mt5_req = {"type": FUNCTION_QUERYCONTRACT}
        mt5_rep = self.client.send_request(mt5_req)

        if mt5_rep:
            self.write_log("MT5连接成功")

        for d in mt5_rep["data"]:
            contract = ContractData(
                symbol=d["symbol"],
                exchange=Exchange.OTC,
                name=d["symbol"],
                product=Product.FOREX,
                size=d["lot_size"],
                pricetick=pow(10, -d["digits"]),
                min_volume=d["min_lot"],
                history_data=True,
                gateway_name=self.gateway_name,
            )
            self.on_contract(contract)

        self.write_log("合约信息查询成功")
Ejemplo n.º 12
0
 def get_position(self,
                  vt_symbol: str,
                  direction: Direction = Direction.NET,
                  gateway_name: str = ''):
     """
     查询合约在账号的持仓
     """
     if not gateway_name:
         gateway_name = self.gateway_name
     k = f'{gateway_name}.{vt_symbol}.{direction.value}'
     pos = self.positions.get(k, None)
     if not pos:
         contract = self.get_contract(vt_symbol)
         if not contract:
             self.write_log(f'{vt_symbol}合约信息不存在,构造一个')
             symbol, exchange = extract_vt_symbol(vt_symbol)
             if self.contract_type == 'future':
                 product = Product.FUTURES
             elif self.contract_type == 'stock':
                 product = Product.EQUITY
             else:
                 product = Product.SPOT
             contract = ContractData(
                 gateway_name=gateway_name,
                 name=vt_symbol,
                 product=product,
                 symbol=symbol,
                 exchange=exchange,
                 size=self.get_size(vt_symbol),
                 pricetick=self.get_price_tick(vt_symbol),
                 margin_rate=self.get_margin_rate(vt_symbol))
         pos = PositionData(gateway_name=gateway_name,
                            symbol=contract.symbol,
                            exchange=contract.exchange,
                            direction=direction)
         self.positions[k] = pos
     return pos
Ejemplo n.º 13
0
 def to_contract(self):
     """
     Generate ContractData object from DbContractData.
     """
     contract = ContractData(
         symbol=self.symbol,
         exchange=Exchange(self.exchange),
         name=self.name,
         product=Product(self.product),
         size=self.size,
         pricetick=self.pricetick,
         min_volume=self.min_volume,
         stop_supported=self.stop_supported,
         net_position=self.net_position,
         history_data=self.history_data,
         option_strike=self.option_strike,
         option_expiry=self.option_expiry,
         # option_type=OptionType(self.option_type),
         # 因为option_type没有值,会实例化失败,暂时to_contract过程中不实例化
         option_type=self.option_type,
         option_underlying=self.option_underlying,
         gateway_name="DB",
     )
     return contract
Ejemplo n.º 14
0
    def on_query_contract(self, data: dict, request: Request) -> None:
        """"""
        if self.check_error(data, "查询合约"):
            return

        for d in data["data"]:
            self.contract_codes.add(d["contract_code"])

            contract = ContractData(
                symbol=d["contract_code"],
                exchange=Exchange.HUOBI,
                name=d["contract_code"],
                pricetick=d["price_tick"],
                size=int(d["contract_size"]),
                min_volume=1,
                product=Product.FUTURES,
                history_data=True,
                gateway_name=self.gateway_name,
            )
            self.gateway.on_contract(contract)

        self.gateway.write_log("合约信息查询成功")

        self.query_order()
Ejemplo n.º 15
0
    def OnRspQrySecurity(self, data: dict, error: dict, reqid: int,
                         last: bool) -> None:
        """
        Callback of instrument query.
        """
        if last:
            self.gateway.write_log("合约信息查询成功")
        if not data:
            return

        contract_data = ContractData(
            gateway_name=self.gateway.gateway_name,
            symbol=data["SecurityID"],
            exchange=EXCHANGE_TORA2VT[bytes.decode(data["ExchangeID"])],
            name=data["SecurityName"],
            product=PRODUCT_TORA2VT[bytes.decode(data["ProductID"])],
            size=data["VolumeMultiple"],
            pricetick=data["PriceTick"],
            min_volume=data["MinLimitOrderBuyVolume"],
            stop_supported=False,
            net_position=True,
            history_data=False,
        )
        self.gateway.on_contract(contract_data)
Ejemplo n.º 16
0
    def OnQueryAllTickers(self, ticker_info: XTPQuoteStaticInfo,
                          error_info: XTPRspInfoStruct, is_last: bool) -> Any:
        """"""
        if self.check_error("查询合约", error_info):
            return

        contract = ContractData(
            symbol=ticker_info.ticker,
            exchange=EXCHANGE_XTP2VT[ticker_info.exchange_id],
            name=ticker_info.ticker_name,
            product=PRODUCT_XTP2VT[ticker_info.ticker_type],
            size=1,
            pricetick=ticker_info.price_tick,
            min_volume=ticker_info.buy_qty_unit,
            gateway_name=self.gateway_name)
        self.gateway.on_contract(contract)

        symbol_name_map[contract.vt_symbol] = contract.name

        if contract.product != Product.INDEX:
            symbol_exchange_map[contract.symbol] = contract.exchange

        if is_last:
            self.gateway.write_log(f"{contract.exchange.value}合约信息查询成功")
Ejemplo n.º 17
0
    def on_query_contract(self, data, request):
        """查询合约,这里是每次调用查询合约,要清空合约和货币"""

        instruments.clear()
        currencies.clear()

        for instrument_data in data:
            symbol = instrument_data["instrument_id"]
            contract = ContractData(
                symbol=symbol,
                exchange=Exchange.OKEXF,
                name=symbol,
                product=Product.FUTURES,
                size=int(instrument_data["trade_increment"]),
                pricetick=float(instrument_data["tick_size"]),
                gateway_name=self.gateway_name,
            )
            self.gateway.on_contract(contract)

            instruments.add(instrument_data["instrument_id"])
            currencies.add(instrument_data["underlying_index"])
            currencies.add(instrument_data["quote_currency"])

        self.gateway.write_log("合约信息查询成功")
Ejemplo n.º 18
0
    def onRspQryInstrument(self, data: dict, error: dict, reqid: int,
                           last: bool):
        """
        Callback of instrument query.
        """
        # Femas gateway provides no ProductClass data, so need to determine
        # product type using other logic.
        option_type = OPTIONTYPE_FEMAS2VT.get(data["OptionsType"], None)
        if option_type:
            product = Product.OPTION
        elif data["InstrumentID_2"]:
            product = Product.SPREAD
        else:
            product = Product.FUTURES

        contract = ContractData(symbol=data["InstrumentID"],
                                exchange=EXCHANGE_FEMAS2VT[data["ExchangeID"]],
                                name=data["InstrumentName"],
                                size=data["VolumeMultiple"],
                                pricetick=data["PriceTick"],
                                product=product,
                                gateway_name=self.gateway_name)

        if product == Product.OPTION:
            contract.option_underlying = data["UnderlyingInstrID"]
            contract.option_type = OPTIONTYPE_FEMAS2VT.get(
                data["OptionsType"], None)
            contract.option_strike = data["StrikePrice"]
            contract.option_expiry = datetime.strptime(data["ExpireDate"],
                                                       "%Y%m%d")

        self.gateway.on_contract(contract)

        symbol_exchange_map[contract.symbol] = contract.exchange
        symbol_name_map[contract.symbol] = contract.name
        symbol_size_map[contract.symbol] = contract.size

        if last:
            self.gateway.write_log("合约信息查询成功")
Ejemplo n.º 19
0
    def query_contract(self, securities_type=None):
        self.write_log(f"Download 商品檔 {securities_type} 完成")
        if securities_type == constant.SecurityType.Future:
            for category in self.api.Contracts.Futures:
                for contract in category:
                    data = ContractData(
                        symbol=contract.code,
                        exchange=Exchange.TFE,
                        name=contract.name + contract.delivery_month,
                        product=Product.FUTURES,
                        size=200,
                        pricetick=0.01,
                        stop_supported=False,
                        net_position=True,
                        min_volume=1,
                        gateway_name=self.gateway_name,
                    )
                    self.on_contract(data)
                    symbol = f"{contract.code}.{Exchange.TFE.value}"
                    self.code2contract[symbol] = contract
        if securities_type == constant.SecurityType.Option:
            for category in self.api.Contracts.Options:
                for contract in category:
                    data = ContractData(
                        symbol=contract.code,
                        exchange=Exchange.TFE,
                        name=f"{contract.name} {contract.delivery_month} {contract.strike_price}{contract.option_right}",
                        product=Product.OPTION,
                        size=50,
                        net_position=True,
                        pricetick=0.01,
                        min_volume=1,
                        gateway_name=self.gateway_name,
                        option_strike=contract.strike_price,
                        option_underlying=contract.underlying_code,
                        option_type=OptionType.CALL
                        if contract.option_right == constant.OptionRight.Call
                        else OptionType.PUT,
                        option_expiry=None,
                    )
                    self.on_contract(data)
                    symbol = f"{contract.code}.{Exchange.TFE.value}"
                    self.code2contract[symbol] = contract

        if securities_type == constant.SecurityType.Stock:
            for category in self.api.Contracts.Stocks:
                for contract in category:
                    pricetick = 5
                    if contract.limit_down < 10:
                        pricetick = 0.01
                    elif contract.limit_down < 50:
                        pricetick = 0.05
                    elif contract.limit_down < 100:
                        pricetick = 0.1
                    elif contract.limit_down < 500:
                        pricetick = 0.5
                    elif contract.limit_down < 1000:
                        pricetick = 1

                    data = ContractData(
                        symbol=contract.code,
                        exchange=Exchange.TSE,
                        name=f"{contract.name} (不可當沖)"
                        if contract.day_trade != constant.DayTrade.Yes
                        else contract.name,
                        product=Product.EQUITY,
                        size=1,
                        net_position=False,
                        pricetick=pricetick,
                        min_volume=1,
                        gateway_name=self.gateway_name,
                    )
                    self.on_contract(data)
                    symbol = f"{contract.code}.{Exchange.TSE.value}"
                    self.code2contract[symbol] = contract
Ejemplo n.º 20
0
    def query_contract(self):
        """"""
        # HK Stock

        symbols_names_HK = self.quote_client.get_symbol_names(
            lang=Language.zh_CN, market=Market.HK)
        contract_names_HK = DataFrame(symbols_names_HK,
                                      columns=["symbol", "name"])

        contractList = list(contract_names_HK["symbol"])
        i, n = 0, len(contractList)
        result = pd.DataFrame()
        while i < n:
            i += 50
            c = contractList[i - 50:i]
            r = self.quote_client.get_trade_metas(c)
            result = result.append(r)

        contract_detail_HK = result.sort_values(by="symbol", ascending=True)
        contract_HK = pd.merge(contract_names_HK,
                               contract_detail_HK,
                               how="left",
                               on="symbol")

        for ix, row in contract_HK.iterrows():
            contract = ContractData(
                symbol=row["symbol"],
                exchange=Exchange.SEHK,
                name=row["name"],
                product=Product.EQUITY,
                size=1,
                min_volume=row["lot_size"],
                pricetick=row["min_tick"],
                net_position=True,
                gateway_name=self.gateway_name,
            )
            self.on_contract(contract)
            self.contracts[contract.vt_symbol] = contract

        # US Stock
        symbols_names_US = self.quote_client.get_symbol_names(
            lang=Language.zh_CN, market=Market.US)
        contract_US = DataFrame(symbols_names_US, columns=["symbol", "name"])

        for ix, row in contract_US.iterrows():
            contract = ContractData(
                symbol=row["symbol"],
                exchange=Exchange.SMART,
                name=row["name"],
                product=Product.EQUITY,
                size=1,
                min_volume=100,
                pricetick=0.001,
                gateway_name=self.gateway_name,
            )
            self.on_contract(contract)
            self.contracts[contract.vt_symbol] = contract

        # CN Stock
        symbols_names_CN = self.quote_client.get_symbol_names(
            lang=Language.zh_CN, market=Market.CN)
        contract_CN = DataFrame(symbols_names_CN, columns=["symbol", "name"])

        for ix, row in contract_CN.iterrows():
            symbol = row["symbol"]
            symbol, exchange = convert_symbol_tiger2vt(symbol)

            contract = ContractData(
                symbol=symbol,
                exchange=exchange,
                name=row["name"],
                product=Product.EQUITY,
                size=1,
                min_volume=100,
                pricetick=0.001,
                gateway_name=self.gateway_name,
            )
            self.on_contract(contract)
            self.contracts[contract.vt_symbol] = contract
Ejemplo n.º 21
0
    def onRspQryInstrument(self, data: dict, error: dict, reqid: int,
                           last: bool):
        """
        Callback of instrument query.
        """
        product = PRODUCT_CTP2VT.get(data["ProductClass"], None)
        if product:
            contract = ContractData(
                symbol=data["InstrumentID"],
                exchange=EXCHANGE_CTP2VT[data["ExchangeID"]],
                name=data["InstrumentName"],
                product=product,
                size=data["VolumeMultiple"],
                pricetick=data["PriceTick"],  # 合约最小价格变动
                max_order_volume=data["MaxLimitOrderVolume"],  # 限价单次最大委托量
                gateway_name=self.gateway_name)

            #手续费数据合并到contract
            for symbol in self.commission_data.keys():
                if symbol == contract.symbol:
                    contract.open_commission_ratio = self.commission_data[
                        symbol]['OpenRatioByMoney']  #开仓手续费率
                    contract.open_commission = self.commission_data[symbol][
                        'OpenRatioByVolume']  #开仓手续费
                    contract.close_commission_ratio = self.commission_data[
                        symbol]['CloseRatioByMoney']  #平仓手续费率
                    contract.close_commission = self.commission_data[symbol][
                        'CloseRatioByVolume']  #平仓手续费
                    contract.close_commission_today_ratio = self.commission_data[
                        symbol]['CloseTodayRatioByMoney']  #平今手续费率
                    contract.close_commission_today = self.commission_data[
                        symbol]['CloseTodayRatioByVolume']  #平今手续费
                elif remain_alpha(symbol) == remain_alpha(contract.symbol):
                    contract.open_commission_ratio = self.commission_data[
                        symbol]['OpenRatioByMoney']  #开仓手续费率
                    contract.open_commission = self.commission_data[symbol][
                        'OpenRatioByVolume']  #开仓手续费
                    contract.close_commission_ratio = self.commission_data[
                        symbol]['CloseRatioByMoney']  #平仓手续费率
                    contract.close_commission = self.commission_data[symbol][
                        'CloseRatioByVolume']  #平仓手续费
                    contract.close_commission_today_ratio = self.commission_data[
                        symbol]['CloseTodayRatioByMoney']  #平今手续费率
                    contract.close_commission_today = self.commission_data[
                        symbol]['CloseTodayRatioByVolume']  #平今手续费

            #保证金数据合并到contract
            for symbol in self.margin_ratio_data.keys():
                if symbol == contract.symbol:
                    contract.margin_ratio = max(
                        self.margin_ratio_data[symbol]
                        ['LongMarginRatioByMoney'],
                        self.margin_ratio_data[symbol]
                        ['ShortMarginRatioByMoney'])  #合约保证金比率
                elif remain_alpha(symbol) == remain_alpha(contract.symbol):
                    contract.margin_ratio = max(
                        self.margin_ratio_data[symbol]
                        ['LongMarginRatioByMoney'],
                        self.margin_ratio_data[symbol]
                        ['ShortMarginRatioByMoney'])  #合约保证金比率

            # For option only
            if contract.product == Product.OPTION:
                # Remove C/P suffix of CZCE option product name
                if contract.exchange == Exchange.CZCE:
                    contract.option_portfolio = data["ProductID"][:-1]
                else:
                    contract.option_portfolio = data["ProductID"]

                contract.option_underlying = data["UnderlyingInstrID"]
                contract.option_type = OPTIONTYPE_CTP2VT.get(
                    data["OptionsType"], None)
                contract.option_strike = data["StrikePrice"]
                contract.option_index = str(data["StrikePrice"])
                contract.option_expiry = datetime.strptime(
                    data["ExpireDate"], "%Y%m%d")

            self.gateway.on_contract(contract)

            symbol_exchange_map[contract.symbol] = contract.exchange
            symbol_name_map[contract.symbol] = contract.name
            symbol_size_map[contract.symbol] = contract.size

        if last:
            self.contract_inited = True
            self.gateway.write_log("合约信息查询成功")

            for data in self.order_data:
                self.onRtnOrder(data)
            self.order_data.clear()

            for data in self.trade_data:
                self.onRtnTrade(data)
            self.trade_data.clear()
Ejemplo n.º 22
0
    "经纪商代码": "9999",
    "交易服务器": "180.168.146.187:10101",
    "行情服务器": "180.168.146.187:10111",
    "产品名称": "simnow_client_test",
    "授权编码": "0000000000000000",
    "产品信息": "11111"
}


def process_tick_event(event: Event):
    tick = event.data
    print(tick)
    print("--" * 40)


contract = ContractData(
    symbol="zn1910",
    exchange=Exchange("SHFE"),
    gateway_name="CTP",
    name="SHFE",
    product="SHFE",
    size=100,
    pricetick=2.0,
)

event_engine = EventEngine()
event_engine.register(EVENT_TICK, process_tick_event)  #注册事件
main_engine = MainEngine(event_engine)
main_engine.add_gateway(CtpGateway)
main_engine.connect(setting, "CTP")
main_engine.subscribe(contract, "CTP")  #订阅行情
Ejemplo n.º 23
0
    def query_contract(self):
        """"""
        self.write_log('开始查询合约信息')
        # HK Stock
        # 查询的速度太慢了, 注释掉了
        try:
            symbols_names_HK = self.quote_client.get_symbol_names(
                lang=Language.zh_CN, market=Market.HK)
            contract_names_HK = DataFrame(symbols_names_HK,
                                          columns=["symbol", "name"])

            contractList = list(contract_names_HK["symbol"])
            i, n = 0, len(contractList)
            result = DataFrame()
            while i < n:
                i += 50
                c = contractList[i - 50:i]
                r = self.quote_client.get_trade_metas(c)
                result = result.append(r)
                sleep(0.1)
        except:
            self.write_log('查询港股合约失败')

        contract_detail_HK = result.sort_values(by="symbol", ascending=True)
        contract_HK = merge(contract_names_HK,
                            contract_detail_HK,
                            how="left",
                            on="symbol")

        for ix, row in contract_HK.iterrows():
            contract = ContractData(
                symbol=row["symbol"],
                exchange=Exchange.SEHK,
                name=row["name"],
                product=Product.EQUITY,
                size=1,
                min_volume=row["lot_size"],
                pricetick=row["min_tick"],
                net_position=True,
                gateway_name=self.gateway_name,
            )
            self.on_contract(contract)
            self.contracts[contract.vt_symbol] = contract
            self.vt_tiger_symbol_map.update({
                contract.symbol:
                (Exchange.SEHK, stock_contract(contract.symbol,
                                               currency='HKD'))
            })

        # US Stock
        symbols_names_US = self.quote_client.get_symbol_names(
            lang=Language.zh_CN, market=Market.US)
        contract_US = DataFrame(symbols_names_US, columns=["symbol", "name"])

        for ix, row in contract_US.iterrows():
            contract = ContractData(
                symbol=row["symbol"],
                exchange=Exchange.SMART,
                name=row["name"],
                product=Product.EQUITY,
                size=1,
                min_volume=1,
                pricetick=0.001,
                gateway_name=self.gateway_name,
            )
            self.on_contract(contract)
            self.vt_tiger_symbol_map.update({
                contract.symbol:
                (Exchange.SMART, stock_contract(contract.symbol,
                                                currency='USD'))
            })
            self.contracts[contract.vt_symbol] = contract
        self.write_log('初始化美股合约完成')

        # Future contracts
        exchanges = self.quote_client.get_future_exchanges(
            sec_type=SecurityType.FUT, lang=Language.zh_CN)
        exchanges_list = exchanges['code']
        contract_futures = DataFrame()
        for e in exchanges_list:
            exchange_contract = self.quote_client.get_future_contracts(
                e, lang=Language.zh_CN)
            if len(exchange_contract) != 0:
                contract_futures = contract_futures.append(exchange_contract)

        for ix, row in contract_futures.iterrows():
            contract = ContractData(
                # symbol 用于查询存储数据 NQ1909
                symbol=row.loc['contract_code'],
                exchange=config_future_exchange(row.loc['exchange']),
                name=row.loc['name'],
                product=Product.FUTURES,
                size=1,
                min_volume=1,
                pricetick=0.001,
                gateway_name=self.gateway_name)
            self.on_contract(contract)
            self.vt_tiger_symbol_map.update({
                contract.symbol: (contract.exchange,
                                  future_contract(
                                      symbol=row.type,
                                      currency=row.currency,
                                      expiry=row.last_trading_date,
                                      exchange=row.exchange,
                                      multiplier=row.multiplier,
                                  ))
            })
            self.contracts[contract.vt_symbol] = contract
        self.write_log('初始化期货合约完成')
Ejemplo n.º 24
0
    def query_contract(self):
        """
        请求所有的合约(现货)
        :return: 
        """
        data = self.gateway.load_markets()
        for key in data:
            instrument_data = data[key]
            symbol = instrument_data["symbol"]
            # 判断是否为
            product = None
            contract = None
            if instrument_data["futures"]:
                # 交割
                contract = ContractData(
                    symbol=symbol,
                    exchange=Exchange.OKEX,
                    name=symbol,
                    product=product,
                    size=int(instrument_data["info"]["trade_increment"]),
                    pricetick=float(instrument_data["info"]["tick_size"]),
                    history_data=True,
                    gateway_name=self.gateway_name,
                )
            elif instrument_data["spot"]:
                # 现货
                product = Product.SPOT
                contract = ContractData(
                    symbol=symbol,
                    exchange=Exchange.OKEX,
                    name=symbol,
                    product=product,
                    size=1,
                    pricetick=float(instrument_data["info"]["tick_size"]),
                    min_volume=float(instrument_data["info"]["min_size"]),
                    history_data=True,
                    gateway_name=self.gateway_name)
            elif instrument_data["swap"]:
                # 永续合约
                product = Product.FUTURES
                contract = ContractData(
                    symbol=symbol,
                    exchange=Exchange.OKEX,
                    name=symbol,
                    product=product,
                    size=int(instrument_data["info"]["size_increment"]),
                    pricetick=float(instrument_data["info"]["tick_size"]),
                    history_data=True,
                    gateway_name=self.gateway_name,
                )
            else:
                self.gateway.write_log(f"未知交易对{symbol}")
                return None

            # 获取所有的交易对
            instruments.add(symbol)
            # 获取所有的产品(BTC, USDT, EOS, USD, ……)
            currencies.add(instrument_data["base"])
            currencies.add(instrument_data["quote"])
            self.on_contract(contract)

        self.write_log("合约(现货)信息查询成功")