@@ -643,7 +643,8 @@ def __set_contingent(self, type, price):
643
643
644
644
645
645
class _Broker :
646
- def __init__ (self , * , data , cash , commission , margin , trade_on_close , hedging , index ):
646
+ def __init__ (self , * , data , cash , commission , margin ,
647
+ trade_on_close , hedging , exclusive_orders , index ):
647
648
assert 0 < cash , "cash shosuld be >0, is {}" .format (cash )
648
649
assert 0 <= commission < .1 , "commission should be between 0-10%, is {}" .format (commission )
649
650
assert 0 < margin <= 1 , "margin should be between 0 and 1, is {}" .format (margin )
@@ -653,6 +654,7 @@ def __init__(self, *, data, cash, commission, margin, trade_on_close, hedging, i
653
654
self ._leverage = 1 / margin
654
655
self ._trade_on_close = trade_on_close
655
656
self ._hedging = hedging
657
+ self ._exclusive_orders = exclusive_orders
656
658
657
659
self ._equity = np .tile (np .nan , len (index ))
658
660
self .orders = [] # type: List[Order]
@@ -699,7 +701,17 @@ def new_order(self,
699
701
if trade :
700
702
self .orders .insert (0 , order )
701
703
else :
704
+ # If exclusive orders (each new order auto-closes previous orders/position),
705
+ # cancel all non-contingent orders and close all open trades beforehand
706
+ if self ._exclusive_orders :
707
+ for o in self .orders :
708
+ if not o .is_contingent :
709
+ o .cancel ()
710
+ for t in self .trades :
711
+ t .close ()
712
+
702
713
self .orders .append (order )
714
+
703
715
return order
704
716
705
717
@property
@@ -919,6 +931,7 @@ def __init__(self,
919
931
margin : float = 1. ,
920
932
trade_on_close = False ,
921
933
hedging = False ,
934
+ exclusive_orders = False ,
922
935
):
923
936
"""
924
937
Initialize a backtest. Requires data and a strategy to test.
@@ -1006,7 +1019,7 @@ def __init__(self,
1006
1019
self ._broker = partial (
1007
1020
_Broker , cash = cash , commission = commission , margin = margin ,
1008
1021
trade_on_close = trade_on_close , hedging = hedging ,
1009
- index = data .index ,
1022
+ exclusive_orders = exclusive_orders , index = data .index ,
1010
1023
)
1011
1024
self ._strategy = strategy
1012
1025
self ._results = None
0 commit comments