forked from mementum/backtrader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy.py
More file actions
1718 lines (1277 loc) · 60.3 KB
/
strategy.py
File metadata and controls
1718 lines (1277 loc) · 60.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin389/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015-2020 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import collections
import copy
import datetime
import inspect
import itertools
import operator
from .utils.py3 import (filter, keys, integer_types, iteritems, itervalues,
map, MAXINT, string_types, with_metaclass)
import backtrader as bt
from .lineiterator import LineIterator, StrategyBase
from .lineroot import LineSingle
from .lineseries import LineSeriesStub
from .metabase import ItemCollection, findowner
from .trade import Trade
from .utils import OrderedDict, AutoOrderedDict, AutoDictList
class MetaStrategy(StrategyBase.__class__):
_indcol = dict()
def __new__(meta, name, bases, dct):
# Hack to support original method name for notify_order
if 'notify' in dct:
# rename 'notify' to 'notify_order'
dct['notify_order'] = dct.pop('notify')
if 'notify_operation' in dct:
# rename 'notify' to 'notify_order'
dct['notify_trade'] = dct.pop('notify_operation')
return super(MetaStrategy, meta).__new__(meta, name, bases, dct)
def __init__(cls, name, bases, dct):
'''
Class has already been created ... register subclasses
'''
# Initialize the class
super(MetaStrategy, cls).__init__(name, bases, dct)
if not cls.aliased and \
name != 'Strategy' and not name.startswith('_'):
cls._indcol[name] = cls
def donew(cls, *args, **kwargs):
_obj, args, kwargs = super(MetaStrategy, cls).donew(*args, **kwargs)
# Find the owner and store it
_obj.env = _obj.cerebro = cerebro = findowner(_obj, bt.Cerebro)
_obj._id = cerebro._next_stid()
return _obj, args, kwargs
def dopreinit(cls, _obj, *args, **kwargs):
_obj, args, kwargs = \
super(MetaStrategy, cls).dopreinit(_obj, *args, **kwargs)
_obj.broker = _obj.env.broker
_obj._sizer = bt.sizers.FixedSize()
_obj._orders = list()
_obj._orderspending = list()
_obj._trades = collections.defaultdict(AutoDictList)
_obj._tradespending = list()
_obj.stats = _obj.observers = ItemCollection()
_obj.analyzers = ItemCollection()
_obj._alnames = collections.defaultdict(itertools.count)
_obj.writers = list()
_obj._slave_analyzers = list()
_obj._tradehistoryon = False
return _obj, args, kwargs
def dopostinit(cls, _obj, *args, **kwargs):
_obj, args, kwargs = \
super(MetaStrategy, cls).dopostinit(_obj, *args, **kwargs)
_obj._sizer.set(_obj, _obj.broker)
return _obj, args, kwargs
class Strategy(with_metaclass(MetaStrategy, StrategyBase)):
'''
Base class to be subclassed for user defined strategies.
'''
_ltype = LineIterator.StratType
csv = True
_oldsync = False # update clock using old methodology : data 0
# keep the latest delivered data date in the line
lines = ('datetime',)
def qbuffer(self, savemem=0, replaying=False):
'''Enable the memory saving schemes. Possible values for ``savemem``:
0: No savings. Each lines object keeps in memory all values
1: All lines objects save memory, using the strictly minimum needed
Negative values are meant to be used when plotting is required:
-1: Indicators at Strategy Level and Observers do not enable memory
savings (but anything declared below it does)
-2: Same as -1 plus activation of memory saving for any indicators
which has declared *plotinfo.plot* as False (will not be plotted)
'''
if savemem < 0:
# Get any attribute which labels itself as Indicator
for ind in self._lineiterators[self.IndType]:
subsave = isinstance(ind, (LineSingle,))
if not subsave and savemem < -1:
subsave = not ind.plotinfo.plot
ind.qbuffer(savemem=subsave)
elif savemem > 0:
for data in self.datas:
data.qbuffer(replaying=replaying)
for line in self.lines:
line.qbuffer(savemem=1)
# Save in all object types depending on the strategy
for itcls in self._lineiterators:
for it in self._lineiterators[itcls]:
it.qbuffer(savemem=1)
def _periodset(self):
dataids = [id(data) for data in self.datas]
_dminperiods = collections.defaultdict(list)
for lineiter in self._lineiterators[LineIterator.IndType]:
# if multiple datas are used and multiple timeframes the larger
# timeframe may place larger time constraints in calling next.
clk = getattr(lineiter, '_clock', None)
if clk is None:
clk = getattr(lineiter._owner, '_clock', None)
if clk is None:
continue
while True:
if id(clk) in dataids:
break # already top-level clock (data feed)
# See if the current clock has higher level clocks
clk2 = getattr(clk, '_clock', None)
if clk2 is None:
clk2 = getattr(clk._owner, '_clock', None)
if clk2 is None:
break # if no clock found, bail out
clk = clk2 # keep the ref and try to go up the hierarchy
if clk is None:
continue # no clock found, go to next
# LineSeriesStup wraps a line and the clock is the wrapped line and
# no the wrapper itself.
if isinstance(clk, LineSeriesStub):
clk = clk.lines[0]
_dminperiods[clk].append(lineiter._minperiod)
self._minperiods = list()
for data in self.datas:
# Do not only consider the data as clock but also its lines which
# may have been individually passed as clock references and
# discovered as clocks above
# Initialize with data min period if any
dlminperiods = _dminperiods[data]
for l in data.lines: # search each line for min periods
if l in _dminperiods:
dlminperiods += _dminperiods[l] # found, add it
# keep the reference to the line if any was found
_dminperiods[data] = [max(dlminperiods)] if dlminperiods else []
dminperiod = max(_dminperiods[data] or [data._minperiod])
self._minperiods.append(dminperiod)
# Set the minperiod
minperiods = \
[x._minperiod for x in self._lineiterators[LineIterator.IndType]]
self._minperiod = max(minperiods or [self._minperiod])
def _addwriter(self, writer):
'''
Unlike the other _addxxx functions this one receives an instance
because the writer works at cerebro level and is only passed to the
strategy to simplify the logic
'''
self.writers.append(writer)
def _addindicator(self, indcls, *indargs, **indkwargs):
indcls(*indargs, **indkwargs)
def _addanalyzer_slave(self, ancls, *anargs, **ankwargs):
'''Like _addanalyzer but meant for observers (or other entities) which
rely on the output of an analyzer for the data. These analyzers have
not been added by the user and are kept separate from the main
analyzers
Returns the created analyzer
'''
analyzer = ancls(*anargs, **ankwargs)
self._slave_analyzers.append(analyzer)
return analyzer
def _getanalyzer_slave(self, idx):
return self._slave_analyzers.append[idx]
def _addanalyzer(self, ancls, *anargs, **ankwargs):
anname = ankwargs.pop('_name', '') or ancls.__name__.lower()
nsuffix = next(self._alnames[anname])
anname += str(nsuffix or '') # 0 (first instance) gets no suffix
analyzer = ancls(*anargs, **ankwargs)
self.analyzers.append(analyzer, anname)
def _addobserver(self, multi, obscls, *obsargs, **obskwargs):
obsname = obskwargs.pop('obsname', '')
if not obsname:
obsname = obscls.__name__.lower()
if not multi:
newargs = list(itertools.chain(self.datas, obsargs))
obs = obscls(*newargs, **obskwargs)
self.stats.append(obs, obsname)
return
setattr(self.stats, obsname, list())
l = getattr(self.stats, obsname)
for data in self.datas:
obs = obscls(data, *obsargs, **obskwargs)
l.append(obs)
def _getminperstatus(self):
# check the min period status connected to datas
dlens = map(operator.sub, self._minperiods, map(len, self.datas))
self._minperstatus = minperstatus = max(dlens)
return minperstatus
def prenext_open(self):
pass
def nextstart_open(self):
self.next_open()
def next_open(self):
pass
def _oncepost_open(self):
minperstatus = self._minperstatus
if minperstatus < 0:
self.next_open()
elif minperstatus == 0:
self.nextstart_open() # only called for the 1st value
else:
self.prenext_open()
def _oncepost(self, dt):
for indicator in self._lineiterators[LineIterator.IndType]:
if len(indicator._clock) > len(indicator):
indicator.advance()
if self._oldsync:
# Strategy has not been reset, the line is there
self.advance()
else:
# strategy has been reset to beginning. advance step by step
self.forward()
self.lines.datetime[0] = dt
self._notify()
minperstatus = self._getminperstatus()
if minperstatus < 0:
self.next()
elif minperstatus == 0:
self.nextstart() # only called for the 1st value
else:
self.prenext()
self._next_analyzers(minperstatus, once=True)
self._next_observers(minperstatus, once=True)
self.clear()
def _clk_update(self):
if self._oldsync:
clk_len = super(Strategy, self)._clk_update()
self.lines.datetime[0] = max(d.datetime[0]
for d in self.datas if len(d))
return clk_len
newdlens = [len(d) for d in self.datas]
if any(nl > l for l, nl in zip(self._dlens, newdlens)):
self.forward()
self.lines.datetime[0] = max(d.datetime[0]
for d in self.datas if len(d))
self._dlens = newdlens
return len(self)
def _next_open(self):
minperstatus = self._minperstatus
if minperstatus < 0:
self.next_open()
elif minperstatus == 0:
self.nextstart_open() # only called for the 1st value
else:
self.prenext_open()
def _next(self):
super(Strategy, self)._next()
minperstatus = self._getminperstatus()
self._next_analyzers(minperstatus)
self._next_observers(minperstatus)
self.clear()
def _next_observers(self, minperstatus, once=False):
for observer in self._lineiterators[LineIterator.ObsType]:
for analyzer in observer._analyzers:
if minperstatus < 0:
analyzer._next()
elif minperstatus == 0:
analyzer._nextstart() # only called for the 1st value
else:
analyzer._prenext()
if once:
if len(self) > len(observer):
if self._oldsync:
observer.advance()
else:
observer.forward()
if minperstatus < 0:
observer.next()
elif minperstatus == 0:
observer.nextstart() # only called for the 1st value
elif len(observer):
observer.prenext()
else:
observer._next()
def _next_analyzers(self, minperstatus, once=False):
for analyzer in self.analyzers:
if minperstatus < 0:
analyzer._next()
elif minperstatus == 0:
analyzer._nextstart() # only called for the 1st value
else:
analyzer._prenext()
def _settz(self, tz):
self.lines.datetime._settz(tz)
def _start(self):
self._periodset()
for analyzer in itertools.chain(self.analyzers, self._slave_analyzers):
analyzer._start()
for obs in self.observers:
if not isinstance(obs, list):
obs = [obs] # support of multi-data observers
for o in obs:
o._start()
# change operators to stage 2
self._stage2()
self._dlens = [len(data) for data in self.datas]
self._minperstatus = MAXINT # start in prenext
self.start()
def start(self):
'''Called right before the backtesting is about to be started.'''
pass
def getwriterheaders(self):
self.indobscsv = [self]
indobs = itertools.chain(
self.getindicators_lines(), self.getobservers())
self.indobscsv.extend(filter(lambda x: x.csv, indobs))
headers = list()
# prepare the indicators/observers data headers
for iocsv in self.indobscsv:
name = iocsv.plotinfo.plotname or iocsv.__class__.__name__
headers.append(name)
headers.append('len')
headers.extend(iocsv.getlinealiases())
return headers
def getwritervalues(self):
values = list()
for iocsv in self.indobscsv:
name = iocsv.plotinfo.plotname or iocsv.__class__.__name__
values.append(name)
lio = len(iocsv)
values.append(lio)
if lio:
values.extend(map(lambda l: l[0], iocsv.lines.itersize()))
else:
values.extend([''] * iocsv.lines.size())
return values
def getwriterinfo(self):
wrinfo = AutoOrderedDict()
wrinfo['Params'] = self.p._getkwargs()
sections = [
['Indicators', self.getindicators_lines()],
['Observers', self.getobservers()]
]
for sectname, sectitems in sections:
sinfo = wrinfo[sectname]
for item in sectitems:
itname = item.__class__.__name__
sinfo[itname].Lines = item.lines.getlinealiases() or None
sinfo[itname].Params = item.p._getkwargs() or None
ainfo = wrinfo.Analyzers
# Internal Value Analyzer
ainfo.Value.Begin = self.broker.startingcash
ainfo.Value.End = self.broker.getvalue()
# no slave analyzers for writer
for aname, analyzer in self.analyzers.getitems():
ainfo[aname].Params = analyzer.p._getkwargs() or None
ainfo[aname].Analysis = analyzer.get_analysis()
return wrinfo
def _stop(self):
self.stop()
for analyzer in itertools.chain(self.analyzers, self._slave_analyzers):
analyzer._stop()
# change operators back to stage 1 - allows reuse of datas
self._stage1()
def stop(self):
'''Called right before the backtesting is about to be stopped'''
pass
def set_tradehistory(self, onoff=True):
self._tradehistoryon = onoff
def clear(self):
self._orders.extend(self._orderspending)
self._orderspending = list()
self._tradespending = list()
def _addnotification(self, order, quicknotify=False):
if not order.p.simulated:
self._orderspending.append(order)
if quicknotify:
qorders = [order]
qtrades = []
if not order.executed.size:
if quicknotify:
self._notify(qorders=qorders, qtrades=qtrades)
return
tradedata = order.data._compensate
if tradedata is None:
tradedata = order.data
datatrades = self._trades[tradedata][order.tradeid]
if not datatrades:
trade = Trade(data=tradedata, tradeid=order.tradeid,
historyon=self._tradehistoryon)
datatrades.append(trade)
else:
trade = datatrades[-1]
for exbit in order.executed.iterpending():
if exbit is None:
break
if exbit.closed:
trade.update(order,
exbit.closed,
exbit.price,
exbit.closedvalue,
exbit.closedcomm,
exbit.pnl,
comminfo=order.comminfo)
if trade.isclosed:
self._tradespending.append(copy.copy(trade))
if quicknotify:
qtrades.append(copy.copy(trade))
# Update it if needed
if exbit.opened:
if trade.isclosed:
trade = Trade(data=tradedata, tradeid=order.tradeid,
historyon=self._tradehistoryon)
datatrades.append(trade)
trade.update(order,
exbit.opened,
exbit.price,
exbit.openedvalue,
exbit.openedcomm,
exbit.pnl,
comminfo=order.comminfo)
# This extra check covers the case in which different tradeid
# orders have put the position down to 0 and the next order
# "opens" a position but "closes" the trade
if trade.isclosed:
self._tradespending.append(copy.copy(trade))
if quicknotify:
qtrades.append(copy.copy(trade))
if trade.justopened:
self._tradespending.append(copy.copy(trade))
if quicknotify:
qtrades.append(copy.copy(trade))
if quicknotify:
self._notify(qorders=qorders, qtrades=qtrades)
def _notify(self, qorders=[], qtrades=[]):
if self.cerebro.p.quicknotify:
# need to know if quicknotify is on, to not reprocess pendingorders
# and pendingtrades, which have to exist for things like observers
# which look into it
procorders = qorders
proctrades = qtrades
else:
procorders = self._orderspending
proctrades = self._tradespending
for order in procorders:
if order.exectype != order.Historical or order.histnotify:
self.notify_order(order)
for analyzer in itertools.chain(self.analyzers,
self._slave_analyzers):
analyzer._notify_order(order)
for trade in proctrades:
self.notify_trade(trade)
for analyzer in itertools.chain(self.analyzers,
self._slave_analyzers):
analyzer._notify_trade(trade)
if qorders:
return # cash is notified on a regular basis
cash = self.broker.getcash()
value = self.broker.getvalue()
fundvalue = self.broker.fundvalue
fundshares = self.broker.fundshares
self.notify_cashvalue(cash, value)
self.notify_fund(cash, value, fundvalue, fundshares)
for analyzer in itertools.chain(self.analyzers, self._slave_analyzers):
analyzer._notify_cashvalue(cash, value)
analyzer._notify_fund(cash, value, fundvalue, fundshares)
def add_timer(self, when,
offset=datetime.timedelta(), repeat=datetime.timedelta(),
weekdays=[], weekcarry=False,
monthdays=[], monthcarry=True,
allow=None,
tzdata=None, cheat=False,
*args, **kwargs):
'''
**Note**: can be called during ``__init__`` or ``start``
Schedules a timer to invoke either a specified callback or the
``notify_timer`` of one or more strategies.
Arguments:
- ``when``: can be
- ``datetime.time`` instance (see below ``tzdata``)
- ``bt.timer.SESSION_START`` to reference a session start
- ``bt.timer.SESSION_END`` to reference a session end
- ``offset`` which must be a ``datetime.timedelta`` instance
Used to offset the value ``when``. It has a meaningful use in
combination with ``SESSION_START`` and ``SESSION_END``, to indicated
things like a timer being called ``15 minutes`` after the session
start.
- ``repeat`` which must be a ``datetime.timedelta`` instance
Indicates if after a 1st call, further calls will be scheduled
within the same session at the scheduled ``repeat`` delta
Once the timer goes over the end of the session it is reset to the
original value for ``when``
- ``weekdays``: a **sorted** iterable with integers indicating on
which days (iso codes, Monday is 1, Sunday is 7) the timers can
be actually invoked
If not specified, the timer will be active on all days
- ``weekcarry`` (default: ``False``). If ``True`` and the weekday was
not seen (ex: trading holiday), the timer will be executed on the
next day (even if in a new week)
- ``monthdays``: a **sorted** iterable with integers indicating on
which days of the month a timer has to be executed. For example
always on day *15* of the month
If not specified, the timer will be active on all days
- ``monthcarry`` (default: ``True``). If the day was not seen
(weekend, trading holiday), the timer will be executed on the next
available day.
- ``allow`` (default: ``None``). A callback which receives a
`datetime.date`` instance and returns ``True`` if the date is
allowed for timers or else returns ``False``
- ``tzdata`` which can be either ``None`` (default), a ``pytz``
instance or a ``data feed`` instance.
``None``: ``when`` is interpreted at face value (which translates
to handling it as if it where UTC even if it's not)
``pytz`` instance: ``when`` will be interpreted as being specified
in the local time specified by the timezone instance.
``data feed`` instance: ``when`` will be interpreted as being
specified in the local time specified by the ``tz`` parameter of
the data feed instance.
**Note**: If ``when`` is either ``SESSION_START`` or
``SESSION_END`` and ``tzdata`` is ``None``, the 1st *data feed*
in the system (aka ``self.data0``) will be used as the reference
to find out the session times.
- ``cheat`` (default ``False``) if ``True`` the timer will be called
before the broker has a chance to evaluate the orders. This opens
the chance to issue orders based on opening price for example right
before the session starts
- ``*args``: any extra args will be passed to ``notify_timer``
- ``**kwargs``: any extra kwargs will be passed to ``notify_timer``
Return Value:
- The created timer
'''
return self.cerebro._add_timer(
owner=self, when=when, offset=offset, repeat=repeat,
weekdays=weekdays, weekcarry=weekcarry,
monthdays=monthdays, monthcarry=monthcarry,
allow=allow,
tzdata=tzdata, strats=False, cheat=cheat,
*args, **kwargs)
def notify_timer(self, timer, when, *args, **kwargs):
'''Receives a timer notification where ``timer`` is the timer which was
returned by ``add_timer``, and ``when`` is the calling time. ``args``
and ``kwargs`` are any additional arguments passed to ``add_timer``
The actual ``when`` time can be later, but the system may have not be
able to call the timer before. This value is the timer value and no the
system time.
'''
pass
def notify_cashvalue(self, cash, value):
'''
Receives the current fund value, value status of the strategy's broker
'''
pass
def notify_fund(self, cash, value, fundvalue, shares):
'''
Receives the current cash, value, fundvalue and fund shares
'''
pass
def notify_order(self, order):
'''
Receives an order whenever there has been a change in one
'''
pass
def notify_trade(self, trade):
'''
Receives a trade whenever there has been a change in one
'''
pass
def notify_store(self, msg, *args, **kwargs):
'''Receives a notification from a store provider'''
pass
def notify_data(self, data, status, *args, **kwargs):
'''Receives a notification from data'''
pass
def getdatanames(self):
'''
Returns a list of the existing data names
'''
return keys(self.env.datasbyname)
def getdatabyname(self, name):
'''
Returns a given data by name using the environment (cerebro)
'''
return self.env.datasbyname[name]
def cancel(self, order):
'''Cancels the order in the broker'''
self.broker.cancel(order)
def buy(self, data=None,
size=None, price=None, plimit=None,
exectype=None, valid=None, tradeid=0, oco=None,
trailamount=None, trailpercent=None,
parent=None, transmit=True,
**kwargs):
'''Create a buy (long) order and send it to the broker
- ``data`` (default: ``None``)
For which data the order has to be created. If ``None`` then the
first data in the system, ``self.datas[0] or self.data0`` (aka
``self.data``) will be used
- ``size`` (default: ``None``)
Size to use (positive) of units of data to use for the order.
If ``None`` the ``sizer`` instance retrieved via ``getsizer`` will
be used to determine the size.
- ``price`` (default: ``None``)
Price to use (live brokers may place restrictions on the actual
format if it does not comply to minimum tick size requirements)
``None`` is valid for ``Market`` and ``Close`` orders (the market
determines the price)
For ``Limit``, ``Stop`` and ``StopLimit`` orders this value
determines the trigger point (in the case of ``Limit`` the trigger
is obviously at which price the order should be matched)
- ``plimit`` (default: ``None``)
Only applicable to ``StopLimit`` orders. This is the price at which
to set the implicit *Limit* order, once the *Stop* has been
triggered (for which ``price`` has been used)
- ``trailamount`` (default: ``None``)
If the order type is StopTrail or StopTrailLimit, this is an
absolute amount which determines the distance to the price (below
for a Sell order and above for a buy order) to keep the trailing
stop
- ``trailpercent`` (default: ``None``)
If the order type is StopTrail or StopTrailLimit, this is a
percentage amount which determines the distance to the price (below
for a Sell order and above for a buy order) to keep the trailing
stop (if ``trailamount`` is also specified it will be used)
- ``exectype`` (default: ``None``)
Possible values:
- ``Order.Market`` or ``None``. A market order will be executed
with the next available price. In backtesting it will be the
opening price of the next bar
- ``Order.Limit``. An order which can only be executed at the given
``price`` or better
- ``Order.Stop``. An order which is triggered at ``price`` and
executed like an ``Order.Market`` order
- ``Order.StopLimit``. An order which is triggered at ``price`` and
executed as an implicit *Limit* order with price given by
``pricelimit``
- ``Order.Close``. An order which can only be executed with the
closing price of the session (usually during a closing auction)
- ``Order.StopTrail``. An order which is triggered at ``price``
minus ``trailamount`` (or ``trailpercent``) and which is updated
if the price moves away from the stop
- ``Order.StopTrailLimit``. An order which is triggered at
``price`` minus ``trailamount`` (or ``trailpercent``) and which
is updated if the price moves away from the stop
- ``valid`` (default: ``None``)
Possible values:
- ``None``: this generates an order that will not expire (aka
*Good till cancel*) and remain in the market until matched or
canceled. In reality brokers tend to impose a temporal limit,
but this is usually so far away in time to consider it as not
expiring
- ``datetime.datetime`` or ``datetime.date`` instance: the date
will be used to generate an order valid until the given
datetime (aka *good till date*)
- ``Order.DAY`` or ``0`` or ``timedelta()``: a day valid until
the *End of the Session* (aka *day* order) will be generated
- ``numeric value``: This is assumed to be a value corresponding
to a datetime in ``matplotlib`` coding (the one used by
``backtrader``) and will used to generate an order valid until
that time (*good till date*)
- ``tradeid`` (default: ``0``)
This is an internal value applied by ``backtrader`` to keep track
of overlapping trades on the same asset. This ``tradeid`` is sent
back to the *strategy* when notifying changes to the status of the
orders.
- ``oco`` (default: ``None``)
Another ``order`` instance. This order will become part of an OCO
(Order Cancel Others) group. The execution of one of the orders,
immediately cancels all others in the same group
- ``parent`` (default: ``None``)
Controls the relationship of a group of orders, for example a buy
which is bracketed by a high-side limit sell and a low side stop
sell. The high/low side orders remain inactive until the parent
order has been either executed (they become active) or is
canceled/expires (the children are also canceled) bracket orders
have the same size
- ``transmit`` (default: ``True``)
Indicates if the order has to be **transmitted**, ie: not only
placed in the broker but also issued. This is meant for example to
control bracket orders, in which one disables the transmission for
the parent and 1st set of children and activates it for the last
children, which triggers the full placement of all bracket orders.
- ``**kwargs``: additional broker implementations may support extra
parameters. ``backtrader`` will pass the *kwargs* down to the
created order objects
Example: if the 4 order execution types directly supported by
``backtrader`` are not enough, in the case of for example
*Interactive Brokers* the following could be passed as *kwargs*::
orderType='LIT', lmtPrice=10.0, auxPrice=9.8
This would override the settings created by ``backtrader`` and
generate a ``LIMIT IF TOUCHED`` order with a *touched* price of 9.8
and a *limit* price of 10.0.
Returns:
- the submitted order
'''
if isinstance(data, string_types):
data = self.getdatabyname(data)
data = data if data is not None else self.datas[0]
size = size if size is not None else self.getsizing(data, isbuy=True)
if size:
return self.broker.buy(
self, data,
size=abs(size), price=price, plimit=plimit,
exectype=exectype, valid=valid, tradeid=tradeid, oco=oco,
trailamount=trailamount, trailpercent=trailpercent,
parent=parent, transmit=transmit,
**kwargs)
return None
def sell(self, data=None,
size=None, price=None, plimit=None,
exectype=None, valid=None, tradeid=0, oco=None,
trailamount=None, trailpercent=None,
parent=None, transmit=True,
**kwargs):
'''
To create a selll (short) order and send it to the broker
See the documentation for ``buy`` for an explanation of the parameters
Returns: the submitted order
'''
if isinstance(data, string_types):
data = self.getdatabyname(data)
data = data if data is not None else self.datas[0]
size = size if size is not None else self.getsizing(data, isbuy=False)
if size:
return self.broker.sell(
self, data,
size=abs(size), price=price, plimit=plimit,
exectype=exectype, valid=valid, tradeid=tradeid, oco=oco,
trailamount=trailamount, trailpercent=trailpercent,
parent=parent, transmit=transmit,
**kwargs)
return None
def close(self, data=None, size=None, **kwargs):
'''
Counters a long/short position closing it
See the documentation for ``buy`` for an explanation of the parameters
Note:
- ``size``: automatically calculated from the existing position if
not provided (default: ``None``) by the caller
Returns: the submitted order
'''
if isinstance(data, string_types):
data = self.getdatabyname(data)
elif data is None:
data = self.data
possize = self.getposition(data, self.broker).size
size = abs(size if size is not None else possize)
if possize > 0:
return self.sell(data=data, size=size, **kwargs)
elif possize < 0:
return self.buy(data=data, size=size, **kwargs)
return None