Comments (4)
Hi @edtechre
I tried your code, but it still doesn't work, no trade happens.
So I made some changes to your code based on my understanding of ATR Trailing Stop.
I list code below, in case anyone needs it.
def exec_fn(ctx: ExecContext):
if ctx.long_pos():
stop = ctx.session.setdefault(
"stop",
ctx.close[-1] - ctx.indicator("atr_100")[-1] * 2
)
stop = max(
stop,
ctx.close[-1] - ctx.indicator("atr_100")[-1] * 2,
)
if ctx.low[-1] <= stop:
ctx.sell_all_shares()
del ctx.session["stop"]
else:
ctx.session["stop"] = stop
elif ctx.short_pos():
stop = ctx.session.setdefault(
"stop",
ctx.close[-1] + ctx.indicator("atr_100")[-1] * 2
)
stop = min(
stop,
ctx.close[-1] + ctx.indicator("atr_100")[-1] * 2,
)
if ctx.high[-1] >= stop:
ctx.cover_all_shares()
del ctx.session["stop"]
else:
ctx.session["stop"] = stop
else:
# some buy/long or sell/short code here
pass
from pybroker.
Hi @none2003,
The field stop_trailing will behave just like stop_trailing_pct, except the units are set in absolute price points.
The reason the code isn't working is that the stop is created when the entry is created (i.e., ctx.buy_shares) and cannot be updated afterwards because each stop only applies to its associated entry.
To support your case of dynamically updating the stop, I can add support for setting a Callable that would return the points amount based on the current context (e.g., ATR).
In the meantime, you can determine if a stop is hit by checking ctx.long_pos() and ctx.high. Additionally, you can then update and save the stop threshold in ctx.session to achieve the trailing behavior.
from pybroker.
After considering this further, I have come to the conclusion that introducing support for dynamic stop values using Callables would make the API confusing. The desired behavior can already be achieved using the execution function. Because stop thresholds are intended to be static, I have implemented checks to prevent your example from failing silently. Instead, it will now throw an error.
To achieve what you are after, you can reference this code:
import pybroker as pyb
import talib
def exec_fn(ctx):
if ctx.long_pos():
stop = ctx.session.setdefault(
"stop",
ctx.high[-1] - ctx.indicator("atr_100")[-1] * 2
)
if ctx.low[-1] <= stop:
ctx.sell_all_shares()
del ctx.session["stop"]
else:
ctx.session["stop"] = max(
stop,
ctx.high[-1] - ctx.indicator("atr_100")[-1] * 2,
)
else:
ctx.buy_shares = ctx.calc_target_shares(1)
atr_100 = pyb.indicator("atr_100", lambda data: talib.ATR(data.high, data.low, data.close, timeperiod=100))
strategy.clear_executions()
strategy.add_execution(exec_fn, ['TSLA'], indicators=atr_100)
result = strategy.backtest(warmup=100)
Let me know if you need anything else!
from pybroker.
Whether a trade is made is going to depend on the data you're using for the backtest. My example uses the daily high price instead of close for updating the stop, and it placed trades for my dataset. But glad you have something working, thanks for sharing!
from pybroker.
Related Issues (20)
- enable_fractional_shares is not considered by calc_target_shares HOT 3
- Adding interactive examples
- Add cababillity to pickle the Portfolio object and then reuse it for incremental backtests or live trading HOT 14
- Unclear which timezone between_time uses HOT 9
- How to limit the order price to satisfy "Limit up" or "Limit down" rule? HOT 1
- profit_factor below confidence interval HOT 1
- How to specify the closing price as the opening price of the next bar in Strategy.backtest()? HOT 1
- dependency conflicts HOT 1
- Suspicious short trade in a pure long trades HOT 6
- pip install lib-pybroker fail HOT 1
- "ValueError: DataSource is empty." for Akshare as data sources HOT 4
- Question about shares and pnl number in "result.trades" HOT 8
- can't backtest with fresh installation HOT 4
- Support Pandas 2 HOT 5
- Return indicator values and model predictions from Strategy HOT 1
- Add support for global models HOT 1
- Support custom fee structure HOT 3
- Add config option for disabling quantization in results HOT 1
- question about ctx.dt and indicator value HOT 3
- Error: Fill price 0 for prices below 0.005$ (like many cryptocurrencies) HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pybroker.