[Mod]reformat code

This commit is contained in:
vn.py 2019-02-23 16:01:19 +08:00
parent a9f652607c
commit e6f8060e99
12 changed files with 297 additions and 272 deletions

View File

@ -0,0 +1 @@
__version__ == "2.0"

View File

@ -201,10 +201,10 @@ class BacktestingEngine:
s = ( s = (
DbBarData.select() DbBarData.select()
.where( .where(
(DbBarData.vt_symbol == self.vt_symbol) & (DbBarData.vt_symbol == self.vt_symbol)
(DbBarData.interval == self.interval) & & (DbBarData.interval == self.interval)
(DbBarData.datetime >= self.start) & & (DbBarData.datetime >= self.start)
(DbBarData.datetime <= self.end) & (DbBarData.datetime <= self.end)
) )
.order_by(DbBarData.datetime) .order_by(DbBarData.datetime)
) )
@ -213,9 +213,9 @@ class BacktestingEngine:
s = ( s = (
DbTickData.select() DbTickData.select()
.where( .where(
(DbTickData.vt_symbol == self.vt_symbol) & (DbTickData.vt_symbol == self.vt_symbol)
(DbTickData.datetime >= self.start) & & (DbTickData.datetime >= self.start)
(DbTickData.datetime <= self.end) & (DbTickData.datetime <= self.end)
) )
.order_by(DbTickData.datetime) .order_by(DbTickData.datetime)
) )
@ -567,15 +567,15 @@ class BacktestingEngine:
# Check whether limit orders can be filled. # Check whether limit orders can be filled.
long_cross = ( long_cross = (
order.direction == Direction.LONG and order.direction == Direction.LONG
order.price >= long_cross_price and and order.price >= long_cross_price
long_cross_price > 0 and long_cross_price > 0
) )
short_cross = ( short_cross = (
order.direction == Direction.SHORT and order.direction == Direction.SHORT
order.price <= short_cross_price and and order.price <= short_cross_price
short_cross_price > 0 and short_cross_price > 0
) )
if not long_cross and not short_cross: if not long_cross and not short_cross:
@ -635,13 +635,13 @@ class BacktestingEngine:
for stop_order in list(self.active_stop_orders.values()): for stop_order in list(self.active_stop_orders.values()):
# Check whether stop order can be triggered. # Check whether stop order can be triggered.
long_cross = ( long_cross = (
stop_order.direction == Direction.LONG and stop_order.direction == Direction.LONG
stop_order.price <= long_cross_price and stop_order.price <= long_cross_price
) )
short_cross = ( short_cross = (
stop_order.direction == Direction.SHORT and stop_order.direction == Direction.SHORT
stop_order.price >= short_cross_price and stop_order.price >= short_cross_price
) )
if not long_cross and not short_cross: if not long_cross and not short_cross:

View File

@ -405,10 +405,10 @@ class CtaEngine(BaseEngine):
s = ( s = (
DbBarData.select() DbBarData.select()
.where( .where(
(DbBarData.vt_symbol == vt_symbol) & (DbBarData.vt_symbol == vt_symbol)
(DbBarData.interval == interval) & & (DbBarData.interval == interval)
(DbBarData.datetime >= start) & & (DbBarData.datetime >= start)
(DbBarData.datetime <= end) & (DbBarData.datetime <= end)
) )
.order_by(DbBarData.datetime) .order_by(DbBarData.datetime)
) )
@ -425,9 +425,9 @@ class CtaEngine(BaseEngine):
s = ( s = (
DbTickData.select() DbTickData.select()
.where( .where(
(DbBarData.vt_symbol == vt_symbol) & (DbBarData.vt_symbol == vt_symbol)
(DbBarData.datetime >= start) & & (DbBarData.datetime >= start)
(DbBarData.datetime <= end) & (DbBarData.datetime <= end)
) )
.order_by(DbBarData.datetime) .order_by(DbBarData.datetime)
) )

View File

