Exemple #1
0
    def _is_opened(self, wait_start_timestamp: int) -> bool:
        conn = Conn(self["db_name"])
        if self["trade_type"] == TRADE_TYPE_FUTURE:
            opened = conn.query(
                "SELECT id FROM future_instance_{mode} WHERE symbol = ? AND exchange = ? AND contract_type = ?"
                " AND strategy = ? AND wait_start_timestamp = ? AND status > ?".format(
                    mode=MODE_BACKTEST if self["mode"] == MODE_BACKTEST else MODE_STRATEGY,
                ),
                (
                    self["symbol"], self["exchange"], self["contract_type"], self["strategy"],
                    wait_start_timestamp, INSTANCE_STATUS_WAITING,
                ),
            )
            return len(opened) > 0

        opened = conn.query(
            "SELECT id FROM {trade_type}_instance_{mode} WHERE symbol = ? AND exchange = ? AND strategy = ? "
            "AND wait_start_timestamp = ? AND status > ?".format(
                trade_type=self["trade_type"],
                mode=MODE_BACKTEST if self["mode"] == MODE_BACKTEST else MODE_STRATEGY,
            ),
            (
                self["symbol"], self["exchange"], self["strategy"],
                wait_start_timestamp, INSTANCE_STATUS_WAITING,
            ),
        )
        return len(opened) > 0
Exemple #2
0
    def _get_waiting_instance_id(self) -> int:
        query_sql = """
        SELECT id FROM {trade_type}_instance_strategy WHERE symbol = ? AND exchange = ? AND strategy = ?
        AND status = ? AND wait_start_timestamp = ? ORDER BY id DESC LIMIT 1
        """
        params = (
            self["symbol"], self["exchange"], self["strategy"],
            INSTANCE_STATUS_WAITING, 0,
        )

        if self["trade_type"] == TRADE_TYPE_FUTURE:
            query_sql = """
            SELECT id FROM {trade_type}_instance_strategy WHERE symbol = ? AND exchange = ? 
            AND contract_type = ? AND strategy = ? AND status = ? AND wait_start_timestamp = ? ORDER BY id DESC LIMIT 1
            """
            params = (
                self["symbol"], self["exchange"], self["contract_type"],
                self["strategy"], INSTANCE_STATUS_WAITING, 0,
            )

        conn = Conn(self["db_name"])
        one = conn.query_one(
            query_sql.format(trade_type=self["trade_type"]),
            params,
        )
        return one["id"] if one else 0
Exemple #3
0
    def load_from_db(self, instance_id):
        conn = Conn(self["db_name"])
        tmp_instance = conn.query_one(
            "SELECT * FROM {trade_type}_instance_{mode} WHERE id = ?".format(
                trade_type=self["trade_type"],
                mode=MODE_BACKTEST if self["mode"] == MODE_BACKTEST else MODE_STRATEGY,
            ),
            (instance_id,),
        )

        if tmp_instance is None:
            raise RuntimeError("the instance is None. ")

        self["id"] = tmp_instance["id"]
        self["status"] = tmp_instance["status"]
        self["unit_amount"] = tmp_instance.get("unit_amount") or 1

        self["asset_total"] = tmp_instance["asset_total"]
        self["asset_freeze"] = tmp_instance["asset_freeze"]

        self["param_position"] = tmp_instance["param_position"]
        self["param_max_abs_loss_ratio"] = tmp_instance["param_max_abs_loss_ratio"]

        self["wait_start_timestamp"] = tmp_instance["wait_start_timestamp"]
        self["wait_start_datetime"] = tmp_instance["wait_start_datetime"]
        self["wait_finish_timestamp"] = tmp_instance["wait_finish_timestamp"]
        self["wait_finish_datetime"] = tmp_instance["wait_finish_datetime"]

        self["open_times"] = tmp_instance["open_times"]
        self["open_start_timestamp"] = tmp_instance["open_start_timestamp"]
        self["open_start_datetime"] = tmp_instance["open_start_datetime"]
        self["open_finish_timestamp"] = tmp_instance["open_finish_timestamp"]
        self["open_finish_datetime"] = tmp_instance["open_finish_datetime"]
        self["open_expired_timestamp"] = tmp_instance["open_expired_timestamp"]
        self["open_expired_datetime"] = tmp_instance["open_expired_datetime"]

        self["liquidate_times"] = tmp_instance["liquidate_times"]
        self["liquidate_start_timestamp"] = tmp_instance["liquidate_start_timestamp"]
        self["liquidate_start_datetime"] = tmp_instance["liquidate_start_datetime"]
        self["liquidate_finish_timestamp"] = tmp_instance["liquidate_finish_timestamp"]
        self["liquidate_finish_datetime"] = tmp_instance["liquidate_finish_datetime"]

        param = Param(
            {},
            trade_type=self["trade_type"],
            db_name=self["db_name"],
            mode=self["mode"],
        )
        param.load(instance_id)
        self["param"] = param

        indices = Indices(
            {},
            trade_type=self["trade_type"],
            db_name=self["db_name"],
            mode=self["mode"],
        )
        indices.load(instance_id)
        self["indices"] = indices
