Beispiel #1
0
 def __init__(self):
     self.inds = dict(
     )  # going to store indicators in dictionary for each stock ive added
     self.sma = dict()
     for i, d in enumerate(self.datas):
         self.inds[d] = btind.BollingerBands(
             d, period=self.params.BBandsPeriod)
Beispiel #2
0
    def __init__(self, store):
        self.buy_order = None
        self.live_data = False

        # You can hookup backtrader to any indicator that runs in MT5
        # Attach and retrieve values from the MT5 indicator "Examples/MACD"
        self.mt5macd = getMTraderIndicator(
            # MTraderStorestore instance
            store,
            # Data stream to run the indicator calculations on
            self.datas[0],
            # Set accessor(s) for the indicator output buffers
            (
                "macd",
                "signal",
            ),
            # MT5 inidicator name
            indicator="Examples/MACD",
            # Indicator parameters.
            # Any omitted values will use the defaults as defind by the indicator
            params=[12, 26, 9, "PRICE_CLOSE"],
        )()

        # Attach any inidcator to be drawn to a chart window _before_ instantiating the MTraderChart class.
        # self.sma = btind.SimpleMovingAverage(self.data)
        self.bb = btind.BollingerBands(self.data)

        # Open a new chart window in MT5 with symbol and timeframe provided by the passed data stream object.
        # Important: instantiate a new chart with class MTraderChart only after you attached any
        # indicator you want to plot by calling getMTraderIndicator as shown on line 17 above. Otherwise it will fail!
        chart = MTraderChart(data_obj=self.datas[0])

        # Plot the backtrader BollingerBand indicator to a chart window in MT5.
        chart.addline(
            self.bb.top,
            style={
                "shortname": "BT-BollingerBands",
                "linelabel": "Top",
                "color": "clrBlue",
            },
        )
        chart.addline(
            self.bb.mid,
            style={
                "shortname": "BT-BollingerBands",
                "linelabel": "Middle",
                "color": "clrYellow",
            },
        )
        chart.addline(
            self.bb.bot,
            style={
                "shortname": "BT-BollingerBands",
                "linelabel": "Bottom",
                "color": "clrGreen",
            },
        )
Beispiel #3
0
 def __init__(self):
     super().__init__()
     self.di = btind.DirectionalMovement(self.datas[0], period = self.p.di_period)
     self.ma1 = btind.MovingAverageSimple(self.datas[0], period = self.p.ma1)
     self.ma2 = btind.MovingAverageSimple(self.datas[0], period=self.p.ma2)
     self.bbands = btind.BollingerBands(self.datas[0], period = self.p.band_period, devfactor = self.p.devfactor)
     self.ma = btind.MovingAverageSimple(self.datas[0], period=self.p.band_period)
     range = btind.TrueRange(self.datas[0])
     self.rangema = btind.MovingAverageSimple(range, period = self.p.band_period)
Beispiel #4
0
 def __init__(self):
     # Reference to "close" line
     self.p.devfactor= self.p.devfactor/10
     self.close = self.data.close
     self.open = self.data.open
     self.high = self.data.high
     self.order = None
     self.orderTime = None
     self.sellprice = None
     # Bollinger Band indicator
     self.boll = btind.BollingerBands(period=self.p.period, devfactor=self.p.devfactor)
Beispiel #5
0
    def __init__(self):
        self.buysellLog = ""
        self.dataclose = self.datas[0].close

        self.order = None
        self.buyprice = 0
        self.buycomm = 0
        self.buytime = 0

        # 使用自带的indicators中自带的函数计算出支撑线和压力线,period设置周期,默认是20
        self.top = btind.BollingerBands(self.datas[0],
                                        period=self.params.maperiod).top
        self.bot = btind.BollingerBands(self.datas[0],
                                        period=self.params.maperiod,
                                        plot=False).bot

        self.Crossovertop = btind.CrossOver(self.dataclose,
                                            self.top,
                                            plotname='压力线交叉')
        self.Crossoverbot = btind.CrossOver(self.dataclose,
                                            self.bot,
                                            plotname='支撑线交叉')
    def __init__(self):
        super(SARStrategy, self).__init__()

        self.MA = btind.HullMA(period=self.p.MA)  #pylint: disable-all
        self.sar = btind.PSAR(period=self.p.period,
                              af=self.p.af,
                              afmax=self.p.afmax)  #pylint: disable-all
        self.bb = btind.BollingerBands(plot=True)  #pylint: disable-all
        self.DoubleCross = DoubleCross(self.data,
                                       self.MA,
                                       self.sar,
                                       self.bb,
                                       use_bb=self.p.use_bb)
