量化交易之vnpy篇 - 多线程dump账户权益、风险度数据(互斥锁、异常处理)

本文介绍了如何在事件驱动的环境下,使用vntrader库处理账户事件,包括读写JSON文件锁定,计算账户风险百分比,并将更新后的数据保存到accounts_data.json中。重点在于同步账户信息与数据持久化的实现。
摘要由CSDN通过智能技术生成
""" 部分代码 """

   def __init__(self, main_engine: MainEngine, event_engine: EventEngine):
        """"""
        super().__init__(main_engine, event_engine, APP_NAME)

        """ 部分代码 """
        self.read_write_jsonfile_lock = threading.Lock()




   def process_account_event(self, event: Event) -> None:
        """
        Dump balance、risk_percent data of account
        """
        account = event.data

        self.accounts[account.vt_accountid] = account

        tqz_vnpy_path = TQZFilePathOperator.grandfather_path(source_path=TQZFilePathOperator.current_file_grandfather_path(file=__file__))
        accounts_data_path = tqz_vnpy_path + "/.vntrader/accounts_data/accounts_data.json"

        self.read_write_jsonfile_lock.acquire()
        try:
            account_list = TQZJsonOperator.tqz_load_jsonfile(jsonfile=accounts_data_path)
            for account in self.accounts.values():

                risk_percent = 0
                if account.balance is not 0:
                    risk_percent = (account.balance - account.available) / account.balance * 100

                account_list[account.accountid] = {
                    "account_id": account.accountid,
                    "balance": round(account.balance, 2),
                    "risk_percent": round(risk_percent, 2)
                }

            TQZJsonOperator.tqz_write_jsonfile(content=account_list, target_jsonfile=accounts_data_path)

        except Exception as result:
            pass

        finally:
            self.read_write_jsonfile_lock.release()


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值