Exemple #4
0
 def _value_by_id(self, signal_id: int, timestamp: int):
     conn = Conn(self._db_name)
     dataset = conn.query_one(
         "SELECT * FROM signal_dataset WHERE signal_id = ? AND start_timestamp <= ? AND finish_timestamp > ?"
         " ORDER BY start_timestamp DESC LIMIT 1",
         (signal_id, timestamp, timestamp),
     )
     return dataset
Exemple #5
0
    def _values_by_id(self, fact_id: int, start_timestamp: int, finish_timestamp: int) -> List[float]:
        conn = Conn(self._db_name)
        fact_values = conn.query(
            "SELECT factor_value FROM factor_dataset"
            " WHERE factor_id = ? AND timestamp >= ? AND timestamp <= ? ORDER BY timestamp",
            (fact_id, start_timestamp, finish_timestamp),
        )

        return [f["factor_value"] for f in fact_values]
Exemple #6
0
    def _get_previous_instances(self, start_timestamp=0, finish_timestamp=0):
        if start_timestamp == 0:
            raise RuntimeError("start_timestamp must bigger than 0. ")

        if finish_timestamp == 0:
            finish_timestamp = moment.now().millisecond_timestamp

        conn = Conn(self["db_name"])
        table_name = "{trade_type}_instance_{mode}".format(
            trade_type=self["trade_type"],
            mode=MODE_BACKTEST if self["mode"] == MODE_BACKTEST else MODE_STRATEGY,
        )

        if self["trade_type"] == TRADE_TYPE_FUTURE:
            query_sql = """
            SELECT * FROM {} WHERE symbol = ? AND exchange = ? AND contract_type = ? AND strategy = ?
             AND wait_start_timestamp >= ? AND wait_start_timestamp < ? AND status != ? ORDER BY wait_start_timestamp
            """.format(table_name)
            query_param = (
                self["symbol"], self["exchange"], self["contract_type"], self["strategy"],
                start_timestamp, finish_timestamp, INSTANCE_STATUS_WAITING,
            )

            if self["mode"] == MODE_BACKTEST:
                query_sql = """
                        SELECT * FROM {} WHERE symbol = ? AND exchange = ? AND contract_type = ?
                        AND strategy = ? AND wait_start_timestamp >= ? AND wait_start_timestamp < ?
                        AND backtest_id = ? AND status != ? ORDER BY wait_start_timestamp
                """.format(table_name)

                query_param = (
                    self["symbol"], self["exchange"], self["contract_type"], self["strategy"],
                    start_timestamp, finish_timestamp, self["backtest_id"], INSTANCE_STATUS_WAITING,
                )
        else:
            query_sql = """
            SELECT * FROM {} WHERE symbol = ? AND exchange = ? AND strategy = ?
            AND wait_start_timestamp >= ? AND wait_start_timestamp < ? AND status != ?
            ORDER BY wait_start_timestamp 
            """.format(table_name)
            query_param = (
                self["symbol"], self["exchange"], self["strategy"],
                start_timestamp, finish_timestamp, INSTANCE_STATUS_WAITING,
            )

            if self["mode"] == MODE_BACKTEST:
                query_sql = """
                SELECT * FROM {} WHERE symbol = ? AND exchange = ? AND strategy = ?
                AND wait_start_timestamp >= ? AND wait_start_timestamp < ?
                AND backtest_id = ? AND status != ? ORDER BY wait_start_timestamp 
                """.format(table_name)
                query_param = (
                    self["symbol"], self["exchange"], self["strategy"],
                    start_timestamp, finish_timestamp, self["backtest_id"], INSTANCE_STATUS_WAITING,
                )
        return conn.query(query_sql, query_param)
