Exemple #1
0
    def save(self, instance_id):
        if self._mode != MODE_BACKTEST:
            raise RuntimeError("You only can save data in backtest mode")
        # 入库前保证属性没有被篡改
        validate(instance=self, schema=indices_input)

        for name in self:
            if isinstance(self[name], int):
                sql_param = (PARAM_TYPE_INTEGER, str(self[name]), instance_id, name)
            elif isinstance(self[name], float):
                sql_param = (PARAM_TYPE_FLOAT, str(self[name]), instance_id, name)
            else:
                sql_param = (PARAM_TYPE_STRING, self[name], instance_id, name)

            conn = Conn(self._db_name)
            one = conn.query_one(
                "SELECT * FROM {} WHERE instance_id = ? AND indices_name = ?".format(self._table_name),
                (instance_id, name)
            )
            if one:
                conn.execute(
                    "UPDATE {} SET indices_type = ?, indices_value = ?"
                    " WHERE instance_id = ? AND indices_name = ?".format(self._table_name),
                    sql_param,
                )
            else:
                conn.insert(
                    "INSERT INTO {} (indices_type, indices_value, instance_id, indices_name)"
                    " VALUES (?, ?, ?, ?)".format(self._table_name),
                    sql_param,
                )
Exemple #2
0
    def __insert_asset_item(self, timestamp, datetime):
        position_total, asset_total = self.__calculate_total(timestamp)
        position_freeze, asset_freeze = self.__calculate_freeze(timestamp)
        position_sub, asset_sub = self.__calculate_sub(timestamp)

        conn = Conn(self._db_name)
        one = conn.query_one(
            """SELECT * FROM {} WHERE exchange = ? AND settle_mode = ? AND settle_currency = ? 
            AND timestamp = ? AND backtest_id = ?""".format(
                self._asset_table_name),
            (self._exchange, self._settle_mode, self._settle_currency,
             timestamp, self._backtest_id))
        if one:
            conn.execute(
                """
                UPDATE {} SET asset_total = ?, asset_sub = ?, asset_freeze = ?, 
                position_total = ?, position_sub = ?, position_freeze = ? WHERE id = ? 
                """.format(self._asset_table_name),
                (
                    asset_total,
                    asset_sub,
                    asset_freeze,
                    position_total,
                    position_sub,
                    position_freeze,
                    one["id"],
                ),
            )
        else:
            conn.insert(
                """
                INSERT INTO {} (exchange, settle_mode, settle_currency, backtest_id, 
                asset_total, asset_sub, asset_freeze, 
                position_total, position_sub, position_freeze,
                timestamp, datetime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """.format(self._asset_table_name),
                (
                    self._exchange,
                    self._settle_mode,
                    self._settle_currency,
                    self._backtest_id,
                    asset_total,
                    asset_sub,
                    asset_freeze,
                    position_total,
                    position_sub,
                    position_freeze,
                    timestamp,
                    datetime,
                ),
            )

        one = conn.query_one(
            """SELECT * FROM {} WHERE exchange = ? AND settle_mode = ? AND settle_currency = ? 
            AND timestamp > ? AND backtest_id = ? ORDER BY timestamp LIMIT 1"""
            .format(self._asset_table_name),
            (self._exchange, self._settle_mode, self._settle_currency,
             timestamp, self._backtest_id))
        if one:
            self.__insert_asset_item(one["timestamp"], one["datetime"])
