body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
---|---|---|---|---|---|---|---|
@virtual
def on_tick(self, tick: TickData):
'\n Callback of new tick data update.\n '
pass | -5,404,603,894,278,310,000 | Callback of new tick data update. | vnpy/app/cta_strategy_pro/template.py | on_tick | UtorYeung/vnpy | python | @virtual
def on_tick(self, tick: TickData):
'\n \n '
pass |
@virtual
def on_bar(self, bar: BarData):
'\n Callback of new bar data update.\n '
pass | 959,336,517,627,439,700 | Callback of new bar data update. | vnpy/app/cta_strategy_pro/template.py | on_bar | UtorYeung/vnpy | python | @virtual
def on_bar(self, bar: BarData):
'\n \n '
pass |
@virtual
def on_trade(self, trade: TradeData):
'\n Callback of new trade data update.\n '
pass | -2,060,187,208,861,163,800 | Callback of new trade data update. | vnpy/app/cta_strategy_pro/template.py | on_trade | UtorYeung/vnpy | python | @virtual
def on_trade(self, trade: TradeData):
'\n \n '
pass |
@virtual
def on_order(self, order: OrderData):
'\n Callback of new order data update.\n '
pass | 685,206,543,045,577,000 | Callback of new order data update. | vnpy/app/cta_strategy_pro/template.py | on_order | UtorYeung/vnpy | python | @virtual
def on_order(self, order: OrderData):
'\n \n '
pass |
@virtual
def on_stop_order(self, stop_order: StopOrder):
'\n Callback of stop order update.\n '
pass | 7,482,887,281,911,738,000 | Callback of stop order update. | vnpy/app/cta_strategy_pro/template.py | on_stop_order | UtorYeung/vnpy | python | @virtual
def on_stop_order(self, stop_order: StopOrder):
'\n \n '
pass |
def buy(self, price: float, volume: float, stop: bool=False, lock: bool=False, vt_symbol: str='', order_type: OrderType=OrderType.LIMIT, order_time: datetime=None, grid: CtaGrid=None):
'\n Send buy order to open a long position.\n '
if (order_type in [OrderType.FAK, OrderType.FOK]):
if self.is_upper_limit(vt_symbol):
self.write_error(u'涨停价不做FAK/FOK委托')
return []
if (volume == 0):
self.write_error(f'委托数量有误,必须大于0,{vt_symbol}, price:{price}')
return []
return self.send_order(vt_symbol=vt_symbol, direction=Direction.LONG, offset=Offset.OPEN, price=price, volume=volume, stop=stop, lock=lock, order_type=order_type, order_time=order_time, grid=grid) | -9,080,480,501,627,685,000 | Send buy order to open a long position. | vnpy/app/cta_strategy_pro/template.py | buy | UtorYeung/vnpy | python | def buy(self, price: float, volume: float, stop: bool=False, lock: bool=False, vt_symbol: str=, order_type: OrderType=OrderType.LIMIT, order_time: datetime=None, grid: CtaGrid=None):
'\n \n '
if (order_type in [OrderType.FAK, OrderType.FOK]):
if self.is_upper_limit(vt_symbol):
self.write_error(u'涨停价不做FAK/FOK委托')
return []
if (volume == 0):
self.write_error(f'委托数量有误,必须大于0,{vt_symbol}, price:{price}')
return []
return self.send_order(vt_symbol=vt_symbol, direction=Direction.LONG, offset=Offset.OPEN, price=price, volume=volume, stop=stop, lock=lock, order_type=order_type, order_time=order_time, grid=grid) |
def sell(self, price: float, volume: float, stop: bool=False, lock: bool=False, vt_symbol: str='', order_type: OrderType=OrderType.LIMIT, order_time: datetime=None, grid: CtaGrid=None):
'\n Send sell order to close a long position.\n '
if (order_type in [OrderType.FAK, OrderType.FOK]):
if self.is_lower_limit(vt_symbol):
self.write_error(u'跌停价不做FAK/FOK sell委托')
return []
if (volume == 0):
self.write_error(f'委托数量有误,必须大于0,{vt_symbol}, price:{price}')
return []
return self.send_order(vt_symbol=vt_symbol, direction=Direction.SHORT, offset=Offset.CLOSE, price=price, volume=volume, stop=stop, lock=lock, order_type=order_type, order_time=order_time, grid=grid) | 6,360,702,185,854,788,000 | Send sell order to close a long position. | vnpy/app/cta_strategy_pro/template.py | sell | UtorYeung/vnpy | python | def sell(self, price: float, volume: float, stop: bool=False, lock: bool=False, vt_symbol: str=, order_type: OrderType=OrderType.LIMIT, order_time: datetime=None, grid: CtaGrid=None):
'\n \n '
if (order_type in [OrderType.FAK, OrderType.FOK]):
if self.is_lower_limit(vt_symbol):
self.write_error(u'跌停价不做FAK/FOK sell委托')
return []
if (volume == 0):
self.write_error(f'委托数量有误,必须大于0,{vt_symbol}, price:{price}')
return []
return self.send_order(vt_symbol=vt_symbol, direction=Direction.SHORT, offset=Offset.CLOSE, price=price, volume=volume, stop=stop, lock=lock, order_type=order_type, order_time=order_time, grid=grid) |
def short(self, price: float, volume: float, stop: bool=False, lock: bool=False, vt_symbol: str='', order_type: OrderType=OrderType.LIMIT, order_time: datetime=None, grid: CtaGrid=None):
'\n Send short order to open as short position.\n '
if (order_type in [OrderType.FAK, OrderType.FOK]):
if self.is_lower_limit(vt_symbol):
self.write_error(u'跌停价不做FAK/FOK short委托')
return []
if (volume == 0):
self.write_error(f'委托数量有误,必须大于0,{vt_symbol}, price:{price}')
return []
return self.send_order(vt_symbol=vt_symbol, direction=Direction.SHORT, offset=Offset.OPEN, price=price, volume=volume, stop=stop, lock=lock, order_type=order_type, order_time=order_time, grid=grid) | 4,953,141,459,008,334,000 | Send short order to open as short position. | vnpy/app/cta_strategy_pro/template.py | short | UtorYeung/vnpy | python | def short(self, price: float, volume: float, stop: bool=False, lock: bool=False, vt_symbol: str=, order_type: OrderType=OrderType.LIMIT, order_time: datetime=None, grid: CtaGrid=None):
'\n \n '
if (order_type in [OrderType.FAK, OrderType.FOK]):
if self.is_lower_limit(vt_symbol):
self.write_error(u'跌停价不做FAK/FOK short委托')
return []
if (volume == 0):
self.write_error(f'委托数量有误,必须大于0,{vt_symbol}, price:{price}')
return []
return self.send_order(vt_symbol=vt_symbol, direction=Direction.SHORT, offset=Offset.OPEN, price=price, volume=volume, stop=stop, lock=lock, order_type=order_type, order_time=order_time, grid=grid) |
def cover(self, price: float, volume: float, stop: bool=False, lock: bool=False, vt_symbol: str='', order_type: OrderType=OrderType.LIMIT, order_time: datetime=None, grid: CtaGrid=None):
'\n Send cover order to close a short position.\n '
if (order_type in [OrderType.FAK, OrderType.FOK]):
if self.is_upper_limit(vt_symbol):
self.write_error(u'涨停价不做FAK/FOK cover委托')
return []
if (volume == 0):
self.write_error(f'委托数量有误,必须大于0,{vt_symbol}, price:{price}')
return []
return self.send_order(vt_symbol=vt_symbol, direction=Direction.LONG, offset=Offset.CLOSE, price=price, volume=volume, stop=stop, lock=lock, order_type=order_type, order_time=order_time, grid=grid) | 6,435,601,325,156,773,000 | Send cover order to close a short position. | vnpy/app/cta_strategy_pro/template.py | cover | UtorYeung/vnpy | python | def cover(self, price: float, volume: float, stop: bool=False, lock: bool=False, vt_symbol: str=, order_type: OrderType=OrderType.LIMIT, order_time: datetime=None, grid: CtaGrid=None):
'\n \n '
if (order_type in [OrderType.FAK, OrderType.FOK]):
if self.is_upper_limit(vt_symbol):
self.write_error(u'涨停价不做FAK/FOK cover委托')
return []
if (volume == 0):
self.write_error(f'委托数量有误,必须大于0,{vt_symbol}, price:{price}')
return []
return self.send_order(vt_symbol=vt_symbol, direction=Direction.LONG, offset=Offset.CLOSE, price=price, volume=volume, stop=stop, lock=lock, order_type=order_type, order_time=order_time, grid=grid) |
def send_order(self, vt_symbol: str, direction: Direction, offset: Offset, price: float, volume: float, stop: bool=False, lock: bool=False, order_type: OrderType=OrderType.LIMIT, order_time: datetime=None, grid: CtaGrid=None):
'\n Send a new order.\n '
if (vt_symbol == ''):
vt_symbol = self.vt_symbol
if (not self.trading):
self.write_log(f'非交易状态')
return []
vt_orderids = self.cta_engine.send_order(strategy=self, vt_symbol=vt_symbol, direction=direction, offset=offset, price=price, volume=volume, stop=stop, lock=lock, order_type=order_type)
if (len(vt_orderids) == 0):
self.write_error(f'{self.strategy_name}调用cta_engine.send_order委托返回失败,vt_symbol:{vt_symbol}')
if (order_time is None):
order_time = datetime.now()
for vt_orderid in vt_orderids:
d = {'direction': direction, 'offset': offset, 'vt_symbol': vt_symbol, 'price': price, 'volume': volume, 'order_type': order_type, 'traded': 0, 'order_time': order_time, 'status': Status.SUBMITTING}
if grid:
d.update({'grid': grid})
grid.order_ids.append(vt_orderid)
self.active_orders.update({vt_orderid: d})
if (direction == Direction.LONG):
self.entrust = 1
elif (direction == Direction.SHORT):
self.entrust = (- 1)
return vt_orderids | -7,242,398,835,969,134,000 | Send a new order. | vnpy/app/cta_strategy_pro/template.py | send_order | UtorYeung/vnpy | python | def send_order(self, vt_symbol: str, direction: Direction, offset: Offset, price: float, volume: float, stop: bool=False, lock: bool=False, order_type: OrderType=OrderType.LIMIT, order_time: datetime=None, grid: CtaGrid=None):
'\n \n '
if (vt_symbol == ):
vt_symbol = self.vt_symbol
if (not self.trading):
self.write_log(f'非交易状态')
return []
vt_orderids = self.cta_engine.send_order(strategy=self, vt_symbol=vt_symbol, direction=direction, offset=offset, price=price, volume=volume, stop=stop, lock=lock, order_type=order_type)
if (len(vt_orderids) == 0):
self.write_error(f'{self.strategy_name}调用cta_engine.send_order委托返回失败,vt_symbol:{vt_symbol}')
if (order_time is None):
order_time = datetime.now()
for vt_orderid in vt_orderids:
d = {'direction': direction, 'offset': offset, 'vt_symbol': vt_symbol, 'price': price, 'volume': volume, 'order_type': order_type, 'traded': 0, 'order_time': order_time, 'status': Status.SUBMITTING}
if grid:
d.update({'grid': grid})
grid.order_ids.append(vt_orderid)
self.active_orders.update({vt_orderid: d})
if (direction == Direction.LONG):
self.entrust = 1
elif (direction == Direction.SHORT):
self.entrust = (- 1)
return vt_orderids |
def cancel_order(self, vt_orderid: str):
'\n Cancel an existing order.\n '
if self.trading:
return self.cta_engine.cancel_order(self, vt_orderid)
return False | 6,330,077,215,582,117,000 | Cancel an existing order. | vnpy/app/cta_strategy_pro/template.py | cancel_order | UtorYeung/vnpy | python | def cancel_order(self, vt_orderid: str):
'\n \n '
if self.trading:
return self.cta_engine.cancel_order(self, vt_orderid)
return False |
def cancel_all(self):
'\n Cancel all orders sent by strategy.\n '
if self.trading:
self.cta_engine.cancel_all(self) | 4,049,518,702,072,619,000 | Cancel all orders sent by strategy. | vnpy/app/cta_strategy_pro/template.py | cancel_all | UtorYeung/vnpy | python | def cancel_all(self):
'\n \n '
if self.trading:
self.cta_engine.cancel_all(self) |
def is_upper_limit(self, symbol):
'是否涨停'
tick = self.tick_dict.get(symbol, None)
if ((tick is None) or (tick.limit_up is None) or (tick.limit_up == 0)):
return False
if (tick.bid_price_1 == tick.limit_up):
return True | -3,416,308,772,781,506,000 | 是否涨停 | vnpy/app/cta_strategy_pro/template.py | is_upper_limit | UtorYeung/vnpy | python | def is_upper_limit(self, symbol):
tick = self.tick_dict.get(symbol, None)
if ((tick is None) or (tick.limit_up is None) or (tick.limit_up == 0)):
return False
if (tick.bid_price_1 == tick.limit_up):
return True |
def is_lower_limit(self, symbol):
'是否跌停'
tick = self.tick_dict.get(symbol, None)
if ((tick is None) or (tick.limit_down is None) or (tick.limit_down == 0)):
return False
if (tick.ask_price_1 == tick.limit_down):
return True | 2,973,849,828,281,988,000 | 是否跌停 | vnpy/app/cta_strategy_pro/template.py | is_lower_limit | UtorYeung/vnpy | python | def is_lower_limit(self, symbol):
tick = self.tick_dict.get(symbol, None)
if ((tick is None) or (tick.limit_down is None) or (tick.limit_down == 0)):
return False
if (tick.ask_price_1 == tick.limit_down):
return True |
def write_log(self, msg: str, level: int=INFO):
'\n Write a log message.\n '
self.cta_engine.write_log(msg=msg, strategy_name=self.strategy_name, level=level) | -3,863,003,474,144,610,000 | Write a log message. | vnpy/app/cta_strategy_pro/template.py | write_log | UtorYeung/vnpy | python | def write_log(self, msg: str, level: int=INFO):
'\n \n '
self.cta_engine.write_log(msg=msg, strategy_name=self.strategy_name, level=level) |
def write_error(self, msg: str):
'write error log message'
self.write_log(msg=msg, level=ERROR) | 3,193,733,022,767,435,000 | write error log message | vnpy/app/cta_strategy_pro/template.py | write_error | UtorYeung/vnpy | python | def write_error(self, msg: str):
self.write_log(msg=msg, level=ERROR) |
def get_engine_type(self):
'\n Return whether the cta_engine is backtesting or live trading.\n '
return self.cta_engine.get_engine_type() | 7,297,224,918,648,383,000 | Return whether the cta_engine is backtesting or live trading. | vnpy/app/cta_strategy_pro/template.py | get_engine_type | UtorYeung/vnpy | python | def get_engine_type(self):
'\n \n '
return self.cta_engine.get_engine_type() |
def load_bar(self, days: int, interval: Interval=Interval.MINUTE, callback: Callable=None, interval_num: int=1):
'\n Load historical bar data for initializing strategy.\n '
if (not callback):
callback = self.on_bar
self.cta_engine.load_bar(self.vt_symbol, days, interval, callback, interval_num) | 294,891,323,061,072,960 | Load historical bar data for initializing strategy. | vnpy/app/cta_strategy_pro/template.py | load_bar | UtorYeung/vnpy | python | def load_bar(self, days: int, interval: Interval=Interval.MINUTE, callback: Callable=None, interval_num: int=1):
'\n \n '
if (not callback):
callback = self.on_bar
self.cta_engine.load_bar(self.vt_symbol, days, interval, callback, interval_num) |
def load_tick(self, days: int):
'\n Load historical tick data for initializing strategy.\n '
self.cta_engine.load_tick(self.vt_symbol, days, self.on_tick) | 5,586,702,844,267,469,000 | Load historical tick data for initializing strategy. | vnpy/app/cta_strategy_pro/template.py | load_tick | UtorYeung/vnpy | python | def load_tick(self, days: int):
'\n \n '
self.cta_engine.load_tick(self.vt_symbol, days, self.on_tick) |
def put_event(self):
'\n Put an strategy data event for ui update.\n '
if self.inited:
self.cta_engine.put_strategy_event(self) | 8,639,283,256,132,671,000 | Put an strategy data event for ui update. | vnpy/app/cta_strategy_pro/template.py | put_event | UtorYeung/vnpy | python | def put_event(self):
'\n \n '
if self.inited:
self.cta_engine.put_strategy_event(self) |
def send_email(self, msg):
'\n Send email to default receiver.\n '
if self.inited:
self.cta_engine.send_email(msg, self) | 6,436,060,040,956,104,000 | Send email to default receiver. | vnpy/app/cta_strategy_pro/template.py | send_email | UtorYeung/vnpy | python | def send_email(self, msg):
'\n \n '
if self.inited:
self.cta_engine.send_email(msg, self) |
def sync_data(self):
'\n Sync strategy variables value into disk storage.\n '
if self.trading:
self.cta_engine.sync_strategy_data(self) | 943,088,262,176,522,200 | Sync strategy variables value into disk storage. | vnpy/app/cta_strategy_pro/template.py | sync_data | UtorYeung/vnpy | python | def sync_data(self):
'\n \n '
if self.trading:
self.cta_engine.sync_strategy_data(self) |
@virtual
def on_tick(self, tick: TickData):
'\n Callback of new tick data update.\n '
pass | -5,404,603,894,278,310,000 | Callback of new tick data update. | vnpy/app/cta_strategy_pro/template.py | on_tick | UtorYeung/vnpy | python | @virtual
def on_tick(self, tick: TickData):
'\n \n '
pass |
@virtual
def on_bar(self, bar: BarData):
'\n Callback of new bar data update.\n '
pass | 959,336,517,627,439,700 | Callback of new bar data update. | vnpy/app/cta_strategy_pro/template.py | on_bar | UtorYeung/vnpy | python | @virtual
def on_bar(self, bar: BarData):
'\n \n '
pass |
@virtual
def on_tick(self, tick: TickData):
'\n Callback of new tick data update.\n '
self.last_tick = tick
if self.trading:
self.trade() | 319,937,858,261,153,700 | Callback of new tick data update. | vnpy/app/cta_strategy_pro/template.py | on_tick | UtorYeung/vnpy | python | @virtual
def on_tick(self, tick: TickData):
'\n \n '
self.last_tick = tick
if self.trading:
self.trade() |
@virtual
def on_bar(self, bar: BarData):
'\n Callback of new bar data update.\n '
self.last_bar = bar | 3,089,873,859,974,323,000 | Callback of new bar data update. | vnpy/app/cta_strategy_pro/template.py | on_bar | UtorYeung/vnpy | python | @virtual
def on_bar(self, bar: BarData):
'\n \n '
self.last_bar = bar |
@virtual
def on_order(self, order: OrderData):
'\n Callback of new order data update.\n '
vt_orderid = order.vt_orderid
if ((not order.is_active()) and (vt_orderid in self.vt_orderids)):
self.vt_orderids.remove(vt_orderid) | 2,346,660,776,233,848,300 | Callback of new order data update. | vnpy/app/cta_strategy_pro/template.py | on_order | UtorYeung/vnpy | python | @virtual
def on_order(self, order: OrderData):
'\n \n '
vt_orderid = order.vt_orderid
if ((not order.is_active()) and (vt_orderid in self.vt_orderids)):
self.vt_orderids.remove(vt_orderid) |
def update_setting(self, setting: dict):
'\n Update strategy parameter wtih value in setting dict.\n '
for name in self.parameters:
if (name in setting):
setattr(self, name, setting[name])
(symbol, self.exchange) = extract_vt_symbol(self.vt_symbol)
if (self.idx_symbol is None):
self.idx_symbol = ((get_underlying_symbol(symbol).upper() + '99.') + self.exchange.value)
if (self.vt_symbol != self.idx_symbol):
self.write_log(f'指数合约:{self.idx_symbol}, 主力合约:{self.vt_symbol}')
self.price_tick = self.cta_engine.get_price_tick(self.vt_symbol)
self.symbol_size = self.cta_engine.get_size(self.vt_symbol)
self.margin_rate = self.cta_engine.get_margin_rate(self.vt_symbol) | -4,360,711,793,639,846,000 | Update strategy parameter wtih value in setting dict. | vnpy/app/cta_strategy_pro/template.py | update_setting | UtorYeung/vnpy | python | def update_setting(self, setting: dict):
'\n \n '
for name in self.parameters:
if (name in setting):
setattr(self, name, setting[name])
(symbol, self.exchange) = extract_vt_symbol(self.vt_symbol)
if (self.idx_symbol is None):
self.idx_symbol = ((get_underlying_symbol(symbol).upper() + '99.') + self.exchange.value)
if (self.vt_symbol != self.idx_symbol):
self.write_log(f'指数合约:{self.idx_symbol}, 主力合约:{self.vt_symbol}')
self.price_tick = self.cta_engine.get_price_tick(self.vt_symbol)
self.symbol_size = self.cta_engine.get_size(self.vt_symbol)
self.margin_rate = self.cta_engine.get_margin_rate(self.vt_symbol) |
def sync_data(self):
'同步更新数据'
if (not self.backtesting):
self.write_log(u'保存k线缓存数据')
self.save_klines_to_cache()
if (self.inited and self.trading):
self.write_log(u'保存policy数据')
self.policy.save() | -5,144,947,309,974,197,000 | 同步更新数据 | vnpy/app/cta_strategy_pro/template.py | sync_data | UtorYeung/vnpy | python | def sync_data(self):
if (not self.backtesting):
self.write_log(u'保存k线缓存数据')
self.save_klines_to_cache()
if (self.inited and self.trading):
self.write_log(u'保存policy数据')
self.policy.save() |
def save_klines_to_cache(self, kline_names: list=[]):
'\n 保存K线数据到缓存\n :param kline_names: 一般为self.klines的keys\n :return:\n '
if (len(kline_names) == 0):
kline_names = list(self.klines.keys())
save_path = self.cta_engine.get_data_path()
file_name = os.path.abspath(os.path.join(save_path, f'{self.strategy_name}_klines.pkb2'))
with bz2.BZ2File(file_name, 'wb') as f:
klines = {}
for kline_name in kline_names:
kline = self.klines.get(kline_name, None)
klines.update({kline_name: kline})
pickle.dump(klines, f) | 1,396,282,516,568,408,800 | 保存K线数据到缓存
:param kline_names: 一般为self.klines的keys
:return: | vnpy/app/cta_strategy_pro/template.py | save_klines_to_cache | UtorYeung/vnpy | python | def save_klines_to_cache(self, kline_names: list=[]):
'\n 保存K线数据到缓存\n :param kline_names: 一般为self.klines的keys\n :return:\n '
if (len(kline_names) == 0):
kline_names = list(self.klines.keys())
save_path = self.cta_engine.get_data_path()
file_name = os.path.abspath(os.path.join(save_path, f'{self.strategy_name}_klines.pkb2'))
with bz2.BZ2File(file_name, 'wb') as f:
klines = {}
for kline_name in kline_names:
kline = self.klines.get(kline_name, None)
klines.update({kline_name: kline})
pickle.dump(klines, f) |
def load_klines_from_cache(self, kline_names: list=[]):
'\n 从缓存加载K线数据\n :param kline_names:\n :return:\n '
if (len(kline_names) == 0):
kline_names = list(self.klines.keys())
save_path = self.cta_engine.get_data_path()
file_name = os.path.abspath(os.path.join(save_path, f'{self.strategy_name}_klines.pkb2'))
try:
last_bar_dt = None
with bz2.BZ2File(file_name, 'rb') as f:
klines = pickle.load(f)
for kline_name in kline_names:
cache_kline = klines.get(kline_name, None)
strategy_kline = self.klines.get(kline_name, None)
if (cache_kline and strategy_kline):
cb_on_bar = strategy_kline.cb_on_bar
strategy_kline.__dict__.update(cache_kline.__dict__)
kline_first_bar_dt = None
kline_last_bar_dt = None
if (len(strategy_kline.line_bar) > 0):
kline_first_bar_dt = strategy_kline.line_bar[0].datetime
kline_last_bar_dt = strategy_kline.line_bar[(- 1)].datetime
if (last_bar_dt and strategy_kline.cur_datetime):
last_bar_dt = max(last_bar_dt, strategy_kline.cur_datetime)
else:
last_bar_dt = strategy_kline.cur_datetime
strategy_kline.strategy = self
strategy_kline.cb_on_bar = cb_on_bar
self.write_log(f'恢复{kline_name}缓存数据:[{kline_first_bar_dt}] => [{kline_last_bar_dt}], bar结束时间:{last_bar_dt}')
self.write_log(u'加载缓存k线数据完毕')
return last_bar_dt
except Exception as ex:
self.write_error(f'加载缓存K线数据失败:{str(ex)}')
return None | -1,286,653,908,774,571,500 | 从缓存加载K线数据
:param kline_names:
:return: | vnpy/app/cta_strategy_pro/template.py | load_klines_from_cache | UtorYeung/vnpy | python | def load_klines_from_cache(self, kline_names: list=[]):
'\n 从缓存加载K线数据\n :param kline_names:\n :return:\n '
if (len(kline_names) == 0):
kline_names = list(self.klines.keys())
save_path = self.cta_engine.get_data_path()
file_name = os.path.abspath(os.path.join(save_path, f'{self.strategy_name}_klines.pkb2'))
try:
last_bar_dt = None
with bz2.BZ2File(file_name, 'rb') as f:
klines = pickle.load(f)
for kline_name in kline_names:
cache_kline = klines.get(kline_name, None)
strategy_kline = self.klines.get(kline_name, None)
if (cache_kline and strategy_kline):
cb_on_bar = strategy_kline.cb_on_bar
strategy_kline.__dict__.update(cache_kline.__dict__)
kline_first_bar_dt = None
kline_last_bar_dt = None
if (len(strategy_kline.line_bar) > 0):
kline_first_bar_dt = strategy_kline.line_bar[0].datetime
kline_last_bar_dt = strategy_kline.line_bar[(- 1)].datetime
if (last_bar_dt and strategy_kline.cur_datetime):
last_bar_dt = max(last_bar_dt, strategy_kline.cur_datetime)
else:
last_bar_dt = strategy_kline.cur_datetime
strategy_kline.strategy = self
strategy_kline.cb_on_bar = cb_on_bar
self.write_log(f'恢复{kline_name}缓存数据:[{kline_first_bar_dt}] => [{kline_last_bar_dt}], bar结束时间:{last_bar_dt}')
self.write_log(u'加载缓存k线数据完毕')
return last_bar_dt
except Exception as ex:
self.write_error(f'加载缓存K线数据失败:{str(ex)}')
return None |
def get_klines_snapshot(self):
'返回当前klines的切片数据'
try:
d = {'strategy': self.strategy_name, 'datetime': datetime.now()}
klines = {}
for kline_name in sorted(self.klines.keys()):
klines.update({kline_name: self.klines.get(kline_name).get_data()})
kline_names = list(klines.keys())
binary_data = zlib.compress(pickle.dumps(klines))
d.update({'kline_names': kline_names, 'klines': binary_data, 'zlib': True})
return d
except Exception as ex:
self.write_error(f'获取klines切片数据失败:{str(ex)}')
return {} | -1,498,021,857,701,842,700 | 返回当前klines的切片数据 | vnpy/app/cta_strategy_pro/template.py | get_klines_snapshot | UtorYeung/vnpy | python | def get_klines_snapshot(self):
try:
d = {'strategy': self.strategy_name, 'datetime': datetime.now()}
klines = {}
for kline_name in sorted(self.klines.keys()):
klines.update({kline_name: self.klines.get(kline_name).get_data()})
kline_names = list(klines.keys())
binary_data = zlib.compress(pickle.dumps(klines))
d.update({'kline_names': kline_names, 'klines': binary_data, 'zlib': True})
return d
except Exception as ex:
self.write_error(f'获取klines切片数据失败:{str(ex)}')
return {} |
def init_position(self):
'\n 初始化Positin\n 使用网格的持久化,获取开仓状态的多空单,更新\n :return:\n '
self.write_log(u'init_position(),初始化持仓')
pos_symbols = set()
remove_ids = []
if (len(self.gt.up_grids) <= 0):
self.position.short_pos = 0
short_grids = self.gt.load(direction=Direction.SHORT, open_status_filter=[True])
if (len(short_grids) == 0):
self.write_log(u'没有持久化的空单数据')
self.gt.up_grids = []
else:
self.gt.up_grids = short_grids
for sg in short_grids:
if ((len(sg.order_ids) > 0) or sg.order_status):
self.write_log(f'重置委托状态:{sg.order_status},清除委托单:{sg.order_ids}')
sg.order_status = False
sg.order_ids = []
short_symbol = sg.snapshot.get('mi_symbol', self.vt_symbol)
if (sg.traded_volume > 0):
if (sg.open_status and (sg.volume == sg.traded_volume)):
msg = f'{self.strategy_name} {short_symbol}空单持仓{sg.volume},已成交:{sg.traded_volume},不加载'
self.write_log(msg)
self.send_wechat(msg)
remove_ids.append(sg.id)
continue
pos_symbols.add(short_symbol)
self.write_log(u'加载持仓空单[ID:{},vt_symbol:{},价格:{}],[指数:{},价格:{}],数量:{}手'.format(sg.id, short_symbol, sg.snapshot.get('open_price'), self.idx_symbol, sg.open_price, sg.volume))
self.position.short_pos -= sg.volume
self.write_log(u'持久化空单,共持仓:{}手'.format(abs(self.position.short_pos)))
if (len(remove_ids) > 0):
self.gt.remove_grids_by_ids(direction=Direction.SHORT, ids=remove_ids)
remove_ids = []
if (len(self.gt.dn_grids) <= 0):
self.position.long_pos = 0
long_grids = self.gt.load(direction=Direction.LONG, open_status_filter=[True])
if (len(long_grids) == 0):
self.write_log(u'没有持久化的多单数据')
self.gt.dn_grids = []
else:
self.gt.dn_grids = long_grids
for lg in long_grids:
if ((len(lg.order_ids) > 0) or lg.order_status):
self.write_log(f'重置委托状态:{lg.order_status},清除委托单:{lg.order_ids}')
lg.order_status = False
lg.order_ids = []
long_symbol = lg.snapshot.get('mi_symbol', self.vt_symbol)
if (lg.traded_volume > 0):
if (lg.open_status and (lg.volume == lg.traded_volume)):
msg = f'{self.strategy_name} {long_symbol}多单持仓{lg.volume},已成交:{lg.traded_volume},不加载'
self.write_log(msg)
self.send_wechat(msg)
remove_ids.append(lg.id)
continue
pos_symbols.add(long_symbol)
self.write_log(u'加载持仓多单[ID:{},vt_symbol:{},价格:{}],[指数{},价格:{}],数量:{}手'.format(lg.id, long_symbol, lg.snapshot.get('open_price'), self.idx_symbol, lg.open_price, lg.volume))
self.position.long_pos += lg.volume
self.write_log(f'持久化多单,共持仓:{self.position.long_pos}手')
if (len(remove_ids) > 0):
self.gt.remove_grids_by_ids(direction=Direction.LONG, ids=remove_ids)
self.position.pos = (self.position.long_pos + self.position.short_pos)
self.write_log(u'{}加载持久化数据完成,多单:{},空单:{},共:{}手'.format(self.strategy_name, self.position.long_pos, abs(self.position.short_pos), self.position.pos))
self.pos = self.position.pos
self.gt.save()
self.display_grids()
if ((len(self.vt_symbol) > 0) and (self.vt_symbol not in pos_symbols)):
pos_symbols.add(self.vt_symbol)
if (self.idx_symbol and (self.idx_symbol not in pos_symbols)):
pos_symbols.add(self.idx_symbol)
for symbol in list(pos_symbols):
self.write_log(f'新增订阅合约:{symbol}')
self.cta_engine.subscribe_symbol(strategy_name=self.strategy_name, vt_symbol=symbol) | -3,441,370,031,846,856,000 | 初始化Positin
使用网格的持久化,获取开仓状态的多空单,更新
:return: | vnpy/app/cta_strategy_pro/template.py | init_position | UtorYeung/vnpy | python | def init_position(self):
'\n 初始化Positin\n 使用网格的持久化,获取开仓状态的多空单,更新\n :return:\n '
self.write_log(u'init_position(),初始化持仓')
pos_symbols = set()
remove_ids = []
if (len(self.gt.up_grids) <= 0):
self.position.short_pos = 0
short_grids = self.gt.load(direction=Direction.SHORT, open_status_filter=[True])
if (len(short_grids) == 0):
self.write_log(u'没有持久化的空单数据')
self.gt.up_grids = []
else:
self.gt.up_grids = short_grids
for sg in short_grids:
if ((len(sg.order_ids) > 0) or sg.order_status):
self.write_log(f'重置委托状态:{sg.order_status},清除委托单:{sg.order_ids}')
sg.order_status = False
sg.order_ids = []
short_symbol = sg.snapshot.get('mi_symbol', self.vt_symbol)
if (sg.traded_volume > 0):
if (sg.open_status and (sg.volume == sg.traded_volume)):
msg = f'{self.strategy_name} {short_symbol}空单持仓{sg.volume},已成交:{sg.traded_volume},不加载'
self.write_log(msg)
self.send_wechat(msg)
remove_ids.append(sg.id)
continue
pos_symbols.add(short_symbol)
self.write_log(u'加载持仓空单[ID:{},vt_symbol:{},价格:{}],[指数:{},价格:{}],数量:{}手'.format(sg.id, short_symbol, sg.snapshot.get('open_price'), self.idx_symbol, sg.open_price, sg.volume))
self.position.short_pos -= sg.volume
self.write_log(u'持久化空单,共持仓:{}手'.format(abs(self.position.short_pos)))
if (len(remove_ids) > 0):
self.gt.remove_grids_by_ids(direction=Direction.SHORT, ids=remove_ids)
remove_ids = []
if (len(self.gt.dn_grids) <= 0):
self.position.long_pos = 0
long_grids = self.gt.load(direction=Direction.LONG, open_status_filter=[True])
if (len(long_grids) == 0):
self.write_log(u'没有持久化的多单数据')
self.gt.dn_grids = []
else:
self.gt.dn_grids = long_grids
for lg in long_grids:
if ((len(lg.order_ids) > 0) or lg.order_status):
self.write_log(f'重置委托状态:{lg.order_status},清除委托单:{lg.order_ids}')
lg.order_status = False
lg.order_ids = []
long_symbol = lg.snapshot.get('mi_symbol', self.vt_symbol)
if (lg.traded_volume > 0):
if (lg.open_status and (lg.volume == lg.traded_volume)):
msg = f'{self.strategy_name} {long_symbol}多单持仓{lg.volume},已成交:{lg.traded_volume},不加载'
self.write_log(msg)
self.send_wechat(msg)
remove_ids.append(lg.id)
continue
pos_symbols.add(long_symbol)
self.write_log(u'加载持仓多单[ID:{},vt_symbol:{},价格:{}],[指数{},价格:{}],数量:{}手'.format(lg.id, long_symbol, lg.snapshot.get('open_price'), self.idx_symbol, lg.open_price, lg.volume))
self.position.long_pos += lg.volume
self.write_log(f'持久化多单,共持仓:{self.position.long_pos}手')
if (len(remove_ids) > 0):
self.gt.remove_grids_by_ids(direction=Direction.LONG, ids=remove_ids)
self.position.pos = (self.position.long_pos + self.position.short_pos)
self.write_log(u'{}加载持久化数据完成,多单:{},空单:{},共:{}手'.format(self.strategy_name, self.position.long_pos, abs(self.position.short_pos), self.position.pos))
self.pos = self.position.pos
self.gt.save()
self.display_grids()
if ((len(self.vt_symbol) > 0) and (self.vt_symbol not in pos_symbols)):
pos_symbols.add(self.vt_symbol)
if (self.idx_symbol and (self.idx_symbol not in pos_symbols)):
pos_symbols.add(self.idx_symbol)
for symbol in list(pos_symbols):
self.write_log(f'新增订阅合约:{symbol}')
self.cta_engine.subscribe_symbol(strategy_name=self.strategy_name, vt_symbol=symbol) |
def get_positions(self):
"\n 获取策略当前持仓(重构,使用主力合约)\n :return: [{'vt_symbol':symbol,'direction':direction,'volume':volume]\n "
if (not self.position):
return []
pos_list = []
if (self.position.long_pos > 0):
for g in self.gt.get_opened_grids(direction=Direction.LONG):
vt_symbol = g.snapshot.get('mi_symbol', (g.vt_symbol if (g.vt_symbol and ('99' not in g.vt_symbol)) else self.vt_symbol))
open_price = g.snapshot.get('open_price', g.open_price)
pos_list.append({'vt_symbol': vt_symbol, 'direction': 'long', 'volume': (g.volume - g.traded_volume), 'price': open_price})
if (abs(self.position.short_pos) > 0):
for g in self.gt.get_opened_grids(direction=Direction.SHORT):
vt_symbol = g.snapshot.get('mi_symbol', (g.vt_symbol if (g.vt_symbol and ('99' not in g.vt_symbol)) else self.vt_symbol))
open_price = g.snapshot.get('open_price', g.open_price)
pos_list.append({'vt_symbol': vt_symbol, 'direction': 'short', 'volume': abs((g.volume - g.traded_volume)), 'price': open_price})
if (self.cur_datetime and ((datetime.now() - self.cur_datetime).total_seconds() < 10)):
self.write_log(u'当前持仓:{}'.format(pos_list))
return pos_list | -4,157,647,331,058,156,000 | 获取策略当前持仓(重构,使用主力合约)
:return: [{'vt_symbol':symbol,'direction':direction,'volume':volume] | vnpy/app/cta_strategy_pro/template.py | get_positions | UtorYeung/vnpy | python | def get_positions(self):
"\n 获取策略当前持仓(重构,使用主力合约)\n :return: [{'vt_symbol':symbol,'direction':direction,'volume':volume]\n "
if (not self.position):
return []
pos_list = []
if (self.position.long_pos > 0):
for g in self.gt.get_opened_grids(direction=Direction.LONG):
vt_symbol = g.snapshot.get('mi_symbol', (g.vt_symbol if (g.vt_symbol and ('99' not in g.vt_symbol)) else self.vt_symbol))
open_price = g.snapshot.get('open_price', g.open_price)
pos_list.append({'vt_symbol': vt_symbol, 'direction': 'long', 'volume': (g.volume - g.traded_volume), 'price': open_price})
if (abs(self.position.short_pos) > 0):
for g in self.gt.get_opened_grids(direction=Direction.SHORT):
vt_symbol = g.snapshot.get('mi_symbol', (g.vt_symbol if (g.vt_symbol and ('99' not in g.vt_symbol)) else self.vt_symbol))
open_price = g.snapshot.get('open_price', g.open_price)
pos_list.append({'vt_symbol': vt_symbol, 'direction': 'short', 'volume': abs((g.volume - g.traded_volume)), 'price': open_price})
if (self.cur_datetime and ((datetime.now() - self.cur_datetime).total_seconds() < 10)):
self.write_log(u'当前持仓:{}'.format(pos_list))
return pos_list |
def get_policy_json(self):
'获取policy的json格式数据'
if (not self.policy):
return None
data = self.policy.to_json()
return data | -7,284,977,415,092,988,000 | 获取policy的json格式数据 | vnpy/app/cta_strategy_pro/template.py | get_policy_json | UtorYeung/vnpy | python | def get_policy_json(self):
if (not self.policy):
return None
data = self.policy.to_json()
return data |
def get_grid_trade_json(self):
'获取gt组件的json格式数据'
if (not self.gt):
return None
data = self.gt.to_json()
return data | 1,568,559,070,898,897,000 | 获取gt组件的json格式数据 | vnpy/app/cta_strategy_pro/template.py | get_grid_trade_json | UtorYeung/vnpy | python | def get_grid_trade_json(self):
if (not self.gt):
return None
data = self.gt.to_json()
return data |
def tns_cancel_logic(self, dt, force=False):
'撤单逻辑'
if (len(self.active_orders) < 1):
self.entrust = 0
return
for vt_orderid in list(self.active_orders.keys()):
order_info = self.active_orders.get(vt_orderid)
order_grid = order_info.get('grid', None)
if (order_info.get('status', None) in [Status.CANCELLED, Status.REJECTED]):
self.active_orders.pop(vt_orderid, None)
continue
order_time = order_info.get('order_time')
over_ms = (dt - order_time).total_seconds()
if (f'{dt.hour}:{dt.minute}' in ['10:30', '13:30']):
continue
if ((over_ms > self.cancel_seconds) or force):
self.write_log(f'{dt}, 超时{over_ms}秒未成交,取消委托单:{order_info}')
if self.cancel_order(vt_orderid):
order_info.update({'status': Status.CANCELLING})
else:
order_info.update({'status': Status.CANCELLED})
if order_grid:
if (vt_orderid in order_grid.order_ids):
order_grid.order_ids.remove(vt_orderid)
if (len(order_grid.order_ids) == 0):
order_grid.order_status = False
if (len(self.active_orders) < 1):
self.entrust = 0 | -7,555,482,025,060,726,000 | 撤单逻辑 | vnpy/app/cta_strategy_pro/template.py | tns_cancel_logic | UtorYeung/vnpy | python | def tns_cancel_logic(self, dt, force=False):
if (len(self.active_orders) < 1):
self.entrust = 0
return
for vt_orderid in list(self.active_orders.keys()):
order_info = self.active_orders.get(vt_orderid)
order_grid = order_info.get('grid', None)
if (order_info.get('status', None) in [Status.CANCELLED, Status.REJECTED]):
self.active_orders.pop(vt_orderid, None)
continue
order_time = order_info.get('order_time')
over_ms = (dt - order_time).total_seconds()
if (f'{dt.hour}:{dt.minute}' in ['10:30', '13:30']):
continue
if ((over_ms > self.cancel_seconds) or force):
self.write_log(f'{dt}, 超时{over_ms}秒未成交,取消委托单:{order_info}')
if self.cancel_order(vt_orderid):
order_info.update({'status': Status.CANCELLING})
else:
order_info.update({'status': Status.CANCELLED})
if order_grid:
if (vt_orderid in order_grid.order_ids):
order_grid.order_ids.remove(vt_orderid)
if (len(order_grid.order_ids) == 0):
order_grid.order_status = False
if (len(self.active_orders) < 1):
self.entrust = 0 |
def tns_switch_long_pos(self, open_new=True):
'\n 切换合约,从持仓的非主力合约,切换至主力合约\n :param open_new: 是否开仓主力合约\n :return:\n '
if (self.entrust != 0):
return
if (self.position.long_pos == 0):
return
if (self.cur_mi_price == 0):
return
none_mi_grid = None
none_mi_symbol = None
self.write_log(f'持仓换月=>启动.')
for g in self.gt.get_opened_grids(direction=Direction.LONG):
none_mi_symbol = g.snapshot.get('mi_symbol', g.vt_symbol)
if ((none_mi_symbol is None) or (none_mi_symbol == self.vt_symbol)):
self.write_log(f'none_mi_symbol:{none_mi_symbol}, vt_symbol:{self.vt_symbol} 一致,不处理')
continue
if ((not g.open_status) or g.order_status or ((g.volume - g.traded_volume) <= 0)):
self.write_log(f'开仓状态:{g.open_status}, 委托状态:{g.order_status},网格持仓:{g.volume} ,已交易数量:{g.traded_volume}, 不处理')
continue
none_mi_grid = g
if ((g.traded_volume > 0) and ((g.volume - g.traded_volume) > 0)):
g.volume -= g.traded_volume
g.traded_volume = 0
break
if (none_mi_grid is None):
return
self.write_log(f'持仓换月=>找到多单持仓:{none_mi_symbol},持仓数量:{none_mi_grid.volume}')
none_mi_tick = self.tick_dict.get(none_mi_symbol)
mi_tick = self.tick_dict.get(self.vt_symbol, None)
if ((none_mi_tick is None) or (mi_tick is None)):
return
if (self.is_upper_limit(none_mi_symbol) or self.is_upper_limit(self.vt_symbol)):
self.write_log(f'{none_mi_symbol} 或 {self.vt_symbol} 为涨停价,不做换仓')
return
none_mi_price = max(none_mi_tick.last_price, none_mi_tick.bid_price_1)
grid = deepcopy(none_mi_grid)
grid.id = str(uuid.uuid1())
grid.open_status = False
self.write_log(f'持仓换月=>复制持仓信息{none_mi_symbol},ID:{none_mi_grid.id} => {self.vt_symbol},ID:{grid.id}')
vt_orderids = self.sell(price=none_mi_price, volume=none_mi_grid.volume, vt_symbol=none_mi_symbol, order_type=self.order_type, grid=none_mi_grid)
if (len(vt_orderids) > 0):
self.write_log(f'持仓换月=>委托卖出非主力合约{none_mi_symbol}持仓:{none_mi_grid.volume}')
if none_mi_grid.snapshot.get('switched', False):
self.write_log(f'持仓换月=>已经执行过换月,不再创建新的买入操作')
return
none_mi_grid.snapshot.update({'switched': True})
if (not open_new):
self.write_log(f'不买入新的主力合约:{self.vt_symbol},数量:{grid.volume}')
self.gt.save()
return
grid.snapshot.update({'mi_symbol': self.vt_symbol, 'open_price': self.cur_mi_price})
self.gt.dn_grids.append(grid)
vt_orderids = self.buy(price=(self.cur_mi_price + (5 * self.price_tick)), volume=grid.volume, vt_symbol=self.vt_symbol, order_type=self.order_type, grid=grid)
if (len(vt_orderids) > 0):
self.write_log(u'持仓换月=>委托买入主力合约:{},价格:{},数量:{}'.format(self.vt_symbol, self.cur_mi_price, grid.volume))
else:
self.write_error(f'持仓换月=>委托买入主力合约:{self.vt_symbol}失败')
self.gt.save()
else:
self.write_error(f'持仓换月=>委托卖出非主力合约:{none_mi_symbol}失败') | -7,377,124,469,565,173,000 | 切换合约,从持仓的非主力合约,切换至主力合约
:param open_new: 是否开仓主力合约
:return: | vnpy/app/cta_strategy_pro/template.py | tns_switch_long_pos | UtorYeung/vnpy | python | def tns_switch_long_pos(self, open_new=True):
'\n 切换合约,从持仓的非主力合约,切换至主力合约\n :param open_new: 是否开仓主力合约\n :return:\n '
if (self.entrust != 0):
return
if (self.position.long_pos == 0):
return
if (self.cur_mi_price == 0):
return
none_mi_grid = None
none_mi_symbol = None
self.write_log(f'持仓换月=>启动.')
for g in self.gt.get_opened_grids(direction=Direction.LONG):
none_mi_symbol = g.snapshot.get('mi_symbol', g.vt_symbol)
if ((none_mi_symbol is None) or (none_mi_symbol == self.vt_symbol)):
self.write_log(f'none_mi_symbol:{none_mi_symbol}, vt_symbol:{self.vt_symbol} 一致,不处理')
continue
if ((not g.open_status) or g.order_status or ((g.volume - g.traded_volume) <= 0)):
self.write_log(f'开仓状态:{g.open_status}, 委托状态:{g.order_status},网格持仓:{g.volume} ,已交易数量:{g.traded_volume}, 不处理')
continue
none_mi_grid = g
if ((g.traded_volume > 0) and ((g.volume - g.traded_volume) > 0)):
g.volume -= g.traded_volume
g.traded_volume = 0
break
if (none_mi_grid is None):
return
self.write_log(f'持仓换月=>找到多单持仓:{none_mi_symbol},持仓数量:{none_mi_grid.volume}')
none_mi_tick = self.tick_dict.get(none_mi_symbol)
mi_tick = self.tick_dict.get(self.vt_symbol, None)
if ((none_mi_tick is None) or (mi_tick is None)):
return
if (self.is_upper_limit(none_mi_symbol) or self.is_upper_limit(self.vt_symbol)):
self.write_log(f'{none_mi_symbol} 或 {self.vt_symbol} 为涨停价,不做换仓')
return
none_mi_price = max(none_mi_tick.last_price, none_mi_tick.bid_price_1)
grid = deepcopy(none_mi_grid)
grid.id = str(uuid.uuid1())
grid.open_status = False
self.write_log(f'持仓换月=>复制持仓信息{none_mi_symbol},ID:{none_mi_grid.id} => {self.vt_symbol},ID:{grid.id}')
vt_orderids = self.sell(price=none_mi_price, volume=none_mi_grid.volume, vt_symbol=none_mi_symbol, order_type=self.order_type, grid=none_mi_grid)
if (len(vt_orderids) > 0):
self.write_log(f'持仓换月=>委托卖出非主力合约{none_mi_symbol}持仓:{none_mi_grid.volume}')
if none_mi_grid.snapshot.get('switched', False):
self.write_log(f'持仓换月=>已经执行过换月,不再创建新的买入操作')
return
none_mi_grid.snapshot.update({'switched': True})
if (not open_new):
self.write_log(f'不买入新的主力合约:{self.vt_symbol},数量:{grid.volume}')
self.gt.save()
return
grid.snapshot.update({'mi_symbol': self.vt_symbol, 'open_price': self.cur_mi_price})
self.gt.dn_grids.append(grid)
vt_orderids = self.buy(price=(self.cur_mi_price + (5 * self.price_tick)), volume=grid.volume, vt_symbol=self.vt_symbol, order_type=self.order_type, grid=grid)
if (len(vt_orderids) > 0):
self.write_log(u'持仓换月=>委托买入主力合约:{},价格:{},数量:{}'.format(self.vt_symbol, self.cur_mi_price, grid.volume))
else:
self.write_error(f'持仓换月=>委托买入主力合约:{self.vt_symbol}失败')
self.gt.save()
else:
self.write_error(f'持仓换月=>委托卖出非主力合约:{none_mi_symbol}失败') |
def tns_switch_short_pos(self, open_new=True):
'\n 切换合约,从持仓的非主力合约,切换至主力合约\n :param open_new: 是否开仓新得主力合约\n :return:\n '
if (self.entrust != 0):
return
if (self.position.short_pos == 0):
return
if (self.cur_mi_price == 0):
return
none_mi_grid = None
none_mi_symbol = None
for g in self.gt.get_opened_grids(direction=Direction.SHORT):
none_mi_symbol = g.snapshot.get('mi_symbol')
if ((none_mi_symbol is None) or (none_mi_symbol == self.vt_symbol)):
continue
if ((not g.open_status) or g.order_status or ((g.volume - g.traded_volume) <= 0)):
continue
none_mi_grid = g
if ((g.traded_volume > 0) and ((g.volume - g.traded_volume) > 0)):
g.volume -= g.traded_volume
g.traded_volume = 0
break
if (none_mi_grid is None):
return
none_mi_tick = self.tick_dict.get(none_mi_symbol)
mi_tick = self.tick_dict.get(self.vt_symbol, None)
if ((none_mi_tick is None) or (mi_tick is None)):
return
if (self.is_lower_limit(none_mi_symbol) or self.is_lower_limit(self.vt_symbol)):
return
none_mi_price = max(none_mi_tick.last_price, none_mi_tick.bid_price_1)
grid = deepcopy(none_mi_grid)
grid.id = str(uuid.uuid1())
vt_orderids = self.cover(price=none_mi_price, volume=none_mi_grid.volume, vt_symbol=none_mi_symbol, order_type=self.order_type, grid=none_mi_grid)
if (len(vt_orderids) > 0):
self.write_log(f'委托平空非主力合约{none_mi_symbol}持仓:{none_mi_grid.volume}')
if none_mi_grid.snapshot.get('switched', False):
self.write_log(f'已经执行过换月,不再创建新的空操作')
return
none_mi_grid.snapshot.update({'switched': True})
if (not open_new):
self.write_log(f'不开空新的主力合约:{self.vt_symbol},数量:{grid.volume}')
self.gt.save()
return
grid.id = str(uuid.uuid1())
grid.snapshot.update({'mi_symbol': self.vt_symbol, 'open_price': self.cur_mi_price})
self.gt.up_grids.append(grid)
vt_orderids = self.short(price=self.cur_mi_price, volume=grid.volume, vt_symbol=self.vt_symbol, order_type=self.order_type, grid=grid)
if (len(vt_orderids) > 0):
self.write_log(f'委托做空主力合约:{self.vt_symbol},价格:{self.cur_mi_price},数量:{grid.volume}')
else:
self.write_error(f'委托做空主力合约:{self.vt_symbol}失败')
self.gt.save()
else:
self.write_error(f'委托平空非主力合约:{none_mi_symbol}失败') | -2,319,968,849,727,294,500 | 切换合约,从持仓的非主力合约,切换至主力合约
:param open_new: 是否开仓新得主力合约
:return: | vnpy/app/cta_strategy_pro/template.py | tns_switch_short_pos | UtorYeung/vnpy | python | def tns_switch_short_pos(self, open_new=True):
'\n 切换合约,从持仓的非主力合约,切换至主力合约\n :param open_new: 是否开仓新得主力合约\n :return:\n '
if (self.entrust != 0):
return
if (self.position.short_pos == 0):
return
if (self.cur_mi_price == 0):
return
none_mi_grid = None
none_mi_symbol = None
for g in self.gt.get_opened_grids(direction=Direction.SHORT):
none_mi_symbol = g.snapshot.get('mi_symbol')
if ((none_mi_symbol is None) or (none_mi_symbol == self.vt_symbol)):
continue
if ((not g.open_status) or g.order_status or ((g.volume - g.traded_volume) <= 0)):
continue
none_mi_grid = g
if ((g.traded_volume > 0) and ((g.volume - g.traded_volume) > 0)):
g.volume -= g.traded_volume
g.traded_volume = 0
break
if (none_mi_grid is None):
return
none_mi_tick = self.tick_dict.get(none_mi_symbol)
mi_tick = self.tick_dict.get(self.vt_symbol, None)
if ((none_mi_tick is None) or (mi_tick is None)):
return
if (self.is_lower_limit(none_mi_symbol) or self.is_lower_limit(self.vt_symbol)):
return
none_mi_price = max(none_mi_tick.last_price, none_mi_tick.bid_price_1)
grid = deepcopy(none_mi_grid)
grid.id = str(uuid.uuid1())
vt_orderids = self.cover(price=none_mi_price, volume=none_mi_grid.volume, vt_symbol=none_mi_symbol, order_type=self.order_type, grid=none_mi_grid)
if (len(vt_orderids) > 0):
self.write_log(f'委托平空非主力合约{none_mi_symbol}持仓:{none_mi_grid.volume}')
if none_mi_grid.snapshot.get('switched', False):
self.write_log(f'已经执行过换月,不再创建新的空操作')
return
none_mi_grid.snapshot.update({'switched': True})
if (not open_new):
self.write_log(f'不开空新的主力合约:{self.vt_symbol},数量:{grid.volume}')
self.gt.save()
return
grid.id = str(uuid.uuid1())
grid.snapshot.update({'mi_symbol': self.vt_symbol, 'open_price': self.cur_mi_price})
self.gt.up_grids.append(grid)
vt_orderids = self.short(price=self.cur_mi_price, volume=grid.volume, vt_symbol=self.vt_symbol, order_type=self.order_type, grid=grid)
if (len(vt_orderids) > 0):
self.write_log(f'委托做空主力合约:{self.vt_symbol},价格:{self.cur_mi_price},数量:{grid.volume}')
else:
self.write_error(f'委托做空主力合约:{self.vt_symbol}失败')
self.gt.save()
else:
self.write_error(f'委托平空非主力合约:{none_mi_symbol}失败') |
def display_grids(self):
'更新网格显示信息'
if (not self.inited):
return
up_grids_info = self.gt.to_str(direction=Direction.SHORT)
if (len(self.gt.up_grids) > 0):
self.write_log(up_grids_info)
dn_grids_info = self.gt.to_str(direction=Direction.LONG)
if (len(self.gt.dn_grids) > 0):
self.write_log(dn_grids_info) | -7,978,628,409,817,070,000 | 更新网格显示信息 | vnpy/app/cta_strategy_pro/template.py | display_grids | UtorYeung/vnpy | python | def display_grids(self):
if (not self.inited):
return
up_grids_info = self.gt.to_str(direction=Direction.SHORT)
if (len(self.gt.up_grids) > 0):
self.write_log(up_grids_info)
dn_grids_info = self.gt.to_str(direction=Direction.LONG)
if (len(self.gt.dn_grids) > 0):
self.write_log(dn_grids_info) |
def display_tns(self):
'显示事务的过程记录=》 log'
if (not self.inited):
return
self.write_log(u'{} 当前指数{}价格:{},当前主力{}价格:{}'.format(self.cur_datetime, self.idx_symbol, self.cur_99_price, self.vt_symbol, self.cur_mi_price))
if hasattr(self, 'policy'):
policy = getattr(self, 'policy')
op = getattr(policy, 'to_json', None)
if callable(op):
self.write_log(u'当前Policy:{}'.format(policy.to_json())) | -1,050,589,898,606,807,700 | 显示事务的过程记录=》 log | vnpy/app/cta_strategy_pro/template.py | display_tns | UtorYeung/vnpy | python | def display_tns(self):
if (not self.inited):
return
self.write_log(u'{} 当前指数{}价格:{},当前主力{}价格:{}'.format(self.cur_datetime, self.idx_symbol, self.cur_99_price, self.vt_symbol, self.cur_mi_price))
if hasattr(self, 'policy'):
policy = getattr(self, 'policy')
op = getattr(policy, 'to_json', None)
if callable(op):
self.write_log(u'当前Policy:{}'.format(policy.to_json())) |
def save_dist(self, dist_data):
'\n 保存策略逻辑过程记录=》 csv文件按\n :param dist_data:\n :return:\n '
if self.backtesting:
save_path = self.cta_engine.get_logs_path()
else:
save_path = self.cta_engine.get_data_path()
try:
if (self.position and ('long_pos' not in dist_data)):
dist_data.update({'long_pos': self.position.long_pos})
if (self.position and ('short_pos' not in dist_data)):
dist_data.update({'short_pos': self.position.short_pos})
file_name = os.path.abspath(os.path.join(save_path, f'{self.strategy_name}_dist.csv'))
append_data(file_name=file_name, dict_data=dist_data, field_names=self.dist_fieldnames)
except Exception as ex:
self.write_error(u'save_dist 异常:{} {}'.format(str(ex), traceback.format_exc())) | 6,534,891,654,396,555,000 | 保存策略逻辑过程记录=》 csv文件按
:param dist_data:
:return: | vnpy/app/cta_strategy_pro/template.py | save_dist | UtorYeung/vnpy | python | def save_dist(self, dist_data):
'\n 保存策略逻辑过程记录=》 csv文件按\n :param dist_data:\n :return:\n '
if self.backtesting:
save_path = self.cta_engine.get_logs_path()
else:
save_path = self.cta_engine.get_data_path()
try:
if (self.position and ('long_pos' not in dist_data)):
dist_data.update({'long_pos': self.position.long_pos})
if (self.position and ('short_pos' not in dist_data)):
dist_data.update({'short_pos': self.position.short_pos})
file_name = os.path.abspath(os.path.join(save_path, f'{self.strategy_name}_dist.csv'))
append_data(file_name=file_name, dict_data=dist_data, field_names=self.dist_fieldnames)
except Exception as ex:
self.write_error(u'save_dist 异常:{} {}'.format(str(ex), traceback.format_exc())) |
def save_tns(self, tns_data):
'\n 保存多空事务记录=》csv文件,便于后续分析\n :param tns_data: {"datetime":xxx, "direction":"long"或者"short", "price":xxx}\n :return:\n '
if self.backtesting:
save_path = self.cta_engine.get_logs_path()
else:
save_path = self.cta_engine.get_data_path()
try:
file_name = os.path.abspath(os.path.join(save_path, f'{self.strategy_name}_tns.csv'))
append_data(file_name=file_name, dict_data=tns_data)
except Exception as ex:
self.write_error(u'save_tns 异常:{} {}'.format(str(ex), traceback.format_exc())) | 3,043,168,499,550,988,000 | 保存多空事务记录=》csv文件,便于后续分析
:param tns_data: {"datetime":xxx, "direction":"long"或者"short", "price":xxx}
:return: | vnpy/app/cta_strategy_pro/template.py | save_tns | UtorYeung/vnpy | python | def save_tns(self, tns_data):
'\n 保存多空事务记录=》csv文件,便于后续分析\n :param tns_data: {"datetime":xxx, "direction":"long"或者"short", "price":xxx}\n :return:\n '
if self.backtesting:
save_path = self.cta_engine.get_logs_path()
else:
save_path = self.cta_engine.get_data_path()
try:
file_name = os.path.abspath(os.path.join(save_path, f'{self.strategy_name}_tns.csv'))
append_data(file_name=file_name, dict_data=tns_data)
except Exception as ex:
self.write_error(u'save_tns 异常:{} {}'.format(str(ex), traceback.format_exc())) |
def send_wechat(self, msg: str):
'实盘时才发送微信'
if self.backtesting:
return
self.cta_engine.send_wechat(msg=msg, strategy=self) | 4,796,113,719,315,409,000 | 实盘时才发送微信 | vnpy/app/cta_strategy_pro/template.py | send_wechat | UtorYeung/vnpy | python | def send_wechat(self, msg: str):
if self.backtesting:
return
self.cta_engine.send_wechat(msg=msg, strategy=self) |
def update_setting(self, setting: dict):
'更新配置参数'
super().update_setting(setting)
if (not self.backtesting):
if self.activate_fak:
self.order_type = OrderType.FAK | 8,905,263,113,275,753,000 | 更新配置参数 | vnpy/app/cta_strategy_pro/template.py | update_setting | UtorYeung/vnpy | python | def update_setting(self, setting: dict):
super().update_setting(setting)
if (not self.backtesting):
if self.activate_fak:
self.order_type = OrderType.FAK |
def load_policy(self):
'加载policy'
if self.policy:
self.write_log(u'load_policy(),初始化Policy')
self.policy.load()
self.write_log(u'Policy:{}'.format(self.policy.to_json())) | -1,173,244,053,206,510,600 | 加载policy | vnpy/app/cta_strategy_pro/template.py | load_policy | UtorYeung/vnpy | python | def load_policy(self):
if self.policy:
self.write_log(u'load_policy(),初始化Policy')
self.policy.load()
self.write_log(u'Policy:{}'.format(self.policy.to_json())) |
def on_start(self):
'启动策略(必须由用户继承实现)'
self.write_log(u'启动')
self.trading = True
self.put_event() | -5,815,070,311,948,098,000 | 启动策略(必须由用户继承实现) | vnpy/app/cta_strategy_pro/template.py | on_start | UtorYeung/vnpy | python | def on_start(self):
self.write_log(u'启动')
self.trading = True
self.put_event() |
def on_stop(self):
'停止策略(必须由用户继承实现)'
self.active_orders.clear()
self.pos = 0
self.entrust = 0
self.write_log(u'停止')
self.put_event() | -7,447,439,848,410,118,000 | 停止策略(必须由用户继承实现) | vnpy/app/cta_strategy_pro/template.py | on_stop | UtorYeung/vnpy | python | def on_stop(self):
self.active_orders.clear()
self.pos = 0
self.entrust = 0
self.write_log(u'停止')
self.put_event() |
def on_trade(self, trade: TradeData):
'\n 交易更新\n 支持股指期货的对锁单或者解锁\n :param trade:\n :return:\n '
self.write_log(u'{},交易更新 =>{},\n 当前持仓:{} '.format(self.cur_datetime, trade.__dict__, self.position.pos))
dist_record = dict()
if self.backtesting:
dist_record['datetime'] = trade.time
else:
dist_record['datetime'] = ' '.join([self.cur_datetime.strftime('%Y-%m-%d'), trade.time])
dist_record['volume'] = trade.volume
dist_record['price'] = trade.price
dist_record['symbol'] = trade.vt_symbol
if ((trade.exchange == Exchange.CFFEX) and (not self.backtesting)):
if (trade.direction == Direction.LONG):
if (abs(self.position.short_pos) >= trade.volume):
self.position.short_pos += trade.volume
else:
self.position.long_pos += trade.volume
elif (self.position.long_pos >= trade.volume):
self.position.long_pos -= trade.volume
else:
self.position.short_pos -= trade.volume
self.position.pos = (self.position.long_pos + self.position.short_pos)
dist_record['long_pos'] = self.position.long_pos
dist_record['short_pos'] = self.position.short_pos
else:
if ((trade.direction == Direction.LONG) and (trade.offset == Offset.OPEN)):
dist_record['operation'] = 'buy'
self.position.open_pos(trade.direction, volume=trade.volume)
dist_record['long_pos'] = self.position.long_pos
dist_record['short_pos'] = self.position.short_pos
if ((trade.direction == Direction.SHORT) and (trade.offset == Offset.OPEN)):
dist_record['operation'] = 'short'
self.position.open_pos(trade.direction, volume=trade.volume)
dist_record['long_pos'] = self.position.long_pos
dist_record['short_pos'] = self.position.short_pos
if ((trade.direction == Direction.LONG) and (trade.offset != Offset.OPEN)):
dist_record['operation'] = 'cover'
self.position.close_pos(trade.direction, volume=trade.volume)
dist_record['long_pos'] = self.position.long_pos
dist_record['short_pos'] = self.position.short_pos
if ((trade.direction == Direction.SHORT) and (trade.offset != Offset.OPEN)):
dist_record['operation'] = 'sell'
self.position.close_pos(trade.direction, volume=trade.volume)
dist_record['long_pos'] = self.position.long_pos
dist_record['short_pos'] = self.position.short_pos
self.save_dist(dist_record)
self.pos = self.position.pos | -1,073,388,828,579,977,900 | 交易更新
支持股指期货的对锁单或者解锁
:param trade:
:return: | vnpy/app/cta_strategy_pro/template.py | on_trade | UtorYeung/vnpy | python | def on_trade(self, trade: TradeData):
'\n 交易更新\n 支持股指期货的对锁单或者解锁\n :param trade:\n :return:\n '
self.write_log(u'{},交易更新 =>{},\n 当前持仓:{} '.format(self.cur_datetime, trade.__dict__, self.position.pos))
dist_record = dict()
if self.backtesting:
dist_record['datetime'] = trade.time
else:
dist_record['datetime'] = ' '.join([self.cur_datetime.strftime('%Y-%m-%d'), trade.time])
dist_record['volume'] = trade.volume
dist_record['price'] = trade.price
dist_record['symbol'] = trade.vt_symbol
if ((trade.exchange == Exchange.CFFEX) and (not self.backtesting)):
if (trade.direction == Direction.LONG):
if (abs(self.position.short_pos) >= trade.volume):
self.position.short_pos += trade.volume
else:
self.position.long_pos += trade.volume
elif (self.position.long_pos >= trade.volume):
self.position.long_pos -= trade.volume
else:
self.position.short_pos -= trade.volume
self.position.pos = (self.position.long_pos + self.position.short_pos)
dist_record['long_pos'] = self.position.long_pos
dist_record['short_pos'] = self.position.short_pos
else:
if ((trade.direction == Direction.LONG) and (trade.offset == Offset.OPEN)):
dist_record['operation'] = 'buy'
self.position.open_pos(trade.direction, volume=trade.volume)
dist_record['long_pos'] = self.position.long_pos
dist_record['short_pos'] = self.position.short_pos
if ((trade.direction == Direction.SHORT) and (trade.offset == Offset.OPEN)):
dist_record['operation'] = 'short'
self.position.open_pos(trade.direction, volume=trade.volume)
dist_record['long_pos'] = self.position.long_pos
dist_record['short_pos'] = self.position.short_pos
if ((trade.direction == Direction.LONG) and (trade.offset != Offset.OPEN)):
dist_record['operation'] = 'cover'
self.position.close_pos(trade.direction, volume=trade.volume)
dist_record['long_pos'] = self.position.long_pos
dist_record['short_pos'] = self.position.short_pos
if ((trade.direction == Direction.SHORT) and (trade.offset != Offset.OPEN)):
dist_record['operation'] = 'sell'
self.position.close_pos(trade.direction, volume=trade.volume)
dist_record['long_pos'] = self.position.long_pos
dist_record['short_pos'] = self.position.short_pos
self.save_dist(dist_record)
self.pos = self.position.pos |
def fix_order(self, order: OrderData):
'修正order被拆单得情况'
order_info = self.active_orders.get(order.vt_orderid, None)
if order_info:
volume = order_info.get('volume')
if (volume != order.volume):
self.write_log(f'修正order被拆单得情况,调整{order.vt_orderid} volume:{volume}=>{order.volume}')
order_info.update({'volume': order.volume}) | -1,537,104,623,017,642,000 | 修正order被拆单得情况 | vnpy/app/cta_strategy_pro/template.py | fix_order | UtorYeung/vnpy | python | def fix_order(self, order: OrderData):
order_info = self.active_orders.get(order.vt_orderid, None)
if order_info:
volume = order_info.get('volume')
if (volume != order.volume):
self.write_log(f',调整{order.vt_orderid} volume:{volume}=>{order.volume}')
order_info.update({'volume': order.volume}) |
def on_order(self, order: OrderData):
'报单更新'
self.write_log(u'{}报单更新 => {}'.format(self.cur_datetime, order.__dict__))
self.fix_order(order)
if (order.vt_orderid in self.active_orders):
active_order = self.active_orders[order.vt_orderid]
if ((order.volume == order.traded) and (order.status in [Status.ALLTRADED])):
self.on_order_all_traded(order)
elif ((active_order['offset'] == Offset.OPEN) and (order.status in [Status.CANCELLED])):
self.on_order_open_canceled(order)
elif ((active_order['offset'] != Offset.OPEN) and (order.status in [Status.CANCELLED])):
self.on_order_close_canceled(order)
elif (order.status == Status.REJECTED):
if (active_order['offset'] == Offset.OPEN):
self.write_error(u'{}委托单开{}被拒,price:{},total:{},traded:{},status:{}'.format(order.vt_symbol, order.direction, order.price, order.volume, order.traded, order.status))
self.on_order_open_canceled(order)
else:
self.write_error(u'OnOrder({})委托单平{}被拒,price:{},total:{},traded:{},status:{}'.format(order.vt_symbol, order.direction, order.price, order.volume, order.traded, order.status))
self.on_order_close_canceled(order)
else:
self.write_log(u'委托单未完成,total:{},traded:{},tradeStatus:{}'.format(order.volume, order.traded, order.status))
else:
self.write_error(u'委托单{}不在策略的未完成订单列表中:{}'.format(order.vt_orderid, self.active_orders)) | -6,724,270,649,476,190,000 | 报单更新 | vnpy/app/cta_strategy_pro/template.py | on_order | UtorYeung/vnpy | python | def on_order(self, order: OrderData):
self.write_log(u'{} => {}'.format(self.cur_datetime, order.__dict__))
self.fix_order(order)
if (order.vt_orderid in self.active_orders):
active_order = self.active_orders[order.vt_orderid]
if ((order.volume == order.traded) and (order.status in [Status.ALLTRADED])):
self.on_order_all_traded(order)
elif ((active_order['offset'] == Offset.OPEN) and (order.status in [Status.CANCELLED])):
self.on_order_open_canceled(order)
elif ((active_order['offset'] != Offset.OPEN) and (order.status in [Status.CANCELLED])):
self.on_order_close_canceled(order)
elif (order.status == Status.REJECTED):
if (active_order['offset'] == Offset.OPEN):
self.write_error(u'{}委托单开{}被拒,price:{},total:{},traded:{},status:{}'.format(order.vt_symbol, order.direction, order.price, order.volume, order.traded, order.status))
self.on_order_open_canceled(order)
else:
self.write_error(u'OnOrder({})委托单平{}被拒,price:{},total:{},traded:{},status:{}'.format(order.vt_symbol, order.direction, order.price, order.volume, order.traded, order.status))
self.on_order_close_canceled(order)
else:
self.write_log(u'委托单未完成,total:{},traded:{},tradeStatus:{}'.format(order.volume, order.traded, order.status))
else:
self.write_error(u'委托单{}不在策略的未完成订单列表中:{}'.format(order.vt_orderid, self.active_orders)) |
def on_order_all_traded(self, order: OrderData):
'\n 订单全部成交\n :param order:\n :return:\n '
self.write_log(u'报单更新 => 委托单全部完成:{}'.format(order.__dict__))
active_order = self.active_orders[order.vt_orderid]
grid = active_order.get('grid', None)
if (grid is not None):
if (order.vt_orderid in grid.order_ids):
grid.order_ids.remove(order.vt_orderid)
if (len(grid.order_ids) == 0):
grid.order_status = False
grid.traded_volume = 0
if (active_order['offset'] != Offset.OPEN):
grid.open_status = False
grid.close_status = True
grid.open_time = None
self.write_log((f'{grid.direction.value}单已平仓完毕,order_price:{order.price}' + f',volume:{order.volume}'))
self.write_log(f'移除网格:{grid.to_json()}')
self.gt.remove_grids_by_ids(direction=grid.direction, ids=[grid.id])
else:
grid.open_status = True
grid.open_time = self.cur_datetime
self.write_log((f'{grid.direction.value}单已开仓完毕,order_price:{order.price}' + f',volume:{order.volume}'))
else:
old_traded_volume = grid.traded_volume
grid.traded_volume += order.volume
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
self.write_log(f'剩余委托单号:{grid.order_ids}')
self.gt.save()
else:
self.write_error(f'on_trade找不到对应grid')
self.active_orders.pop(order.vt_orderid, None) | 7,630,674,831,798,039,000 | 订单全部成交
:param order:
:return: | vnpy/app/cta_strategy_pro/template.py | on_order_all_traded | UtorYeung/vnpy | python | def on_order_all_traded(self, order: OrderData):
'\n 订单全部成交\n :param order:\n :return:\n '
self.write_log(u'报单更新 => 委托单全部完成:{}'.format(order.__dict__))
active_order = self.active_orders[order.vt_orderid]
grid = active_order.get('grid', None)
if (grid is not None):
if (order.vt_orderid in grid.order_ids):
grid.order_ids.remove(order.vt_orderid)
if (len(grid.order_ids) == 0):
grid.order_status = False
grid.traded_volume = 0
if (active_order['offset'] != Offset.OPEN):
grid.open_status = False
grid.close_status = True
grid.open_time = None
self.write_log((f'{grid.direction.value}单已平仓完毕,order_price:{order.price}' + f',volume:{order.volume}'))
self.write_log(f'移除网格:{grid.to_json()}')
self.gt.remove_grids_by_ids(direction=grid.direction, ids=[grid.id])
else:
grid.open_status = True
grid.open_time = self.cur_datetime
self.write_log((f'{grid.direction.value}单已开仓完毕,order_price:{order.price}' + f',volume:{order.volume}'))
else:
old_traded_volume = grid.traded_volume
grid.traded_volume += order.volume
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
self.write_log(f'剩余委托单号:{grid.order_ids}')
self.gt.save()
else:
self.write_error(f'on_trade找不到对应grid')
self.active_orders.pop(order.vt_orderid, None) |
def on_order_open_canceled(self, order: OrderData):
'\n 委托开仓单撤销\n 如果是FAK模式,重新修改价格,再提交\n FAK用于实盘,需要增加涨跌停判断\n :param order:\n :return:\n '
self.write_log(u'报单更新 => 委托开仓 => 撤销:{}'.format(order.__dict__))
if (not self.trading):
if (not self.backtesting):
self.write_error(u'当前不允许交易')
return
if (order.vt_orderid not in self.active_orders):
self.write_error(u'{}不在未完成的委托单中{}。'.format(order.vt_orderid, self.active_orders))
return
old_order = self.active_orders[order.vt_orderid]
self.write_log(u'报单更新 => {} 未完成订单信息:{}'.format(order.vt_orderid, old_order))
old_order['traded'] = order.traded
order_vt_symbol = copy(old_order['vt_symbol'])
order_volume = (old_order['volume'] - old_order['traded'])
order_price = old_order['price']
order_type = old_order.get('order_type', OrderType.LIMIT)
order_retry = old_order.get('retry', 0)
grid = old_order.get('grid', None)
if grid:
if (order.vt_orderid in grid.order_ids):
grid.order_ids.remove(order.vt_orderid)
if (order_volume <= 0):
msg = u'{} {}{}需重新开仓数量为{},不再开仓'.format(self.strategy_name, order.vt_orderid, order_vt_symbol, order_volume)
self.write_error(msg)
self.write_log(u'移除:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
return
if (order_retry > 20):
msg = u'{} {}/{}手, 重试开仓次数{}>20'.format(self.strategy_name, order_vt_symbol, order_volume, order_retry)
self.write_error(msg)
self.send_wechat(msg)
if (len(grid.order_ids) == 0):
grid.order_status = False
self.gt.save()
self.write_log(u'网格信息更新:{}'.format(grid.__dict__))
self.write_log(u'移除:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
return
order_retry += 1
if ((old_order['direction'] == Direction.LONG) and (order_type == OrderType.FAK)):
self.write_log(u'移除旧的委托记录:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
if (order.traded > 0):
old_traded_volume = grid.traded_volume
grid.traded_volume += order.traded
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
self.write_log(u'FAK模式,需要重新发送buy委托.grid:{}'.format(grid.__dict__))
buy_price = (max(self.cur_mi_tick.ask_price_1, self.cur_mi_tick.last_price, order_price) + self.price_tick)
if ((self.cur_mi_tick.limit_up > 0) and (buy_price > self.cur_mi_tick.limit_up)):
buy_price = self.cur_mi_tick.limit_up
if self.is_upper_limit(self.vt_symbol):
self.write_log(u'{}涨停,不做buy'.format(self.vt_symbol))
return
vt_orderids = self.buy(price=buy_price, volume=order_volume, vt_symbol=self.vt_symbol, order_type=OrderType.FAK, order_time=self.cur_datetime, grid=grid)
if (not vt_orderids):
self.write_error(u'重新提交{} {}手开多单,价格:{},失败'.format(self.vt_symbol, order_volume, buy_price))
return
for vt_orderid in vt_orderids:
info = self.active_orders.get(vt_orderid, None)
info.update({'retry': order_retry})
self.gt.save()
elif ((old_order['direction'] == Direction.SHORT) and (order_type == OrderType.FAK)):
self.write_log(u'移除旧的委托记录:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
if (order.traded > 0):
old_traded_volume = grid.traded_volume
grid.traded_volume += order.traded
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
self.write_log(u'FAK模式,需要重新发送short委托.grid:{}'.format(grid.__dict__))
short_price = (min(self.cur_mi_tick.bid_price_1, self.cur_mi_tick.last_price, order_price) - self.price_tick)
if ((self.cur_mi_tick.limit_down > 0) and (short_price < self.cur_mi_tick.limit_down)):
short_price = self.cur_mi_tick.limit_down
if self.is_lower_limit(self.vt_symbol):
self.write_log(u'{}跌停,不做short'.format(self.vt_symbol))
return
vt_orderids = self.short(price=short_price, volume=order_volume, vt_symbol=self.vt_symbol, order_type=OrderType.FAK, order_time=self.cur_datetime, grid=grid)
if (not vt_orderids):
self.write_error(u'重新提交{} {}手开空单,价格:{}, 失败'.format(self.vt_symbol, order_volume, short_price))
return
for vt_orderid in vt_orderids:
info = self.active_orders.get(vt_orderid, None)
info.update({'retry': order_retry})
self.gt.save()
else:
pre_status = old_order.get('status', Status.NOTTRADED)
old_order.update({'status': Status.CANCELLED})
self.write_log(u'委托单方式{},状态:{}=>{}'.format(order_type, pre_status, old_order.get('status')))
if grid:
if (order.vt_orderid in grid.order_ids):
grid.order_ids.remove(order.vt_orderid)
if (not grid.order_ids):
grid.order_status = False
self.gt.save()
self.active_orders.update({order.vt_orderid: old_order})
self.display_grids() | -5,928,078,699,495,564,000 | 委托开仓单撤销
如果是FAK模式,重新修改价格,再提交
FAK用于实盘,需要增加涨跌停判断
:param order:
:return: | vnpy/app/cta_strategy_pro/template.py | on_order_open_canceled | UtorYeung/vnpy | python | def on_order_open_canceled(self, order: OrderData):
'\n 委托开仓单撤销\n 如果是FAK模式,重新修改价格,再提交\n FAK用于实盘,需要增加涨跌停判断\n :param order:\n :return:\n '
self.write_log(u'报单更新 => 委托开仓 => 撤销:{}'.format(order.__dict__))
if (not self.trading):
if (not self.backtesting):
self.write_error(u'当前不允许交易')
return
if (order.vt_orderid not in self.active_orders):
self.write_error(u'{}不在未完成的委托单中{}。'.format(order.vt_orderid, self.active_orders))
return
old_order = self.active_orders[order.vt_orderid]
self.write_log(u'报单更新 => {} 未完成订单信息:{}'.format(order.vt_orderid, old_order))
old_order['traded'] = order.traded
order_vt_symbol = copy(old_order['vt_symbol'])
order_volume = (old_order['volume'] - old_order['traded'])
order_price = old_order['price']
order_type = old_order.get('order_type', OrderType.LIMIT)
order_retry = old_order.get('retry', 0)
grid = old_order.get('grid', None)
if grid:
if (order.vt_orderid in grid.order_ids):
grid.order_ids.remove(order.vt_orderid)
if (order_volume <= 0):
msg = u'{} {}{}需重新开仓数量为{},不再开仓'.format(self.strategy_name, order.vt_orderid, order_vt_symbol, order_volume)
self.write_error(msg)
self.write_log(u'移除:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
return
if (order_retry > 20):
msg = u'{} {}/{}手, 重试开仓次数{}>20'.format(self.strategy_name, order_vt_symbol, order_volume, order_retry)
self.write_error(msg)
self.send_wechat(msg)
if (len(grid.order_ids) == 0):
grid.order_status = False
self.gt.save()
self.write_log(u'网格信息更新:{}'.format(grid.__dict__))
self.write_log(u'移除:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
return
order_retry += 1
if ((old_order['direction'] == Direction.LONG) and (order_type == OrderType.FAK)):
self.write_log(u'移除旧的委托记录:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
if (order.traded > 0):
old_traded_volume = grid.traded_volume
grid.traded_volume += order.traded
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
self.write_log(u'FAK模式,需要重新发送buy委托.grid:{}'.format(grid.__dict__))
buy_price = (max(self.cur_mi_tick.ask_price_1, self.cur_mi_tick.last_price, order_price) + self.price_tick)
if ((self.cur_mi_tick.limit_up > 0) and (buy_price > self.cur_mi_tick.limit_up)):
buy_price = self.cur_mi_tick.limit_up
if self.is_upper_limit(self.vt_symbol):
self.write_log(u'{}涨停,不做buy'.format(self.vt_symbol))
return
vt_orderids = self.buy(price=buy_price, volume=order_volume, vt_symbol=self.vt_symbol, order_type=OrderType.FAK, order_time=self.cur_datetime, grid=grid)
if (not vt_orderids):
self.write_error(u'重新提交{} {}手开多单,价格:{},失败'.format(self.vt_symbol, order_volume, buy_price))
return
for vt_orderid in vt_orderids:
info = self.active_orders.get(vt_orderid, None)
info.update({'retry': order_retry})
self.gt.save()
elif ((old_order['direction'] == Direction.SHORT) and (order_type == OrderType.FAK)):
self.write_log(u'移除旧的委托记录:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
if (order.traded > 0):
old_traded_volume = grid.traded_volume
grid.traded_volume += order.traded
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
self.write_log(u'FAK模式,需要重新发送short委托.grid:{}'.format(grid.__dict__))
short_price = (min(self.cur_mi_tick.bid_price_1, self.cur_mi_tick.last_price, order_price) - self.price_tick)
if ((self.cur_mi_tick.limit_down > 0) and (short_price < self.cur_mi_tick.limit_down)):
short_price = self.cur_mi_tick.limit_down
if self.is_lower_limit(self.vt_symbol):
self.write_log(u'{}跌停,不做short'.format(self.vt_symbol))
return
vt_orderids = self.short(price=short_price, volume=order_volume, vt_symbol=self.vt_symbol, order_type=OrderType.FAK, order_time=self.cur_datetime, grid=grid)
if (not vt_orderids):
self.write_error(u'重新提交{} {}手开空单,价格:{}, 失败'.format(self.vt_symbol, order_volume, short_price))
return
for vt_orderid in vt_orderids:
info = self.active_orders.get(vt_orderid, None)
info.update({'retry': order_retry})
self.gt.save()
else:
pre_status = old_order.get('status', Status.NOTTRADED)
old_order.update({'status': Status.CANCELLED})
self.write_log(u'委托单方式{},状态:{}=>{}'.format(order_type, pre_status, old_order.get('status')))
if grid:
if (order.vt_orderid in grid.order_ids):
grid.order_ids.remove(order.vt_orderid)
if (not grid.order_ids):
grid.order_status = False
self.gt.save()
self.active_orders.update({order.vt_orderid: old_order})
self.display_grids() |
def on_order_close_canceled(self, order: OrderData):
'委托平仓单撤销'
self.write_log(u'报单更新 => 委托平仓 => 撤销:{}'.format(order.__dict__))
if (order.vt_orderid not in self.active_orders):
self.write_error(u'{}不在未完成的委托单中:{}。'.format(order.vt_orderid, self.active_orders))
return
if (not self.trading):
self.write_error(u'当前不允许交易')
return
old_order = self.active_orders[order.vt_orderid]
self.write_log(u'报单更新 => {} 未完成订单信息:{}'.format(order.vt_orderid, old_order))
old_order['traded'] = order.traded
order_vt_symbol = copy(old_order['vt_symbol'])
order_volume = (old_order['volume'] - old_order['traded'])
order_price = old_order['price']
order_type = old_order.get('order_type', OrderType.LIMIT)
order_retry = old_order.get('retry', 0)
grid = old_order.get('grid', None)
if grid:
if (order.vt_orderid in grid.order_ids):
grid.order_ids.remove(order.vt_orderid)
if (order_volume <= 0):
msg = u'{} {}{}重新平仓数量为{},不再平仓'.format(self.strategy_name, order.vt_orderid, order_vt_symbol, order_volume)
self.write_error(msg)
self.send_wechat(msg)
self.write_log(u'活动订单移除:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
return
if (order_retry > 20):
msg = u'{} 平仓撤单 {}/{}手, 重试平仓次数{}>20'.format(self.strategy_name, order_vt_symbol, order_volume, order_retry)
self.write_error(msg)
self.send_wechat(msg)
if (not grid.order_ids):
grid.order_status = False
self.gt.save()
self.write_log(u'更新网格=>{}'.format(grid.__dict__))
self.write_log(u'移除活动订单:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
return
order_retry += 1
if ((old_order['direction'] == Direction.LONG) and (order_type == OrderType.FAK)):
self.write_log(u'移除活动订单:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
if (order.traded > 0):
old_traded_volume = grid.traded_volume
grid.traded_volume += order.traded
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
self.write_log(u'FAK模式,需要重新发送cover委托.grid:{}'.format(grid.__dict__))
cover_tick = self.tick_dict.get(order_vt_symbol, self.cur_mi_tick)
cover_price = (max(cover_tick.ask_price_1, cover_tick.last_price, order_price) + self.price_tick)
if ((cover_tick.limit_up > 0) and (cover_price > cover_tick.limit_up)):
cover_price = cover_tick.limit_up
if self.is_upper_limit(order_vt_symbol):
self.write_log(u'{}涨停,不做cover'.format(order_vt_symbol))
return
pos = self.cta_engine.get_position_holding(vt_symbol=order_vt_symbol)
if (pos is None):
self.write_error(f'{self.strategy_name}无法获取{order_vt_symbol}的持仓信息,无法平仓')
return
if (pos.short_pos < order_volume):
self.write_error(f'{self.strategy_name}{order_vt_symbol}的持仓空单{pos.short_pos}不满足平仓{order_volume}要求,无法平仓')
return
vt_orderids = self.cover(price=cover_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=OrderType.FAK, order_time=self.cur_datetime, grid=grid)
if (not vt_orderids):
self.write_error(u'重新提交{} {}手平空单{}失败'.format(order_vt_symbol, order_volume, cover_price))
return
for vt_orderid in vt_orderids:
info = self.active_orders.get(vt_orderid)
info.update({'retry': order_retry})
self.gt.save()
elif ((old_order['direction'] == Direction.SHORT) and (order_type == OrderType.FAK)):
self.write_log(u'移除活动订单:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
if (order.traded > 0):
old_traded_volume = grid.traded_volume
grid.traded_volume += order.traded
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
self.write_log(u'FAK模式,需要重新发送sell委托.grid:{}'.format(grid.__dict__))
sell_tick = self.tick_dict.get(order_vt_symbol, self.cur_mi_tick)
sell_price = (min(sell_tick.bid_price_1, sell_tick.last_price, order_price) - self.price_tick)
if ((sell_tick.limit_down > 0) and (sell_price < sell_tick.limit_down)):
sell_price = sell_tick.limit_down
if self.is_lower_limit(order_vt_symbol):
self.write_log(u'{}涨停,不做sell'.format(order_vt_symbol))
return
pos = self.cta_engine.get_position_holding(vt_symbol=order_vt_symbol)
if (pos is None):
self.write_error(f'{self.strategy_name}无法获取{order_vt_symbol}的持仓信息,无法平仓')
return
if (pos.long_pos < order_volume):
self.write_error(f'{self.strategy_name}{order_vt_symbol}的持仓多单{pos.long_pos}不满足平仓{order_volume}要求,无法平仓')
return
vt_orderids = self.sell(price=sell_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=OrderType.FAK, order_time=self.cur_datetime, grid=grid)
if (not vt_orderids):
self.write_error(u'重新提交{} {}手平多单{}失败'.format(order_vt_symbol, order_volume, sell_price))
return
for vt_orderid in vt_orderids:
info = self.active_orders.get(vt_orderid)
info.update({'retry': order_retry})
self.gt.save()
else:
pre_status = old_order.get('status', Status.NOTTRADED)
old_order.update({'status': Status.CANCELLED})
self.write_log(u'委托单状态:{}=>{}'.format(pre_status, old_order.get('status')))
if grid:
if (order.traded > 0):
old_traded_volume = grid.traded_volume
grid.traded_volume += order.traded
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
if (order.vt_orderid in grid.order_ids):
grid.order_ids.remove(order.vt_orderid)
if (len(grid.order_ids) == 0):
grid.order_status = False
self.gt.save()
self.active_orders.update({order.vt_orderid: old_order})
self.display_grids() | 2,936,763,617,247,122,400 | 委托平仓单撤销 | vnpy/app/cta_strategy_pro/template.py | on_order_close_canceled | UtorYeung/vnpy | python | def on_order_close_canceled(self, order: OrderData):
self.write_log(u'报单更新 => 委托平仓 => 撤销:{}'.format(order.__dict__))
if (order.vt_orderid not in self.active_orders):
self.write_error(u'{}不在未完成的委托单中:{}。'.format(order.vt_orderid, self.active_orders))
return
if (not self.trading):
self.write_error(u'当前不允许交易')
return
old_order = self.active_orders[order.vt_orderid]
self.write_log(u'报单更新 => {} 未完成订单信息:{}'.format(order.vt_orderid, old_order))
old_order['traded'] = order.traded
order_vt_symbol = copy(old_order['vt_symbol'])
order_volume = (old_order['volume'] - old_order['traded'])
order_price = old_order['price']
order_type = old_order.get('order_type', OrderType.LIMIT)
order_retry = old_order.get('retry', 0)
grid = old_order.get('grid', None)
if grid:
if (order.vt_orderid in grid.order_ids):
grid.order_ids.remove(order.vt_orderid)
if (order_volume <= 0):
msg = u'{} {}{}重新平仓数量为{},不再平仓'.format(self.strategy_name, order.vt_orderid, order_vt_symbol, order_volume)
self.write_error(msg)
self.send_wechat(msg)
self.write_log(u'活动订单移除:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
return
if (order_retry > 20):
msg = u'{} 平仓撤单 {}/{}手, 重试平仓次数{}>20'.format(self.strategy_name, order_vt_symbol, order_volume, order_retry)
self.write_error(msg)
self.send_wechat(msg)
if (not grid.order_ids):
grid.order_status = False
self.gt.save()
self.write_log(u'更新网格=>{}'.format(grid.__dict__))
self.write_log(u'移除活动订单:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
return
order_retry += 1
if ((old_order['direction'] == Direction.LONG) and (order_type == OrderType.FAK)):
self.write_log(u'移除活动订单:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
if (order.traded > 0):
old_traded_volume = grid.traded_volume
grid.traded_volume += order.traded
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
self.write_log(u'FAK模式,需要重新发送cover委托.grid:{}'.format(grid.__dict__))
cover_tick = self.tick_dict.get(order_vt_symbol, self.cur_mi_tick)
cover_price = (max(cover_tick.ask_price_1, cover_tick.last_price, order_price) + self.price_tick)
if ((cover_tick.limit_up > 0) and (cover_price > cover_tick.limit_up)):
cover_price = cover_tick.limit_up
if self.is_upper_limit(order_vt_symbol):
self.write_log(u'{}涨停,不做cover'.format(order_vt_symbol))
return
pos = self.cta_engine.get_position_holding(vt_symbol=order_vt_symbol)
if (pos is None):
self.write_error(f'{self.strategy_name}无法获取{order_vt_symbol}的持仓信息,无法平仓')
return
if (pos.short_pos < order_volume):
self.write_error(f'{self.strategy_name}{order_vt_symbol}的持仓空单{pos.short_pos}不满足平仓{order_volume}要求,无法平仓')
return
vt_orderids = self.cover(price=cover_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=OrderType.FAK, order_time=self.cur_datetime, grid=grid)
if (not vt_orderids):
self.write_error(u'重新提交{} {}手平空单{}失败'.format(order_vt_symbol, order_volume, cover_price))
return
for vt_orderid in vt_orderids:
info = self.active_orders.get(vt_orderid)
info.update({'retry': order_retry})
self.gt.save()
elif ((old_order['direction'] == Direction.SHORT) and (order_type == OrderType.FAK)):
self.write_log(u'移除活动订单:{}'.format(order.vt_orderid))
self.active_orders.pop(order.vt_orderid, None)
if (order.traded > 0):
old_traded_volume = grid.traded_volume
grid.traded_volume += order.traded
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
self.write_log(u'FAK模式,需要重新发送sell委托.grid:{}'.format(grid.__dict__))
sell_tick = self.tick_dict.get(order_vt_symbol, self.cur_mi_tick)
sell_price = (min(sell_tick.bid_price_1, sell_tick.last_price, order_price) - self.price_tick)
if ((sell_tick.limit_down > 0) and (sell_price < sell_tick.limit_down)):
sell_price = sell_tick.limit_down
if self.is_lower_limit(order_vt_symbol):
self.write_log(u'{}涨停,不做sell'.format(order_vt_symbol))
return
pos = self.cta_engine.get_position_holding(vt_symbol=order_vt_symbol)
if (pos is None):
self.write_error(f'{self.strategy_name}无法获取{order_vt_symbol}的持仓信息,无法平仓')
return
if (pos.long_pos < order_volume):
self.write_error(f'{self.strategy_name}{order_vt_symbol}的持仓多单{pos.long_pos}不满足平仓{order_volume}要求,无法平仓')
return
vt_orderids = self.sell(price=sell_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=OrderType.FAK, order_time=self.cur_datetime, grid=grid)
if (not vt_orderids):
self.write_error(u'重新提交{} {}手平多单{}失败'.format(order_vt_symbol, order_volume, sell_price))
return
for vt_orderid in vt_orderids:
info = self.active_orders.get(vt_orderid)
info.update({'retry': order_retry})
self.gt.save()
else:
pre_status = old_order.get('status', Status.NOTTRADED)
old_order.update({'status': Status.CANCELLED})
self.write_log(u'委托单状态:{}=>{}'.format(pre_status, old_order.get('status')))
if grid:
if (order.traded > 0):
old_traded_volume = grid.traded_volume
grid.traded_volume += order.traded
self.write_log((f'{grid.direction.value}单部分{order.offset}仓,' + f'网格volume:{grid.volume}, traded_volume:{old_traded_volume}=>{grid.traded_volume}'))
if (order.vt_orderid in grid.order_ids):
grid.order_ids.remove(order.vt_orderid)
if (len(grid.order_ids) == 0):
grid.order_status = False
self.gt.save()
self.active_orders.update({order.vt_orderid: old_order})
self.display_grids() |
def on_stop_order(self, stop_order: StopOrder):
'\n 停止单更新\n 需要自己重载,处理各类触发、撤单等情况\n '
self.write_log(f'停止单触发:{stop_order.__dict__}') | 3,201,659,518,581,367,000 | 停止单更新
需要自己重载,处理各类触发、撤单等情况 | vnpy/app/cta_strategy_pro/template.py | on_stop_order | UtorYeung/vnpy | python | def on_stop_order(self, stop_order: StopOrder):
'\n 停止单更新\n 需要自己重载,处理各类触发、撤单等情况\n '
self.write_log(f'停止单触发:{stop_order.__dict__}') |
def cancel_all_orders(self):
'\n 重载撤销所有正在进行得委托\n :return:\n '
self.write_log(u'撤销所有正在进行得委托')
self.tns_cancel_logic(dt=datetime.now(), force=True, reopen=False) | 5,625,485,002,846,538,000 | 重载撤销所有正在进行得委托
:return: | vnpy/app/cta_strategy_pro/template.py | cancel_all_orders | UtorYeung/vnpy | python | def cancel_all_orders(self):
'\n 重载撤销所有正在进行得委托\n :return:\n '
self.write_log(u'撤销所有正在进行得委托')
self.tns_cancel_logic(dt=datetime.now(), force=True, reopen=False) |
def tns_cancel_logic(self, dt, force=False, reopen=False):
'撤单逻辑'
if (len(self.active_orders) < 1):
self.entrust = 0
return
canceled_ids = []
for vt_orderid in list(self.active_orders.keys()):
order_info = self.active_orders[vt_orderid]
order_vt_symbol = order_info.get('vt_symbol', self.vt_symbol)
order_time = order_info['order_time']
order_volume = (order_info['volume'] - order_info['traded'])
order_grid = order_info['grid']
order_status = order_info.get('status', Status.NOTTRADED)
order_type = order_info.get('order_type', OrderType.LIMIT)
over_seconds = (dt - order_time).total_seconds()
if ((order_status in [Status.NOTTRADED, Status.SUBMITTING]) and ((order_type == OrderType.LIMIT) or ('.SPD' in order_vt_symbol))):
if ((over_seconds > self.cancel_seconds) or force):
self.write_log(u'撤单逻辑 => 超时{}秒未成交,取消委托单:vt_orderid:{},order:{}'.format(over_seconds, vt_orderid, order_info))
order_info.update({'status': Status.CANCELLING})
self.active_orders.update({vt_orderid: order_info})
ret = self.cancel_order(str(vt_orderid))
if (not ret):
self.write_error(f'{self.strategy_name}撤单逻辑 => {order_vt_symbol}撤单失败')
continue
elif (order_status == Status.CANCELLED):
self.write_log(u'撤单逻辑 => 委托单{}已成功撤单,将删除未完成订单{}'.format(vt_orderid, order_info))
canceled_ids.append(vt_orderid)
if reopen:
if (order_info['offset'] == Offset.OPEN):
self.write_log(u'撤单逻辑 => 重新开仓')
if (order_info['direction'] == Direction.SHORT):
short_price = (self.cur_mi_price - self.price_tick)
if ((order_grid.volume != order_volume) and (order_volume > 0)):
self.write_log(u'网格volume:{},order_volume:{}不一致,修正'.format(order_grid.volume, order_volume))
order_grid.volume = order_volume
self.write_log(u'重新提交{}开空委托,开空价{},v:{}'.format(order_vt_symbol, short_price, order_volume))
vt_orderids = self.short(price=short_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=order_type, order_time=self.cur_datetime, grid=order_grid)
if (len(vt_orderids) > 0):
self.write_log(u'委托成功,orderid:{}'.format(vt_orderids))
order_grid.snapshot.update({'open_price': short_price})
else:
self.write_error(u'撤单后,重新委托开空仓失败')
else:
buy_price = (self.cur_mi_price + self.price_tick)
if ((order_grid.volume != order_volume) and (order_volume > 0)):
self.write_log(u'网格volume:{},order_volume:{}不一致,修正'.format(order_grid.volume, order_volume))
order_grid.volume = order_volume
self.write_log(u'重新提交{}开多委托,开多价{},v:{}'.format(order_vt_symbol, buy_price, order_volume))
vt_orderids = self.buy(price=buy_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=order_type, order_time=self.cur_datetime, grid=order_grid)
if (len(vt_orderids) > 0):
self.write_log(u'委托成功,orderids:{}'.format(vt_orderids))
order_grid.snapshot.update({'open_price': buy_price})
else:
self.write_error(u'撤单后,重新委托开多仓失败')
elif (order_info['direction'] == Direction.SHORT):
sell_price = (self.cur_mi_price - self.price_tick)
self.write_log(u'重新提交{}平多委托,{},v:{}'.format(order_vt_symbol, sell_price, order_volume))
vt_orderids = self.sell(price=sell_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=order_type, order_time=self.cur_datetime, grid=order_grid)
if (len(vt_orderids) > 0):
self.write_log(u'委托成功,orderids:{}'.format(vt_orderids))
else:
self.write_error(u'撤单后,重新委托平多仓失败')
else:
cover_price = (self.cur_mi_price + self.price_tick)
self.write_log(u'重新提交{}平空委托,委托价{},v:{}'.format(order_vt_symbol, cover_price, order_volume))
vt_orderids = self.cover(price=cover_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=order_type, order_time=self.cur_datetime, grid=order_grid)
if (len(vt_orderids) > 0):
self.write_log(u'委托成功,orderids:{}'.format(vt_orderids))
else:
self.write_error(u'撤单后,重新委托平空仓失败')
else:
self.write_log(u'撤单逻辑 => 无须重新开仓')
if ((order_info['offset'] == Offset.OPEN) and order_grid and (len(order_grid.order_ids) == 0)):
if ((order_info['traded'] == 0) and (order_grid.traded_volume == 0)):
self.write_log(u'撤单逻辑 => 无任何成交 => 移除委托网格{}'.format(order_grid.__dict__))
order_info['grid'] = None
self.gt.remove_grids_by_ids(direction=order_grid.direction, ids=[order_grid.id])
elif (order_info['traded'] > 0):
self.write_log('撤单逻辑 = > 部分开仓')
if (order_grid.traded_volume < order_info['traded']):
self.write_log('撤单逻辑 = > 调整网格开仓数 {} => {}'.format(order_grid.traded_volume, order_info['traded']))
order_grid.traded_volume = order_info['traded']
self.write_log(f'撤单逻辑 => 调整网格委托状态=> False, 开仓状态:True, 开仓数量:{order_grid.volume}=>{order_grid.traded_volume}')
order_grid.order_status = False
order_grid.open_status = True
order_grid.volume = order_grid.traded_volume
order_grid.traded_volume = 0
for vt_orderid in canceled_ids:
self.write_log(u'撤单逻辑 => 删除未完成订单:{}'.format(vt_orderid))
self.active_orders.pop(vt_orderid, None)
if (len(self.active_orders) == 0):
self.entrust = 0 | 5,498,034,421,116,743,000 | 撤单逻辑 | vnpy/app/cta_strategy_pro/template.py | tns_cancel_logic | UtorYeung/vnpy | python | def tns_cancel_logic(self, dt, force=False, reopen=False):
if (len(self.active_orders) < 1):
self.entrust = 0
return
canceled_ids = []
for vt_orderid in list(self.active_orders.keys()):
order_info = self.active_orders[vt_orderid]
order_vt_symbol = order_info.get('vt_symbol', self.vt_symbol)
order_time = order_info['order_time']
order_volume = (order_info['volume'] - order_info['traded'])
order_grid = order_info['grid']
order_status = order_info.get('status', Status.NOTTRADED)
order_type = order_info.get('order_type', OrderType.LIMIT)
over_seconds = (dt - order_time).total_seconds()
if ((order_status in [Status.NOTTRADED, Status.SUBMITTING]) and ((order_type == OrderType.LIMIT) or ('.SPD' in order_vt_symbol))):
if ((over_seconds > self.cancel_seconds) or force):
self.write_log(u' => 超时{}秒未成交,取消委托单:vt_orderid:{},order:{}'.format(over_seconds, vt_orderid, order_info))
order_info.update({'status': Status.CANCELLING})
self.active_orders.update({vt_orderid: order_info})
ret = self.cancel_order(str(vt_orderid))
if (not ret):
self.write_error(f'{self.strategy_name} => {order_vt_symbol}撤单失败')
continue
elif (order_status == Status.CANCELLED):
self.write_log(u' => 委托单{}已成功撤单,将删除未完成订单{}'.format(vt_orderid, order_info))
canceled_ids.append(vt_orderid)
if reopen:
if (order_info['offset'] == Offset.OPEN):
self.write_log(u' => 重新开仓')
if (order_info['direction'] == Direction.SHORT):
short_price = (self.cur_mi_price - self.price_tick)
if ((order_grid.volume != order_volume) and (order_volume > 0)):
self.write_log(u'网格volume:{},order_volume:{}不一致,修正'.format(order_grid.volume, order_volume))
order_grid.volume = order_volume
self.write_log(u'重新提交{}开空委托,开空价{},v:{}'.format(order_vt_symbol, short_price, order_volume))
vt_orderids = self.short(price=short_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=order_type, order_time=self.cur_datetime, grid=order_grid)
if (len(vt_orderids) > 0):
self.write_log(u'委托成功,orderid:{}'.format(vt_orderids))
order_grid.snapshot.update({'open_price': short_price})
else:
self.write_error(u'撤单后,重新委托开空仓失败')
else:
buy_price = (self.cur_mi_price + self.price_tick)
if ((order_grid.volume != order_volume) and (order_volume > 0)):
self.write_log(u'网格volume:{},order_volume:{}不一致,修正'.format(order_grid.volume, order_volume))
order_grid.volume = order_volume
self.write_log(u'重新提交{}开多委托,开多价{},v:{}'.format(order_vt_symbol, buy_price, order_volume))
vt_orderids = self.buy(price=buy_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=order_type, order_time=self.cur_datetime, grid=order_grid)
if (len(vt_orderids) > 0):
self.write_log(u'委托成功,orderids:{}'.format(vt_orderids))
order_grid.snapshot.update({'open_price': buy_price})
else:
self.write_error(u'撤单后,重新委托开多仓失败')
elif (order_info['direction'] == Direction.SHORT):
sell_price = (self.cur_mi_price - self.price_tick)
self.write_log(u'重新提交{}平多委托,{},v:{}'.format(order_vt_symbol, sell_price, order_volume))
vt_orderids = self.sell(price=sell_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=order_type, order_time=self.cur_datetime, grid=order_grid)
if (len(vt_orderids) > 0):
self.write_log(u'委托成功,orderids:{}'.format(vt_orderids))
else:
self.write_error(u'撤单后,重新委托平多仓失败')
else:
cover_price = (self.cur_mi_price + self.price_tick)
self.write_log(u'重新提交{}平空委托,委托价{},v:{}'.format(order_vt_symbol, cover_price, order_volume))
vt_orderids = self.cover(price=cover_price, volume=order_volume, vt_symbol=order_vt_symbol, order_type=order_type, order_time=self.cur_datetime, grid=order_grid)
if (len(vt_orderids) > 0):
self.write_log(u'委托成功,orderids:{}'.format(vt_orderids))
else:
self.write_error(u'撤单后,重新委托平空仓失败')
else:
self.write_log(u' => 无须重新开仓')
if ((order_info['offset'] == Offset.OPEN) and order_grid and (len(order_grid.order_ids) == 0)):
if ((order_info['traded'] == 0) and (order_grid.traded_volume == 0)):
self.write_log(u' => 无任何成交 => 移除委托网格{}'.format(order_grid.__dict__))
order_info['grid'] = None
self.gt.remove_grids_by_ids(direction=order_grid.direction, ids=[order_grid.id])
elif (order_info['traded'] > 0):
self.write_log(' = > 部分开仓')
if (order_grid.traded_volume < order_info['traded']):
self.write_log(' = > 调整网格开仓数 {} => {}'.format(order_grid.traded_volume, order_info['traded']))
order_grid.traded_volume = order_info['traded']
self.write_log(f' => 调整网格委托状态=> False, 开仓状态:True, 开仓数量:{order_grid.volume}=>{order_grid.traded_volume}')
order_grid.order_status = False
order_grid.open_status = True
order_grid.volume = order_grid.traded_volume
order_grid.traded_volume = 0
for vt_orderid in canceled_ids:
self.write_log(u' => 删除未完成订单:{}'.format(vt_orderid))
self.active_orders.pop(vt_orderid, None)
if (len(self.active_orders) == 0):
self.entrust = 0 |
def tns_close_long_pos(self, grid):
'\n 事务平多单仓位\n 1.来源自止损止盈平仓\n 逻辑: 如果当前账号昨仓满足平仓数量,直接平仓,如果不满足,则创建锁仓网格.\n :param 平仓网格\n :return:\n '
self.write_log(u'执行事务平多仓位:{}'.format(grid.to_json()))
sell_symbol = grid.snapshot.get('mi_symbol', self.vt_symbol)
grid_pos = self.cta_engine.get_position_holding(vt_symbol=sell_symbol)
if (grid_pos is None):
self.write_error(u'无法获取{}得持仓信息'.format(sell_symbol))
return False
if (((grid_pos.long_yd >= grid.volume > 0) and (grid_pos.long_td == 0) and (grid_pos.short_td == 0)) or (not self.activate_today_lock)):
if self.activate_today_lock:
self.write_log(u'昨仓多单:{},没有今仓,满足条件,直接平昨仓'.format(grid_pos.long_yd))
sell_price = self.cta_engine.get_price(sell_symbol)
if (sell_price is None):
self.write_error(f'暂时不能获取{sell_symbol}价格,不能平仓')
return False
if (not self.backtesting):
sell_tick = self.cta_engine.get_tick(sell_symbol)
if (sell_tick and (0 < sell_tick.bid_price_1 < sell_price)):
sell_price = sell_tick.bid_price_1
if (grid.traded_volume > 0):
grid.volume -= grid.traded_volume
grid.traded_volume = 0
if ((self.exchange != Exchange.CFFEX) and (grid_pos.long_pos < grid.volume)):
self.write_error(f'账号{sell_symbol}多单持仓:{grid_pos.long_pos}不满足平仓:{grid.volume}要求:')
return False
vt_orderids = self.sell(price=sell_price, volume=grid.volume, vt_symbol=sell_symbol, order_type=self.order_type, order_time=self.cur_datetime, lock=(self.exchange == Exchange.CFFEX), grid=grid)
if (len(vt_orderids) == 0):
self.write_error(u'多单平仓委托失败')
return False
else:
self.write_log(u'多单平仓委托成功,编号:{}'.format(vt_orderids))
return True
else:
self.write_log(u'昨仓多单:{}不满足条件,创建对锁仓'.format(grid_pos.long_yd))
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = sell_symbol
dist_record['price'] = self.cur_mi_price
dist_record['volume'] = grid.volume
dist_record['operation'] = 'add short lock[long]'
self.save_dist(dist_record)
lock_grid = copy(grid)
lock_grid.type = LOCK_GRID
lock_grid.id = str(uuid.uuid1())
lock_grid.direction = Direction.SHORT
lock_grid.open_status = False
lock_grid.order_status = False
lock_grid.order_ids = []
vt_orderids = self.short(self.cur_mi_price, volume=lock_grid.volume, vt_symbol=self.vt_symbol, order_type=self.order_type, order_time=self.cur_datetime, grid=lock_grid)
if (len(vt_orderids) > 0):
grid.type = LOCK_GRID
self.write_log(u'委托创建对锁单(空单)成功,委托编号:{},{},p:{},v:{}'.format(vt_orderids, sell_symbol, self.cur_mi_price, lock_grid.volume))
lock_grid.snapshot.update({'mi_symbol': self.vt_symbol, 'open_price': self.cur_mi_price})
self.gt.up_grids.append(lock_grid)
return True
else:
self.write_error(u'未能委托对锁单(空单)')
return False | -4,714,678,350,882,631,000 | 事务平多单仓位
1.来源自止损止盈平仓
逻辑: 如果当前账号昨仓满足平仓数量,直接平仓,如果不满足,则创建锁仓网格.
:param 平仓网格
:return: | vnpy/app/cta_strategy_pro/template.py | tns_close_long_pos | UtorYeung/vnpy | python | def tns_close_long_pos(self, grid):
'\n 事务平多单仓位\n 1.来源自止损止盈平仓\n 逻辑: 如果当前账号昨仓满足平仓数量,直接平仓,如果不满足,则创建锁仓网格.\n :param 平仓网格\n :return:\n '
self.write_log(u'执行事务平多仓位:{}'.format(grid.to_json()))
sell_symbol = grid.snapshot.get('mi_symbol', self.vt_symbol)
grid_pos = self.cta_engine.get_position_holding(vt_symbol=sell_symbol)
if (grid_pos is None):
self.write_error(u'无法获取{}得持仓信息'.format(sell_symbol))
return False
if (((grid_pos.long_yd >= grid.volume > 0) and (grid_pos.long_td == 0) and (grid_pos.short_td == 0)) or (not self.activate_today_lock)):
if self.activate_today_lock:
self.write_log(u'昨仓多单:{},没有今仓,满足条件,直接平昨仓'.format(grid_pos.long_yd))
sell_price = self.cta_engine.get_price(sell_symbol)
if (sell_price is None):
self.write_error(f'暂时不能获取{sell_symbol}价格,不能平仓')
return False
if (not self.backtesting):
sell_tick = self.cta_engine.get_tick(sell_symbol)
if (sell_tick and (0 < sell_tick.bid_price_1 < sell_price)):
sell_price = sell_tick.bid_price_1
if (grid.traded_volume > 0):
grid.volume -= grid.traded_volume
grid.traded_volume = 0
if ((self.exchange != Exchange.CFFEX) and (grid_pos.long_pos < grid.volume)):
self.write_error(f'账号{sell_symbol}多单持仓:{grid_pos.long_pos}不满足平仓:{grid.volume}要求:')
return False
vt_orderids = self.sell(price=sell_price, volume=grid.volume, vt_symbol=sell_symbol, order_type=self.order_type, order_time=self.cur_datetime, lock=(self.exchange == Exchange.CFFEX), grid=grid)
if (len(vt_orderids) == 0):
self.write_error(u'多单平仓委托失败')
return False
else:
self.write_log(u'多单平仓委托成功,编号:{}'.format(vt_orderids))
return True
else:
self.write_log(u'昨仓多单:{}不满足条件,创建对锁仓'.format(grid_pos.long_yd))
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = sell_symbol
dist_record['price'] = self.cur_mi_price
dist_record['volume'] = grid.volume
dist_record['operation'] = 'add short lock[long]'
self.save_dist(dist_record)
lock_grid = copy(grid)
lock_grid.type = LOCK_GRID
lock_grid.id = str(uuid.uuid1())
lock_grid.direction = Direction.SHORT
lock_grid.open_status = False
lock_grid.order_status = False
lock_grid.order_ids = []
vt_orderids = self.short(self.cur_mi_price, volume=lock_grid.volume, vt_symbol=self.vt_symbol, order_type=self.order_type, order_time=self.cur_datetime, grid=lock_grid)
if (len(vt_orderids) > 0):
grid.type = LOCK_GRID
self.write_log(u'委托创建对锁单(空单)成功,委托编号:{},{},p:{},v:{}'.format(vt_orderids, sell_symbol, self.cur_mi_price, lock_grid.volume))
lock_grid.snapshot.update({'mi_symbol': self.vt_symbol, 'open_price': self.cur_mi_price})
self.gt.up_grids.append(lock_grid)
return True
else:
self.write_error(u'未能委托对锁单(空单)')
return False |
def tns_close_short_pos(self, grid):
'\n 事务平空单仓位\n 1.来源自止损止盈平仓\n 2.来源自换仓\n 逻辑: 如果当前账号昨仓满足平仓数量,直接平仓,如果不满足,则创建锁仓网格.\n :param 平仓网格\n :return:\n '
self.write_log(u'执行事务平空仓位:{}'.format(grid.to_json()))
cover_symbol = grid.snapshot.get('mi_symbol', self.vt_symbol)
grid_pos = self.cta_engine.get_position_holding(cover_symbol)
if (grid_pos is None):
self.write_error(u'无法获取{}得持仓信息'.format(cover_symbol))
return False
if (((grid_pos.short_yd >= grid.volume > 0) and (grid_pos.long_td == 0) and (grid_pos.short_td == 0)) or (not self.activate_today_lock)):
if self.activate_today_lock:
self.write_log(u'昨仓空单:{},没有今仓, 满足条件,直接平昨仓'.format(grid_pos.short_yd))
cover_price = self.cta_engine.get_price(cover_symbol)
if (cover_price is None):
self.write_error(f'暂时没有{cover_symbol}行情,不能执行平仓')
return False
if (not self.backtesting):
cover_tick = self.cta_engine.get_tick(cover_symbol)
if (cover_tick and (0 < cover_price < cover_tick.ask_price_1)):
cover_price = cover_tick.ask_price_1
if (grid.traded_volume > 0):
grid.volume -= grid.traded_volume
grid.traded_volume = 0
if ((self.exchange != Exchange.CFFEX) and (grid_pos.short_pos < grid.volume)):
self.write_error(f'账号{cover_symbol}空单持仓:{grid_pos.short_pos}不满足平仓:{grid.volume}要求:')
return False
vt_orderids = self.cover(price=cover_price, volume=grid.volume, vt_symbol=cover_symbol, order_type=self.order_type, order_time=self.cur_datetime, lock=(self.exchange == Exchange.CFFEX), grid=grid)
if (len(vt_orderids) == 0):
self.write_error(u'空单平仓委托失败')
return False
else:
self.write_log(u'空单平仓委托成功,编号:{}'.format(vt_orderids))
return True
else:
self.write_log(u'昨仓空单:{}不满足条件,建立对锁仓'.format(grid_pos.short_yd))
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = cover_symbol
dist_record['price'] = self.cur_mi_price
dist_record['volume'] = grid.volume
dist_record['operation'] = 'add long lock[short]'
self.save_dist(dist_record)
lock_grid = copy(grid)
lock_grid.type = LOCK_GRID
lock_grid.id = str(uuid.uuid1())
lock_grid.direction = Direction.LONG
lock_grid.open_status = False
lock_grid.order_status = False
lock_grid.order_ids = []
vt_orderids = self.buy(price=self.cur_mi_price, volume=lock_grid.volume, vt_symbol=cover_symbol, order_type=self.order_type, grid=lock_grid)
if (len(vt_orderids) > 0):
grid.type = LOCK_GRID
self.write_log(u'委托创建对锁单(多单)成功,委托编号:{},{},p:{},v:{}'.format(vt_orderids, self.vt_symbol, self.cur_mi_price, lock_grid.volume))
lock_grid.snapshot.update({'mi_symbol': self.vt_symbol, 'open_price': self.cur_mi_price})
self.gt.dn_grids.append(lock_grid)
return True
else:
self.write_error(u'未能委托对锁单(多单)')
return False | -5,664,663,188,158,522,000 | 事务平空单仓位
1.来源自止损止盈平仓
2.来源自换仓
逻辑: 如果当前账号昨仓满足平仓数量,直接平仓,如果不满足,则创建锁仓网格.
:param 平仓网格
:return: | vnpy/app/cta_strategy_pro/template.py | tns_close_short_pos | UtorYeung/vnpy | python | def tns_close_short_pos(self, grid):
'\n 事务平空单仓位\n 1.来源自止损止盈平仓\n 2.来源自换仓\n 逻辑: 如果当前账号昨仓满足平仓数量,直接平仓,如果不满足,则创建锁仓网格.\n :param 平仓网格\n :return:\n '
self.write_log(u'执行事务平空仓位:{}'.format(grid.to_json()))
cover_symbol = grid.snapshot.get('mi_symbol', self.vt_symbol)
grid_pos = self.cta_engine.get_position_holding(cover_symbol)
if (grid_pos is None):
self.write_error(u'无法获取{}得持仓信息'.format(cover_symbol))
return False
if (((grid_pos.short_yd >= grid.volume > 0) and (grid_pos.long_td == 0) and (grid_pos.short_td == 0)) or (not self.activate_today_lock)):
if self.activate_today_lock:
self.write_log(u'昨仓空单:{},没有今仓, 满足条件,直接平昨仓'.format(grid_pos.short_yd))
cover_price = self.cta_engine.get_price(cover_symbol)
if (cover_price is None):
self.write_error(f'暂时没有{cover_symbol}行情,不能执行平仓')
return False
if (not self.backtesting):
cover_tick = self.cta_engine.get_tick(cover_symbol)
if (cover_tick and (0 < cover_price < cover_tick.ask_price_1)):
cover_price = cover_tick.ask_price_1
if (grid.traded_volume > 0):
grid.volume -= grid.traded_volume
grid.traded_volume = 0
if ((self.exchange != Exchange.CFFEX) and (grid_pos.short_pos < grid.volume)):
self.write_error(f'账号{cover_symbol}空单持仓:{grid_pos.short_pos}不满足平仓:{grid.volume}要求:')
return False
vt_orderids = self.cover(price=cover_price, volume=grid.volume, vt_symbol=cover_symbol, order_type=self.order_type, order_time=self.cur_datetime, lock=(self.exchange == Exchange.CFFEX), grid=grid)
if (len(vt_orderids) == 0):
self.write_error(u'空单平仓委托失败')
return False
else:
self.write_log(u'空单平仓委托成功,编号:{}'.format(vt_orderids))
return True
else:
self.write_log(u'昨仓空单:{}不满足条件,建立对锁仓'.format(grid_pos.short_yd))
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = cover_symbol
dist_record['price'] = self.cur_mi_price
dist_record['volume'] = grid.volume
dist_record['operation'] = 'add long lock[short]'
self.save_dist(dist_record)
lock_grid = copy(grid)
lock_grid.type = LOCK_GRID
lock_grid.id = str(uuid.uuid1())
lock_grid.direction = Direction.LONG
lock_grid.open_status = False
lock_grid.order_status = False
lock_grid.order_ids = []
vt_orderids = self.buy(price=self.cur_mi_price, volume=lock_grid.volume, vt_symbol=cover_symbol, order_type=self.order_type, grid=lock_grid)
if (len(vt_orderids) > 0):
grid.type = LOCK_GRID
self.write_log(u'委托创建对锁单(多单)成功,委托编号:{},{},p:{},v:{}'.format(vt_orderids, self.vt_symbol, self.cur_mi_price, lock_grid.volume))
lock_grid.snapshot.update({'mi_symbol': self.vt_symbol, 'open_price': self.cur_mi_price})
self.gt.dn_grids.append(lock_grid)
return True
else:
self.write_error(u'未能委托对锁单(多单)')
return False |
def tns_open_from_lock(self, open_symbol, open_volume, grid_type, open_direction):
'\n 从锁仓单中,获取已开的网格(对手仓设置为止损)\n 1, 检查多空锁仓单中,是否有满足数量得昨仓,\n 2, 定位到需求网格,\n :param open_symbol: 开仓合约(主力合约)\n :param open_volume:\n :param grid_type 更新网格的类型\n :param open_direction: 开仓方向\n :return: None, 保留的格\n '
locked_long_grids = self.gt.get_opened_grids_within_types(direction=Direction.LONG, types=[LOCK_GRID])
if (len(locked_long_grids) == 0):
return None
locked_long_dict = {}
for g in locked_long_grids:
symbol = g.snapshot.get('mi_symbol', self.vt_symbol)
if (g.order_status or g.order_ids):
self.write_log(u'当前对锁格:{}存在委托,不纳入计算'.format(g.to_json()))
continue
if (symbol != open_symbol):
self.write_log(u'不处理symbol不一致: 委托请求:{}, Grid mi Symbol:{}'.format(open_symbol, symbol))
continue
volume = (g.volume - g.traded_volume)
locked_long_dict.update({symbol: (locked_long_dict.get(symbol, 0) + volume)})
locked_long_volume = locked_long_dict.get(open_symbol, 0)
if (locked_long_volume < open_volume):
self.write_log(u'锁单中,没有足够得多单:{},需求:{}'.format(locked_long_volume, open_volume))
return None
locked_short_grids = self.gt.get_opened_grids_within_types(direction=Direction.SHORT, types=[LOCK_GRID])
if (len(locked_short_grids) == 0):
return None
locked_short_dict = {}
for g in locked_short_grids:
symbol = g.snapshot.get('mi_symbol', self.vt_symbol)
if (g.order_status or g.order_ids):
self.write_log(u'当前对锁格:{}存在委托,不进行解锁'.format(g.to_json()))
continue
if (symbol != open_symbol):
self.write_log(u'不处理symbol不一致: 委托请求:{}, Grid mi Symbol:{}'.format(open_symbol, symbol))
continue
volume = (g.volume - g.traded_volume)
locked_short_dict.update({symbol: (locked_short_dict.get(symbol, 0) + volume)})
locked_short_volume = locked_short_dict.get(open_symbol, 0)
if (locked_short_volume < open_volume):
self.write_log(u'锁单中,没有足够得空单:{},需求:{}'.format(locked_short_volume, open_volume))
return None
symbol_pos = self.cta_engine.get_position_holding(open_symbol)
if (((open_direction == Direction.LONG) and (symbol_pos.short_yd < open_volume)) or ((open_direction == Direction.SHORT) and (symbol_pos.long_yd < open_volume))):
self.write_log(u'昨仓数量,多单:{},空单:{},不满足:{}'.format(symbol_pos.long_yd, symbol_pos.short_yd, open_volume))
return None
target_long_grid = None
remove_long_grid_ids = []
for g in sorted(locked_long_grids, key=(lambda grid: grid.volume)):
if (g.order_status or (len(g.order_ids) > 0)):
continue
if (target_long_grid is None):
target_long_grid = g
if (g.volume == open_volume):
self.write_log(u'第一个网格持仓数量一致:g.volume:{},open_volume:{}'.format(g.volume, open_volume))
break
elif (g.volume > open_volume):
self.write_log(u'第一个网格持仓数量大于需求:g.volume:{},open_volume:{}'.format(g.volume, open_volume))
remain_grid = copy(g)
g.volume = open_volume
remain_grid.volume -= open_volume
remain_grid.id = str(uuid.uuid1())
self.gt.dn_grids.append(remain_grid)
self.write_log(u'添加剩余仓位到新多单网格:g.volume:{}'.format(remain_grid.volume))
break
elif (g.volume <= (open_volume - target_long_grid.volume)):
self.write_log(u'网格持仓数量:g.volume:{},open_volume:{},保留格:{}'.format(g.volume, open_volume, target_long_grid.volume))
target_long_grid.volume += g.volume
g.volume = 0
self.write_log(u'计划移除:{}'.format(g.id))
remove_long_grid_ids.append(g.id)
else:
self.write_log(u'转移前网格持仓数量:g.volume:{},open_volume:{},保留格:{}'.format(g.volume, open_volume, target_long_grid.volume))
g.volume -= (open_volume - target_long_grid.volume)
target_long_grid.volume = open_volume
self.write_log(u'转移后网格持仓数量:g.volume:{},open_volume:{},保留格:{}'.format(g.volume, open_volume, target_long_grid.volume))
break
target_short_grid = None
remove_short_grid_ids = []
for g in sorted(locked_short_grids, key=(lambda grid: grid.volume)):
if (g.order_status or g.order_ids):
continue
if (target_short_grid is None):
target_short_grid = g
if (g.volume == open_volume):
self.write_log(u'第一个空单网格持仓数量满足需求:g.volume:{},open_volume:{}'.format(g.volume, open_volume))
break
elif (g.volume > open_volume):
self.write_log(u'第一个空单网格持仓数量大于需求:g.volume:{},open_volume:{}'.format(g.volume, open_volume))
remain_grid = copy(g)
g.volume = open_volume
remain_grid.volume -= open_volume
remain_grid.id = str(uuid.uuid1())
self.gt.up_grids.append(remain_grid)
self.write_log(u'添加剩余仓位到新空单网格:g.volume:{}'.format(remain_grid.volume))
break
elif (g.volume <= (open_volume - target_short_grid.volume)):
target_short_grid.volume += g.volume
g.volume = 0
remove_short_grid_ids.append(g.id)
else:
self.write_log(u'转移前空单网格持仓数量:g.volume:{},open_volume:{},保留格:{}'.format(g.volume, open_volume, target_short_grid.volume))
g.volume -= (open_volume - target_short_grid.volume)
target_short_grid.volume = open_volume
self.write_log(u'转移后空单网格持仓数量:g.volume:{},open_volume:{},保留格:{}'.format(g.volume, open_volume, target_short_grid.volume))
break
if ((target_long_grid.volume is None) or (target_short_grid is None)):
self.write_log(u'未能定位多单网格和空单网格,不能解锁')
return None
self.gt.remove_grids_by_ids(direction=Direction.LONG, ids=remove_long_grid_ids)
self.gt.remove_grids_by_ids(direction=Direction.SHORT, ids=remove_short_grid_ids)
if (open_direction == Direction.LONG):
self.write_log(u'保留多单,对空单:{}平仓'.format(target_short_grid.id))
cover_price = self.cta_engine.get_price(open_symbol)
self.write_log(u'空单止损价 :{} =>{}'.format(target_short_grid.stop_price, (cover_price - (10 * self.price_tick))))
target_short_grid.stop_price = (cover_price - (10 * self.price_tick))
self.write_log(u'空单类型 :{} =>{}'.format(target_short_grid.type, grid_type))
target_short_grid.type = grid_type
return target_long_grid
else:
self.write_log(u'保留空单,对多单平仓')
sell_price = self.cta_engine.get_price(open_symbol)
self.write_log(u'多单止损价 :{} =>{}'.format(target_short_grid.stop_price, (sell_price + (10 * self.price_tick))))
target_long_grid.stop_price = (sell_price + (10 * self.price_tick))
self.write_log(u'多单类型 :{} =>{}'.format(target_short_grid.type, grid_type))
target_long_grid.type = grid_type
return target_short_grid | 4,465,916,099,554,728,000 | 从锁仓单中,获取已开的网格(对手仓设置为止损)
1, 检查多空锁仓单中,是否有满足数量得昨仓,
2, 定位到需求网格,
:param open_symbol: 开仓合约(主力合约)
:param open_volume:
:param grid_type 更新网格的类型
:param open_direction: 开仓方向
:return: None, 保留的格 | vnpy/app/cta_strategy_pro/template.py | tns_open_from_lock | UtorYeung/vnpy | python | def tns_open_from_lock(self, open_symbol, open_volume, grid_type, open_direction):
'\n 从锁仓单中,获取已开的网格(对手仓设置为止损)\n 1, 检查多空锁仓单中,是否有满足数量得昨仓,\n 2, 定位到需求网格,\n :param open_symbol: 开仓合约(主力合约)\n :param open_volume:\n :param grid_type 更新网格的类型\n :param open_direction: 开仓方向\n :return: None, 保留的格\n '
locked_long_grids = self.gt.get_opened_grids_within_types(direction=Direction.LONG, types=[LOCK_GRID])
if (len(locked_long_grids) == 0):
return None
locked_long_dict = {}
for g in locked_long_grids:
symbol = g.snapshot.get('mi_symbol', self.vt_symbol)
if (g.order_status or g.order_ids):
self.write_log(u'当前对锁格:{}存在委托,不纳入计算'.format(g.to_json()))
continue
if (symbol != open_symbol):
self.write_log(u'不处理symbol不一致: 委托请求:{}, Grid mi Symbol:{}'.format(open_symbol, symbol))
continue
volume = (g.volume - g.traded_volume)
locked_long_dict.update({symbol: (locked_long_dict.get(symbol, 0) + volume)})
locked_long_volume = locked_long_dict.get(open_symbol, 0)
if (locked_long_volume < open_volume):
self.write_log(u'锁单中,没有足够得多单:{},需求:{}'.format(locked_long_volume, open_volume))
return None
locked_short_grids = self.gt.get_opened_grids_within_types(direction=Direction.SHORT, types=[LOCK_GRID])
if (len(locked_short_grids) == 0):
return None
locked_short_dict = {}
for g in locked_short_grids:
symbol = g.snapshot.get('mi_symbol', self.vt_symbol)
if (g.order_status or g.order_ids):
self.write_log(u'当前对锁格:{}存在委托,不进行解锁'.format(g.to_json()))
continue
if (symbol != open_symbol):
self.write_log(u'不处理symbol不一致: 委托请求:{}, Grid mi Symbol:{}'.format(open_symbol, symbol))
continue
volume = (g.volume - g.traded_volume)
locked_short_dict.update({symbol: (locked_short_dict.get(symbol, 0) + volume)})
locked_short_volume = locked_short_dict.get(open_symbol, 0)
if (locked_short_volume < open_volume):
self.write_log(u'锁单中,没有足够得空单:{},需求:{}'.format(locked_short_volume, open_volume))
return None
symbol_pos = self.cta_engine.get_position_holding(open_symbol)
if (((open_direction == Direction.LONG) and (symbol_pos.short_yd < open_volume)) or ((open_direction == Direction.SHORT) and (symbol_pos.long_yd < open_volume))):
self.write_log(u'昨仓数量,多单:{},空单:{},不满足:{}'.format(symbol_pos.long_yd, symbol_pos.short_yd, open_volume))
return None
target_long_grid = None
remove_long_grid_ids = []
for g in sorted(locked_long_grids, key=(lambda grid: grid.volume)):
if (g.order_status or (len(g.order_ids) > 0)):
continue
if (target_long_grid is None):
target_long_grid = g
if (g.volume == open_volume):
self.write_log(u'第一个网格持仓数量一致:g.volume:{},open_volume:{}'.format(g.volume, open_volume))
break
elif (g.volume > open_volume):
self.write_log(u'第一个网格持仓数量大于需求:g.volume:{},open_volume:{}'.format(g.volume, open_volume))
remain_grid = copy(g)
g.volume = open_volume
remain_grid.volume -= open_volume
remain_grid.id = str(uuid.uuid1())
self.gt.dn_grids.append(remain_grid)
self.write_log(u'添加剩余仓位到新多单网格:g.volume:{}'.format(remain_grid.volume))
break
elif (g.volume <= (open_volume - target_long_grid.volume)):
self.write_log(u'网格持仓数量:g.volume:{},open_volume:{},保留格:{}'.format(g.volume, open_volume, target_long_grid.volume))
target_long_grid.volume += g.volume
g.volume = 0
self.write_log(u'计划移除:{}'.format(g.id))
remove_long_grid_ids.append(g.id)
else:
self.write_log(u'转移前网格持仓数量:g.volume:{},open_volume:{},保留格:{}'.format(g.volume, open_volume, target_long_grid.volume))
g.volume -= (open_volume - target_long_grid.volume)
target_long_grid.volume = open_volume
self.write_log(u'转移后网格持仓数量:g.volume:{},open_volume:{},保留格:{}'.format(g.volume, open_volume, target_long_grid.volume))
break
target_short_grid = None
remove_short_grid_ids = []
for g in sorted(locked_short_grids, key=(lambda grid: grid.volume)):
if (g.order_status or g.order_ids):
continue
if (target_short_grid is None):
target_short_grid = g
if (g.volume == open_volume):
self.write_log(u'第一个空单网格持仓数量满足需求:g.volume:{},open_volume:{}'.format(g.volume, open_volume))
break
elif (g.volume > open_volume):
self.write_log(u'第一个空单网格持仓数量大于需求:g.volume:{},open_volume:{}'.format(g.volume, open_volume))
remain_grid = copy(g)
g.volume = open_volume
remain_grid.volume -= open_volume
remain_grid.id = str(uuid.uuid1())
self.gt.up_grids.append(remain_grid)
self.write_log(u'添加剩余仓位到新空单网格:g.volume:{}'.format(remain_grid.volume))
break
elif (g.volume <= (open_volume - target_short_grid.volume)):
target_short_grid.volume += g.volume
g.volume = 0
remove_short_grid_ids.append(g.id)
else:
self.write_log(u'转移前空单网格持仓数量:g.volume:{},open_volume:{},保留格:{}'.format(g.volume, open_volume, target_short_grid.volume))
g.volume -= (open_volume - target_short_grid.volume)
target_short_grid.volume = open_volume
self.write_log(u'转移后空单网格持仓数量:g.volume:{},open_volume:{},保留格:{}'.format(g.volume, open_volume, target_short_grid.volume))
break
if ((target_long_grid.volume is None) or (target_short_grid is None)):
self.write_log(u'未能定位多单网格和空单网格,不能解锁')
return None
self.gt.remove_grids_by_ids(direction=Direction.LONG, ids=remove_long_grid_ids)
self.gt.remove_grids_by_ids(direction=Direction.SHORT, ids=remove_short_grid_ids)
if (open_direction == Direction.LONG):
self.write_log(u'保留多单,对空单:{}平仓'.format(target_short_grid.id))
cover_price = self.cta_engine.get_price(open_symbol)
self.write_log(u'空单止损价 :{} =>{}'.format(target_short_grid.stop_price, (cover_price - (10 * self.price_tick))))
target_short_grid.stop_price = (cover_price - (10 * self.price_tick))
self.write_log(u'空单类型 :{} =>{}'.format(target_short_grid.type, grid_type))
target_short_grid.type = grid_type
return target_long_grid
else:
self.write_log(u'保留空单,对多单平仓')
sell_price = self.cta_engine.get_price(open_symbol)
self.write_log(u'多单止损价 :{} =>{}'.format(target_short_grid.stop_price, (sell_price + (10 * self.price_tick))))
target_long_grid.stop_price = (sell_price + (10 * self.price_tick))
self.write_log(u'多单类型 :{} =>{}'.format(target_short_grid.type, grid_type))
target_long_grid.type = grid_type
return target_short_grid |
def tns_close_locked_grids(self, grid_type):
'\n 事务对所有对锁网格进行平仓\n :return:\n '
if (self.entrust != 0):
return
if (not self.activate_today_lock):
return
locked_long_grids = self.gt.get_opened_grids_within_types(direction=Direction.LONG, types=[LOCK_GRID])
if (len(locked_long_grids) == 0):
return
locked_long_dict = {}
for g in locked_long_grids:
vt_symbol = g.snapshot.get('mi_symbol', self.vt_symbol)
volume = (g.volume - g.traded_volume)
locked_long_dict.update({vt_symbol: (locked_long_dict.get(vt_symbol, 0) + volume)})
if (g.order_status or g.order_ids):
self.write_log(u'当前对锁格:{}存在委托,不进行解锁'.format(g.to_json()))
return
locked_long_volume = sum(locked_long_dict.values(), 0)
locked_short_grids = self.gt.get_opened_grids_within_types(direction=Direction.SHORT, types=[LOCK_GRID])
if (len(locked_short_grids) == 0):
return
locked_short_dict = {}
for g in locked_short_grids:
vt_symbol = g.snapshot.get('mi_symbol', self.vt_symbol)
volume = (g.volume - g.traded_volume)
locked_short_dict.update({vt_symbol: (locked_short_dict.get(vt_symbol, 0) + volume)})
if (g.order_status or g.order_ids):
self.write_log(u'当前对锁格:{}存在委托,不进行解锁'.format(g.to_json()))
return
locked_short_volume = sum(locked_short_dict.values(), 0)
self.write_log(u'多单对锁格:{}'.format([g.to_json() for g in locked_long_grids]))
self.write_log(u'空单对锁格:{}'.format([g.to_json() for g in locked_short_grids]))
if (locked_long_volume != locked_short_volume):
self.write_error(u'{}对锁格多空数量不一致,不能解锁.\n多:{},\n空:{}'.format(self.strategy_name, locked_long_volume, locked_short_volume))
return
for (vt_symbol, volume) in locked_long_dict.items():
pos = self.cta_engine.get_position_holding(vt_symbol, None)
if (pos is None):
self.write_error(u'{} 没有获取{}得持仓信息,不能解锁')
return
if ((pos.long_yd < volume) or (pos.short_yd < volume)):
self.write_error(u'{}持仓昨仓多单:{},空单:{},不满足解锁数量:{}'.format(vt_symbol, pos.long_yd, pos.short_td, volume))
return
if ((pos.long_td > 0) or (pos.short_td > 0)):
self.write_log(u'{}存在今多仓:{},空仓{},不满足解锁条件'.format(vt_symbol, pos.long_td, pos.short_td))
return
price = self.cta_engine.get_price(vt_symbol)
if (price is None):
self.write_error(u'{}价格不在tick_dict缓存中,不能解锁'.format(vt_symbol))
for g in locked_long_grids:
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = self.vt_symbol
dist_record['price'] = self.cur_mi_price
dist_record['volume'] = g.volume
dist_record['operation'] = 'close lock[long]'
self.save_dist(dist_record)
self.write_log(u'网格 从锁仓 {}=>{},提升止损价{}=>{}进行离场'.format(LOCK_GRID, grid_type, g.stop_price, (self.cur_99_price / 2)))
g.type = grid_type
g.stop_price = (self.cur_99_price / 2)
for g in locked_short_grids:
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = self.vt_symbol
dist_record['price'] = self.cur_mi_price
dist_record['volume'] = g.volume
dist_record['operation'] = 'close lock[short]'
self.save_dist(dist_record)
self.write_log(u'网格 从锁仓 {}=>{},提升止损价{}=>{}进行离场'.format(LOCK_GRID, grid_type, g.stop_price, (self.cur_99_price * 2)))
g.type = grid_type
g.stop_price = (self.cur_99_price * 2) | -4,562,718,120,327,982,000 | 事务对所有对锁网格进行平仓
:return: | vnpy/app/cta_strategy_pro/template.py | tns_close_locked_grids | UtorYeung/vnpy | python | def tns_close_locked_grids(self, grid_type):
'\n 事务对所有对锁网格进行平仓\n :return:\n '
if (self.entrust != 0):
return
if (not self.activate_today_lock):
return
locked_long_grids = self.gt.get_opened_grids_within_types(direction=Direction.LONG, types=[LOCK_GRID])
if (len(locked_long_grids) == 0):
return
locked_long_dict = {}
for g in locked_long_grids:
vt_symbol = g.snapshot.get('mi_symbol', self.vt_symbol)
volume = (g.volume - g.traded_volume)
locked_long_dict.update({vt_symbol: (locked_long_dict.get(vt_symbol, 0) + volume)})
if (g.order_status or g.order_ids):
self.write_log(u'当前对锁格:{}存在委托,不进行解锁'.format(g.to_json()))
return
locked_long_volume = sum(locked_long_dict.values(), 0)
locked_short_grids = self.gt.get_opened_grids_within_types(direction=Direction.SHORT, types=[LOCK_GRID])
if (len(locked_short_grids) == 0):
return
locked_short_dict = {}
for g in locked_short_grids:
vt_symbol = g.snapshot.get('mi_symbol', self.vt_symbol)
volume = (g.volume - g.traded_volume)
locked_short_dict.update({vt_symbol: (locked_short_dict.get(vt_symbol, 0) + volume)})
if (g.order_status or g.order_ids):
self.write_log(u'当前对锁格:{}存在委托,不进行解锁'.format(g.to_json()))
return
locked_short_volume = sum(locked_short_dict.values(), 0)
self.write_log(u'多单对锁格:{}'.format([g.to_json() for g in locked_long_grids]))
self.write_log(u'空单对锁格:{}'.format([g.to_json() for g in locked_short_grids]))
if (locked_long_volume != locked_short_volume):
self.write_error(u'{}对锁格多空数量不一致,不能解锁.\n多:{},\n空:{}'.format(self.strategy_name, locked_long_volume, locked_short_volume))
return
for (vt_symbol, volume) in locked_long_dict.items():
pos = self.cta_engine.get_position_holding(vt_symbol, None)
if (pos is None):
self.write_error(u'{} 没有获取{}得持仓信息,不能解锁')
return
if ((pos.long_yd < volume) or (pos.short_yd < volume)):
self.write_error(u'{}持仓昨仓多单:{},空单:{},不满足解锁数量:{}'.format(vt_symbol, pos.long_yd, pos.short_td, volume))
return
if ((pos.long_td > 0) or (pos.short_td > 0)):
self.write_log(u'{}存在今多仓:{},空仓{},不满足解锁条件'.format(vt_symbol, pos.long_td, pos.short_td))
return
price = self.cta_engine.get_price(vt_symbol)
if (price is None):
self.write_error(u'{}价格不在tick_dict缓存中,不能解锁'.format(vt_symbol))
for g in locked_long_grids:
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = self.vt_symbol
dist_record['price'] = self.cur_mi_price
dist_record['volume'] = g.volume
dist_record['operation'] = 'close lock[long]'
self.save_dist(dist_record)
self.write_log(u'网格 从锁仓 {}=>{},提升止损价{}=>{}进行离场'.format(LOCK_GRID, grid_type, g.stop_price, (self.cur_99_price / 2)))
g.type = grid_type
g.stop_price = (self.cur_99_price / 2)
for g in locked_short_grids:
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = self.vt_symbol
dist_record['price'] = self.cur_mi_price
dist_record['volume'] = g.volume
dist_record['operation'] = 'close lock[short]'
self.save_dist(dist_record)
self.write_log(u'网格 从锁仓 {}=>{},提升止损价{}=>{}进行离场'.format(LOCK_GRID, grid_type, g.stop_price, (self.cur_99_price * 2)))
g.type = grid_type
g.stop_price = (self.cur_99_price * 2) |
def grid_check_stop(self):
'\n 网格逐一止损/止盈检查 (根据指数价格进行止损止盈)\n :return:\n '
if (self.entrust != 0):
return
if (not self.trading):
if (not self.backtesting):
self.write_error(u'当前不允许交易')
return
long_grids = self.gt.get_opened_grids_without_types(direction=Direction.LONG, types=[LOCK_GRID])
for g in long_grids:
if ((g.stop_price > 0) and (g.stop_price > self.cur_99_price) and g.open_status and (not g.order_status)):
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = self.idx_symbol
dist_record['volume'] = g.volume
dist_record['price'] = self.cur_99_price
dist_record['operation'] = 'stop leave'
dist_record['signals'] = '{}<{}'.format(self.cur_99_price, g.stop_price)
self.write_log(u'{} 指数价:{} 触发多单止损线{},{}当前价:{}。指数开仓价:{},主力开仓价:{},v:{}'.format(self.cur_datetime, self.cur_99_price, g.stop_price, self.vt_symbol, self.cur_mi_price, g.open_price, g.snapshot.get('open_price'), g.volume))
self.save_dist(dist_record)
if self.tns_close_long_pos(g):
self.write_log(u'多单止盈/止损委托成功')
else:
self.write_error(u'多单止损委托失败')
short_grids = self.gt.get_opened_grids_without_types(direction=Direction.SHORT, types=[LOCK_GRID])
for g in short_grids:
if ((g.stop_price > 0) and (g.stop_price < self.cur_99_price) and g.open_status and (not g.order_status)):
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = self.idx_symbol
dist_record['volume'] = g.volume
dist_record['price'] = self.cur_99_price
dist_record['operation'] = 'stop leave'
dist_record['signals'] = '{}<{}'.format(self.cur_99_price, g.stop_price)
self.write_log(u'{} 指数价:{} 触发空单止损线:{},{}最新价:{}。指数开仓价:{},主力开仓价:{},v:{}'.format(self.cur_datetime, self.cur_99_price, g.stop_price, self.vt_symbol, self.cur_mi_price, g.open_price, g.snapshot.get('open_price'), g.volume))
self.save_dist(dist_record)
if self.tns_close_short_pos(g):
self.write_log(u'空单止盈/止损委托成功')
else:
self.write_error(u'委托空单平仓失败') | -1,047,088,386,559,161,900 | 网格逐一止损/止盈检查 (根据指数价格进行止损止盈)
:return: | vnpy/app/cta_strategy_pro/template.py | grid_check_stop | UtorYeung/vnpy | python | def grid_check_stop(self):
'\n 网格逐一止损/止盈检查 (根据指数价格进行止损止盈)\n :return:\n '
if (self.entrust != 0):
return
if (not self.trading):
if (not self.backtesting):
self.write_error(u'当前不允许交易')
return
long_grids = self.gt.get_opened_grids_without_types(direction=Direction.LONG, types=[LOCK_GRID])
for g in long_grids:
if ((g.stop_price > 0) and (g.stop_price > self.cur_99_price) and g.open_status and (not g.order_status)):
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = self.idx_symbol
dist_record['volume'] = g.volume
dist_record['price'] = self.cur_99_price
dist_record['operation'] = 'stop leave'
dist_record['signals'] = '{}<{}'.format(self.cur_99_price, g.stop_price)
self.write_log(u'{} 指数价:{} 触发多单止损线{},{}当前价:{}。指数开仓价:{},主力开仓价:{},v:{}'.format(self.cur_datetime, self.cur_99_price, g.stop_price, self.vt_symbol, self.cur_mi_price, g.open_price, g.snapshot.get('open_price'), g.volume))
self.save_dist(dist_record)
if self.tns_close_long_pos(g):
self.write_log(u'多单止盈/止损委托成功')
else:
self.write_error(u'多单止损委托失败')
short_grids = self.gt.get_opened_grids_without_types(direction=Direction.SHORT, types=[LOCK_GRID])
for g in short_grids:
if ((g.stop_price > 0) and (g.stop_price < self.cur_99_price) and g.open_status and (not g.order_status)):
dist_record = dict()
dist_record['datetime'] = self.cur_datetime
dist_record['symbol'] = self.idx_symbol
dist_record['volume'] = g.volume
dist_record['price'] = self.cur_99_price
dist_record['operation'] = 'stop leave'
dist_record['signals'] = '{}<{}'.format(self.cur_99_price, g.stop_price)
self.write_log(u'{} 指数价:{} 触发空单止损线:{},{}最新价:{}。指数开仓价:{},主力开仓价:{},v:{}'.format(self.cur_datetime, self.cur_99_price, g.stop_price, self.vt_symbol, self.cur_mi_price, g.open_price, g.snapshot.get('open_price'), g.volume))
self.save_dist(dist_record)
if self.tns_close_short_pos(g):
self.write_log(u'空单止盈/止损委托成功')
else:
self.write_error(u'委托空单平仓失败') |
def logando_notification(tipo, mensagem):
"\n Generates the log message/Gera a mensagem de log.\n\n :param tipo: Sets the log type/Seta o tipo de log.\n :param mensagem: Sets the message of log/Seta a mensagem do log.\n :return: Returns the complete log's body/Retorna o corpo completo do log.\n "
logger = logging.getLogger(__name__)
coloredlogs.install(level='DEBUG')
coloredlogs.install(level='DEBUG', logger=logger)
logging.basicConfig(format='%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s')
logger = verboselogs.VerboseLogger('')
if (tipo == 'verbose'):
logger.verbose(mensagem)
elif (tipo == 'debug'):
logger.debug(mensagem)
elif (tipo == 'info'):
logger.info(mensagem)
elif (tipo == 'warning'):
logger.warning(mensagem)
elif (tipo == 'error'):
logger.error(mensagem)
elif (tipo == 'critical'):
logger.critical(mensagem)
else:
pass | 2,179,398,016,320,366,000 | Generates the log message/Gera a mensagem de log.
:param tipo: Sets the log type/Seta o tipo de log.
:param mensagem: Sets the message of log/Seta a mensagem do log.
:return: Returns the complete log's body/Retorna o corpo completo do log. | Linux/etc/notification/telegram.py | logando_notification | 4jinetes/Oblivion | python | def logando_notification(tipo, mensagem):
"\n Generates the log message/Gera a mensagem de log.\n\n :param tipo: Sets the log type/Seta o tipo de log.\n :param mensagem: Sets the message of log/Seta a mensagem do log.\n :return: Returns the complete log's body/Retorna o corpo completo do log.\n "
logger = logging.getLogger(__name__)
coloredlogs.install(level='DEBUG')
coloredlogs.install(level='DEBUG', logger=logger)
logging.basicConfig(format='%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s')
logger = verboselogs.VerboseLogger()
if (tipo == 'verbose'):
logger.verbose(mensagem)
elif (tipo == 'debug'):
logger.debug(mensagem)
elif (tipo == 'info'):
logger.info(mensagem)
elif (tipo == 'warning'):
logger.warning(mensagem)
elif (tipo == 'error'):
logger.error(mensagem)
elif (tipo == 'critical'):
logger.critical(mensagem)
else:
pass |
def notificar_telegram(status_nosafe=False, data_nosafe=None):
'\n Generates the notification to Telegram account/Gera a notificação para a conta do Telegram.\n '
usuarios = []
with open(f'{path_tl_final}/etc/notification/users.txt', 'r') as lista:
separar = lista.readlines()
if status_nosafe:
mensagem = str(data_nosafe)
else:
with open(f'{path_tl_final}/etc/notification/message.txt', 'r') as mensagem_corpo:
mensagem = str(mensagem_corpo.read())
for i in separar:
i = i.strip('\r')
i = i.strip('\n')
i = i.split(';')
usuarios += i
for i in usuarios:
if ((i == '') or (i == ' ')):
usuarios.remove(i)
for mandar in usuarios:
token = telegram_bot
chat_id = mandar
texto = mensagem
send_message(chat_id=mandar, text=mensagem, token=telegram_bot) | -4,091,007,493,826,592,000 | Generates the notification to Telegram account/Gera a notificação para a conta do Telegram. | Linux/etc/notification/telegram.py | notificar_telegram | 4jinetes/Oblivion | python | def notificar_telegram(status_nosafe=False, data_nosafe=None):
'\n \n '
usuarios = []
with open(f'{path_tl_final}/etc/notification/users.txt', 'r') as lista:
separar = lista.readlines()
if status_nosafe:
mensagem = str(data_nosafe)
else:
with open(f'{path_tl_final}/etc/notification/message.txt', 'r') as mensagem_corpo:
mensagem = str(mensagem_corpo.read())
for i in separar:
i = i.strip('\r')
i = i.strip('\n')
i = i.split(';')
usuarios += i
for i in usuarios:
if ((i == ) or (i == ' ')):
usuarios.remove(i)
for mandar in usuarios:
token = telegram_bot
chat_id = mandar
texto = mensagem
send_message(chat_id=mandar, text=mensagem, token=telegram_bot) |
def send_message(chat_id, text=None, parse_mode='Markdown', token=None):
'\n Sends message in bold mode/Enviar mensagem em negrito.\n\n :param chat_id: ID of Telegram account/ID da conta Telgram.\n :param text: Message/Mensagem.\n :param parse_mode: Ignore.\n :param token: ID Telegram bot/ID do bot Telegram.\n '
URL = f'https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={text}'
answer = {'chat_id': chat_id, 'text': text, 'parse_mode': 'Markdown'}
r = requests.post(URL, json=answer)
if (text == '/bold'):
send_message(chat_id, (((('Here comes the' + '*') + 'bold') + '*') + 'text!')) | 5,812,060,372,968,654,000 | Sends message in bold mode/Enviar mensagem em negrito.
:param chat_id: ID of Telegram account/ID da conta Telgram.
:param text: Message/Mensagem.
:param parse_mode: Ignore.
:param token: ID Telegram bot/ID do bot Telegram. | Linux/etc/notification/telegram.py | send_message | 4jinetes/Oblivion | python | def send_message(chat_id, text=None, parse_mode='Markdown', token=None):
'\n Sends message in bold mode/Enviar mensagem em negrito.\n\n :param chat_id: ID of Telegram account/ID da conta Telgram.\n :param text: Message/Mensagem.\n :param parse_mode: Ignore.\n :param token: ID Telegram bot/ID do bot Telegram.\n '
URL = f'https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={text}'
answer = {'chat_id': chat_id, 'text': text, 'parse_mode': 'Markdown'}
r = requests.post(URL, json=answer)
if (text == '/bold'):
send_message(chat_id, (((('Here comes the' + '*') + 'bold') + '*') + 'text!')) |
async def _on_input(self, command, seat):
'Switch input functionality\n\n Calls on and off depending on command state\n :param command: Command from game engine\n :type command: dict\n :param seat: Robot seat\n :type seat: int\n '
if ('state' not in command):
logging.warning('Switch: invalid command received')
return
try:
val = str(command['state'])
except (ValueError, TypeError):
logging.warn(f"Switch: could not convert {command['state']} into String")
return
if ((val != 'up') and (val != 'down')):
logging.warn('Switch: command not <up|down>')
return
if (val == 'up'):
(await self.off(seat))
else:
(await self.on(seat)) | -7,261,439,614,335,508,000 | Switch input functionality
Calls on and off depending on command state
:param command: Command from game engine
:type command: dict
:param seat: Robot seat
:type seat: int | surrortg/inputs/switch.py | _on_input | SurrogateInc/surrortg-sdk | python | async def _on_input(self, command, seat):
'Switch input functionality\n\n Calls on and off depending on command state\n :param command: Command from game engine\n :type command: dict\n :param seat: Robot seat\n :type seat: int\n '
if ('state' not in command):
logging.warning('Switch: invalid command received')
return
try:
val = str(command['state'])
except (ValueError, TypeError):
logging.warn(f"Switch: could not convert {command['state']} into String")
return
if ((val != 'up') and (val != 'down')):
logging.warn('Switch: command not <up|down>')
return
if (val == 'up'):
(await self.off(seat))
else:
(await self.on(seat)) |
@abstractmethod
async def on(self, seat):
'Switch turned on functionality\n\n :param seat: Robot seat\n :type seat: int\n '
pass | -6,835,234,047,209,246,000 | Switch turned on functionality
:param seat: Robot seat
:type seat: int | surrortg/inputs/switch.py | on | SurrogateInc/surrortg-sdk | python | @abstractmethod
async def on(self, seat):
'Switch turned on functionality\n\n :param seat: Robot seat\n :type seat: int\n '
pass |
@abstractmethod
async def off(self, seat):
'Switch turned off functionality\n\n :param seat: Robot seat\n :type seat: int\n '
pass | -2,710,125,614,147,228,700 | Switch turned off functionality
:param seat: Robot seat
:type seat: int | surrortg/inputs/switch.py | off | SurrogateInc/surrortg-sdk | python | @abstractmethod
async def off(self, seat):
'Switch turned off functionality\n\n :param seat: Robot seat\n :type seat: int\n '
pass |
async def reset(self, seat):
'Switch reset functionality\n\n Defaults to calling off()\n\n :param seat: Robot seat\n :type seat: int\n '
(await self.off(seat)) | -6,922,977,932,009,814,000 | Switch reset functionality
Defaults to calling off()
:param seat: Robot seat
:type seat: int | surrortg/inputs/switch.py | reset | SurrogateInc/surrortg-sdk | python | async def reset(self, seat):
'Switch reset functionality\n\n Defaults to calling off()\n\n :param seat: Robot seat\n :type seat: int\n '
(await self.off(seat)) |
def get_name(self):
'Returns the name of the input\n\n :return: name of the input\n :rtype: str\n '
return 'button' | 3,793,174,537,542,569,500 | Returns the name of the input
:return: name of the input
:rtype: str | surrortg/inputs/switch.py | get_name | SurrogateInc/surrortg-sdk | python | def get_name(self):
'Returns the name of the input\n\n :return: name of the input\n :rtype: str\n '
return 'button' |
def get_default_keybinds(self):
'Returns a single keybind or a list of keybinds.\n\n Switches are bound to the space key by default.\n\n To override the defaults, override this method in your switch\n subclass and return different keybinds.\n '
return [] | -132,505,091,344,185,620 | Returns a single keybind or a list of keybinds.
Switches are bound to the space key by default.
To override the defaults, override this method in your switch
subclass and return different keybinds. | surrortg/inputs/switch.py | get_default_keybinds | SurrogateInc/surrortg-sdk | python | def get_default_keybinds(self):
'Returns a single keybind or a list of keybinds.\n\n Switches are bound to the space key by default.\n\n To override the defaults, override this method in your switch\n subclass and return different keybinds.\n '
return [] |
@classmethod
def _cnn_net(cls):
'\n Create the CNN net topology.\n :return keras.Sequential(): CNN topology.\n '
qrs_detector = keras.Sequential()
qrs_detector.add(keras.layers.Conv1D(96, 49, activation=tf.nn.relu, input_shape=(300, 1), strides=1, name='conv1'))
qrs_detector.add(keras.layers.MaxPool1D(pool_size=2, strides=2, name='pool1'))
qrs_detector.add(keras.layers.Conv1D(128, 25, activation=tf.nn.relu, strides=1, name='conv2'))
qrs_detector.add(keras.layers.MaxPool1D(pool_size=2, strides=2, name='pool2'))
qrs_detector.add(keras.layers.Conv1D(256, 9, activation=tf.nn.relu, strides=1, name='conv3'))
qrs_detector.add(keras.layers.MaxPool1D(pool_size=2, strides=2, name='pool3'))
qrs_detector.add(keras.layers.Conv1D(512, 9, activation=tf.nn.relu, strides=1, name='conv4'))
qrs_detector.add(keras.layers.MaxPool1D(pool_size=2, strides=2, name='pool4'))
qrs_detector.add(keras.layers.Flatten(data_format=None, name='flatten'))
qrs_detector.add(keras.layers.Dense(units=4096, activation=tf.nn.relu, name='fc1'))
qrs_detector.add(keras.layers.Dense(units=4096, activation=tf.nn.relu, name='fc2'))
qrs_detector.add(keras.layers.Dropout(rate=0.5, name='drop1'))
qrs_detector.add(keras.layers.Dense(units=2, name='classes'))
qrs_detector.add(keras.layers.Activation(activation=tf.nn.softmax, name='softmax'))
return qrs_detector | 4,818,998,698,767,064,000 | Create the CNN net topology.
:return keras.Sequential(): CNN topology. | python/qrs/qrs_net.py | _cnn_net | ufopcsilab/ECGClassification | python | @classmethod
def _cnn_net(cls):
'\n Create the CNN net topology.\n :return keras.Sequential(): CNN topology.\n '
qrs_detector = keras.Sequential()
qrs_detector.add(keras.layers.Conv1D(96, 49, activation=tf.nn.relu, input_shape=(300, 1), strides=1, name='conv1'))
qrs_detector.add(keras.layers.MaxPool1D(pool_size=2, strides=2, name='pool1'))
qrs_detector.add(keras.layers.Conv1D(128, 25, activation=tf.nn.relu, strides=1, name='conv2'))
qrs_detector.add(keras.layers.MaxPool1D(pool_size=2, strides=2, name='pool2'))
qrs_detector.add(keras.layers.Conv1D(256, 9, activation=tf.nn.relu, strides=1, name='conv3'))
qrs_detector.add(keras.layers.MaxPool1D(pool_size=2, strides=2, name='pool3'))
qrs_detector.add(keras.layers.Conv1D(512, 9, activation=tf.nn.relu, strides=1, name='conv4'))
qrs_detector.add(keras.layers.MaxPool1D(pool_size=2, strides=2, name='pool4'))
qrs_detector.add(keras.layers.Flatten(data_format=None, name='flatten'))
qrs_detector.add(keras.layers.Dense(units=4096, activation=tf.nn.relu, name='fc1'))
qrs_detector.add(keras.layers.Dense(units=4096, activation=tf.nn.relu, name='fc2'))
qrs_detector.add(keras.layers.Dropout(rate=0.5, name='drop1'))
qrs_detector.add(keras.layers.Dense(units=2, name='classes'))
qrs_detector.add(keras.layers.Activation(activation=tf.nn.softmax, name='softmax'))
return qrs_detector |
@classmethod
def build(cls, net_type):
'\n Build the CNN topology.\n :param str net_type: the network type, CNN or LSTM.\n :return keras.Sequential(): CNN topology.\n '
if (net_type == 'cnn'):
qrs_detector = cls._cnn_net()
else:
raise NotImplementedError('Only the CNN network was implemented.')
return qrs_detector | -4,566,898,852,637,497,300 | Build the CNN topology.
:param str net_type: the network type, CNN or LSTM.
:return keras.Sequential(): CNN topology. | python/qrs/qrs_net.py | build | ufopcsilab/ECGClassification | python | @classmethod
def build(cls, net_type):
'\n Build the CNN topology.\n :param str net_type: the network type, CNN or LSTM.\n :return keras.Sequential(): CNN topology.\n '
if (net_type == 'cnn'):
qrs_detector = cls._cnn_net()
else:
raise NotImplementedError('Only the CNN network was implemented.')
return qrs_detector |
@classmethod
def _prepare_data(cls, data_x, input_shape, data_y, number_of_classes, normalize):
'\n Prepare the data for the training, turning it into a numpy array.\n :param list data_x: data that will be used to train.\n :param tuple input_shape: the input shape that the data must have to be used as training data.\n :param list data_y: the labels related to the data used to train.\n :param int number_of_classes: number of classes of the problem.\n :param bool normalize: if the data should be normalized (True) or not (False).\n :return np.array: the data processed.\n '
if (len(input_shape) == 2):
data_x = np.asarray(data_x).reshape((- 1), input_shape[0], input_shape[1])
elif (len(input_shape) == 3):
data_x = np.asarray(data_x).reshape((- 1), input_shape[0], input_shape[1], input_shape[2])
else:
raise Exception('Only inputs of two and three dimensions were implemented.')
if normalize:
data_x = (data_x / np.amax(data_x))
data_y = keras.utils.to_categorical(data_y).reshape((- 1), number_of_classes)
return (data_x, data_y) | -6,894,264,797,384,032,000 | Prepare the data for the training, turning it into a numpy array.
:param list data_x: data that will be used to train.
:param tuple input_shape: the input shape that the data must have to be used as training data.
:param list data_y: the labels related to the data used to train.
:param int number_of_classes: number of classes of the problem.
:param bool normalize: if the data should be normalized (True) or not (False).
:return np.array: the data processed. | python/qrs/qrs_net.py | _prepare_data | ufopcsilab/ECGClassification | python | @classmethod
def _prepare_data(cls, data_x, input_shape, data_y, number_of_classes, normalize):
'\n Prepare the data for the training, turning it into a numpy array.\n :param list data_x: data that will be used to train.\n :param tuple input_shape: the input shape that the data must have to be used as training data.\n :param list data_y: the labels related to the data used to train.\n :param int number_of_classes: number of classes of the problem.\n :param bool normalize: if the data should be normalized (True) or not (False).\n :return np.array: the data processed.\n '
if (len(input_shape) == 2):
data_x = np.asarray(data_x).reshape((- 1), input_shape[0], input_shape[1])
elif (len(input_shape) == 3):
data_x = np.asarray(data_x).reshape((- 1), input_shape[0], input_shape[1], input_shape[2])
else:
raise Exception('Only inputs of two and three dimensions were implemented.')
if normalize:
data_x = (data_x / np.amax(data_x))
data_y = keras.utils.to_categorical(data_y).reshape((- 1), number_of_classes)
return (data_x, data_y) |
@classmethod
def train(cls, model, train_x, train_y, validation_x, validation_y, number_of_classes, input_shape=(300, 1), epochs=10, lr=0.0001, batch_size=4, optimizer=None, loss=None, metrics=None, normalize=False, show_net_info=True):
'\n Function used to train the model.\n :param keras.Sequential model: model to be trained.\n :param list train_x: data that will be used to train.\n :param list train_y: the labels related to the data used to train.\n :param list validation_x: data that will be used to validate the model trained.\n :param list validation_y: the labels related to the data used to validate the model trained.\n :param int number_of_classes: number of classes of the problem.\n :param tuple input_shape: the input shape that the data must have to be used as training data.\n :param int epochs: total epochs that the model will be trained.\n :param float lr: learning rate used to train.\n :param int batch_size: batch size used to train.\n :param optimizer: which optimizer will be used to train.\n :param str loss: loss function used during the training.\n :param list metrics: metrics used to evaluate the trained model.\n :param bool normalize: if the data should be normalized (True) or not (False).\n :param bool show_net_info: if the network topology should be showed (True) or not (False).\n :return keras.Sequential, dict: model trained and the history of the training process.\n '
if (optimizer is None):
optimizer = keras.optimizers.SGD(lr=lr, momentum=0.9, decay=(0.0001 / epochs))
if (loss is None):
loss = keras.losses.categorical_crossentropy
if (metrics is None):
metrics = ['acc']
elif (type(metrics) is not list):
metrics = [metrics]
model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
if show_net_info:
print(model.summary())
(train_x, train_y) = cls._prepare_data(train_x, input_shape, train_y, number_of_classes, normalize)
(validation_x, validation_y) = cls._prepare_data(validation_x, input_shape, validation_y, number_of_classes, normalize)
kback.set_value(model.optimizer.lr, lr)
train_history = model.fit(x=train_x, y=train_y, validation_data=(validation_x, validation_y), batch_size=batch_size, epochs=epochs)
return (model, train_history) | -7,580,206,974,420,679,000 | Function used to train the model.
:param keras.Sequential model: model to be trained.
:param list train_x: data that will be used to train.
:param list train_y: the labels related to the data used to train.
:param list validation_x: data that will be used to validate the model trained.
:param list validation_y: the labels related to the data used to validate the model trained.
:param int number_of_classes: number of classes of the problem.
:param tuple input_shape: the input shape that the data must have to be used as training data.
:param int epochs: total epochs that the model will be trained.
:param float lr: learning rate used to train.
:param int batch_size: batch size used to train.
:param optimizer: which optimizer will be used to train.
:param str loss: loss function used during the training.
:param list metrics: metrics used to evaluate the trained model.
:param bool normalize: if the data should be normalized (True) or not (False).
:param bool show_net_info: if the network topology should be showed (True) or not (False).
:return keras.Sequential, dict: model trained and the history of the training process. | python/qrs/qrs_net.py | train | ufopcsilab/ECGClassification | python | @classmethod
def train(cls, model, train_x, train_y, validation_x, validation_y, number_of_classes, input_shape=(300, 1), epochs=10, lr=0.0001, batch_size=4, optimizer=None, loss=None, metrics=None, normalize=False, show_net_info=True):
'\n Function used to train the model.\n :param keras.Sequential model: model to be trained.\n :param list train_x: data that will be used to train.\n :param list train_y: the labels related to the data used to train.\n :param list validation_x: data that will be used to validate the model trained.\n :param list validation_y: the labels related to the data used to validate the model trained.\n :param int number_of_classes: number of classes of the problem.\n :param tuple input_shape: the input shape that the data must have to be used as training data.\n :param int epochs: total epochs that the model will be trained.\n :param float lr: learning rate used to train.\n :param int batch_size: batch size used to train.\n :param optimizer: which optimizer will be used to train.\n :param str loss: loss function used during the training.\n :param list metrics: metrics used to evaluate the trained model.\n :param bool normalize: if the data should be normalized (True) or not (False).\n :param bool show_net_info: if the network topology should be showed (True) or not (False).\n :return keras.Sequential, dict: model trained and the history of the training process.\n '
if (optimizer is None):
optimizer = keras.optimizers.SGD(lr=lr, momentum=0.9, decay=(0.0001 / epochs))
if (loss is None):
loss = keras.losses.categorical_crossentropy
if (metrics is None):
metrics = ['acc']
elif (type(metrics) is not list):
metrics = [metrics]
model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
if show_net_info:
print(model.summary())
(train_x, train_y) = cls._prepare_data(train_x, input_shape, train_y, number_of_classes, normalize)
(validation_x, validation_y) = cls._prepare_data(validation_x, input_shape, validation_y, number_of_classes, normalize)
kback.set_value(model.optimizer.lr, lr)
train_history = model.fit(x=train_x, y=train_y, validation_data=(validation_x, validation_y), batch_size=batch_size, epochs=epochs)
return (model, train_history) |
def _convert_dataset_to_ground_truth(self, dataset_bboxes):
'\n @param `dataset_bboxes`: [[b_x, b_y, b_w, b_h, class_id], ...]\n\n @return `groud_truth_one`:\n [Dim(yolo.h, yolo.w, yolo.c + len(mask))] * len(yolo)\n '
return _convert_dataset_to_ground_truth(dataset_bboxes, self._metayolos_np, self._anchors_np) | 5,234,496,081,387,635,000 | @param `dataset_bboxes`: [[b_x, b_y, b_w, b_h, class_id], ...]
@return `groud_truth_one`:
[Dim(yolo.h, yolo.w, yolo.c + len(mask))] * len(yolo) | py_src/yolov4/tf/dataset/keras_sequence.py | _convert_dataset_to_ground_truth | fcakyon/tensorflow-yolov4 | python | def _convert_dataset_to_ground_truth(self, dataset_bboxes):
'\n @param `dataset_bboxes`: [[b_x, b_y, b_w, b_h, class_id], ...]\n\n @return `groud_truth_one`:\n [Dim(yolo.h, yolo.w, yolo.c + len(mask))] * len(yolo)\n '
return _convert_dataset_to_ground_truth(dataset_bboxes, self._metayolos_np, self._anchors_np) |
def _convert_dataset_to_image_and_bboxes(self, dataset):
'\n @param dataset: [image_path, [[x, y, w, h, class_id], ...]]\n\n @return image, bboxes\n image: 0.0 ~ 1.0, Dim(1, height, width, channels)\n '
try:
image = cv2.imread(dataset[0])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
except:
return (None, None)
(resized_image, resized_bboxes) = media.resize_image(image, target_shape=self._metanet.input_shape, ground_truth=dataset[1])
resized_image = np.expand_dims((resized_image / 255.0), axis=0)
return (resized_image, resized_bboxes) | -5,174,543,971,841,476,000 | @param dataset: [image_path, [[x, y, w, h, class_id], ...]]
@return image, bboxes
image: 0.0 ~ 1.0, Dim(1, height, width, channels) | py_src/yolov4/tf/dataset/keras_sequence.py | _convert_dataset_to_image_and_bboxes | fcakyon/tensorflow-yolov4 | python | def _convert_dataset_to_image_and_bboxes(self, dataset):
'\n @param dataset: [image_path, [[x, y, w, h, class_id], ...]]\n\n @return image, bboxes\n image: 0.0 ~ 1.0, Dim(1, height, width, channels)\n '
try:
image = cv2.imread(dataset[0])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
except:
return (None, None)
(resized_image, resized_bboxes) = media.resize_image(image, target_shape=self._metanet.input_shape, ground_truth=dataset[1])
resized_image = np.expand_dims((resized_image / 255.0), axis=0)
return (resized_image, resized_bboxes) |
def __getitem__(self, index):
'\n @return\n `images`: Dim(batch, height, width, channels)\n `groud_truth_one`:\n [Dim(batch, yolo.h, yolo.w, yolo.c + len(mask))] * len(yolo)\n '
batch_x = []
batch_y = [[] for _ in range(len(self._metayolos))]
start_index = (index * self._metanet.batch)
for i in range((self._metanet.batch - self._augmentation_batch)):
(image, bboxes) = self._get_dataset((start_index + i))
self._augmentation_cache[self._augmentation_cache_index] = (image, bboxes)
self._augmentation_cache_index = ((self._augmentation_cache_index + 1) % _AUGMETATION_CACHE_SIZE)
batch_x.append(image)
ground_truth = self._convert_dataset_to_ground_truth(bboxes)
for j in range(len(self._metayolos)):
batch_y[j].append(ground_truth[j])
for i in range(self._augmentation_batch):
augmentation = self._augmentation[np.random.randint(0, len(self._augmentation))]
image = None
bboxes = None
if (augmentation == 'mosaic'):
(image, bboxes) = mosaic(*[self._augmentation_cache[np.random.randint(0, _AUGMETATION_CACHE_SIZE)] for _ in range(4)])
batch_x.append(image)
ground_truth = self._convert_dataset_to_ground_truth(bboxes)
for j in range(len(self._metayolos)):
batch_y[j].append(ground_truth[j])
return (np.concatenate(batch_x, axis=0), [np.stack(y, axis=0) for y in batch_y]) | -8,114,848,881,290,818,000 | @return
`images`: Dim(batch, height, width, channels)
`groud_truth_one`:
[Dim(batch, yolo.h, yolo.w, yolo.c + len(mask))] * len(yolo) | py_src/yolov4/tf/dataset/keras_sequence.py | __getitem__ | fcakyon/tensorflow-yolov4 | python | def __getitem__(self, index):
'\n @return\n `images`: Dim(batch, height, width, channels)\n `groud_truth_one`:\n [Dim(batch, yolo.h, yolo.w, yolo.c + len(mask))] * len(yolo)\n '
batch_x = []
batch_y = [[] for _ in range(len(self._metayolos))]
start_index = (index * self._metanet.batch)
for i in range((self._metanet.batch - self._augmentation_batch)):
(image, bboxes) = self._get_dataset((start_index + i))
self._augmentation_cache[self._augmentation_cache_index] = (image, bboxes)
self._augmentation_cache_index = ((self._augmentation_cache_index + 1) % _AUGMETATION_CACHE_SIZE)
batch_x.append(image)
ground_truth = self._convert_dataset_to_ground_truth(bboxes)
for j in range(len(self._metayolos)):
batch_y[j].append(ground_truth[j])
for i in range(self._augmentation_batch):
augmentation = self._augmentation[np.random.randint(0, len(self._augmentation))]
image = None
bboxes = None
if (augmentation == 'mosaic'):
(image, bboxes) = mosaic(*[self._augmentation_cache[np.random.randint(0, _AUGMETATION_CACHE_SIZE)] for _ in range(4)])
batch_x.append(image)
ground_truth = self._convert_dataset_to_ground_truth(bboxes)
for j in range(len(self._metayolos)):
batch_y[j].append(ground_truth[j])
return (np.concatenate(batch_x, axis=0), [np.stack(y, axis=0) for y in batch_y]) |
def setup_logging(name, dir=''):
'\n Setup the logging device to log into a uniquely created directory.\n\n Args:\n name: Name of the directory for the log-files.\n dir: Optional sub-directory within log\n '
global log_name
log_name = name
global log_dir
log_dir = os.path.join('log', dir)
if (not os.path.isdir(log_dir)):
os.makedirs(log_dir)
reload(logging)
logging.basicConfig(level=logging.INFO, format='[%(levelname)-5.5s %(asctime)s] %(message)s', datefmt='%H:%M:%S', handlers=[logging.FileHandler(os.path.join(log_dir, (((time.strftime('%Y%m%d_%H%M') + '_') + name) + '.log'))), logging.StreamHandler()]) | -7,427,697,294,495,630,000 | Setup the logging device to log into a uniquely created directory.
Args:
name: Name of the directory for the log-files.
dir: Optional sub-directory within log | lib/config.py | setup_logging | SudeepSarkar/equilibrium-propagation | python | def setup_logging(name, dir=):
'\n Setup the logging device to log into a uniquely created directory.\n\n Args:\n name: Name of the directory for the log-files.\n dir: Optional sub-directory within log\n '
global log_name
log_name = name
global log_dir
log_dir = os.path.join('log', dir)
if (not os.path.isdir(log_dir)):
os.makedirs(log_dir)
reload(logging)
logging.basicConfig(level=logging.INFO, format='[%(levelname)-5.5s %(asctime)s] %(message)s', datefmt='%H:%M:%S', handlers=[logging.FileHandler(os.path.join(log_dir, (((time.strftime('%Y%m%d_%H%M') + '_') + name) + '.log'))), logging.StreamHandler()]) |
def __init__(self, lf, lr, mass, Iz, Cf, Cr, Bf=None, Br=None, Df=None, Dr=None, Cm1=None, Cm2=None, Cr0=None, Cr2=None, input_acc=False, **kwargs):
'\tspecify model params here\n\t\t'
self.lf = lf
self.lr = lr
self.dr = (lr / (lf + lr))
self.mass = mass
self.Iz = Iz
self.Cf = Cf
self.Cr = Cr
self.Bf = Bf
self.Br = Br
self.Df = Df
self.Dr = Dr
self.Cm1 = Cm1
self.Cm2 = Cm2
self.Cr0 = Cr0
self.Cr2 = Cr2
self.approx = False
if ((Bf is None) or (Br is None) or (Df is None) or (Dr is None)):
self.approx = True
self.input_acc = input_acc
self.n_states = 6
self.n_inputs = 2
Model.__init__(self) | -3,487,673,847,780,308,500 | specify model params here | bayes_race/models/dynamic.py | __init__ | KlrShaK/bayesrace | python | def __init__(self, lf, lr, mass, Iz, Cf, Cr, Bf=None, Br=None, Df=None, Dr=None, Cm1=None, Cm2=None, Cr0=None, Cr2=None, input_acc=False, **kwargs):
'\t\n\t\t'
self.lf = lf
self.lr = lr
self.dr = (lr / (lf + lr))
self.mass = mass
self.Iz = Iz
self.Cf = Cf
self.Cr = Cr
self.Bf = Bf
self.Br = Br
self.Df = Df
self.Dr = Dr
self.Cm1 = Cm1
self.Cm2 = Cm2
self.Cr0 = Cr0
self.Cr2 = Cr2
self.approx = False
if ((Bf is None) or (Br is None) or (Df is None) or (Dr is None)):
self.approx = True
self.input_acc = input_acc
self.n_states = 6
self.n_inputs = 2
Model.__init__(self) |
def sim_continuous(self, x0, u, t):
'\tsimulates the nonlinear continuous model with given input vector\n\t\t\tby numerical integration using 6th order Runge Kutta method\n\t\t\tx0 is the initial state of size 6x1\n\t\t\tu is the input vector of size 2xn\n\t\t\tt is the time vector of size 1x(n+1)\n\t\t'
n_steps = u.shape[1]
x = np.zeros([6, (n_steps + 1)])
dxdt = np.zeros([6, (n_steps + 1)])
dxdt[:, 0] = self._diffequation(None, x0, [0, 0])
x[:, 0] = x0
for ids in range(1, (n_steps + 1)):
x[:, ids] = self._integrate(x[:, (ids - 1)], u[:, (ids - 1)], t[(ids - 1)], t[ids])
dxdt[:, ids] = self._diffequation(None, x[:, ids], u[:, (ids - 1)])
return (x, dxdt) | 8,414,995,335,463,568,000 | simulates the nonlinear continuous model with given input vector
by numerical integration using 6th order Runge Kutta method
x0 is the initial state of size 6x1
u is the input vector of size 2xn
t is the time vector of size 1x(n+1) | bayes_race/models/dynamic.py | sim_continuous | KlrShaK/bayesrace | python | def sim_continuous(self, x0, u, t):
'\tsimulates the nonlinear continuous model with given input vector\n\t\t\tby numerical integration using 6th order Runge Kutta method\n\t\t\tx0 is the initial state of size 6x1\n\t\t\tu is the input vector of size 2xn\n\t\t\tt is the time vector of size 1x(n+1)\n\t\t'
n_steps = u.shape[1]
x = np.zeros([6, (n_steps + 1)])
dxdt = np.zeros([6, (n_steps + 1)])
dxdt[:, 0] = self._diffequation(None, x0, [0, 0])
x[:, 0] = x0
for ids in range(1, (n_steps + 1)):
x[:, ids] = self._integrate(x[:, (ids - 1)], u[:, (ids - 1)], t[(ids - 1)], t[ids])
dxdt[:, ids] = self._diffequation(None, x[:, ids], u[:, (ids - 1)])
return (x, dxdt) |
def _diffequation(self, t, x, u):
'\twrite dynamics as first order ODE: dxdt = f(x(t))\n\t\t\tx is a 6x1 vector: [x, y, psi, vx, vy, omega]^T\n\t\t\tu is a 2x1 vector: [acc/pwm, steer]^T\n\t\t'
steer = u[1]
psi = x[2]
vx = x[3]
vy = x[4]
omega = x[5]
(Ffy, Frx, Fry) = self.calc_forces(x, u)
dxdt = np.zeros(6)
dxdt[0] = ((vx * np.cos(psi)) - (vy * np.sin(psi)))
dxdt[1] = ((vx * np.sin(psi)) + (vy * np.cos(psi)))
dxdt[2] = omega
dxdt[3] = (((1 / self.mass) * (Frx - (Ffy * np.sin(steer)))) + (vy * omega))
dxdt[4] = (((1 / self.mass) * (Fry + (Ffy * np.cos(steer)))) - (vx * omega))
dxdt[5] = ((1 / self.Iz) * (((Ffy * self.lf) * np.cos(steer)) - (Fry * self.lr)))
return dxdt | -43,071,347,659,589,810 | write dynamics as first order ODE: dxdt = f(x(t))
x is a 6x1 vector: [x, y, psi, vx, vy, omega]^T
u is a 2x1 vector: [acc/pwm, steer]^T | bayes_race/models/dynamic.py | _diffequation | KlrShaK/bayesrace | python | def _diffequation(self, t, x, u):
'\twrite dynamics as first order ODE: dxdt = f(x(t))\n\t\t\tx is a 6x1 vector: [x, y, psi, vx, vy, omega]^T\n\t\t\tu is a 2x1 vector: [acc/pwm, steer]^T\n\t\t'
steer = u[1]
psi = x[2]
vx = x[3]
vy = x[4]
omega = x[5]
(Ffy, Frx, Fry) = self.calc_forces(x, u)
dxdt = np.zeros(6)
dxdt[0] = ((vx * np.cos(psi)) - (vy * np.sin(psi)))
dxdt[1] = ((vx * np.sin(psi)) + (vy * np.cos(psi)))
dxdt[2] = omega
dxdt[3] = (((1 / self.mass) * (Frx - (Ffy * np.sin(steer)))) + (vy * omega))
dxdt[4] = (((1 / self.mass) * (Fry + (Ffy * np.cos(steer)))) - (vx * omega))
dxdt[5] = ((1 / self.Iz) * (((Ffy * self.lf) * np.cos(steer)) - (Fry * self.lr)))
return dxdt |
def casadi(self, x, u, dxdt):
'\twrite dynamics as first order ODE: dxdt = f(x(t))\n\t\t\tx is a 6x1 vector: [x, y, psi, vx, vy, omega]^T\n\t\t\tu is a 2x1 vector: [acc/pwm, steer]^T\n\t\t\tdxdt is a casadi.SX variable\n\t\t'
pwm = u[0]
steer = u[1]
psi = x[2]
vx = x[3]
vy = x[4]
omega = x[5]
vmin = 0.05
vy = cs.if_else((vx < vmin), 0, vy)
omega = cs.if_else((vx < vmin), 0, omega)
steer = cs.if_else((vx < vmin), 0, steer)
vx = cs.if_else((vx < vmin), vmin, vx)
Frx = ((((self.Cm1 - (self.Cm2 * vx)) * pwm) - self.Cr0) - (self.Cr2 * (vx ** 2)))
alphaf = (steer - cs.atan2(((self.lf * omega) + vy), vx))
alphar = cs.atan2(((self.lr * omega) - vy), vx)
Ffy = (self.Df * cs.sin((self.Cf * cs.arctan((self.Bf * alphaf)))))
Fry = (self.Dr * cs.sin((self.Cr * cs.arctan((self.Br * alphar)))))
dxdt[0] = ((vx * cs.cos(psi)) - (vy * cs.sin(psi)))
dxdt[1] = ((vx * cs.sin(psi)) + (vy * cs.cos(psi)))
dxdt[2] = omega
dxdt[3] = (((1 / self.mass) * (Frx - (Ffy * cs.sin(steer)))) + (vy * omega))
dxdt[4] = (((1 / self.mass) * (Fry + (Ffy * cs.cos(steer)))) - (vx * omega))
dxdt[5] = ((1 / self.Iz) * (((Ffy * self.lf) * cs.cos(steer)) - (Fry * self.lr)))
return dxdt | 2,081,638,097,302,288,000 | write dynamics as first order ODE: dxdt = f(x(t))
x is a 6x1 vector: [x, y, psi, vx, vy, omega]^T
u is a 2x1 vector: [acc/pwm, steer]^T
dxdt is a casadi.SX variable | bayes_race/models/dynamic.py | casadi | KlrShaK/bayesrace | python | def casadi(self, x, u, dxdt):
'\twrite dynamics as first order ODE: dxdt = f(x(t))\n\t\t\tx is a 6x1 vector: [x, y, psi, vx, vy, omega]^T\n\t\t\tu is a 2x1 vector: [acc/pwm, steer]^T\n\t\t\tdxdt is a casadi.SX variable\n\t\t'
pwm = u[0]
steer = u[1]
psi = x[2]
vx = x[3]
vy = x[4]
omega = x[5]
vmin = 0.05
vy = cs.if_else((vx < vmin), 0, vy)
omega = cs.if_else((vx < vmin), 0, omega)
steer = cs.if_else((vx < vmin), 0, steer)
vx = cs.if_else((vx < vmin), vmin, vx)
Frx = ((((self.Cm1 - (self.Cm2 * vx)) * pwm) - self.Cr0) - (self.Cr2 * (vx ** 2)))
alphaf = (steer - cs.atan2(((self.lf * omega) + vy), vx))
alphar = cs.atan2(((self.lr * omega) - vy), vx)
Ffy = (self.Df * cs.sin((self.Cf * cs.arctan((self.Bf * alphaf)))))
Fry = (self.Dr * cs.sin((self.Cr * cs.arctan((self.Br * alphar)))))
dxdt[0] = ((vx * cs.cos(psi)) - (vy * cs.sin(psi)))
dxdt[1] = ((vx * cs.sin(psi)) + (vy * cs.cos(psi)))
dxdt[2] = omega
dxdt[3] = (((1 / self.mass) * (Frx - (Ffy * cs.sin(steer)))) + (vy * omega))
dxdt[4] = (((1 / self.mass) * (Fry + (Ffy * cs.cos(steer)))) - (vx * omega))
dxdt[5] = ((1 / self.Iz) * (((Ffy * self.lf) * cs.cos(steer)) - (Fry * self.lr)))
return dxdt |
def sim_discrete(self, x0, u, Ts):
'\tsimulates a continuously linearized discrete model\n\t\t\tu is the input vector of size 2xn\n\t\t\tTs is the sampling time\n\t\t'
n_steps = u.shape[1]
x = np.zeros([6, (n_steps + 1)])
dxdt = np.zeros([6, (n_steps + 1)])
dxdt[:, 0] = self._diffequation(None, x0, [0, 0])
x[:, 0] = x0
for ids in range(1, (n_steps + 1)):
g = self._diffequation(None, x[:, (ids - 1)], u[:, (ids - 1)]).reshape((- 1))
x[:, ids] = (x[:, (ids - 1)] + (g * Ts))
dxdt[:, ids] = self._diffequation(None, x[:, ids], u[:, (ids - 1)])
return (x, dxdt) | -4,940,027,757,049,915,000 | simulates a continuously linearized discrete model
u is the input vector of size 2xn
Ts is the sampling time | bayes_race/models/dynamic.py | sim_discrete | KlrShaK/bayesrace | python | def sim_discrete(self, x0, u, Ts):
'\tsimulates a continuously linearized discrete model\n\t\t\tu is the input vector of size 2xn\n\t\t\tTs is the sampling time\n\t\t'
n_steps = u.shape[1]
x = np.zeros([6, (n_steps + 1)])
dxdt = np.zeros([6, (n_steps + 1)])
dxdt[:, 0] = self._diffequation(None, x0, [0, 0])
x[:, 0] = x0
for ids in range(1, (n_steps + 1)):
g = self._diffequation(None, x[:, (ids - 1)], u[:, (ids - 1)]).reshape((- 1))
x[:, ids] = (x[:, (ids - 1)] + (g * Ts))
dxdt[:, ids] = self._diffequation(None, x[:, ids], u[:, (ids - 1)])
return (x, dxdt) |
def linearize(self, x0, u0):
'\tlinearize at a given x0, u0\n\t\t\tfor a given continuous system dxdt = f(x(t))\n\t\t\tcalculate A = ∂f/∂x, B = ∂f/∂u, g = f evaluated at x0, u0\n\t\t\tA is 6x6, B is 6x2, g is 6x1\n\t\t'
steer = u0[1]
psi = x0[2]
vx = x0[3]
vy = x0[4]
omega = x0[5]
vmin = 0.05
if (vx < vmin):
vy = 0
omega = 0
steer = 0
vx = vmin
sindelta = np.sin(steer)
cosdelta = np.cos(steer)
sinpsi = np.sin(psi)
cospsi = np.cos(psi)
(Ffy, Frx, Fry, alphaf, alphar) = self.calc_forces(x0, u0, return_slip=True)
if self.approx:
dFfy_dvx = (((2 * self.Cf) * ((self.lf * omega) + vy)) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
dFfy_dvy = ((((- 2) * self.Cf) * vx) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
dFfy_domega = (((((- 2) * self.Cf) * self.lf) * vx) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
dFrx_dvx = 0
dFrx_dvu1 = 1
dFry_dvx = ((((- 2) * self.Cr) * ((self.lr * omega) - vy)) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFry_dvy = ((((- 2) * self.Cr) * vx) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFry_domega = ((((2 * self.Cr) * self.lr) * vx) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFfy_delta = (2 * self.Cf)
else:
dFfy_dalphaf = (((self.Bf * self.Cf) * self.Df) * np.cos((self.Cf * np.arctan((self.Bf * alphaf)))))
dFfy_dalphaf *= (1 / (1 + ((self.Bf * alphaf) ** 2)))
dFry_dalphar = (((self.Br * self.Cr) * self.Dr) * np.cos((self.Cr * np.arctan((self.Br * alphar)))))
dFry_dalphar *= (1 / (1 + ((self.Br * alphar) ** 2)))
dFfy_dvx = ((dFfy_dalphaf * ((self.lf * omega) + vy)) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
dFfy_dvy = (((- dFfy_dalphaf) * vx) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
dFfy_domega = ((((- dFfy_dalphaf) * self.lf) * vx) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
if self.input_acc:
raise NotImplementedError
pwm = u0[0]
dFrx_dvx = (((- self.Cm2) * pwm) - ((2 * self.Cr2) * vx))
dFrx_dvu1 = (self.Cm1 - (self.Cm2 * vx))
dFry_dvx = (((- dFry_dalphar) * ((self.lr * omega) - vy)) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFry_dvy = (((- dFry_dalphar) * vx) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFry_domega = (((dFry_dalphar * self.lr) * vx) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFfy_delta = dFfy_dalphaf
f1_psi = (((- vx) * sinpsi) - (vy * cospsi))
f1_vx = cospsi
f1_vy = (- sinpsi)
f2_psi = ((vx * cospsi) - (vy * sinpsi))
f2_vx = sinpsi
f2_vy = cospsi
f4_vx = ((1 / self.mass) * (dFrx_dvx - (dFfy_dvx * sindelta)))
f4_vy = ((1 / self.mass) * (((- dFfy_dvy) * sindelta) + (self.mass * omega)))
f4_omega = ((1 / self.mass) * (((- dFfy_domega) * sindelta) + (self.mass * vy)))
f5_vx = ((1 / self.mass) * ((dFry_dvx + (dFfy_dvx * cosdelta)) - (self.mass * omega)))
f5_vy = ((1 / self.mass) * (dFry_dvy + (dFfy_dvy * cosdelta)))
f5_omega = ((1 / self.mass) * ((dFry_domega + (dFfy_domega * cosdelta)) - (self.mass * vx)))
f6_vx = ((1 / self.Iz) * (((dFfy_dvx * self.lf) * cosdelta) - (dFry_dvx * self.lr)))
f6_vy = ((1 / self.Iz) * (((dFfy_dvy * self.lf) * cosdelta) - (dFry_dvy * self.lr)))
f6_omega = ((1 / self.Iz) * (((dFfy_domega * self.lf) * cosdelta) - (dFry_domega * self.lr)))
f4_u1 = dFrx_dvu1
f4_delta = ((1 / self.mass) * (((- dFfy_delta) * sindelta) - (Ffy * cosdelta)))
f5_delta = ((1 / self.mass) * ((dFfy_delta * cosdelta) - (Ffy * sindelta)))
f6_delta = ((1 / self.Iz) * (((dFfy_delta * self.lf) * cosdelta) - ((Ffy * self.lf) * sindelta)))
A = np.array([[0, 0, f1_psi, f1_vx, f1_vy, 0], [0, 0, f2_psi, f2_vx, f2_vy, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, f4_vx, f4_vy, f4_omega], [0, 0, 0, f5_vx, f5_vy, f5_omega], [0, 0, 0, f6_vx, f6_vy, f6_omega]])
B = np.array([[0, 0], [0, 0], [0, 0], [f4_u1, f4_delta], [0, f5_delta], [0, f6_delta]])
g = self._diffequation(None, x0, u0).reshape((- 1))
return (A, B, g) | 954,568,740,370,182,300 | linearize at a given x0, u0
for a given continuous system dxdt = f(x(t))
calculate A = ∂f/∂x, B = ∂f/∂u, g = f evaluated at x0, u0
A is 6x6, B is 6x2, g is 6x1 | bayes_race/models/dynamic.py | linearize | KlrShaK/bayesrace | python | def linearize(self, x0, u0):
'\tlinearize at a given x0, u0\n\t\t\tfor a given continuous system dxdt = f(x(t))\n\t\t\tcalculate A = ∂f/∂x, B = ∂f/∂u, g = f evaluated at x0, u0\n\t\t\tA is 6x6, B is 6x2, g is 6x1\n\t\t'
steer = u0[1]
psi = x0[2]
vx = x0[3]
vy = x0[4]
omega = x0[5]
vmin = 0.05
if (vx < vmin):
vy = 0
omega = 0
steer = 0
vx = vmin
sindelta = np.sin(steer)
cosdelta = np.cos(steer)
sinpsi = np.sin(psi)
cospsi = np.cos(psi)
(Ffy, Frx, Fry, alphaf, alphar) = self.calc_forces(x0, u0, return_slip=True)
if self.approx:
dFfy_dvx = (((2 * self.Cf) * ((self.lf * omega) + vy)) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
dFfy_dvy = ((((- 2) * self.Cf) * vx) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
dFfy_domega = (((((- 2) * self.Cf) * self.lf) * vx) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
dFrx_dvx = 0
dFrx_dvu1 = 1
dFry_dvx = ((((- 2) * self.Cr) * ((self.lr * omega) - vy)) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFry_dvy = ((((- 2) * self.Cr) * vx) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFry_domega = ((((2 * self.Cr) * self.lr) * vx) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFfy_delta = (2 * self.Cf)
else:
dFfy_dalphaf = (((self.Bf * self.Cf) * self.Df) * np.cos((self.Cf * np.arctan((self.Bf * alphaf)))))
dFfy_dalphaf *= (1 / (1 + ((self.Bf * alphaf) ** 2)))
dFry_dalphar = (((self.Br * self.Cr) * self.Dr) * np.cos((self.Cr * np.arctan((self.Br * alphar)))))
dFry_dalphar *= (1 / (1 + ((self.Br * alphar) ** 2)))
dFfy_dvx = ((dFfy_dalphaf * ((self.lf * omega) + vy)) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
dFfy_dvy = (((- dFfy_dalphaf) * vx) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
dFfy_domega = ((((- dFfy_dalphaf) * self.lf) * vx) / ((((self.lf * omega) + vy) ** 2) + (vx ** 2)))
if self.input_acc:
raise NotImplementedError
pwm = u0[0]
dFrx_dvx = (((- self.Cm2) * pwm) - ((2 * self.Cr2) * vx))
dFrx_dvu1 = (self.Cm1 - (self.Cm2 * vx))
dFry_dvx = (((- dFry_dalphar) * ((self.lr * omega) - vy)) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFry_dvy = (((- dFry_dalphar) * vx) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFry_domega = (((dFry_dalphar * self.lr) * vx) / ((((self.lr * omega) - vy) ** 2) + (vx ** 2)))
dFfy_delta = dFfy_dalphaf
f1_psi = (((- vx) * sinpsi) - (vy * cospsi))
f1_vx = cospsi
f1_vy = (- sinpsi)
f2_psi = ((vx * cospsi) - (vy * sinpsi))
f2_vx = sinpsi
f2_vy = cospsi
f4_vx = ((1 / self.mass) * (dFrx_dvx - (dFfy_dvx * sindelta)))
f4_vy = ((1 / self.mass) * (((- dFfy_dvy) * sindelta) + (self.mass * omega)))
f4_omega = ((1 / self.mass) * (((- dFfy_domega) * sindelta) + (self.mass * vy)))
f5_vx = ((1 / self.mass) * ((dFry_dvx + (dFfy_dvx * cosdelta)) - (self.mass * omega)))
f5_vy = ((1 / self.mass) * (dFry_dvy + (dFfy_dvy * cosdelta)))
f5_omega = ((1 / self.mass) * ((dFry_domega + (dFfy_domega * cosdelta)) - (self.mass * vx)))
f6_vx = ((1 / self.Iz) * (((dFfy_dvx * self.lf) * cosdelta) - (dFry_dvx * self.lr)))
f6_vy = ((1 / self.Iz) * (((dFfy_dvy * self.lf) * cosdelta) - (dFry_dvy * self.lr)))
f6_omega = ((1 / self.Iz) * (((dFfy_domega * self.lf) * cosdelta) - (dFry_domega * self.lr)))
f4_u1 = dFrx_dvu1
f4_delta = ((1 / self.mass) * (((- dFfy_delta) * sindelta) - (Ffy * cosdelta)))
f5_delta = ((1 / self.mass) * ((dFfy_delta * cosdelta) - (Ffy * sindelta)))
f6_delta = ((1 / self.Iz) * (((dFfy_delta * self.lf) * cosdelta) - ((Ffy * self.lf) * sindelta)))
A = np.array([[0, 0, f1_psi, f1_vx, f1_vy, 0], [0, 0, f2_psi, f2_vx, f2_vy, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, f4_vx, f4_vy, f4_omega], [0, 0, 0, f5_vx, f5_vy, f5_omega], [0, 0, 0, f6_vx, f6_vy, f6_omega]])
B = np.array([[0, 0], [0, 0], [0, 0], [f4_u1, f4_delta], [0, f5_delta], [0, f6_delta]])
g = self._diffequation(None, x0, u0).reshape((- 1))
return (A, B, g) |
def custom_callback(self, value):
' A custom callback for dealing with tool output.\n '
if ('%' in value):
try:
str_array = value.split(' ')
label = value.replace(str_array[(len(str_array) - 1)], '').strip()
progress = float(str_array[(len(str_array) - 1)].replace('%', '').strip())
self.progress_var.set(int(progress))
self.progress_label['text'] = label
except ValueError as e:
print('Problem converting parsed data into number: ', e)
except Exception as e:
print(e)
else:
self.print_line_to_output(value)
self.update() | -7,362,732,948,371,499,000 | A custom callback for dealing with tool output. | wb_runner.py | custom_callback | luzpaz/whitebox-tools | python | def custom_callback(self, value):
' \n '
if ('%' in value):
try:
str_array = value.split(' ')
label = value.replace(str_array[(len(str_array) - 1)], ).strip()
progress = float(str_array[(len(str_array) - 1)].replace('%', ).strip())
self.progress_var.set(int(progress))
self.progress_label['text'] = label
except ValueError as e:
print('Problem converting parsed data into number: ', e)
except Exception as e:
print(e)
else:
self.print_line_to_output(value)
self.update() |
def test_rollback(self, local_connection):
'test a basic rollback'
users = self.tables.users
connection = local_connection
transaction = connection.begin()
connection.execute(users.insert(), user_id=1, user_name='user1')
connection.execute(users.insert(), user_id=2, user_name='user2')
connection.execute(users.insert(), user_id=3, user_name='user3')
transaction.rollback()
result = connection.exec_driver_sql('select * from users')
assert (len(result.fetchall()) == 0) | 228,207,505,830,494,270 | test a basic rollback | test/engine/test_transaction.py | test_rollback | 418sec/sqlalchemy | python | def test_rollback(self, local_connection):
users = self.tables.users
connection = local_connection
transaction = connection.begin()
connection.execute(users.insert(), user_id=1, user_name='user1')
connection.execute(users.insert(), user_id=2, user_name='user2')
connection.execute(users.insert(), user_id=3, user_name='user3')
transaction.rollback()
result = connection.exec_driver_sql('select * from users')
assert (len(result.fetchall()) == 0) |
def test_rollback_deadlock(self):
'test that returning connections to the pool clears any object\n locks.'
conn1 = testing.db.connect()
conn2 = testing.db.connect()
users = Table('deadlock_users', metadata, Column('user_id', INT, primary_key=True), Column('user_name', VARCHAR(20)), test_needs_acid=True)
with conn1.begin():
users.create(conn1)
conn1.exec_driver_sql('select * from deadlock_users')
conn1.close()
with conn2.begin():
users.drop(conn2)
conn2.close() | -1,619,799,357,194,359,600 | test that returning connections to the pool clears any object
locks. | test/engine/test_transaction.py | test_rollback_deadlock | 418sec/sqlalchemy | python | def test_rollback_deadlock(self):
'test that returning connections to the pool clears any object\n locks.'
conn1 = testing.db.connect()
conn2 = testing.db.connect()
users = Table('deadlock_users', metadata, Column('user_id', INT, primary_key=True), Column('user_name', VARCHAR(20)), test_needs_acid=True)
with conn1.begin():
users.create(conn1)
conn1.exec_driver_sql('select * from deadlock_users')
conn1.close()
with conn2.begin():
users.drop(conn2)
conn2.close() |
def _nextPurge(self, source: BackupSource, backups, findNext=False):
'\n Given a list of backups, decides if one should be purged.\n '
if ((not source.enabled()) or (len(backups) == 0)):
return None
if ((source.maxCount() == 0) and (not self.config.get(Setting.DELETE_AFTER_UPLOAD))):
return None
scheme = self._buildDeleteScheme(source, findNext=findNext)
consider_purging = []
for backup in backups:
source_backup = backup.getSource(source.name())
if ((source_backup is not None) and source_backup.considerForPurge() and (not backup.ignore())):
consider_purging.append(backup)
if (len(consider_purging) == 0):
return None
return scheme.getOldest(consider_purging) | -8,841,430,968,765,923,000 | Given a list of backups, decides if one should be purged. | hassio-google-drive-backup/backup/model/model.py | _nextPurge | voxipbx/hassio-addons | python | def _nextPurge(self, source: BackupSource, backups, findNext=False):
'\n \n '
if ((not source.enabled()) or (len(backups) == 0)):
return None
if ((source.maxCount() == 0) and (not self.config.get(Setting.DELETE_AFTER_UPLOAD))):
return None
scheme = self._buildDeleteScheme(source, findNext=findNext)
consider_purging = []
for backup in backups:
source_backup = backup.getSource(source.name())
if ((source_backup is not None) and source_backup.considerForPurge() and (not backup.ignore())):
consider_purging.append(backup)
if (len(consider_purging) == 0):
return None
return scheme.getOldest(consider_purging) |
def __init__(self, position, discrete=False):
'\n Initializes a observation in light dark domain.\n\n Args:\n position (tuple): position of the robot.\n '
self._discrete = discrete
if (len(position) != 2):
raise ValueError('Observation position must be a vector of length 2')
if self._discrete:
self.position = position
else:
self.position = (round(position[0], Observation.PRECISION), round(position[1], Observation.PRECISION)) | -1,508,324,807,324,518,400 | Initializes a observation in light dark domain.
Args:
position (tuple): position of the robot. | pomdp_problems/light_dark/domain/observation.py | __init__ | Deathn0t/pomdp-py | python | def __init__(self, position, discrete=False):
'\n Initializes a observation in light dark domain.\n\n Args:\n position (tuple): position of the robot.\n '
self._discrete = discrete
if (len(position) != 2):
raise ValueError('Observation position must be a vector of length 2')
if self._discrete:
self.position = position
else:
self.position = (round(position[0], Observation.PRECISION), round(position[1], Observation.PRECISION)) |
def make_marketing_pref_receiver(sender, instance, created, *args, **kwargs):
'\n User model\n '
if created:
MarketingPreference.objects.get_or_create(user=instance) | -4,182,596,920,956,513,000 | User model | eCommerce-master/src/marketing/models.py | make_marketing_pref_receiver | felipebrigo/Python-Projects | python | def make_marketing_pref_receiver(sender, instance, created, *args, **kwargs):
'\n \n '
if created:
MarketingPreference.objects.get_or_create(user=instance) |
def _find_x12(x12path=None, prefer_x13=True):
'\n If x12path is not given, then either x13as[.exe] or x12a[.exe] must\n be found on the PATH. Otherwise, the environmental variable X12PATH or\n X13PATH must be defined. If prefer_x13 is True, only X13PATH is searched\n for. If it is false, only X12PATH is searched for.\n '
global _binary_names
if ((x12path is not None) and x12path.endswith(_binary_names)):
x12path = os.path.dirname(x12path)
if (not prefer_x13):
_binary_names = _binary_names[::(- 1)]
if (x12path is None):
x12path = os.getenv('X12PATH', '')
if (not x12path):
x12path = os.getenv('X13PATH', '')
elif (x12path is None):
x12path = os.getenv('X13PATH', '')
if (not x12path):
x12path = os.getenv('X12PATH', '')
for binary in _binary_names:
x12 = os.path.join(x12path, binary)
try:
subprocess.check_call(x12, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return x12
except OSError:
pass
else:
return False | 5,155,090,809,194,233,000 | If x12path is not given, then either x13as[.exe] or x12a[.exe] must
be found on the PATH. Otherwise, the environmental variable X12PATH or
X13PATH must be defined. If prefer_x13 is True, only X13PATH is searched
for. If it is false, only X12PATH is searched for. | statsmodels/tsa/x13.py | _find_x12 | diego-mazon/statsmodels | python | def _find_x12(x12path=None, prefer_x13=True):
'\n If x12path is not given, then either x13as[.exe] or x12a[.exe] must\n be found on the PATH. Otherwise, the environmental variable X12PATH or\n X13PATH must be defined. If prefer_x13 is True, only X13PATH is searched\n for. If it is false, only X12PATH is searched for.\n '
global _binary_names
if ((x12path is not None) and x12path.endswith(_binary_names)):
x12path = os.path.dirname(x12path)
if (not prefer_x13):
_binary_names = _binary_names[::(- 1)]
if (x12path is None):
x12path = os.getenv('X12PATH', )
if (not x12path):
x12path = os.getenv('X13PATH', )
elif (x12path is None):
x12path = os.getenv('X13PATH', )
if (not x12path):
x12path = os.getenv('X12PATH', )
for binary in _binary_names:
x12 = os.path.join(x12path, binary)
try:
subprocess.check_call(x12, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return x12
except OSError:
pass
else:
return False |
def _clean_order(order):
'\n Takes something like (1 1 0)(0 1 1) and returns a arma order, sarma\n order tuple. Also accepts (1 1 0) and return arma order and (0, 0, 0)\n '
order = re.findall('\\([0-9 ]*?\\)', order)
def clean(x):
return tuple(map(int, re.sub('[()]', '', x).split(' ')))
if (len(order) > 1):
(order, sorder) = map(clean, order)
else:
order = clean(order[0])
sorder = (0, 0, 0)
return (order, sorder) | -271,275,661,211,769,340 | Takes something like (1 1 0)(0 1 1) and returns a arma order, sarma
order tuple. Also accepts (1 1 0) and return arma order and (0, 0, 0) | statsmodels/tsa/x13.py | _clean_order | diego-mazon/statsmodels | python | def _clean_order(order):
'\n Takes something like (1 1 0)(0 1 1) and returns a arma order, sarma\n order tuple. Also accepts (1 1 0) and return arma order and (0, 0, 0)\n '
order = re.findall('\\([0-9 ]*?\\)', order)
def clean(x):
return tuple(map(int, re.sub('[()]', , x).split(' ')))
if (len(order) > 1):
(order, sorder) = map(clean, order)
else:
order = clean(order[0])
sorder = (0, 0, 0)
return (order, sorder) |
def _convert_out_to_series(x, dates, name):
'\n Convert x to a DataFrame where x is a string in the format given by\n x-13arima-seats output.\n '
from io import StringIO
from pandas import read_csv
out = read_csv(StringIO(x), skiprows=2, header=None, sep='\t', engine='python')
return out.set_index(dates).rename(columns={1: name})[name] | 8,948,449,459,947,929,000 | Convert x to a DataFrame where x is a string in the format given by
x-13arima-seats output. | statsmodels/tsa/x13.py | _convert_out_to_series | diego-mazon/statsmodels | python | def _convert_out_to_series(x, dates, name):
'\n Convert x to a DataFrame where x is a string in the format given by\n x-13arima-seats output.\n '
from io import StringIO
from pandas import read_csv
out = read_csv(StringIO(x), skiprows=2, header=None, sep='\t', engine='python')
return out.set_index(dates).rename(columns={1: name})[name] |
def x13_arima_analysis(endog, maxorder=(2, 1), maxdiff=(2, 1), diff=None, exog=None, log=None, outlier=True, trading=False, forecast_years=None, retspec=False, speconly=False, start=None, freq=None, print_stdout=False, x12path=None, prefer_x13=True):
'\n Perform x13-arima analysis for monthly or quarterly data.\n\n Parameters\n ----------\n endog : array_like, pandas.Series\n The series to model. It is best to use a pandas object with a\n DatetimeIndex or PeriodIndex. However, you can pass an array-like\n object. If your object does not have a dates index then ``start`` and\n ``freq`` are not optional.\n maxorder : tuple\n The maximum order of the regular and seasonal ARMA polynomials to\n examine during the model identification. The order for the regular\n polynomial must be greater than zero and no larger than 4. The\n order for the seasonal polynomial may be 1 or 2.\n maxdiff : tuple\n The maximum orders for regular and seasonal differencing in the\n automatic differencing procedure. Acceptable inputs for regular\n differencing are 1 and 2. The maximum order for seasonal differencing\n is 1. If ``diff`` is specified then ``maxdiff`` should be None.\n Otherwise, ``diff`` will be ignored. See also ``diff``.\n diff : tuple\n Fixes the orders of differencing for the regular and seasonal\n differencing. Regular differencing may be 0, 1, or 2. Seasonal\n differencing may be 0 or 1. ``maxdiff`` must be None, otherwise\n ``diff`` is ignored.\n exog : array_like\n Exogenous variables.\n log : bool or None\n If None, it is automatically determined whether to log the series or\n not. If False, logs are not taken. If True, logs are taken.\n outlier : bool\n Whether or not outliers are tested for and corrected, if detected.\n trading : bool\n Whether or not trading day effects are tested for.\n forecast_years : int\n Number of forecasts produced. The default is one year.\n retspec : bool\n Whether to return the created specification file. Can be useful for\n debugging.\n speconly : bool\n Whether to create the specification file and then return it without\n performing the analysis. Can be useful for debugging.\n start : str, datetime\n Must be given if ``endog`` does not have date information in its index.\n Anything accepted by pandas.DatetimeIndex for the start value.\n freq : str\n Must be givein if ``endog`` does not have date information in its\n index. Anything accepted by pandas.DatetimeIndex for the freq value.\n print_stdout : bool\n The stdout from X12/X13 is suppressed. To print it out, set this\n to True. Default is False.\n x12path : str or None\n The path to x12 or x13 binary. If None, the program will attempt\n to find x13as or x12a on the PATH or by looking at X13PATH or\n X12PATH depending on the value of prefer_x13.\n prefer_x13 : bool\n If True, will look for x13as first and will fallback to the X13PATH\n environmental variable. If False, will look for x12a first and will\n fallback to the X12PATH environmental variable. If x12path points\n to the path for the X12/X13 binary, it does nothing.\n\n\n Returns\n -------\n res : Bunch\n A bunch object with the following attributes:\n\n - results : str\n The full output from the X12/X13 run.\n - seasadj : pandas.Series\n The final seasonally adjusted ``endog``\n - trend : pandas.Series\n The trend-cycle component of ``endog``\n - irregular : pandas.Series\n The final irregular component of ``endog``\n - stdout : str\n The captured stdout produced by x12/x13.\n - spec : str, optional\n Returned if ``retspec`` is True. The only thing returned if\n ``speconly`` is True.\n\n Notes\n -----\n This works by creating a specification file, writing it to a temporary\n directory, invoking X12/X13 in a subprocess, and reading the output\n directory, invoking exog12/X13 in a subprocess, and reading the output\n back in.\n '
x12path = _check_x12(x12path)
if (not isinstance(endog, (pd.DataFrame, pd.Series))):
if ((start is None) or (freq is None)):
raise ValueError('start and freq cannot be none if endog is not a pandas object')
endog = pd.Series(endog, index=pd.DatetimeIndex(start=start, periods=len(endog), freq=freq))
spec_obj = pandas_to_series_spec(endog)
spec = spec_obj.create_spec()
spec += 'transform{{function={0}}}\n'.format(_log_to_x12[log])
if outlier:
spec += 'outlier{}\n'
options = _make_automdl_options(maxorder, maxdiff, diff)
spec += 'automdl{{{0}}}\n'.format(options)
spec += _make_regression_options(trading, exog)
spec += _make_forecast_options(forecast_years)
spec += 'x11{ save=(d11 d12 d13) }'
if speconly:
return spec
ftempin = tempfile.NamedTemporaryFile(delete=False, suffix='.spc')
ftempout = tempfile.NamedTemporaryFile(delete=False)
try:
ftempin.write(spec.encode('utf8'))
ftempin.close()
ftempout.close()
p = run_spec(x12path, ftempin.name[:(- 4)], ftempout.name)
p.wait()
stdout = p.stdout.read()
if print_stdout:
print(p.stdout.read())
errors = _open_and_read((ftempout.name + '.err'))
_check_errors(errors)
results = _open_and_read((ftempout.name + '.out'))
seasadj = _open_and_read((ftempout.name + '.d11'))
trend = _open_and_read((ftempout.name + '.d12'))
irregular = _open_and_read((ftempout.name + '.d13'))
finally:
try:
os.remove(ftempin.name)
os.remove(ftempout.name)
except OSError:
if os.path.exists(ftempin.name):
warn('Failed to delete resource {0}'.format(ftempin.name), IOWarning)
if os.path.exists(ftempout.name):
warn('Failed to delete resource {0}'.format(ftempout.name), IOWarning)
seasadj = _convert_out_to_series(seasadj, endog.index, 'seasadj')
trend = _convert_out_to_series(trend, endog.index, 'trend')
irregular = _convert_out_to_series(irregular, endog.index, 'irregular')
if (not retspec):
res = X13ArimaAnalysisResult(observed=endog, results=results, seasadj=seasadj, trend=trend, irregular=irregular, stdout=stdout)
else:
res = X13ArimaAnalysisResult(observed=endog, results=results, seasadj=seasadj, trend=trend, irregular=irregular, stdout=stdout, spec=spec)
return res | 6,818,303,355,341,706,000 | Perform x13-arima analysis for monthly or quarterly data.
Parameters
----------
endog : array_like, pandas.Series
The series to model. It is best to use a pandas object with a
DatetimeIndex or PeriodIndex. However, you can pass an array-like
object. If your object does not have a dates index then ``start`` and
``freq`` are not optional.
maxorder : tuple
The maximum order of the regular and seasonal ARMA polynomials to
examine during the model identification. The order for the regular
polynomial must be greater than zero and no larger than 4. The
order for the seasonal polynomial may be 1 or 2.
maxdiff : tuple
The maximum orders for regular and seasonal differencing in the
automatic differencing procedure. Acceptable inputs for regular
differencing are 1 and 2. The maximum order for seasonal differencing
is 1. If ``diff`` is specified then ``maxdiff`` should be None.
Otherwise, ``diff`` will be ignored. See also ``diff``.
diff : tuple
Fixes the orders of differencing for the regular and seasonal
differencing. Regular differencing may be 0, 1, or 2. Seasonal
differencing may be 0 or 1. ``maxdiff`` must be None, otherwise
``diff`` is ignored.
exog : array_like
Exogenous variables.
log : bool or None
If None, it is automatically determined whether to log the series or
not. If False, logs are not taken. If True, logs are taken.
outlier : bool
Whether or not outliers are tested for and corrected, if detected.
trading : bool
Whether or not trading day effects are tested for.
forecast_years : int
Number of forecasts produced. The default is one year.
retspec : bool
Whether to return the created specification file. Can be useful for
debugging.
speconly : bool
Whether to create the specification file and then return it without
performing the analysis. Can be useful for debugging.
start : str, datetime
Must be given if ``endog`` does not have date information in its index.
Anything accepted by pandas.DatetimeIndex for the start value.
freq : str
Must be givein if ``endog`` does not have date information in its
index. Anything accepted by pandas.DatetimeIndex for the freq value.
print_stdout : bool
The stdout from X12/X13 is suppressed. To print it out, set this
to True. Default is False.
x12path : str or None
The path to x12 or x13 binary. If None, the program will attempt
to find x13as or x12a on the PATH or by looking at X13PATH or
X12PATH depending on the value of prefer_x13.
prefer_x13 : bool
If True, will look for x13as first and will fallback to the X13PATH
environmental variable. If False, will look for x12a first and will
fallback to the X12PATH environmental variable. If x12path points
to the path for the X12/X13 binary, it does nothing.
Returns
-------
res : Bunch
A bunch object with the following attributes:
- results : str
The full output from the X12/X13 run.
- seasadj : pandas.Series
The final seasonally adjusted ``endog``
- trend : pandas.Series
The trend-cycle component of ``endog``
- irregular : pandas.Series
The final irregular component of ``endog``
- stdout : str
The captured stdout produced by x12/x13.
- spec : str, optional
Returned if ``retspec`` is True. The only thing returned if
``speconly`` is True.
Notes
-----
This works by creating a specification file, writing it to a temporary
directory, invoking X12/X13 in a subprocess, and reading the output
directory, invoking exog12/X13 in a subprocess, and reading the output
back in. | statsmodels/tsa/x13.py | x13_arima_analysis | diego-mazon/statsmodels | python | def x13_arima_analysis(endog, maxorder=(2, 1), maxdiff=(2, 1), diff=None, exog=None, log=None, outlier=True, trading=False, forecast_years=None, retspec=False, speconly=False, start=None, freq=None, print_stdout=False, x12path=None, prefer_x13=True):
'\n Perform x13-arima analysis for monthly or quarterly data.\n\n Parameters\n ----------\n endog : array_like, pandas.Series\n The series to model. It is best to use a pandas object with a\n DatetimeIndex or PeriodIndex. However, you can pass an array-like\n object. If your object does not have a dates index then ``start`` and\n ``freq`` are not optional.\n maxorder : tuple\n The maximum order of the regular and seasonal ARMA polynomials to\n examine during the model identification. The order for the regular\n polynomial must be greater than zero and no larger than 4. The\n order for the seasonal polynomial may be 1 or 2.\n maxdiff : tuple\n The maximum orders for regular and seasonal differencing in the\n automatic differencing procedure. Acceptable inputs for regular\n differencing are 1 and 2. The maximum order for seasonal differencing\n is 1. If ``diff`` is specified then ``maxdiff`` should be None.\n Otherwise, ``diff`` will be ignored. See also ``diff``.\n diff : tuple\n Fixes the orders of differencing for the regular and seasonal\n differencing. Regular differencing may be 0, 1, or 2. Seasonal\n differencing may be 0 or 1. ``maxdiff`` must be None, otherwise\n ``diff`` is ignored.\n exog : array_like\n Exogenous variables.\n log : bool or None\n If None, it is automatically determined whether to log the series or\n not. If False, logs are not taken. If True, logs are taken.\n outlier : bool\n Whether or not outliers are tested for and corrected, if detected.\n trading : bool\n Whether or not trading day effects are tested for.\n forecast_years : int\n Number of forecasts produced. The default is one year.\n retspec : bool\n Whether to return the created specification file. Can be useful for\n debugging.\n speconly : bool\n Whether to create the specification file and then return it without\n performing the analysis. Can be useful for debugging.\n start : str, datetime\n Must be given if ``endog`` does not have date information in its index.\n Anything accepted by pandas.DatetimeIndex for the start value.\n freq : str\n Must be givein if ``endog`` does not have date information in its\n index. Anything accepted by pandas.DatetimeIndex for the freq value.\n print_stdout : bool\n The stdout from X12/X13 is suppressed. To print it out, set this\n to True. Default is False.\n x12path : str or None\n The path to x12 or x13 binary. If None, the program will attempt\n to find x13as or x12a on the PATH or by looking at X13PATH or\n X12PATH depending on the value of prefer_x13.\n prefer_x13 : bool\n If True, will look for x13as first and will fallback to the X13PATH\n environmental variable. If False, will look for x12a first and will\n fallback to the X12PATH environmental variable. If x12path points\n to the path for the X12/X13 binary, it does nothing.\n\n\n Returns\n -------\n res : Bunch\n A bunch object with the following attributes:\n\n - results : str\n The full output from the X12/X13 run.\n - seasadj : pandas.Series\n The final seasonally adjusted ``endog``\n - trend : pandas.Series\n The trend-cycle component of ``endog``\n - irregular : pandas.Series\n The final irregular component of ``endog``\n - stdout : str\n The captured stdout produced by x12/x13.\n - spec : str, optional\n Returned if ``retspec`` is True. The only thing returned if\n ``speconly`` is True.\n\n Notes\n -----\n This works by creating a specification file, writing it to a temporary\n directory, invoking X12/X13 in a subprocess, and reading the output\n directory, invoking exog12/X13 in a subprocess, and reading the output\n back in.\n '
x12path = _check_x12(x12path)
if (not isinstance(endog, (pd.DataFrame, pd.Series))):
if ((start is None) or (freq is None)):
raise ValueError('start and freq cannot be none if endog is not a pandas object')
endog = pd.Series(endog, index=pd.DatetimeIndex(start=start, periods=len(endog), freq=freq))
spec_obj = pandas_to_series_spec(endog)
spec = spec_obj.create_spec()
spec += 'transform{{function={0}}}\n'.format(_log_to_x12[log])
if outlier:
spec += 'outlier{}\n'
options = _make_automdl_options(maxorder, maxdiff, diff)
spec += 'automdl{{{0}}}\n'.format(options)
spec += _make_regression_options(trading, exog)
spec += _make_forecast_options(forecast_years)
spec += 'x11{ save=(d11 d12 d13) }'
if speconly:
return spec
ftempin = tempfile.NamedTemporaryFile(delete=False, suffix='.spc')
ftempout = tempfile.NamedTemporaryFile(delete=False)
try:
ftempin.write(spec.encode('utf8'))
ftempin.close()
ftempout.close()
p = run_spec(x12path, ftempin.name[:(- 4)], ftempout.name)
p.wait()
stdout = p.stdout.read()
if print_stdout:
print(p.stdout.read())
errors = _open_and_read((ftempout.name + '.err'))
_check_errors(errors)
results = _open_and_read((ftempout.name + '.out'))
seasadj = _open_and_read((ftempout.name + '.d11'))
trend = _open_and_read((ftempout.name + '.d12'))
irregular = _open_and_read((ftempout.name + '.d13'))
finally:
try:
os.remove(ftempin.name)
os.remove(ftempout.name)
except OSError:
if os.path.exists(ftempin.name):
warn('Failed to delete resource {0}'.format(ftempin.name), IOWarning)
if os.path.exists(ftempout.name):
warn('Failed to delete resource {0}'.format(ftempout.name), IOWarning)
seasadj = _convert_out_to_series(seasadj, endog.index, 'seasadj')
trend = _convert_out_to_series(trend, endog.index, 'trend')
irregular = _convert_out_to_series(irregular, endog.index, 'irregular')
if (not retspec):
res = X13ArimaAnalysisResult(observed=endog, results=results, seasadj=seasadj, trend=trend, irregular=irregular, stdout=stdout)
else:
res = X13ArimaAnalysisResult(observed=endog, results=results, seasadj=seasadj, trend=trend, irregular=irregular, stdout=stdout, spec=spec)
return res |
def x13_arima_select_order(endog, maxorder=(2, 1), maxdiff=(2, 1), diff=None, exog=None, log=None, outlier=True, trading=False, forecast_years=None, start=None, freq=None, print_stdout=False, x12path=None, prefer_x13=True):
'\n Perform automatic seasonal ARIMA order identification using x12/x13 ARIMA.\n\n Parameters\n ----------\n endog : array_like, pandas.Series\n The series to model. It is best to use a pandas object with a\n DatetimeIndex or PeriodIndex. However, you can pass an array-like\n object. If your object does not have a dates index then ``start`` and\n ``freq`` are not optional.\n maxorder : tuple\n The maximum order of the regular and seasonal ARMA polynomials to\n examine during the model identification. The order for the regular\n polynomial must be greater than zero and no larger than 4. The\n order for the seasonal polynomial may be 1 or 2.\n maxdiff : tuple\n The maximum orders for regular and seasonal differencing in the\n automatic differencing procedure. Acceptable inputs for regular\n differencing are 1 and 2. The maximum order for seasonal differencing\n is 1. If ``diff`` is specified then ``maxdiff`` should be None.\n Otherwise, ``diff`` will be ignored. See also ``diff``.\n diff : tuple\n Fixes the orders of differencing for the regular and seasonal\n differencing. Regular differencing may be 0, 1, or 2. Seasonal\n differencing may be 0 or 1. ``maxdiff`` must be None, otherwise\n ``diff`` is ignored.\n exog : array_like\n Exogenous variables.\n log : bool or None\n If None, it is automatically determined whether to log the series or\n not. If False, logs are not taken. If True, logs are taken.\n outlier : bool\n Whether or not outliers are tested for and corrected, if detected.\n trading : bool\n Whether or not trading day effects are tested for.\n forecast_years : int\n Number of forecasts produced. The default is one year.\n start : str, datetime\n Must be given if ``endog`` does not have date information in its index.\n Anything accepted by pandas.DatetimeIndex for the start value.\n freq : str\n Must be givein if ``endog`` does not have date information in its\n index. Anything accepted by pandas.DatetimeIndex for the freq value.\n print_stdout : bool\n The stdout from X12/X13 is suppressed. To print it out, set this\n to True. Default is False.\n x12path : str or None\n The path to x12 or x13 binary. If None, the program will attempt\n to find x13as or x12a on the PATH or by looking at X13PATH or X12PATH\n depending on the value of prefer_x13.\n prefer_x13 : bool\n If True, will look for x13as first and will fallback to the X13PATH\n environmental variable. If False, will look for x12a first and will\n fallback to the X12PATH environmental variable. If x12path points\n to the path for the X12/X13 binary, it does nothing.\n\n Returns\n -------\n results : Bunch\n A bunch object that has the following attributes:\n\n - order : tuple\n The regular order\n - sorder : tuple\n The seasonal order\n - include_mean : bool\n Whether to include a mean or not\n - results : str\n The full results from the X12/X13 analysis\n - stdout : str\n The captured stdout from the X12/X13 analysis\n\n Notes\n -----\n This works by creating a specification file, writing it to a temporary\n directory, invoking X12/X13 in a subprocess, and reading the output back\n in.\n '
results = x13_arima_analysis(endog, x12path=x12path, exog=exog, log=log, outlier=outlier, trading=trading, forecast_years=forecast_years, maxorder=maxorder, maxdiff=maxdiff, diff=diff, start=start, freq=freq, prefer_x13=prefer_x13)
model = re.search('(?<=Final automatic model choice : ).*', results.results)
order = model.group()
if re.search('Mean is not significant', results.results):
include_mean = False
elif re.search('Constant', results.results):
include_mean = True
else:
include_mean = False
(order, sorder) = _clean_order(order)
res = Bunch(order=order, sorder=sorder, include_mean=include_mean, results=results.results, stdout=results.stdout)
return res | -2,889,664,093,120,679,000 | Perform automatic seasonal ARIMA order identification using x12/x13 ARIMA.
Parameters
----------
endog : array_like, pandas.Series
The series to model. It is best to use a pandas object with a
DatetimeIndex or PeriodIndex. However, you can pass an array-like
object. If your object does not have a dates index then ``start`` and
``freq`` are not optional.
maxorder : tuple
The maximum order of the regular and seasonal ARMA polynomials to
examine during the model identification. The order for the regular
polynomial must be greater than zero and no larger than 4. The
order for the seasonal polynomial may be 1 or 2.
maxdiff : tuple
The maximum orders for regular and seasonal differencing in the
automatic differencing procedure. Acceptable inputs for regular
differencing are 1 and 2. The maximum order for seasonal differencing
is 1. If ``diff`` is specified then ``maxdiff`` should be None.
Otherwise, ``diff`` will be ignored. See also ``diff``.
diff : tuple
Fixes the orders of differencing for the regular and seasonal
differencing. Regular differencing may be 0, 1, or 2. Seasonal
differencing may be 0 or 1. ``maxdiff`` must be None, otherwise
``diff`` is ignored.
exog : array_like
Exogenous variables.
log : bool or None
If None, it is automatically determined whether to log the series or
not. If False, logs are not taken. If True, logs are taken.
outlier : bool
Whether or not outliers are tested for and corrected, if detected.
trading : bool
Whether or not trading day effects are tested for.
forecast_years : int
Number of forecasts produced. The default is one year.
start : str, datetime
Must be given if ``endog`` does not have date information in its index.
Anything accepted by pandas.DatetimeIndex for the start value.
freq : str
Must be givein if ``endog`` does not have date information in its
index. Anything accepted by pandas.DatetimeIndex for the freq value.
print_stdout : bool
The stdout from X12/X13 is suppressed. To print it out, set this
to True. Default is False.
x12path : str or None
The path to x12 or x13 binary. If None, the program will attempt
to find x13as or x12a on the PATH or by looking at X13PATH or X12PATH
depending on the value of prefer_x13.
prefer_x13 : bool
If True, will look for x13as first and will fallback to the X13PATH
environmental variable. If False, will look for x12a first and will
fallback to the X12PATH environmental variable. If x12path points
to the path for the X12/X13 binary, it does nothing.
Returns
-------
results : Bunch
A bunch object that has the following attributes:
- order : tuple
The regular order
- sorder : tuple
The seasonal order
- include_mean : bool
Whether to include a mean or not
- results : str
The full results from the X12/X13 analysis
- stdout : str
The captured stdout from the X12/X13 analysis
Notes
-----
This works by creating a specification file, writing it to a temporary
directory, invoking X12/X13 in a subprocess, and reading the output back
in. | statsmodels/tsa/x13.py | x13_arima_select_order | diego-mazon/statsmodels | python | def x13_arima_select_order(endog, maxorder=(2, 1), maxdiff=(2, 1), diff=None, exog=None, log=None, outlier=True, trading=False, forecast_years=None, start=None, freq=None, print_stdout=False, x12path=None, prefer_x13=True):
'\n Perform automatic seasonal ARIMA order identification using x12/x13 ARIMA.\n\n Parameters\n ----------\n endog : array_like, pandas.Series\n The series to model. It is best to use a pandas object with a\n DatetimeIndex or PeriodIndex. However, you can pass an array-like\n object. If your object does not have a dates index then ``start`` and\n ``freq`` are not optional.\n maxorder : tuple\n The maximum order of the regular and seasonal ARMA polynomials to\n examine during the model identification. The order for the regular\n polynomial must be greater than zero and no larger than 4. The\n order for the seasonal polynomial may be 1 or 2.\n maxdiff : tuple\n The maximum orders for regular and seasonal differencing in the\n automatic differencing procedure. Acceptable inputs for regular\n differencing are 1 and 2. The maximum order for seasonal differencing\n is 1. If ``diff`` is specified then ``maxdiff`` should be None.\n Otherwise, ``diff`` will be ignored. See also ``diff``.\n diff : tuple\n Fixes the orders of differencing for the regular and seasonal\n differencing. Regular differencing may be 0, 1, or 2. Seasonal\n differencing may be 0 or 1. ``maxdiff`` must be None, otherwise\n ``diff`` is ignored.\n exog : array_like\n Exogenous variables.\n log : bool or None\n If None, it is automatically determined whether to log the series or\n not. If False, logs are not taken. If True, logs are taken.\n outlier : bool\n Whether or not outliers are tested for and corrected, if detected.\n trading : bool\n Whether or not trading day effects are tested for.\n forecast_years : int\n Number of forecasts produced. The default is one year.\n start : str, datetime\n Must be given if ``endog`` does not have date information in its index.\n Anything accepted by pandas.DatetimeIndex for the start value.\n freq : str\n Must be givein if ``endog`` does not have date information in its\n index. Anything accepted by pandas.DatetimeIndex for the freq value.\n print_stdout : bool\n The stdout from X12/X13 is suppressed. To print it out, set this\n to True. Default is False.\n x12path : str or None\n The path to x12 or x13 binary. If None, the program will attempt\n to find x13as or x12a on the PATH or by looking at X13PATH or X12PATH\n depending on the value of prefer_x13.\n prefer_x13 : bool\n If True, will look for x13as first and will fallback to the X13PATH\n environmental variable. If False, will look for x12a first and will\n fallback to the X12PATH environmental variable. If x12path points\n to the path for the X12/X13 binary, it does nothing.\n\n Returns\n -------\n results : Bunch\n A bunch object that has the following attributes:\n\n - order : tuple\n The regular order\n - sorder : tuple\n The seasonal order\n - include_mean : bool\n Whether to include a mean or not\n - results : str\n The full results from the X12/X13 analysis\n - stdout : str\n The captured stdout from the X12/X13 analysis\n\n Notes\n -----\n This works by creating a specification file, writing it to a temporary\n directory, invoking X12/X13 in a subprocess, and reading the output back\n in.\n '
results = x13_arima_analysis(endog, x12path=x12path, exog=exog, log=log, outlier=outlier, trading=trading, forecast_years=forecast_years, maxorder=maxorder, maxdiff=maxdiff, diff=diff, start=start, freq=freq, prefer_x13=prefer_x13)
model = re.search('(?<=Final automatic model choice : ).*', results.results)
order = model.group()
if re.search('Mean is not significant', results.results):
include_mean = False
elif re.search('Constant', results.results):
include_mean = True
else:
include_mean = False
(order, sorder) = _clean_order(order)
res = Bunch(order=order, sorder=sorder, include_mean=include_mean, results=results.results, stdout=results.stdout)
return res |
def send_email(to: AddressesType, subject: str, html_content: str, files: Optional[AddressesType]=None, cc: Optional[AddressesType]=None, bcc: Optional[AddressesType]=None, sandbox_mode: bool=False, **kwargs) -> None:
'\n Send an email with html content using `Sendgrid <https://sendgrid.com/>`__.\n\n .. note::\n For more information, see :ref:`email-configuration-sendgrid`\n '
if (files is None):
files = []
mail = Mail()
from_email = (kwargs.get('from_email') or os.environ.get('SENDGRID_MAIL_FROM'))
from_name = (kwargs.get('from_name') or os.environ.get('SENDGRID_MAIL_SENDER'))
mail.from_email = Email(from_email, from_name)
mail.subject = subject
mail.mail_settings = MailSettings()
if sandbox_mode:
mail.mail_settings.sandbox_mode = SandBoxMode(enable=True)
personalization = Personalization()
to = get_email_address_list(to)
for to_address in to:
personalization.add_to(Email(to_address))
if cc:
cc = get_email_address_list(cc)
for cc_address in cc:
personalization.add_cc(Email(cc_address))
if bcc:
bcc = get_email_address_list(bcc)
for bcc_address in bcc:
personalization.add_bcc(Email(bcc_address))
pers_custom_args = kwargs.get('personalization_custom_args', None)
if isinstance(pers_custom_args, dict):
for key in pers_custom_args.keys():
personalization.add_custom_arg(CustomArg(key, pers_custom_args[key]))
mail.add_personalization(personalization)
mail.add_content(Content('text/html', html_content))
categories = kwargs.get('categories', [])
for cat in categories:
mail.add_category(Category(cat))
for fname in files:
basename = os.path.basename(fname)
with open(fname, 'rb') as file:
content = base64.b64encode(file.read()).decode('utf-8')
attachment = Attachment(file_content=content, file_type=mimetypes.guess_type(basename)[0], file_name=basename, disposition='attachment', content_id=f'<{basename}>')
mail.add_attachment(attachment)
_post_sendgrid_mail(mail.get()) | -1,098,207,822,008,200,100 | Send an email with html content using `Sendgrid <https://sendgrid.com/>`__.
.. note::
For more information, see :ref:`email-configuration-sendgrid` | airflow/providers/sendgrid/utils/emailer.py | send_email | AI-ML-Projects/airflow | python | def send_email(to: AddressesType, subject: str, html_content: str, files: Optional[AddressesType]=None, cc: Optional[AddressesType]=None, bcc: Optional[AddressesType]=None, sandbox_mode: bool=False, **kwargs) -> None:
'\n Send an email with html content using `Sendgrid <https://sendgrid.com/>`__.\n\n .. note::\n For more information, see :ref:`email-configuration-sendgrid`\n '
if (files is None):
files = []
mail = Mail()
from_email = (kwargs.get('from_email') or os.environ.get('SENDGRID_MAIL_FROM'))
from_name = (kwargs.get('from_name') or os.environ.get('SENDGRID_MAIL_SENDER'))
mail.from_email = Email(from_email, from_name)
mail.subject = subject
mail.mail_settings = MailSettings()
if sandbox_mode:
mail.mail_settings.sandbox_mode = SandBoxMode(enable=True)
personalization = Personalization()
to = get_email_address_list(to)
for to_address in to:
personalization.add_to(Email(to_address))
if cc:
cc = get_email_address_list(cc)
for cc_address in cc:
personalization.add_cc(Email(cc_address))
if bcc:
bcc = get_email_address_list(bcc)
for bcc_address in bcc:
personalization.add_bcc(Email(bcc_address))
pers_custom_args = kwargs.get('personalization_custom_args', None)
if isinstance(pers_custom_args, dict):
for key in pers_custom_args.keys():
personalization.add_custom_arg(CustomArg(key, pers_custom_args[key]))
mail.add_personalization(personalization)
mail.add_content(Content('text/html', html_content))
categories = kwargs.get('categories', [])
for cat in categories:
mail.add_category(Category(cat))
for fname in files:
basename = os.path.basename(fname)
with open(fname, 'rb') as file:
content = base64.b64encode(file.read()).decode('utf-8')
attachment = Attachment(file_content=content, file_type=mimetypes.guess_type(basename)[0], file_name=basename, disposition='attachment', content_id=f'<{basename}>')
mail.add_attachment(attachment)
_post_sendgrid_mail(mail.get()) |
def corpus_reader(path):
'Lê as extensões dos arquivos .xml no caminho especificado como path e\n retorna uma tupla com duas listas.Uma lista contém os paths para os arquivos\n .xml e a outra contém os arquivos Document gerados para aquele arquilo .xml\n '
prog = re.compile('(\\.xml)$')
doc_list = []
f = []
fps = []
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
fps.append(os.path.normpath(os.path.join(dirpath, filename)))
for path in fps:
if re.search(prog, path):
f.append(path)
doc_list.append(Document(path))
return (f, doc_list) | 7,513,357,988,800,923,000 | Lê as extensões dos arquivos .xml no caminho especificado como path e
retorna uma tupla com duas listas.Uma lista contém os paths para os arquivos
.xml e a outra contém os arquivos Document gerados para aquele arquilo .xml | complexidade_textual.py | corpus_reader | lflage/complexidade_textual | python | def corpus_reader(path):
'Lê as extensões dos arquivos .xml no caminho especificado como path e\n retorna uma tupla com duas listas.Uma lista contém os paths para os arquivos\n .xml e a outra contém os arquivos Document gerados para aquele arquilo .xml\n '
prog = re.compile('(\\.xml)$')
doc_list = []
f = []
fps = []
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
fps.append(os.path.normpath(os.path.join(dirpath, filename)))
for path in fps:
if re.search(prog, path):
f.append(path)
doc_list.append(Document(path))
return (f, doc_list) |
def corpus_yeeter(path):
'Similar ao corpus_reader. Recebe um caminho para a pasta contendo o\n corpus e cria um generator. Cada iteração retorna uma tupla contendo um\n caminho para o arquivo .xml e o objeto Document criado a partir do mesmo\n '
prog = re.compile('(\\.xml)$')
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
if re.search(prog, filename):
path = os.path.normpath(os.path.join(dirpath, filename))
(yield (path, Document(path))) | 5,500,897,651,855,036,000 | Similar ao corpus_reader. Recebe um caminho para a pasta contendo o
corpus e cria um generator. Cada iteração retorna uma tupla contendo um
caminho para o arquivo .xml e o objeto Document criado a partir do mesmo | complexidade_textual.py | corpus_yeeter | lflage/complexidade_textual | python | def corpus_yeeter(path):
'Similar ao corpus_reader. Recebe um caminho para a pasta contendo o\n corpus e cria um generator. Cada iteração retorna uma tupla contendo um\n caminho para o arquivo .xml e o objeto Document criado a partir do mesmo\n '
prog = re.compile('(\\.xml)$')
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
if re.search(prog, filename):
path = os.path.normpath(os.path.join(dirpath, filename))
(yield (path, Document(path))) |
def all_fps(path_to_dir):
'Recebe o caminho para o diretório e retorna uma lista com os caminhos\n absolutos para os arquivos que estão nele\n '
fps = []
for (dirpath, dirnames, filenames) in os.walk(path_to_dir):
for filename in filenames:
fps.append(os.path.normpath(os.path.join(dirpath, filename)))
return fps | -5,625,930,603,436,072,000 | Recebe o caminho para o diretório e retorna uma lista com os caminhos
absolutos para os arquivos que estão nele | complexidade_textual.py | all_fps | lflage/complexidade_textual | python | def all_fps(path_to_dir):
'Recebe o caminho para o diretório e retorna uma lista com os caminhos\n absolutos para os arquivos que estão nele\n '
fps = []
for (dirpath, dirnames, filenames) in os.walk(path_to_dir):
for filename in filenames:
fps.append(os.path.normpath(os.path.join(dirpath, filename)))
return fps |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.