Exemple #7
0
 def previous_signals(self, signal_name: str, timestamp: int) -> List[dict]:
     meta = self.get_metadata(signal_name)
     signal_id = meta["signal_id"]
     conn = Conn(self._db_name)
     dataset = conn.query(
         "SELECT * FROM signal_dataset WHERE signal_id = ? AND finish_timestamp < ?"
         " ORDER BY finish_timestamp DESC LIMIT 5",
         (signal_id, timestamp),
     )
     return dataset
Exemple #8
0
    def _value_by_id(self, fact_id: int, timestamp: int) -> float:
        conn = Conn(self._db_name)
        fact_data = conn.query_one(
            "SELECT factor_value FROM factor_dataset"
            " WHERE factor_id = ? AND timestamp <= ? ORDER BY timestamp DESC LIMIT 1",
            (fact_id, timestamp),
        )

        if fact_data is None:
            raise RuntimeError("Can not find the factor value, there have no value in database. ")
        return fact_data["factor_value"]
Exemple #9
0
    def in_signal(self, signal_name: str, timestamp: int) -> bool:
        meta = self.get_metadata(signal_name)
        signal_id = meta["signal_id"]

        conn = Conn(self._db_name)
        dataset = conn.query_one(
            "SELECT * FROM signal_dataset WHERE signal_id = ? AND start_timestamp >= ? AND finish_timestamp < ?"
            " ORDER BY start_timestamp DESC LIMIT 1",
            (signal_id, timestamp, timestamp),
        )
        return not (dataset is None)
Exemple #10
0
 def get_metadata(self, signal_name: str) -> dict:
     conn = Conn(self._db_name)
     metadata = conn.query_one(
         "SELECT * FROM signal_metadata"
         " WHERE symbol = ? AND exchange = ? AND trade_type = ? AND contract_type = ? AND signal_name = ? ",
         (self._symbol, self._exchange, self._trade_type,
          self._contract_type, signal_name),
     )
     if metadata is None:
         raise RuntimeError("Can not find the meta in database. ")
     return metadata
Exemple #11
0
 def _get_orders(self) -> List:
     conn = Conn(self["db_name"])
     orders = conn.query(
         "SELECT * FROM {trade_type}_order_{mode} WHERE instance_id = ?"
         " ORDER BY sequence".format(
             trade_type=self["trade_type"],
             mode=MODE_BACKTEST if self["mode"] == MODE_BACKTEST else MODE_STRATEGY,
         ),
         (self["id"])
     )
     return orders
Exemple #12
0
    def __init__(self, kw):
        super().__init__(kw)
        validate(instance=kw, schema=strategy_input)
        # 初始化各个组件

        self["asset"] = Asset(
            trade_type=self.get("trade_type"),
            symbol=self.get("symbol"),
            exchange=self.get("exchange"),
            db_name=self.get("db_name_asset") or self.get("db_name"),
            mode=self.get("mode"),
            settle_mode=self.get("settle_mode") or SETTLE_MODE_BASIS,
            backtest_id=self.get("backtest_id"),
        )

        self["indices"] = Indices(
            self.get("indices") or {},
            mode=self.get("mode"),
            trade_type=self.get("trade_type"),
            db_name=self.get("db_name"),
        )
        self["param"] = Param(
            self["param"],
            db_name=self.get("db_name_param") or self.get("db_name"),
            mode=self.get("mode"),
            trade_type=self.get("trade_type"),
        )

        instance_id = kw.get("id")
        if instance_id is not None:
            conn = Conn(self["db_name"])
            instance = conn.query_one(
                "SELECT * FROM {trade_type}_instance_{mode} WHERE id = ?".format(
                    trade_type=self["trade_type"],
                    mode=MODE_BACKTEST if self["mode"] == MODE_BACKTEST else MODE_STRATEGY,
                ),
                (instance_id,),
            )

            self["strategy"] = instance["strategy"]
            self["interval"] = instance["interval"]
            self["unit_amount"] = instance["unit_amount"]
            self["param"] = self["param"].load(instance_id)
            self["indices"] = self["indices"].load(instance_id)

            if self["trade_type"] == TRADE_TYPE_FUTURE:
                self["lever"] = instance["lever"]
                self["status"] = instance["status"]
