Exemplo n.º 1
0
 def on_tick(self, tick: TickData) -> None:
     tick.datetime = str(tick.datetime)
     data = {
         "type": "tick",
         "data": tick._to_dict()
     }
     self.io.emit("tick", data)
Exemplo n.º 2
0
 def on_tick(self, tick: TickData) -> None:
     tick.datetime = str(tick.datetime)
     data = {"type": "tick", "data": tick._to_dict()}
     self.io.emit("tick", data)
     data = {
         "type": "position",
         "data": self.app.recorder.get_all_positions()
     }
     self.io.emit("position", data)
Exemplo n.º 3
0
    def on_tick(self, tick: TickData) -> None:
        self.local_status.setdefault(tick.local_symbol, False)
        self.global_bar.setdefault(tick.local_symbol, [])

        tick.datetime = str(tick.datetime)
        data = {"type": "tick", "data": tick._to_dict()}
        self.io.emit("tick", data)
        data = {
            "type": "position",
            "data": self.app.recorder.get_all_positions()
        }
        self.io.emit("position", data)
        if not self.local_status.get(tick.local_symbol):
            try:
                with open(
                        f"{os.path.dirname(__file__)}/static/json/{tick.symbol}.json",
                        "r") as f:
                    from json import load
                    st = True
                    try:
                        data = load(f)
                    except JSONDecodeError:
                        st = False
                    if data.get("data") is not None and st:
                        klines = data.get("data").get("lines")
                        assert type(klines) == list
                        if len(klines) != 0:
                            self.global_bar.get(
                                tick.local_symbol).extend(klines)
            except FileNotFoundError:
                pass
            self.local_status[tick.local_symbol] = True

        with open(
                f"{os.path.dirname(__file__)}/static/json/{tick.symbol}.json",
                "w") as f:
            from json import dump
            update_result = {
                "success": True,
                "data": {
                    "lines": self.global_bar.get(tick.local_symbol),
                    "depths": {
                        "asks": [[tick.ask_price_1, tick.ask_volume_1]],
                        "bids": [[tick.bid_price_1, tick.bid_volume_1]]
                    }
                }
            }
            f.truncate(0)
            dump(update_result, f)

        self.io.emit("update_all", update_result)
Exemplo n.º 4
0
    def __call__(self, data):
        """
        你必须实现此方法以支持在此层进行中转
        """
        if data.local_symbol not in self.instrument_set:
            return
        if not self.active:
            return

        if isinstance(data, ContractData):
            self.on_contract(data)
        elif isinstance(data, OrderData):
            self.on_order(data)
        elif isinstance(data, TradeData):
            self.on_trade(data)
        elif isinstance(data, AccountData):
            self.on_account(data)
        elif isinstance(data, PositionData):
            self.on_position(data)
        elif data['type'] == "bar":
            self.on_bar(BarData(**data))
        elif data['type'] == "tick":
            self.on_tick(TickData(**data))
        else:
            raise ValueError("unsupported data")
Exemplo n.º 5
0
 def close_position(self):
     """平仓"""
     row = self.position_table.currentRow()
     symbol = self.position_table.item(
         row, position_table_column.index('symbol')).text().split(".")[0]
     exchange = self.position_table.item(
         row, position_table_column.index('exchange')).text()
     direction = self.position_table.item(
         row, position_table_column.index('direction')).text()
     price_type = OrderType.LIMIT if self.price_type.currentText(
     ) == "限价" else OrderType.MARKET
     price = eval(self.price.text())
     volume = self.volume.text()
     tick = TickData(symbol=symbol, exchange=exchange_map[exchange])
     try:
         if direction == "long":
             self.bee_ext.app.action.cover(price=float(price),
                                           volume=float(volume),
                                           origin=tick,
                                           price_type=price_type)
         elif direction == "short":
             self.bee_ext.app.action.sell(price=float(price),
                                          volume=float(volume),
                                          origin=tick,
                                          price_type=price_type)
     except Exception as e:
         QMessageBox().warning(self, "提示", "平仓请求发送失败" + str(e),
                               QMessageBox.Ok, QMessageBox.Ok)
Exemplo n.º 6
0
 def close_position(self):
     """平仓"""
     row = self.position_table.currentRow()
     symbol = self.position_table.item(
         row, position_table_column.index('symbol')).text()
     direction = self.position_table.item(
         row, position_table_column.index('direction')).text()
     exchange = self.position_table.item(
         row, position_table_column.index('exchange')).text()
     volume = self.position_table.item(
         row, position_table_column.index('volume')).text()
     local_symbol = symbol + '.' + exchange
     tick = TickData(symbol=symbol, exchange=exchange_map[exchange])
     try:
         price = self.bee_ext.app.recorder.get_tick(local_symbol).last_price
     except AttributeError:
         TipDialog("未订阅此合约行情")
     else:
         try:
             if direction == "long":
                 self.bee_ext.app.action.cover(price=float(price),
                                               volume=float(volume),
                                               origin=tick)
             if direction == "short":
                 self.bee_ext.app.action.sell(price=float(price),
                                              volume=float(volume),
                                              origin=tick)
             TipDialog("平仓请求发送成功")
         except Exception as e:
             print(e)
             QMessageBox().warning(self, "提示", "平仓请求发送失败" + str(e),
                                   QMessageBox.Ok, QMessageBox.Ok)
