edtechre / pybroker

Algorithmic Trading in Python with Machine Learning
https://www.pybroker.com
Other
2.09k stars 262 forks source link

Stop Loss #140

Closed markxbaker closed 2 months ago

markxbaker commented 2 months ago

Hey Ed, thanks for updating the slippage, tested and working!

I still can't seem to set a stop loss price based on an ATR distance from the entry or close as below - the prints seem correct but no stop loss is set? I want to size my positions based on the stop distance and so forth to maintain a consistent cash exposure.

if not pos: if sma_short[-1] > sma_long[-1] and ctx.close[-1] >= 1 : ctx.buy_shares = ctx.calc_target_shares(0.01)

        # Set stop loss based on ATR
        ATR = (1.5 * atr_10d[-1])
        stop_loss_calc = (ctx.close[-1] - ATR)

        ctx.stop_loss = stop_loss_calc

        ctx.hold_bars = 8
        ctx.score = ctx.volume[-1]

        print(f"Entered trade on {ctx.date[-1]} at price {ctx.close[-1]:.2f}")
        print(f"ATR: {ATR:.2f}")
        print(f"Stop Loss Price: {stop_loss_calc:.2f}")
edtechre commented 2 months ago

Hi @markxbaker,

The stop loss is calculated as the number of points from the entry price of the trade. The stop is never hit with:

stop_loss_calc = (ctx.close[-1] - ATR)
ctx.stop_loss = stop_loss_calc

This should instead be: ctx.stop_loss = ATR

markxbaker commented 2 months ago

Ah ok, thank you.