Broker Cash, Strange Metric
Expected Behavior
Start with $1000
Buy $100 of stock
self._broker._cash should be $900.
Sell $150 of stock
self._broker._cash should be $1050
Actual Behavior
Start with $1000 Buy $100 of stock self._broker._cash doesn't change Sell $150 of stock self._broker._cash is now $1050 (cash += closed_trade.pl)
I don't understand this behavior. The variable is named cash, but it's not really the current cash value.
If you want to make trades based on your actual available cash, self._broker.margin_available seems to be what you want... but that seems strange.
Am I missing something here?
Can you rather show some code?
Note, everything prefixed with an underscore is, as customary, private API with no explicit guarantees.
def _close_trade(self, trade: Trade, price: float, time_index: int):
self.trades.remove(trade)
if trade._sl_order:
self.orders.remove(trade._sl_order)
if trade._tp_order:
self.orders.remove(trade._tp_order)
self.closed_trades.append(trade._replace(exit_price=price, exit_bar=time_index))
self._cash += trade.pl
def _open_trade(self, price: float, size: int, sl: float, tp: float, time_index: int):
trade = Trade(self, size, price, time_index)
self.trades.append(trade)
# Create SL/TP (bracket) orders.
# Make sure SL order is created first so it gets adversarially processed before TP order
# in case of an ambiguous tie (both hit within a single bar).
# Note, sl/tp orders are inserted at the front of the list, thus order reversed.
if tp:
trade.tp = tp
if sl:
trade.sl = sl
Cash is only changed when the trade is closed.
I understand the underscore variables are private -- however, I found this because I was interested in creating an enhancement to plot the available cash.