Exemplo n.º 7
0
 def post(self):
     req_info = request.values.to_dict()
     local_symbol = req_info.get("local_symbol")
     volume = int(req_info.get("volume"))
     direction = req_info.get("direction")
     exchange = req_info.get("exchange")
     symbol = req_info.get("symbol")
     tick = TickData(symbol=symbol, exchange=self.exchange_map[exchange])
     price = bee_current_app.recorder.get_tick(local_symbol).last_price
     try:
         if direction == "long":
             bee_current_app.action.cover(price=price,
                                          volume=volume,
                                          origin=tick)
         if direction == "short":
             bee_current_app.action.sell(price=price,
                                         volume=volume,
                                         origin=tick)
         return true_response(msg="平仓请求发送成功")
     except Exception:
         return false_response(msg="平仓请求发送失败")
Exemplo n.º 8
0
    def onRtnDepthMarketData(self, data: dict):
        """
        Callback of tick data update.
        """
        symbol = data["InstrumentID"]
        exchange = symbol_exchange_map.get(symbol, "")
        if not exchange:
            return

        timestamp = f"{data['ActionDay']} {data['UpdateTime']}.{int(data['UpdateMillisec'] / 100)}"
        try:
            datetimed = datetime.strptime(timestamp, "%Y%m%d %H:%M:%S.%f")
        except ValueError as e:
            datetimed = datetime.strptime(str(date.today()) + " " + timestamp, "%Y-%m-%d %H:%M:%S.%f")

        tick = TickData(
            symbol=symbol,
            exchange=exchange,
            datetime=datetimed,
            name=symbol_name_map[symbol],
            volume=data["Volume"],
            last_price=data["LastPrice"],
            limit_up=data["UpperLimitPrice"],
            limit_down=data["LowerLimitPrice"],
            open_interest=data['OpenInterest'],
            open_price=data["OpenPrice"],
            high_price=data["HighestPrice"],
            low_price=data["LowestPrice"],
            pre_close=data["PreClosePrice"],
            bid_price_1=data["BidPrice1"],
            ask_price_1=data["AskPrice1"],
            bid_volume_1=data["BidVolume1"],
            ask_volume_1=data["AskVolume1"],
            average_price=data['AveragePrice'],
            pre_settlement_price=data['PreSettlementPrice'],
            gateway_name=self.gateway_name
        )
        self.on_event(type=EVENT_TICK, data=tick)
Exemplo n.º 9
0
    def __call__(self, *args, **kwargs):
        """ 回测周期 """
        entity = args[0]
        # 日期不相等时, 更新前日结算价格
        if self.account.date is None:
            self.account.date = self.date
        if self.date is None:
            self.date = entity.datetime.date()
        if not self.auth_time(entity.datetime):
            return
        self.data_type = entity.type
        # 回测的时候自动更新策略的日期
        try:
            seconds = (entity.datetime - self.datetime).seconds
            if seconds >= 60 * 60 * 4 and (entity.datetime.hour >= 21 or (
                (14 <= self.datetime.hour <= 15)
                    and entity.datetime.date() != self.datetime.date())):
                self.account.settle(entity.datetime.date())
                # 针对于账户的实现 我们需要将昨仓转换为今仓
                self.app.recorder.position_manager.covert_to_yesterday_holding(
                )
                for local_symbol, price in self.price_mapping.items():
                    self.pre_close_price[local_symbol] = price
                #  结算完触发初始化函数
                self.on_event(EVENT_INIT_FINISHED, True)
        except KeyError:
            pass
        except AttributeError:
            pass
        self.data_entity = entity
        self.change_month_record["".join(
            filter(str.isalpha,
                   entity.local_symbol.split(".")[0]))] = entity
        # 维护一个最新的价格
        self.price_mapping[self.data_entity.local_symbol] = self.data_entity.close_price if entity.type == "bar" \
            else self.data_entity.last_price
        if self.pre_close_price.get(self.data_entity.local_symbol) is None:
            self.pre_close_price[
                self.data_entity.
                local_symbol] = self.data_entity.last_price if entity.type == "tick" else self.data_entity.close_price
        self.datetime = entity.datetime
        self.match_deal()

        if entity.type == "tick":
            self.account.position_manager.update_tick(
                self.data_entity,
                self.pre_close_price[self.data_entity.local_symbol])
            self.app.recorder.position_manager.update_tick(
                self.data_entity,
                self.pre_close_price[self.data_entity.local_symbol])
            self.on_event(EVENT_TICK, TickData(**entity))

        if entity.type == "bar":
            self.account.position_manager.update_bar(
                self.data_entity,
                self.pre_close_price[self.data_entity.local_symbol])
            self.app.recorder.position_manager.update_bar(
                self.data_entity,
                self.pre_close_price[self.data_entity.local_symbol])
            self.on_event(EVENT_BAR, BarData(**entity))

        if entity.datetime.hour >= 21:
            """if hour > 21, switch to next trade day"""
            index = trade_dates.index(str(entity.datetime.date()))
            self.date = datetime.strptime(trade_dates[index + 1],
                                          "%Y-%m-%d").date()
        else:
            if str(entity.datetime.date()) not in trade_dates:
                last_day = entity.datetime + timedelta(days=-1)
                self.date = datetime.strptime(
                    trade_dates[trade_dates.index(str(last_day.date())) + 1],
                    "%Y-%m-%d").date()
            else:
                self.date = entity.datetime.date()
        # 穿过接口日期检查
        self.account.via_aisle()