Beispiel #7
0
    def __init__(self, pool_list, dataId_to_ticker_d, ticker_to_dataId_d,
                 start_date, end_date):
        # Keep a reference to the "close" line in the data[0] dataseries
        self.bar_num = 0
        #self.index_50_date_stock_dict=self.get_index_50_date_stock()
        self.pool_list = pool_list
        self.dataId_to_ticker_dict = dataId_to_ticker_d
        self.ticker_to_dataId_dict = ticker_to_dataId_d
        self.start_date = start_date
        self.end_date = end_date
        self.position_list = [
        ]  #postion order ["sym", "date", "close", "high", "perc", "exit","edate","eperc"]
        self.csCount = 0

        self.hasPosition = False
        self.entryPrice = 100
        self.highPrice = 100
        self.newLowDiv = 100
        self.newLowBar = 0

        global g_entry_list
        g_entry_list = []

        # add indicators
        for d in self.datas:
            ## d.baseline = btind.ExponentialMovingAverage(d, period=21)
            d.ema20 = btind.ExponentialMovingAverage(d, period=20)
            d.ema60 = btind.ExponentialMovingAverage(d, period=60)
            d.macd = btind.MACD(d)
            d.priceDiv = PriceDiv(d)
            d.data_obv = OnBalanceVolume(d)
            d.data_obv20 = btind.SMA(d.data_obv, period=20)
            d.data_bb = btind.BollingerBands(d, period=14, devfactor=2.0)
            d.data_kc = KeltnerChannel(d,
                                       periodEMA=20,
                                       periodATR=20,
                                       devfactor=1.5)
            d.data_rg = RGChannel(d)

            self.log('stategy data init :' + d._name)
    def __init__(self):
        self.dataclose = self.datas[0].close

        self.bbands = btind.BollingerBands(period=20, devfactor=2)

        self.stoch = btind.Stochastic(period=14,
                                      period_dfast=3,
                                      period_dslow=3)

        self.orders = list()

        self.short_signal = bt.And(self.dataclose > self.bbands.top,
                                   self.stoch.percK > 80)

        self.long_signal = bt.And(self.dataclose < self.bbands.bot,
                                  self.stoch.percK < 20)

        self.close_long_signal = self.dataclose >= self.bbands.top

        self.close_short_signal = self.dataclose <= self.bbands.bot

        self.loss_perc = 0.025
Beispiel #9
0
    def __init__(self):
        super().__init__()
        self.ma = btind.MovingAverageSimple(self.datas[0], period = self.params.ma)
        self.ma1 = btind.MovingAverageSimple(self.datas[0], period = self.params.ma1)
        self.ma2 = btind.MovingAverageSimple(self.datas[0], period = self.params.ma2)
        self.atr = btind.AverageTrueRange(self.datas[0])

        self.kst = btind.KnowSureThing(self.datas[0])

        self.macd = btind.MACD(self.datas[0])

        self.trix = btind.TrixSignal(self.datas[0])

        self.ao = btind.AwesomeOscillator(self.datas[0])

        self.tsi = btind.TrueStrengthIndicator(self.datas[0])

        self.psar = btind.ParabolicSAR(self.datas[0])

        self.adx = btind.AverageDirectionalMovementIndex(self.datas[0])

        self.dpo = btind.DetrendedPriceOscillator(self.datas[0])

        self.rsi = btind.RSI(self.datas[0])

        self.accdec = btind.AccelerationDecelerationOscillator(self.datas[0])

        self.bbands = btind.BollingerBands(self.datas[0])

        self.cci = btind.CommodityChannelIndex(self.datas[0])

        self.pgood = btind.PrettyGoodOscillator(self.datas[0])

        self.williamsr = btind.WilliamsR(self.datas[0])

        self.uo = btind.UltimateOscillator(self.datas[0])

        self.stoch = btind.Stochastic(self.datas[0])
