MCPcopy Create free account
hub / github.com/kernc/backtesting.py / new_order

Method new_order

backtesting/backtesting.py:782–830  ·  view source on GitHub ↗

Argument size indicates whether the order is long or short

(self,
                  size: float,
                  limit: Optional[float] = None,
                  stop: Optional[float] = None,
                  sl: Optional[float] = None,
                  tp: Optional[float] = None,
                  tag: object = None,
                  *,
                  trade: Optional[Trade] = None)

Source from the content-addressed store, hash-verified

780 return f'<Broker: {self._cash:.0f}{self.position.pl:+.1f} ({len(self.trades)} trades)>'
781
782 def new_order(self,
783 size: float,
784 limit: Optional[float] = None,
785 stop: Optional[float] = None,
786 sl: Optional[float] = None,
787 tp: Optional[float] = None,
788 tag: object = None,
789 *,
790 trade: Optional[Trade] = None) -> Order:
791 """
792 Argument size indicates whether the order is long or short
793 """
794 size = float(size)
795 stop = stop and float(stop)
796 limit = limit and float(limit)
797 sl = sl and float(sl)
798 tp = tp and float(tp)
799
800 is_long = size > 0
801 assert size != 0, size
802 adjusted_price = self._adjusted_price(size)
803
804 if is_long:
805 if not (sl or -np.inf) < (limit or stop or adjusted_price) < (tp or np.inf):
806 raise ValueError(
807 "Long orders require: "
808 f"SL ({sl}) < LIMIT ({limit or stop or adjusted_price}) < TP ({tp})")
809 else:
810 if not (tp or -np.inf) < (limit or stop or adjusted_price) < (sl or np.inf):
811 raise ValueError(
812 "Short orders require: "
813 f"TP ({tp}) < LIMIT ({limit or stop or adjusted_price}) < SL ({sl})")
814
815 order = Order(self, size, limit, stop, sl, tp, trade, tag)
816
817 if not trade:
818 # If exclusive orders (each new order auto-closes previous orders/position),
819 # cancel all non-contingent orders and close all open trades beforehand
820 if self._exclusive_orders:
821 for o in self.orders:
822 if not o.is_contingent:
823 o.cancel()
824 for t in self.trades:
825 t.close()
826
827 # Put the new order in the order queue, Ensure SL orders are processed first
828 self.orders.insert(0 if trade and stop else len(self.orders), order)
829
830 return order
831
832 @property
833 def last_price(self) -> float:

Callers 3

buyMethod · 0.80
sellMethod · 0.80
__set_contingentMethod · 0.80

Calls 4

_adjusted_priceMethod · 0.95
OrderClass · 0.85
cancelMethod · 0.45
closeMethod · 0.45

Tested by

no test coverage detected