Exemple #13
0
    def get_spot_value(self, factor_name: str, timestamp: int):
        symbol = self._symbol
        currencies = symbol.split("_")
        if currencies[-1] in ("usdt", "usdc", "busd"):
            symbol = currencies[0] + "_usd"

        conn = Conn(self._db_name)
        meta = conn.query_one(
            "SELECT * FROM factor_metadata"
            " WHERE symbol = ? AND trade_type = ? AND contract_type = ?"
            " AND `interval` = ? AND factor_name = ? ",
            (symbol, TRADE_TYPE_SPOT, CONTRACT_TYPE_NONE, self._interval, factor_name),
        )
        if meta is None:
            return None
        return self._value_by_id(meta["factor_id"], timestamp)
Exemple #14
0
    def _get_risk_level(self, timestamp: int, instance_id: int) -> int:
        conn = Conn(self["db_name"])
        table_name = "{trade_type}_instance_{mode}".format(
            trade_type=self["trade_type"],
            mode=MODE_BACKTEST if self["mode"] == MODE_BACKTEST else MODE_STRATEGY,
        )

        m = moment.get(timestamp).to(self.get("timezone") or "Asia/Shanghai").floor("day")
        query_sql = """
        SELECT id FROM {} WHERE symbol = ? AND exchange = ? AND strategy = ? 
        AND (status IN (?, ?, ?) OR ( status = ? AND liquidate_finish_timestamp > ? )) ORDER BY open_start_timestamp, id
        """
        params = (
            self["symbol"], self["exchange"], self["strategy"],
            INSTANCE_STATUS_OPENING, INSTANCE_STATUS_LIQUIDATING, INSTANCE_STATUS_ERROR,
            INSTANCE_STATUS_FINISHED, m.millisecond_timestamp,
        )

        if self["mode"] == MODE_BACKTEST:
            query_sql = """
            SELECT id FROM {} WHERE backtest_id = ? AND symbol = ? AND exchange = ?
             AND strategy = ? AND open_start_timestamp < ? AND (liquidate_finish_timestamp > ? OR status in (?,?)) 
             ORDER BY open_start_timestamp, id
            """
            params = (
                self["backtest_id"],
                self["symbol"],
                self["exchange"],
                self["strategy"],
                timestamp,
                timestamp,
                INSTANCE_STATUS_OPENING,
                INSTANCE_STATUS_LIQUIDATING,
            )
        instances = conn.query(
            query_sql.format(table_name),
            params,
        )

        instance_ids = [i["id"] for i in instances]
        risk_level = len(instance_ids)
        if instance_id in instance_ids:
            risk_level = instance_ids.index(instance_id)
        return risk_level
Exemple #15
0
    def _values_by_sequence(
            self,
            fact_id: int,
            start_timestamp: int,
            finish_timestamp: int,
            limit: int,
            is_desc: bool,
    ) -> List[float]:
        conn = Conn(self._db_name)
        fact_values = conn.query(
            "SELECT factor_value FROM factor_dataset"
            " WHERE factor_id = ? AND timestamp >= ? AND timestamp <= ? ORDER BY factor_value {} LIMIT {}".format(
                "DESC" if is_desc else "",
                limit,
            ),
            (fact_id, start_timestamp, finish_timestamp),
        )

        return [f["factor_value"] for f in fact_values]