先简单把想法敲出来,起码先得有个模子
先是照抄大神 上弦之月 的作业
ctaengine里面加上:
from vnpy.trader.event import (EVENT_TICK, EVENT_ORDER, EVENT_TRADE, EVENT_POSITION, EVENT_ACCOUNT)
#--------------------------------------------------------------------------------------
def process_account_event(self,event: Event):
"""
收到账户事件推送
"""
account = event.data
for strategy_name in self.strategies.keys():
strategy = self.strategies[strategy_name]
self.call_strategy_func(strategy, strategy.on_account, account)
#------------------------------------------------------------------------------------
def register_event(self):
"""
注册事件监听
"""
self.event_engine.register(EVENT_TICK, self.process_tick_event)
self.event_engine.register(EVENT_ORDER, self.process_order_event)
self.event_engine.register(EVENT_TRADE, self.process_trade_event)
self.event_engine.register(EVENT_POSITION, self.process_position_event)
self.event_engine.register(EVENT_ACCOUNT, self.process_account_event)
cta_strategy\template.py里面加上:
#----------------------------------------------------------------------
@virtual
def on_account(self, account):
"""
账户信息推送
"""
pass
然后是杠杆监视器策略的代码:
from vnpy_ctastrategy import (
CtaTemplate,
StopOrder,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager,
)
class LeverageMonitor(CtaTemplate):
author = "alexfucn"
parameters = []
variables = []
def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
""""""
super().__init__(cta_engine, strategy_name, vt_symbol, setting)
self.bg = BarGenerator(self.on_bar)
self.am = ArrayManager()
def on_init(self):
"""
Callback when strategy is inited.
"""
self.write_log("策略初始化")
self.load_bar(10)
def on_start(self):
"""
Callback when strategy is started.
"""
self.write_log("策略启动")
self.put_event()
def on_stop(self):
"""
Callback when strategy is stopped.
"""
self.write_log("策略停止")
self.put_event()
def on_tick(self, tick: TickData) -> None:
"""
Callback of new tick data update.
"""
pass
def on_bar(self, bar: BarData) :
"""
Callback of new bar data update.
"""
am = self.am
am.update_bar(bar)
if not am.inited:
return
self.put_event()
def on_account(self,account):
"""
账户信息balance:总资金, available:可用资金, commission:今日手续费,pre_balance上个交易日总资金
"""
self.balance = account.balance
self.available=account.available
less = (self.balance-self.available)/self.balance>0.60
more = (self.balance-(self.available-(self.balance-self.available)/self.pos))/self.balance<0.60
#不确定self.pos能否获得具体仓位品种手数,可能要通过手工输入或外链获取
#杠杠比率目标通过外链获取会比较方便根据当时情况进行调整
if less:
self.sell(bar.close_price, 1)
elif more:
self.send_email(msg, "you can buy more")
self.put_event()
纯小白,代码之后再对着书慢慢修吧