Beispiel #10
0
    def __init__(self):
        # To control operation entries
        self.orderid = list()
        self.order = None

        self.counttostop = 0
        self.datastatus = 0

        self.state = np.empty([4, 8])
        self.stateFilled = 0
        self.agent = Agent(8, 4)
        # Create SMA on 2nd data
        self.ema = bt.indicators.MovAv.EMA(self.data, period=self.p.smaperiod)
        #self.ema = bt.indicators.MovAv.SMA(self.data, period=self.p.smaperiod)
        self.macd = btind.MACD(self.data)
        self.williamad = btind.WilliamsAD(self.data)
        self.bollinger = btind.BollingerBands(self.data,
                                              period=self.p.smaperiod)

        self.currentOrder = None
        print('--------------------------------------------------')
        print('Strategy Created')
        print('--------------------------------------------------')
Beispiel #11
0
	def __init__(self):
		
		#Set program start time
		start_time=datetime.now().time()
		print('Program start at {}'.format(start_time))
	
		#print(self.params.sma1, self.p.ema1, self.params.atrperiod) #Proof deep copy worked for params
		
		#initialize counters for prenext/next
		self.nextcounter = 0	
		self.counter = 0
		self.counttostop = 0
		self.datastatus = 0
		self.prenext_done = False
		self.bought = 0
		self.sold = 0
		self.target_long_price = 0
		self.target_short_price = 0
		self.trade_open_counter = 0
		self.trade_close_counter = 0	
		self.trade_total_counter = 0
		self.lost_counter = 0 
		self.won_counter = 0
		
		#Define dictionaries and lists to be accessed from all timeframes
		self.atr_list =[]
		self.inds = dict()
		self.gap_dict=dict()
		self.rnghigh_dict = dict()
		self.rnglow_dict= dict()
		self.longstop_dict = dict()
		self.shortstop_dict = dict()
		self.target_long_dict = dict()
		self.target_short_dict = dict()
		self.size_dict = dict()
		self.inorder_dict = dict()		
		self.sup_dict = dict()
		self.res_dict = dict()
		self.pos_dict = defaultdict(list)
				
		#Create/Instantiate objects to access user input parameters
		modelp = UserInputs.model_params()
		indp = UserInputs.ind_params()
		datalist = UserInputs.datalist('hist')
		ibdatalist = UserInputs.datalist('ib')
		
		#Determine interval for timeframe looping
		if not modelp.get('live_status'):
			data_feed_count = len(self.datas)
			ticker_count = len(datalist)
			self.ticker_interval = int(data_feed_count/ticker_count) #Needs to be an integer
		elif modelp.get('live_status'):   
			data_feed_count = len(self.datas)
			ticker_count = len(ibdatalist)
			self.ticker_interval = int(data_feed_count/ticker_count) #Needs to be an integer
		
		#************************INITITIALIZE INDICATORS*********************************************************
		#Initialize dictionary's
		for x in range(0, len(self.datas), self.ticker_interval):
			
			d = self.datas[x]
			print(d._name)
			
			if not (d._name[:-1]=='VIX' or d._name[:-1]=='TICK-NYSE'):
				#Order dictionaries
				self.target_long_dict[d._name] = dict()
				self.target_short_dict[d._name] = dict()
				self.inorder_dict[d._name] = dict()
				self.target_long_dict[d._name] = 0
				self.target_short_dict[d._name] = 0
				self.inorder_dict[d._name] = False
	
		for i, d in enumerate(self.datas): 	
			if not (d._name[:-1]=='VIX' or d._name[:-1]=='TICK-NYSE'):
				#Sizing dictionary
				self.size_dict[d._name] = dict()
				self.size_dict[d._name] = 0
				
				#For support/resistance dictionaries
				self.sup_dict[d._name] = dict()
				self.res_dict[d._name] = dict()
				self.sup_dict[d._name] = 0
				self.res_dict[d._name] = 10000
				
				#For all indicators
				self.inds[d._name] = dict()

				#Moving Average Indicators - FAST, SLOW, and CROSS
				self.inds[d._name]['sma1'] = btind.SMA(d,
														period=indp.get('sma1'),
														plot=False)
														
				self.inds[d._name]['sma2'] = btind.SMA(d,
														period=indp.get('sma2'),
														plot=True)										
				
				self.inds[d._name]['ema1'] = btind.EMA(d,
														period=indp.get('ema1'),
														plot=False)
															
				self.inds[d._name]['ema2'] = btind.EMA(d,
														period=indp.get('ema2'),
														plot=False)
													
				self.inds[d._name]['ema3'] = btind.EMA(d,
														period=indp.get('ema3'),
														plot=False)
				
				#This will double pre-next 												
				self.inds[d._name]['cross'] = btind.CrossOver(self.inds[d._name]['ema2'],
														self.inds[d._name]['ema3'],
														plot=False)
					
				#RSI
				self.inds[d._name]['rsi']= btind.RSI(d,
													safediv=True,
													plot=True)
							
				#AVERAGE TRUE RANGE INDICATOR
				self.inds[d._name]['atr'] = btind.ATR(d,
												period=indp.get('atrperiod'),
												plot=False)

				#Bollinger Band
				self.inds[d._name]['bollinger'] = btind.BollingerBands(d,
															period=indp.get('bollinger_period'),
															devfactor = indp.get('bollinger_dist'),
															plot=False)
			
				#Stochastics
				self.inds[d._name]['stochastic'] = btind.StochasticFast(d,
															period=indp.get('stoch_per'),
															period_dfast= indp.get('stoch_fast'),
															safediv=True,
															plot=True)
				
				#ADX
				self.inds[d._name]['adx'] = btind.ADX(d,plot=True)
						
				"""											
				#Pivots
				self.inds[d._name]['pivots'] = btind.pivotpoint.PivotPoint(d,
															plot=False)
				"""												
				#Average Volume Indicator
				self.inds[d._name]['avg_volume'] = btind.Average(d.volume,
															period=indp.get('avg_per'),
															plot=False)
				
				#Highest and Lowest Values of Period Indicator
				self.inds[d._name]['highest'] = btind.Highest(d.high,
															period=indp.get('breakout_per'),
															plot=False)
																								
				self.inds[d._name]['lowest'] = btind.Lowest(d.low,
															period=indp.get('breakout_per'),
															plot=False)
				
				#Slope indicators
				self.inds[d._name]['slope']= btind.Slope(d.close,
														period=indp.get('slope_period'),
														plot=False)
														
				self.inds[d._name]['slope_sma1'] = 	btind.Slope(self.inds[d._name]['sma1'],
														period=indp.get('slope_period'),
														plot=False,
														plotname = 'Slope_SMA1')
														
				self.inds[d._name]['slope_of_slope_sma1'] = 	btind.Slope(self.inds[d._name]['slope_sma1'],
														period=indp.get('slope_period'),
														plot=False,
														plotname = 'Slope_of_Slope_SMA1')
														
				self.inds[d._name]['slope_sma_width'] = btind.Slope(self.inds[d._name]['sma1']-self.inds[d._name]['sma2'],
														period=indp.get('slope_period'),
														plot=False,
														plotname = 'Slope_SMA_WIDTH')											
														
				self.inds[d._name]['slope_adx'] = 	btind.Slope(self.inds[d._name]['adx'],
														period=indp.get('slope_period'),
														plot=False,
														plotname = 'Slope_ADX')	
														
				self.inds[d._name]['slope_of_slope_adx'] = 	btind.Slope(self.inds[d._name]['slope_adx'],
														period=indp.get('slope_period'),
														plot=False,
														plotname = 'Slope_of_Slope_ADX')	
														
				self.inds[d._name]['slope_rsi'] = 	btind.Slope(self.inds[d._name]['rsi'],
														period=indp.get('slope_period'),
														plot=False,
														plotname = 'Slope_RSI')
														
				self.inds[d._name]['slope_of_slope_rsi'] = 	btind.Slope(self.inds[d._name]['slope_rsi'],
														period=indp.get('slope_period'),
														plot=False,
														plotname = 'Slope_of_Slope_RSI')									
														
				self.inds[d._name]['slope_ema1'] = 	btind.Slope(self.inds[d._name]['ema1'],
														period=indp.get('slope_period'),
														plot=False,
														plotname = 'Slope_EMA1')
				self.inds[d._name]['slope_ema2'] = 	btind.Slope(self.inds[d._name]['ema2'],
														period=indp.get('slope_period'),
														plot=False,
														plotname = 'Slope_EMA2')
				self.inds[d._name]['slope_ema3'] = 	btind.Slope(self.inds[d._name]['ema3'],
														period=indp.get('slope_period'),
														plot=False,
														plotname = 'Slope_EMA3')
				
				#Plot ADX and Slope on same subplot as stochastic							
				self.inds[d._name]['adx'].plotinfo.plotmaster = self.inds[d._name]['rsi']