Exemple #3
0
    def __insert_account_flow_item(self, **kwargs):
        """
        add record in account flow table
        :param
            subject: the item of account flow
            amount: the amount of flow, the real amount * 100000000
            position: the position of the flow
            timestamp: the item of account flow

        :return: None
        """

        if self._mode != MODE_BACKTEST:
            raise RuntimeError(
                "Only backtest mode can insert data into table. ")
        validate(instance=kwargs, schema=account_flow_input)
        conn = Conn(self._db_name)
        item = conn.query_one(
            """SELECT * FROM {} WHERE symbol = ? AND exchange = ? AND settle_mode = ? AND settle_currency = ?
             AND subject = ? AND timestamp = ? AND backtest_id = ?""".format(
                self._account_flow_table_name),
            (
                self._symbol,
                self._exchange,
                self._settle_mode,
                self._settle_currency,
                kwargs.get("subject"),
                kwargs.get("timestamp"),
                self._backtest_id,
            ),
        )
        conn.insert(
            """INSERT INTO {} (symbol, exchange, settle_mode, settle_currency, backtest_id, 
            subject, amount, position, timestamp, datetime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """.format(self._account_flow_table_name),
            (
                self._symbol,
                self._exchange,
                self._settle_mode,
                self._settle_currency,
                self._backtest_id,
                kwargs.get("subject"),
                kwargs.get("amount"),
                kwargs.get("position"),
                kwargs.get("timestamp") +
                1 if item else kwargs.get("timestamp"),
                kwargs.get("datetime"),
            ),
        )
