期限套利策略,要能够稳定获得各币种期货和现货的报价,计算各币种的基差数据,然后当基差突破阈值时触发交易。以下代码可以得到稳定报价,计算基差数据,然后当突破阈值时收到提示邮件(还没写好交易模块)。
这里记录一下,开发过程遇到的主要问题,以及如何解决的,如果不感兴趣,可以跳过,直接看代码。
问题一:websocket报价数据不更新
简单的ws.run_forever,通常在运行两三天后,会出现报价卡在某个时点,不能更新的情况。例如,现货报价停留在2021年12月25日11:00。
解决方案:用while true + try except语句,一旦websock链接有问题,就发送邮件通知(不知道为啥,一直没有收到报错邮件,发送邮件的代码可能有问题),回收内存,再重新链接。
def s_start(self): while True: try: s_ws=WebSocketApp( url='wss://stream.binance.com:9443/ws', on_open=self._s_on_open, on_message=self._s_on_message, on_error=self._s_on_error, on_close=self._s_on_close ) s_ws.run_forever() except Exception as e: content="%s the spot webscoket is broken,check if it restart"%e self._email(content) gc.collect()
讯享网
问题二:启动阶段报价数据为空
因为涉及到多币种,刚刚建立链接的时候,报价数据获取有先后,有可能btc数据有了,但是bnb数据要到10秒甚至20秒后才能收到。这样程序会因报错而中断。
解决方案:定义好报错的类型,用@retry装饰器,保证程序在遇到特定类型报错的时候,能够持续运行下去。
讯享网 def retry_if_index_error(exception): return isinstance(exception,IndexError) @retry(retry_on_exception=retry_if_index_error) def get_basis(self):
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 5 20:15:41 2021 It seems to work really good, the price and basis data is correct after running 13 days. 2021/12/13 16:30 begin @author: yszhu """ from websocket import WebSocketApp import json,threading import pysnooper import time import smtplib from email.mime.text import MIMEText from retrying import retry import logging import gc class basis_dif(object): """ create variable save dilivery contract price,spot price and basis difference """ def __init__(self,contract_date=): #delivery contract price self.d_eth_price=None self.d_eth_time=None self.d_btc_price=None self.d_btc_time=None self.d_bnb_price=None self.d_bnb_price=None

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/127428.html