Beispiel #12
0
    def __init__(self, store):
        self.buy_order = None
        self.live_data = False

        # Attach and retrieve values from the MT5 indicator "Examples/Custom Moving Average"
        self.mt5cma = getMTraderIndicator(
            # MTraderStorestore instance
            store,
            # Data feed to run the indicator calculations on
            self.datas[0],
            # Set accessor(s) for the indicator output lines
            (
                "cma", ),
            # MT5 inidicator name
            indicator="Examples/Custom Moving Average",
            # Indicator parameters.
            #   Any omitted values will use the defaults as defind by the indicator.
            #   The parameter "params" must exist. If you want to use only the indicator defaults,
            #   pass an empty list: params=[],
            params=[13, 0, "MODE_SMMA"],
        )()

        # Instantiating backtrader indicator Bollinger Bands and Moving Averages
        #   Important: This needs to come before instantiating a chart window
        #   with backtradermql5.mt5indicator.MTraderChart. Otherwise backtrader will fail.
        self.bb = btind.BollingerBands(self.datas[0])
        self.sma = btind.MovingAverageSimple(self.datas[0])

        # -----> Experimental feature BEGIN
        # The feaure to plot data to MT5 chart windows WILL plot false data at this point in time. More work is needed.
        # Plot the backtrader BollingerBand and SMA indicators to a chart window in MT5

        def addChart(chart, bb, sma):
            # Instantiate new indicator and draw to the main window. The parameter idx=0 specifies wether to plot to the
            # main window (idx=0) or a subwindow (idx=1 for the first subwindow, idx=2 for the second etc.).
            indi0 = ChartIndicator(idx=0, shortname="Bollinger Bands")

            # # Add line buffers
            indi0.addline(
                bb.top,
                style={
                    "linelabel": "Top",
                    "color": "clrBlue",
                },
            )
            indi0.addline(
                bb.mid,
                style={
                    "linelabel": "Middle",
                    "color": "clrYellow",
                },
            )
            indi0.addline(
                bb.bot,
                style={
                    "linelabel": "Bottom",
                    "color": "clrGreen",
                },
            )

            # Add the indicator to the chart and draw the line buffers.
            chart.addchartindicator(indi0)

            # # Instantiate second indicator to draw to the first sub-window and add line buffers
            indi1 = ChartIndicator(idx=1, shortname="Simple Moving Average")
            indi1.addline(
                sma.sma,
                style={
                    "linelabel": "SMA",
                    "color": "clrBlue",
                    "linestyle": "STYLE_DASH",
                    "linewidth": 2
                },
            )
            chart.addchartindicator(indi1)

        # Instantiate a new chart window and plot
        chart = MTraderChart(self.datas[0], realtime=False)
        addChart(chart, self.bb, self.sma)