@ -1,7 +1,6 @@
from vnpy.app.cta_strategy import ( from vnpy.app.cta_strategy import (
CtaTemplate, CtaTemplate,
StopOrder, StopOrder,
Direction,
TickData, TickData,
BarData, BarData,
TradeData, TradeData,
@ -31,9 +30,9 @@ class AtrRsiStrategy(CtaTemplate):
intra_trade_high = 0 intra_trade_high = 0
intra_trade_low = 0 intra_trade_low = 0
parameters= [ 'atr_length', 'atr_ma_length', 'rsi_length', 'rsi_entry', 'trailing_percent','fixed_size'] parameters = ['atr_length', 'atr_ma_length', 'rsi_length',
variables= ['atr_value','atr_ma','rsi_value','rsi_buy','rsi_sell'] 'rsi_entry', 'trailing_percent', 'fixed_size']
variables = ['atr_value', 'atr_ma', 'rsi_value', 'rsi_buy', 'rsi_sell']
def __init__(self, cta_engine, strategy_name, vt_symbol, setting): def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
"""""" """"""
@ -94,22 +93,24 @@ class AtrRsiStrategy(CtaTemplate):
if self.atr_value > self.atr_ma: if self.atr_value > self.atr_ma:
if self.rsi_value > self.rsi_buy: if self.rsi_value > self.rsi_buy:
self.buy(bar.close_price+5, self.fixed_size) self.buy(bar.close_price + 5, self.fixed_size)
elif self.rsi_value < self.rsi_sell: elif self.rsi_value < self.rsi_sell:
self.short(bar.close_price-5, self.fixed_size) self.short(bar.close_price - 5, self.fixed_size)
elif self.pos > 0: elif self.pos > 0:
self.intra_trade_high = max(self.intra_trade_high, bar.high_price) self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
self.intra_trade_low = bar.low_price self.intra_trade_low = bar.low_price
long_stop = self.intra_trade_high * (1-self.trailing_percent/100) long_stop = self.intra_trade_high * \
(1 - self.trailing_percent / 100)
self.sell(long_stop, abs(self.pos), stop=True) self.sell(long_stop, abs(self.pos), stop=True)
elif self.pos < 0: elif self.pos < 0:
self.intra_trade_low = min(self.intra_trade_low, bar.low_price) self.intra_trade_low = min(self.intra_trade_low, bar.low_price)
self.intra_trade_high = bar.high_price self.intra_trade_high = bar.high_price
short_stop = self.intra_trade_low * (1+self.trailing_percent/100) short_stop = self.intra_trade_low * \
(1 + self.trailing_percent / 100)
self.cover(short_stop, abs(self.pos), stop=True) self.cover(short_stop, abs(self.pos), stop=True)
self.put_event() self.put_event()

View File

@ -1,7 +1,6 @@
from vnpy.app.cta_strategy import ( from vnpy.app.cta_strategy import (
CtaTemplate, CtaTemplate,
StopOrder, StopOrder,
Direction,
TickData, TickData,
BarData, BarData,
TradeData, TradeData,
@ -33,8 +32,10 @@ class BollChannelStrategy(CtaTemplate):
long_stop = 0 long_stop = 0
short_stop = 0 short_stop = 0
parameters = [ 'boll_window', 'boll_dev', 'cci_window', 'atr_window', 'sl_multiplier', 'fixed_size'] parameters = ['boll_window', 'boll_dev', 'cci_window',
variables = ['boll_up', 'boll_down', 'cci_value', 'atr_value', 'intra_trade_high', 'intra_trade_low', 'long_stop', 'short_stop'] 'atr_window', 'sl_multiplier', 'fixed_size']
variables = ['boll_up', 'boll_down', 'cci_value', 'atr_value',
'intra_trade_high', 'intra_trade_low', 'long_stop', 'short_stop']
def __init__(self, cta_engine, strategy_name, vt_symbol, setting): def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
"""""" """"""
@ -42,7 +43,7 @@ class BollChannelStrategy(CtaTemplate):
cta_engine, strategy_name, vt_symbol, setting cta_engine, strategy_name, vt_symbol, setting
) )
self.bg = BarGenerator(self.on_bar,15, self.on_15min_bar) self.bg = BarGenerator(self.on_bar, 15, self.on_15min_bar)
self.am = ArrayManager() self.am = ArrayManager()
def on_init(self): def on_init(self):
@ -70,13 +71,13 @@ class BollChannelStrategy(CtaTemplate):
""" """
self.bg.update_tick(tick) self.bg.update_tick(tick)
def on_bar(self, bar:BarData): def on_bar(self, bar: BarData):
""" """
Callback of new bar data update. Callback of new bar data update.
""" """
self.bg.update_bar(bar) self.bg.update_bar(bar)
def on_15min_bar(self, bar:BarData): def on_15min_bar(self, bar: BarData):
"""""" """"""
self.cancel_all() self.cancel_all()
@ -131,4 +132,3 @@ class BollChannelStrategy(CtaTemplate):
Callback of stop order update. Callback of stop order update.
""" """
pass pass

View File

@ -1,7 +1,6 @@
from vnpy.app.cta_strategy import ( from vnpy.app.cta_strategy import (
CtaTemplate, CtaTemplate,
StopOrder, StopOrder,
Direction,
TickData, TickData,
BarData, BarData,
TradeData, TradeData,
@ -23,8 +22,8 @@ class DoubleMaStrategy(CtaTemplate):
slow_ma0 = 0.0 slow_ma0 = 0.0
slow_ma1 = 0.0 slow_ma1 = 0.0
parameters = [ 'fast_window', 'slow_window'] parameters = ['fast_window', 'slow_window']
variables = ['fast_ma0','fast_ma1','slow_ma0','slow_ma1'] variables = ['fast_ma0', 'fast_ma1', 'slow_ma0', 'slow_ma1']
def __init__(self, cta_engine, strategy_name, vt_symbol, setting): def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
"""""" """"""
@ -81,8 +80,8 @@ class DoubleMaStrategy(CtaTemplate):
self.slow_ma0 = slow_ma[-1] self.slow_ma0 = slow_ma[-1]
self.slow_ma1 = slow_ma[-2] self.slow_ma1 = slow_ma[-2]
cross_over = self.fast_ma0>self.slow_ma0 and self.fast_ma1<self.slow_ma1 cross_over = self.fast_ma0 > self.slow_ma0 and self.fast_ma1 < self.slow_ma1
cross_below = self.fast_ma0<self.slow_ma0 and self.fast_ma1>self.slow_ma1 cross_below = self.fast_ma0 < self.slow_ma0 and self.fast_ma1 > self.slow_ma1
if cross_over: if cross_over:
if self.pos == 0: if self.pos == 0:

View File

@ -2,7 +2,6 @@ from datetime import time
from vnpy.app.cta_strategy import ( from vnpy.app.cta_strategy import (
CtaTemplate, CtaTemplate,
StopOrder, StopOrder,
Direction,
TickData, TickData,
BarData, BarData,
TradeData, TradeData,
@ -35,9 +34,8 @@ class DualThrustStrategy(CtaTemplate):
long_entered = False long_entered = False
short_entered = False short_entered = False
parameters = ['k1', 'k2', "fixed_size"]
parameters = [ 'k1', 'k2', "fixed_size"] variables = ['range', 'long_entry', 'short_entry', 'exit_time']
variables = ['range','long_entry','short_entry','exit_time']
def __init__(self, cta_engine, strategy_name, vt_symbol, setting): def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
"""""" """"""
@ -113,7 +111,8 @@ class DualThrustStrategy(CtaTemplate):
self.buy(self.long_entry, self.fixed_size, stop=True) self.buy(self.long_entry, self.fixed_size, stop=True)
else: else:
if not self.short_entered: if not self.short_entered:
self.short(self.short_entry, self.fixed_size, stop=True) self.short(self.short_entry,
self.fixed_size, stop=True)
elif self.pos > 0: elif self.pos > 0:
self.long_entered = True self.long_entered = True

View File

@ -1,7 +1,6 @@
from vnpy.app.cta_strategy import ( from vnpy.app.cta_strategy import (
CtaTemplate, CtaTemplate,
StopOrder, StopOrder,
Direction,
TickData, TickData,
BarData, BarData,
TradeData, TradeData,
@ -10,6 +9,7 @@ from vnpy.app.cta_strategy import (
ArrayManager, ArrayManager,
) )
class KingKeltnerStrategy(CtaTemplate): class KingKeltnerStrategy(CtaTemplate):
"""""" """"""
@ -29,8 +29,8 @@ class KingKeltnerStrategy(CtaTemplate):
short_orderidList = [] short_orderidList = []
orderList = [] orderList = []
parameters = [ 'kk_length', 'kk_dev','fixed_size'] parameters = ['kk_length', 'kk_dev', 'fixed_size']
variables = ['kk_up','kk_down'] variables = ['kk_up', 'kk_down']
def __init__(self, cta_engine, strategy_name, vt_symbol, setting): def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
"""""" """"""
@ -38,13 +38,9 @@ class KingKeltnerStrategy(CtaTemplate):
cta_engine, strategy_name, vt_symbol, setting cta_engine, strategy_name, vt_symbol, setting
) )
self.bg = BarGenerator(self.on_bar,5 ,self.on_5min_bar) self.bg = BarGenerator(self.on_bar, 5, self.on_5min_bar)
self.am = ArrayManager() self.am = ArrayManager()
buy_orderidList = []
short_orderidList = []
orderList = []
def on_init(self): def on_init(self):
""" """
Callback when strategy is inited. Callback when strategy is inited.
@ -76,7 +72,7 @@ class KingKeltnerStrategy(CtaTemplate):
""" """
self.bg.update_bar(bar) self.bg.update_bar(bar)
def on_5min_bar(self, bar:BarData): def on_5min_bar(self, bar: BarData):
"""""" """"""
for orderid in self.orderList: for orderid in self.orderList:
self.cancel_order(orderid) self.cancel_order(orderid)
@ -98,7 +94,7 @@ class KingKeltnerStrategy(CtaTemplate):
self.intra_trade_high = max(self.intra_trade_high, bar.high_price) self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
self.intra_trade_low = bar.low_price self.intra_trade_low = bar.low_price
vt_orderid = self.sell(self.intra_trade_high*(1-self.trailing_percent/100), vt_orderid = self.sell(self.intra_trade_high * (1 - self.trailing_percent / 100),
abs(self.pos), True) abs(self.pos), True)
self.orderList.append(vt_orderid) self.orderList.append(vt_orderid)
@ -106,7 +102,7 @@ class KingKeltnerStrategy(CtaTemplate):
self.intra_trade_high = bar.high_price self.intra_trade_high = bar.high_price
self.intra_trade_low = min(self.intra_trade_low, bar.low_price) self.intra_trade_low = min(self.intra_trade_low, bar.low_price)
vt_orderid = self.cover(self.intra_trade_low*(1+self.trailing_percent/100), vt_orderid = self.cover(self.intra_trade_low * (1 + self.trailing_percent / 100),
abs(self.pos), True) abs(self.pos), True)
self.orderList.append(vt_orderid) self.orderList.append(vt_orderid)

View File

@ -1,7 +1,5 @@
from vnpy.app.cta_strategy import ( from vnpy.app.cta_strategy import (
CtaTemplate,
StopOrder, StopOrder,
Direction,
TickData, TickData,
BarData, BarData,
TradeData, TradeData,
@ -16,7 +14,7 @@ from vnpy.app.cta_strategy import (
class RsiSignal(CtaSignal): class RsiSignal(CtaSignal):
"""""" """"""
def __init__(self, rsi_window , rsi_level): def __init__(self, rsi_window: int, rsi_level: float):
"""Constructor""" """Constructor"""
super(RsiSignal, self).__init__() super(RsiSignal, self).__init__()
@ -51,10 +49,11 @@ class RsiSignal(CtaSignal):
else: else:
self.set_signal_pos(0) self.set_signal_pos(0)
class CciSignal(CtaSignal): class CciSignal(CtaSignal):
"""""" """"""
def __init__(self, cci_window, cci_level): def __init__(self, cci_window: int, cci_level: float):
"""""" """"""
super(CciSignal, self).__init__() super(CciSignal, self).__init__()
@ -84,15 +83,16 @@ class CciSignal(CtaSignal):
if cci_value >= self.cci_long: if cci_value >= self.cci_long:
self.set_signal_pos(1) self.set_signal_pos(1)
elif cci_value<= self.cci_short: elif cci_value <= self.cci_short:
self.set_signal_pos(-1) self.set_signal_pos(-1)
else: else:
self.set_signal_pos(0) self.set_signal_pos(0)
class MaSignal(CtaSignal): class MaSignal(CtaSignal):
"""""" """"""
def __init__(self, fast_window, slow_window): def __init__(self, fast_window: int, slow_window: int):
"""""" """"""
super(MaSignal, self).__init__() super(MaSignal, self).__init__()
@ -114,7 +114,7 @@ class MaSignal(CtaSignal):
""" """
self.bg.update_bar(bar) self.bg.update_bar(bar)
def on_5min_bar(self, bar:BarData): def on_5min_bar(self, bar: BarData):
"""""" """"""
self.am.update_bar(bar) self.am.update_bar(bar)
if not self.am.inited: if not self.am.inited:
@ -134,9 +134,9 @@ class MaSignal(CtaSignal):
class MultiSignalStrategy(TargetPosTemplate): class MultiSignalStrategy(TargetPosTemplate):
"""""" """"""
author ='用Python的交易员' author = '用Python的交易员'
rsi_window= 14 rsi_window = 14
rsi_level = 20 rsi_level = 20
cci_window = 30 cci_window = 30
cci_level = 10 cci_level = 10
@ -145,8 +145,9 @@ class MultiSignalStrategy(TargetPosTemplate):
signal_pos = {} signal_pos = {}
parameters = ['rsi_window','rsi_level','cci_window','cci_level','fast_window','slow_window'] parameters = ['rsi_window', 'rsi_level', 'cci_window',
variables = ['signal_pos','target_pos'] 'cci_level', 'fast_window', 'slow_window']
variables = ['signal_pos', 'target_pos']
def __init__(self, cta_engine, strategy_name, vt_symbol, setting): def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
"""""" """"""

View File

@ -2,10 +2,10 @@
from abc import ABC from abc import ABC
from typing import Any, Callable from typing import Any, Callable
from vnpy.trader.constant import Interval from vnpy.trader.constant import Interval, Status
from vnpy.trader.object import BarData, TickData, OrderData, TradeData from vnpy.trader.object import BarData, TickData, OrderData, TradeData
from .base import CtaOrderType, StopOrder from .base import CtaOrderType, StopOrder, EngineType
class CtaTemplate(ABC): class CtaTemplate(ABC):
@ -260,7 +260,6 @@ class CtaSignal(ABC):
""" """
pass pass
def set_signal_pos(self, pos): def set_signal_pos(self, pos):
"""""" """"""
self.signal_pos = pos self.signal_pos = pos
@ -289,7 +288,7 @@ class TargetPosTemplate(CtaTemplate):
cta_engine, strategy_name, vt_symbol, setting cta_engine, strategy_name, vt_symbol, setting
) )
def on_tick(self, tick:TickData): def on_tick(self, tick: TickData):
""" """
Callback of new tick data update. Callback of new tick data update.
""" """

View File

@ -4,7 +4,39 @@
from datetime import datetime from datetime import datetime
from vnpy.api.ctp import * from vnpy.api.ctp import (
MdApi,
TdApi,
THOST_FTDC_OAS_Submitted,
THOST_FTDC_OAS_Accepted,
THOST_FTDC_OAS_Rejected,
THOST_FTDC_OST_NoTradeQueueing,
THOST_FTDC_OST_PartTradedQueueing,
THOST_FTDC_OST_AllTraded,
THOST_FTDC_OST_Canceled,
THOST_FTDC_D_Buy,
THOST_FTDC_D_Sell,
THOST_FTDC_PD_Long,
THOST_FTDC_PD_Short,
THOST_FTDC_OPT_LimitPrice,
THOST_FTDC_OPT_AnyPrice,
THOST_FTDC_OF_Open,
THOST_FTDC_OFEN_Close,
THOST_FTDC_OFEN_CloseYesterday,
THOST_FTDC_OFEN_CloseToday,
THOST_FTDC_PC_Futures,
THOST_FTDC_PC_Options,
THOST_FTDC_CP_CallOptions,
THOST_FTDC_CP_PutOptions,
THOST_FTDC_HF_Speculation,
THOST_FTDC_CC_Immediately,
THOST_FTDC_FCC_NotForceClose,
THOST_FTDC_TC_GFD,
THOST_FTDC_VC_AV,
THOST_FTDC_TC_IOC,
THOST_FTDC_VC_CV,
THOST_FTDC_AF_Delete
)
from vnpy.trader.constant import ( from vnpy.trader.constant import (
Direction, Direction,
Offset, Offset,
@ -84,6 +116,7 @@ symbol_exchange_map = {}
symbol_name_map = {} symbol_name_map = {}
symbol_size_map = {} symbol_size_map = {}
class CtpGateway(BaseGateway): class CtpGateway(BaseGateway):
""" """
VN Trader Gateway for CTP . VN Trader Gateway for CTP .
@ -489,7 +522,7 @@ class CtpTdApi(TdApi):
account = AccountData( account = AccountData(
accountid=data["AccountID"], accountid=data["AccountID"],
balance=data["Balance"], balance=data["Balance"],
frozen=data["FrozenMargin"]+data["FrozenCash"]+data["FrozenCommission"], frozen=data["FrozenMargin"] + data["FrozenCash"] + data["FrozenCommission"],
gateway_name=self.gateway_name gateway_name=self.gateway_name
) )
account.available = data["Available"] account.available = data["Available"]
@ -735,6 +768,3 @@ class CtpTdApi(TdApi):
"""""" """"""
if self.connect_status: if self.connect_status:
self.exit() self.exit()

View File

@ -322,8 +322,7 @@ class FutuGateway(BaseGateway):
account = AccountData( account = AccountData(
accountid=f"{self.gateway_name}_{self.market}", accountid=f"{self.gateway_name}_{self.market}",
balance=float(row["total_assets"]), balance=float(row["total_assets"]),
frozen=(float(row["total_assets"]) - frozen=(float(row["total_assets"]) - float(row["avl_withdrawal_cash"])),
float(row["avl_withdrawal_cash"])),
gateway_name=self.gateway_name, gateway_name=self.gateway_name,
) )
self.on_account(account) self.on_account(account)