Exemple #4
0
    def _get_waiting_instance_id(self) -> int:
        query_sql = """
        SELECT id FROM {trade_type}_instance_backtest WHERE backtest_id = ? AND symbol = ? AND exchange = ?
        AND strategy = ? AND status = ? AND wait_start_timestamp = ? 
        ORDER BY id DESC LIMIT 1
        """
        insert_sql = """
        INSERT INTO {trade_type}_instance_backtest 
        (backtest_id, symbol, exchange, strategy, status, wait_start_timestamp)
        VALUES (?, ?, ?, ?, ?, ?) 
        """
        params = (
            self["backtest_id"],
            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_backtest WHERE backtest_id = ? AND symbol = ? AND exchange = ? 
            AND contract_type = ? AND strategy = ? AND status = ? AND wait_start_timestamp = ? 
            ORDER BY id DESC LIMIT 1
            """
            insert_sql = """
            INSERT INTO {trade_type}_instance_backtest (backtest_id, symbol, exchange, contract_type, strategy, status,
             wait_start_timestamp)
             VALUES (?, ?, ?, ?, ?, ?, ?) 
            """
            params = (
                self["backtest_id"],
                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,
        )
        if one:
            return one["id"]

        insert_id = conn.insert(
            insert_sql.format(trade_type=self["trade_type"]),
            params,
        )
        return insert_id
Exemple #5
0
    def save(self,
             check: bool = False,
             raw_order_data: str = None,
             raw_market_data: str = None):
        if check:
            # 检验参数可用性
            validate(instance=self, schema=future_order_init)
            validate(instance=self, schema=future_order_save)

        conn = Conn(self._db_name)
        one = conn.query_one(
            "SELECT id FROM {} WHERE instance_id = ? AND sequence = ?".format(
                self._table_name),
            (self["instance_id"], self["sequence"]),
        )

        if one:
            conn.execute(
                "UPDATE {} SET place_type = ?, `type` = ?, price = ?, amount = ?,"
                " avg_price = ?, deal_amount = ?, status = ?, lever = ?, fee = ?,"
                " symbol = ?, exchange = ?, contract_type = ?, unit_amount = ?, "
                " place_timestamp = ?, place_datetime = ?, deal_timestamp = ?, deal_datetime = ?,"
                " due_timestamp = ?, due_datetime = ?, swap_timestamp = ?, swap_datetime = ?,"
                " cancel_timestamp = ?, cancel_datetime = ?, raw_order_data = ?, raw_market_data = ?"
                " WHERE instance_id = ? AND sequence = ?".format(
                    self._table_name),
                (
                    self["place_type"],
                    self["type"],
                    self["price"],
                    self["amount"],
                    self["avg_price"],
                    self["deal_amount"],
                    self["status"],
                    self["lever"],
                    self["fee"],
                    self["symbol"],
                    self["exchange"],
                    self["contract_type"],
                    self["unit_amount"],
                    self["place_timestamp"],
                    self["place_datetime"],
                    self["deal_timestamp"],
                    self["deal_datetime"],
                    self["due_timestamp"],
                    self["due_datetime"],
                    self["swap_timestamp"],
                    self["swap_datetime"],
                    self["cancel_timestamp"],
                    self["cancel_datetime"],
                    raw_order_data,
                    raw_market_data,
                    self["instance_id"],
                    self["sequence"],
                ),
            )
        else:
            conn.insert(
                "INSERT INTO {} (instance_id, sequence, place_type, `type`, price,"
                " amount, avg_price, deal_amount, status, lever,"
                " fee, symbol, exchange, contract_type, unit_amount,"
                " place_timestamp, place_datetime, deal_timestamp, deal_datetime,"
                " due_timestamp, due_datetime, swap_timestamp, swap_datetime,"
                " cancel_timestamp, cancel_datetime, raw_order_data, raw_market_data) VALUES"
                " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
                .format(self._table_name, ),
                (
                    self["instance_id"],
                    self["sequence"],
                    self["place_type"],
                    self["type"],
                    self["price"],
                    self["amount"],
                    self["avg_price"],
                    self["deal_amount"],
                    self["status"],
                    self["lever"],
                    self["fee"],
                    self["symbol"],
                    self["exchange"],
                    self["contract_type"],
                    self["unit_amount"],
                    self["place_timestamp"],
                    self["place_datetime"],
                    self["deal_timestamp"],
                    self["deal_datetime"],
                    self["due_timestamp"],
                    self["due_datetime"],
                    self["swap_timestamp"],
                    self["swap_datetime"],
                    self["cancel_timestamp"],
                    self["cancel_datetime"],
                    raw_order_data,
                    raw_market_data,
                ),
            )
        self.__update_instance()
Exemple #6
0
    def save(self,
             check: bool = False,
             raw_order_data: str = None,
             raw_market_data: str = None):
        if check:
            # 检验参数可用性
            validate(instance=self, schema=order_input)

        conn = Conn(self._db_name)
        one = conn.query_one(
            "SELECT id FROM {} WHERE instance_id = ? AND sequence = ?".format(
                self._table_name),
            (self["instance_id"], self["sequence"]),
        )

        if one:
            conn.execute(
                "UPDATE {} SET place_type = ?, `type` = ?, price = ?, amount = ?,"
                " avg_price = ?, deal_amount = ?, status = ?, lever = ?, fee = ?,"
                " symbol = ?, exchange = ?, unit_amount = ?, place_timestamp = ?, place_datetime = ?,"
                " deal_timestamp = ?, deal_datetime = ?, swap_timestamp = ?, swap_datetime = ?,"
                " cancel_timestamp = ?, cancel_datetime = ?, raw_order_data = ?, raw_market_data = ?"
                " WHERE instance_id = ? AND sequence = ?".format(
                    self._table_name),
                (
                    self["place_type"],
                    self["type"],
                    self["price"],
                    self["amount"],
                    self["avg_price"],
                    self["deal_amount"],
                    self["status"],
                    self["lever"],
                    self["fee"],
                    self["symbol"],
                    self["exchange"],
                    self["unit_amount"],
                    self["place_timestamp"],
                    self["place_datetime"],
                    self["deal_timestamp"],
                    self["deal_datetime"],
                    self["swap_timestamp"],
                    self["swap_datetime"],
                    self["cancel_timestamp"],
                    self["cancel_datetime"],
                    raw_order_data,
                    raw_market_data,
                    self["instance_id"],
                    self["sequence"],
                ),
            )
        else:
            conn.insert(
                "INSERT INTO {} (instance_id, sequence, place_type, `type`, price,"
                " amount, avg_price, deal_amount, status, lever,"
                " fee, symbol, exchange, unit_amount, place_timestamp, place_datetime, deal_timestamp, deal_datetime,"
                " cancel_timestamp, cancel_datetime, raw_order_data, raw_market_data) VALUES"
                " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
                .format(self._table_name, ),
                (
                    self["instance_id"],
                    self["sequence"],
                    self["place_type"],
                    self["type"],
                    self["price"],
                    self["amount"],
                    self["avg_price"],
                    self["deal_amount"],
                    self["status"],
                    self["lever"],
                    self["fee"],
                    self["symbol"],
                    self["exchange"],
                    self["unit_amount"],
                    self["place_timestamp"],
                    self["place_datetime"],
                    self["deal_timestamp"],
                    self["deal_datetime"],
                    self["cancel_timestamp"],
                    self["cancel_datetime"],
                    raw_order_data,
                    raw_market_data,
                ),
            )

        orders = conn.query(
            "SELECT * FROM {} WHERE instance_id = ? ORDER BY sequence".format(
                self._table_name),
            (self["instance_id"], ),
        )

        open_amount, open_fee = 0, 0.0
        open_start_timestamp, open_finish_timestamp = 0, 0
        open_start_datetime, open_finish_datetime = "", ""
        open_type, open_place_type = ORDER_TYPE_OPEN_LONG, ""

        liquidate_amount, liquidate_fee = 0, 0.0
        liquidate_start_timestamp, liquidate_finish_timestamp = 0, 0
        liquidate_start_datetime, liquidate_finish_datetime = "", ""
        liquidate_type, liquidate_place_type = ORDER_TYPE_LIQUIDATE_LONG, ""

        for order in orders:
            place_timestamp = order["place_timestamp"]
            place_datetime = moment.get(order["place_timestamp"]).to(
                self.get("timezone")
                or "Asia/Shanghai").format("YYYY-MM-DD HH:mm:ss")

            if order["type"] in (ORDER_TYPE_OPEN_LONG, ORDER_TYPE_OPEN_SHORT):
                open_amount += order["deal_amount"]
                open_fee += order["fee"]
                open_type = order["type"]
                open_place_type = order["place_type"]

                if order["sequence"] == 0:
                    open_start_timestamp = place_timestamp
                    open_start_datetime = place_datetime
                open_finish_timestamp = place_timestamp
                open_finish_datetime = place_datetime

            if order["type"] in (ORDER_TYPE_LIQUIDATE_LONG,
                                 ORDER_TYPE_LIQUIDATE_SHORT):
                liquidate_amount += order["deal_amount"]
                liquidate_fee += order["fee"]
                liquidate_type = order["type"]
                liquidate_place_type = order["place_type"]

                if liquidate_start_timestamp == 0:
                    liquidate_start_timestamp = place_timestamp
                    liquidate_start_datetime = place_datetime
                liquidate_finish_timestamp = place_timestamp
                liquidate_finish_datetime = place_datetime

        if open_amount != liquidate_amount:
            return

        conn.execute(
            "UPDATE {trade_type}_instance_{mode} SET open_fee = ?, open_type = ?, open_place_type = ?,"
            " open_start_timestamp = ?, open_start_datetime = ?, open_finish_timestamp = ?, open_finish_datetime = ?, "
            " liquidate_fee = ?, liquidate_type = ?, liquidate_place_type = ?,"
            " liquidate_start_timestamp = ?, liquidate_start_datetime = ?,"
            " liquidate_finish_timestamp = ?, liquidate_finish_datetime = ? WHERE id = ?"
            .format(
                trade_type=self._trade_type,
                mode=MODE_STRATEGY
                if self._mode != MODE_BACKTEST else MODE_BACKTEST,
            ),
            (
                open_fee,
                open_type,
                open_place_type,
                open_start_timestamp,
                open_start_datetime,
                open_finish_timestamp,
                open_finish_datetime,
                liquidate_fee,
                liquidate_type,
                liquidate_place_type,
                liquidate_start_timestamp,
                liquidate_start_datetime,
                liquidate_finish_timestamp,
                liquidate_finish_datetime,
                self["instance_id"],
            ),
        )