Does anyone have a trade gain % snippet that they could share?
When I tried to implement it I found it tricky to assess the 'cost basis' of closing trades.
Does anyone have a trade gain % snippet that they could share?
When I tried to implement it I found it tricky to assess the 'cost basis' of closing trades.
Tricky is right.
A few clues
https://www.quantopian.com/posts/track-orders
pnl = '' # for the trade only
if cb:
pnl = -filled_amt * (prc - cb)
Would this do?
pos = context.portfolio.positions
oos = get_open_orders()
for s in oos:
for o in oos[s]:
if o.status != 0: # ignoring status 0, order not done yet
s = o.sid
pnl = o.amount * (data.current(s, 'price') - pos[s].cost_basis)
Hopefully you won't have to resort to tracking a running balance.
In this area it can also be useful sometimes to know whether an order is opening, closing or crossover (long to short etc)