For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
How to check whether the order is a buy or a sell order?
-
import pandas as pd import yfinance as yf from ta.utils import dropna import backtrader as bt import backtrader.feeds as btfeeds import talib import math import matplotlib from datetime import datetime from nsepy import get_history import datetime from ta.trend import ADXIndicator import ta import time class TestStrategy(bt.Strategy): def log(self, txt, dt=None): dt = dt or self.datas[0].datetime.date(0) print(f'{dt.isoformat()} {txt}') # Print date and close def __init__(self): self.close = self.datas[0].close self.order = None self.ema = bt.ind.EMA(period=6) self.rsi = bt.indicators.RelativeStrengthIndex(period=7) self.diplus = bt.indicators.PlusDirectionalIndicator() self.diminus = bt.indicators.MinusDirectionalIndicator() dx = abs(self.diplus - self.diminus) / (self.diplus + self.diminus) * 100 self.adx = bt.indicators.MovingAverageSimple(dx, period=7) # self.high_rsi=bt.ind.Highest(self.rsi,period=0) def price_check(self): value = cerebro.broker.getvalue() return (value // self.close[-1]) - 55 def next(self): if self.order: return if not self.position:#when we have not taken any positions if self.rsi > self.rsi[-2] and self.rsi[-1] > 60 and self.rsi[0] >= 62 and self.diplus > 28 and self.adx[-1] > 28 and self.adx[0] > 29 and self.ema[-1] < self.close[-1] and self.ema[0] < self.close[0]: self.order = self.buy(size=self.price_check())#i have made a method to go for maximum size self.log(f'BUY CREATE {self.close[0]:2f}') if (self.position.size>0): # when we are long self.order = self.sell(size=self.position.size, exectype=bt.Order.StopTrail, trailpercent=0.065) cerebro = bt.Cerebro() cerebro.broker.setcash(100000.0) dfy=yf.download("TATAMOTORS.NS",period="1y",interval="1h") dfy1=pd.DataFrame(dfy) feed = bt.feeds.PandasData(dataname=dfy) cerebro.adddata(feed) cerebro.addstrategy(TestStrategy) cerebro.run() cerebro.plot()
The problem that am facing is my self.position.size if showing 0 always. What can I do to check whether the order is a buy or sell
-
Please take look at the docs here.
Once you have an order instance you can check if it a buy or sell by using the following methods:
User Methods: isbuy(): returns bool indicating if the order buys issell(): returns bool indicating if the order sells
-
yes but how can I use this{ self.order.isbuy()} is in next() method because we ain't passing order as an argument ?