Esempio n. 1
0
    def boll_strategy(df, i:int):
        if not df.__contains__('low_boll'):
            Indicators.add_indicator(df, name = "lbb", col_name = "low_boll", args = 14)

        buy_price = 0.975 * df['low_boll'][i]
        if buy_price >= df['close'][i]:
            return min(buy_price, df['high'][i])

        return False
Esempio n. 2
0
    def ma_strategy(df, i: int):
        if not df.__contains__('slow_sma'):
            Indicators.add_indicator(df, name = "sma", col_name = "slow_sma", args = 30)

        buy_price = 0.96 * df['slow_sma'][i]
        if buy_price >= df['close'][i]:
            return min(buy_price, df['high'][i])

        return False
Esempio n. 3
0
    def bollStrategy(df, i: int):
        if not df.__contains__('low_boll'):
            Indicators.addIndicator(df,
                                    indicator_name='lbb',
                                    col_name='low_boll',
                                    args=14)

        #if price 2.5% below lower bollinger, return True
        buy_price = 0.975 * df['low_boll'][i]
        if buy_price >= df['close'][i]:
            return min(buy_price, df['high'][i])

        return False
Esempio n. 4
0
    def maStrategy(df, i: int):

        if not df.__contains__('long_sma'):
            Indicators.addIndicator(df,
                                    indicator_name='sma',
                                    col_name='long_sma',
                                    args=30)

        #If price is 4% below long sma, put buy signal and return True
        buy_price = 0.96 * df['long_sma'][i]
        if buy_price >= df['close'][i]:
            return min(buy_price, df['high'][i])

        return False
Esempio n. 5
0
    def test_strategy(self, indicator, params=None, data=None):
        # DATA
        if data is None:
            stock = pd.read_csv('../Data/bitcoin_histo.csv', sep=';')
            pxlast_csv_str = stock['PX_LAST']
            pxlast = pd.to_numeric(pxlast_csv_str)
            dates_csv_str = stock['Date']
            dates = pd.to_datetime(dates_csv_str, dayfirst=True)
        else:
            # dates = pd.Series(data[0].values)
            pxlast = data  # pd.Series(data[1].values)

        # COMPUTATIONS

        if indicator == 'macd':
            ss = params[0]
            ls = params[1]
            sf = params[2]
            macd, macd_ema9 = Indicators.macd(pxlast,
                                              short_span=ss,
                                              long_span=ls,
                                              smoothing_factor=sf)
            returns = pxlast.pct_change(1)
            invested = Helpers.indicators_to_investment(indicator_name='macd',
                                                        data=(macd, macd_ema9))
        elif indicator == 'ema':
            ema_difference = Indicators.ema_diff(pxlast,
                                                 long_span=26,
                                                 short_span=12)
            returns = pxlast.pct_change(1)
            invested = Helpers.indicators_to_investment(
                indicator_name='ema_diff', data=ema_difference)
        elif indicator == 'macd_rsi':
            macd, macd_ema9 = Indicators.macd(pxlast,
                                              long_span=26,
                                              short_span=12,
                                              smoothing_factor=9)
            rsi = Indicators.RSI(pxlast, period=14)
            invested = Helpers.indicators_to_investment(
                indicator_name='macd_rsi', data=(macd, macd_ema9, rsi))

        # PROFITABILITY
        total_profit, strat_profit = self.profitability(returns, invested)

        # return strat_profit.iloc[-1].values[0]

        # PLOT
        data_plot = pd.concat([total_profit, strat_profit], axis=1)
        data_plot.plot()
        plt.show()
Esempio n. 6
0
    def ichimoku_bullish(df, i: int):
        if not df.__contains__('tenkansen') or not df.__contains__('kijunsen') or \
                not df.__contains__('senkou_a') or not df.__contains__('senkou_b'):
            Indicators.add_indicator(df, name = "ichimoku", col_name = None, args = None)

        if i - 1 > 0 and i < len(df):
            if df['senkou_a'][i] is not None and df['senkou_b'][i] is not None:
                if df['tenkansen'][i] is not None and df['tenkansen'][i - 1] is not None:
                    if df['close'][i - 1] < df['tenkansen'][i - 1] and \
                            df['close'][i] > df['tenkansen'][i] and \
                            df['close'][i] > df['senkou_a'][i] and \
                            df['close'][i] > df['senkou_b'][i]:
                                return df['close'][i]

        return False
Esempio n. 7
0
    def run(self):
        Strategy.strategy_state[self.tick.InstrumentID] = True
        daybar_list = Indicators.getDayBarList(self.tick.InstrumentID)
        if not daybar_list:
            print 'Need one bar at least in database'
            threading.Thread.__init__(self)
            Strategy.strategy_state[self.tick.InstrumentID] = False
            return

        last_daybar = daybar_list[-1]
        #open, high, low, close, volume
        last_high = last_daybar[1]
        last_low = last_daybar[2]

        b_sendorder, s_sendorder = self.getSendOrderCount()

        if self.tick.LastPrice > last_high : # close short and open long
            if s_sendorder > 0 :
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy, ApiStruct.OF_Close, s_sendorder, self.tick.UpperLimitPrice) # LastPrice
            elif b_sendorder < self.volume :
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy, ApiStruct.OF_Open, self.volume-b_sendorder, self.tick.UpperLimitPrice)

        if self.tick.LastPrice < last_low : # close long and open short
            if b_sendorder > 0:
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell, ApiStruct.OF_Close, s_sendorder, self.tick.UpperLimitPrice)  # LastPrice
            elif s_sendorder < self.volume :
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell, ApiStruct.OF_Open, self.volume-s_sendorder, self.tick.LowerLimitPrice)

        # in case restart/reuse thread since python not support
        threading.Thread.__init__(self)
        Strategy.strategy_state[self.tick.InstrumentID] = False
Esempio n. 8
0
def adding_indicators(df, indicators: list = []):
    for indicator in indicators:
        if indicator[0] not in df.columns:
            Indicators.AddIndicator(df=df,
                                    indicator_name=indicator[0],
                                    col_name=indicator[0],
                                    args=indicator[1])
Esempio n. 9
0
    def run(self):
        Strategy.strategy_state[self.tick['InstrumentID']] = True
        daybar_list = Indicators.getDayBarList(self.tick['InstrumentID'])
        if not daybar_list:
            print ('Need one bar at least in database')
            threading.Thread.__init__(self)
            Strategy.strategy_state[self.tick['InstrumentID']] = False
            return

        last_daybar = daybar_list[-1]
        #open, high, low, close, volume
        last_high = last_daybar[1]
        last_low = last_daybar[2]

        b_sendorder, s_sendorder = DatabaseController.getSendOrderCount(self.tick['InstrumentID'])

        if self.tick['LastPrice'] > last_high : # close short and open long
            if s_sendorder > 0 :
                self.PrepareOrder(self.tick['InstrumentID'], D_Buy, OF_Close, s_sendorder, self.tick['UpperLimitPrice']) # LastPrice
            elif b_sendorder < self.volume :
                self.PrepareOrder(self.tick['InstrumentID'], D_Buy, OF_Open, self.volume-b_sendorder, self.tick['UpperLimitPrice'])

        if self.tick['LastPrice'] < last_low : # close long and open short
            if b_sendorder > 0:
                self.PrepareOrder(self.tick['InstrumentID'], D_Sell, OF_Close, s_sendorder, self.tick['LowerLimitPrice'])  # LastPrice
            elif s_sendorder < self.volume :
                self.PrepareOrder(self.tick['InstrumentID'], D_Sell, OF_Open, self.volume-s_sendorder, self.tick['LowerLimitPrice'])

        # in case restart/reuse thread since python not support
        threading.Thread.__init__(self)
        Strategy.strategy_state[self.tick['InstrumentID']] = False
Esempio n. 10
0
    def run(self):
        Strategy.strategy_state[self.tick.InstrumentID] = True
        daybar_list = Indicators.getDayBarList(self.tick.InstrumentID)
        if not daybar_list:
            print 'Need one bar at least in database'
            threading.Thread.__init__(self)
            Strategy.strategy_state[self.tick.InstrumentID] = False
            return

        last_daybar = daybar_list[-1]
        #open, high, low, close, volume
        last_high, last_low, last_close = last_daybar[1:4]

        b_sendorder, s_sendorder = self.getSendOrderCount()
        holding = b_sendorder - s_sendorder
        # Bbreak > Ssetup > Senter >> Benter > Bsetup > Sbreak
        k = 0.2
        tr = last_high - last_low
        (Bbreak, Ssetup, Senter, Benter, Bsetup, Sbreak) = (last_close+3*k*tr, last_close+2*k*tr, last_close+1*k*tr, last_close-1*k*tr, last_close-2*k*tr, last_close-3*k*tr)

        if holding == 0 and self.tick.LastPrice > Bbreak :
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy, ApiStruct.OF_Open, self.volume, self.tick.UpperLimitPrice)
        if holding == 0 and self.tick.LastPrice < Sbreak:
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell, ApiStruct.OF_Open, self.volume, self.tick.UpperLimitPrice)
        if holding > 0 and self.tick.LastPrice < Senter and self.tick.HighestPrice > Ssetup:
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell, ApiStruct.OF_Close, self.volume, self.tick.UpperLimitPrice)
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell, ApiStruct.OF_Open, self.volume, self.tick.UpperLimitPrice)
        if holding < 0 and self.tick.LastPrice > Benter and self.tick.LowestPrice < Bsetup:
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy, ApiStruct.OF_Close, self.volume, self.tick.LowerLimitPrice)
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy, ApiStruct.OF_Open, self.volume, self.tick.LowerLimitPrice)

        # in case restart/reuse thread since python not support
        threading.Thread.__init__(self)
        Strategy.strategy_state[self.tick.InstrumentID] = False
Esempio n. 11
0
def maCrossoverStrategy(df, i: int):
    """ If price is 10% below the Slow MA, return True """

    if not df.__contains__('50_ema') and not df.__contains__('200_ema'):
        Indicators.AddIndicator(df,
                                indicator_name="ema",
                                col_name="50_ema",
                                args=50)
        Indicators.AddIndicator(df,
                                indicator_name="ema",
                                col_name="200_ema",
                                args=200)

    if i > 0 and df['50_ema'][i-1] <= df['200_ema'][i-1] and \
     df['50_ema'][i] > df['200_ema'][i]:
        return df['close'][i]

    return False
Esempio n. 12
0
def maCrossoverStrategy(df, i: int):
    #50 ema cross 200 ema

    if not df.__contains__("50_ema") and not df.__contains__('200_ema'):
        Indicators.addIndicator(df,
                                indicator_name='ema',
                                col_name='50_ema',
                                args=50)
        Indicators.addIndicator(df,
                                indicator_name='ema',
                                col_name='200_ema',
                                args=200)

    if i > 0 and df['50_ema'][i - 1] <= df['200_ema'][
            i - 1] and df['50_ema'][i] > df['200_ema'][i]:
        return df['close'][i]

    return False
Esempio n. 13
0
	def maStrategy(df, i:int):
		''' If price is 10% below the Slow MA, return True'''

		if not df.__contains__('slow_sma'):
			Indicators.AddIndicator(df, indicator_name="sma", col_name="slow_sma", args=30)

		buy_price = 0.96 * df['slow_sma'][i]
		if buy_price >= df['close'][i]:
			return min(buy_price, df['high'][i])

		return False
Esempio n. 14
0
	def bollStrategy(df, i:int):
		''' If price is 2.5% below the Lower Bollinger Band, return True'''

		if not df.__contains__('low_boll'):
			Indicators.AddIndicator(df, indicator_name="lbb", col_name="low_boll", args=14)

		buy_price = 0.975 * df['low_boll'][i]
		if buy_price >= df['close'][i]:
			return min(buy_price, df['high'][i])

		return False
Esempio n. 15
0
    def ichimokuBull(df, i: int):

        if not df.__contains__('tenkansen') or not df.__contains__(
                'kijunsen') or not df.__contains__(
                    'senkou_a') or not df.__contains__('senkou_b'):
            Indicators.addIndicator(df,
                                    indicator_name='ichimoku',
                                    col_name=None,
                                    args=None)

        #Check if valid
        if i - 1 > 0 and i < len(df):
            if df['senkou_a'][i] is not None and df['senkou_b'][i] is not None:
                if df['tenkansen'][i] is not None and df['tenkansen'][
                        i - 1] is not None:
                    if (df['close'][i-1] < df['tenkansen'][i-1]) and \
                        (df['close'][i] > df['tenkansen'][i]) and \
                        (df['close'][i] > df['senkou_a'][i]) and \
                        (df['close'][i] > df['senkou_b'][i]):
                        return df['close'][i]

        return False
Esempio n. 16
0
    def run(self):
        Strategy.strategy_state[self.tick.InstrumentID] = True
        daybar_list = Indicators.getDayBarList(self.tick.InstrumentID)
        if len(daybar_list) < self.slow or self.slow_MA is None:
            print 'Need %d bars at least in database' % self.slow
            threading.Thread.__init__(self)
            Strategy.strategy_state[self.tick.InstrumentID] = False
            return

        #print 'self.slow_MA = ' + str(self.slow_MA)
        atr = Indicators.getATR(self.tick.InstrumentID)
        #print 'self.atr = ' + str(atr)
        hhv = Indicators.HHV(self.tick.InstrumentID, 20)
        #print 'the hhv = %d, index = %d ' %  hhv
        llv = Indicators.LLV(self.tick.InstrumentID, 20)
        print self.tick.InstrumentID
        print 'the llv = %d, index = %d ' %  llv


        b_sendorder, s_sendorder = self.getSendOrderCount()

        #if self.fast_MA[-1] > self.slow_MA[-1] and self.fast_MA[-2] < self.slow_MA[-2]:
        if self.fast_MA[-1] > self.slow_MA[-1]:
            if s_sendorder > 0 :
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy, ApiStruct.OF_Close, s_sendorder, self.tick.UpperLimitPrice) # LastPrice
            elif b_sendorder < self.volume :
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy, ApiStruct.OF_Open, self.volume-b_sendorder, self.tick.UpperLimitPrice)

        #if self.fast_MA[-1] < self.slow_MA[-1] and self.fast_MA[-2] > self.slow_MA[-2]:
        if self.fast_MA[-1] < self.slow_MA[-1]:
            if b_sendorder > 0:
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell, ApiStruct.OF_Close, s_sendorder, self.tick.UpperLimitPrice)  # LastPrice
            elif s_sendorder < self.volume :
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell, ApiStruct.OF_Open, self.volume-s_sendorder, self.tick.LowerLimitPrice)

        # in case restart/reuse thread is not supported by python
        threading.Thread.__init__(self)
        Strategy.strategy_state[self.tick.InstrumentID] = False
Esempio n. 17
0
def ichimokuBull(df, i: int):
    #If price is about cloud formed by span A and span B, and moves above tenkansen, buy signal

    if not df.__contains__('tenkansen') or not df.__contains__(
            'kijunsen') or not df.__contains__(
                'senkou_a') or not df.__contains__('senkou_b'):
        Indicators.addIndicator(df,
                                indicator_name='ichimoku',
                                col_name=None,
                                args=None)

    #Check if valid
    if i - 1 > 0 and i < len(df):
        if df['senkou_a'][i] is not None and df['senkou_b'][i] is not None:
            if df['tenkansen'][i] is not None and df['tenkansen'][
                    i - 1] is not None:
                if (df['close'][i-1] < df['tenkansen'][i-1]) and \
                    (df['close'][i] > df['tenkansen'][i]) and \
                    (df['close'][i] > df['senkou_a'][i]) and \
                    (df['close'][i] > df['senkou_b'][i]):
                    return df['close'][i]

    return False
Esempio n. 18
0
    def run(self):
        Strategy.strategy_state[self.tick.InstrumentID] = True
        daybar_list = Indicators.getDayBarList(self.tick.InstrumentID)
        if not daybar_list:
            print 'Need one bar at least in database'
            threading.Thread.__init__(self)
            Strategy.strategy_state[self.tick.InstrumentID] = False
            return

        last_daybar = daybar_list[-1]
        #open, high, low, close, volume
        last_high, last_low, last_close = last_daybar[1:4]

        b_sendorder, s_sendorder = self.getSendOrderCount()
        holding = b_sendorder - s_sendorder
        # Bbreak > Ssetup > Senter >> Benter > Bsetup > Sbreak
        k = 0.2
        tr = last_high - last_low
        (Bbreak, Ssetup, Senter, Benter, Bsetup,
         Sbreak) = (last_close + 3 * k * tr, last_close + 2 * k * tr,
                    last_close + 1 * k * tr, last_close - 1 * k * tr,
                    last_close - 2 * k * tr, last_close - 3 * k * tr)

        if holding == 0 and self.tick.LastPrice > Bbreak:
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy,
                              ApiStruct.OF_Open, self.volume,
                              self.tick.UpperLimitPrice)
        if holding == 0 and self.tick.LastPrice < Sbreak:
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell,
                              ApiStruct.OF_Open, self.volume,
                              self.tick.UpperLimitPrice)
        if holding > 0 and self.tick.LastPrice < Senter and self.tick.HighestPrice > Ssetup:
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell,
                              ApiStruct.OF_Close, self.volume,
                              self.tick.UpperLimitPrice)
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell,
                              ApiStruct.OF_Open, self.volume,
                              self.tick.UpperLimitPrice)
        if holding < 0 and self.tick.LastPrice > Benter and self.tick.LowestPrice < Bsetup:
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy,
                              ApiStruct.OF_Close, self.volume,
                              self.tick.LowerLimitPrice)
            self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy,
                              ApiStruct.OF_Open, self.volume,
                              self.tick.LowerLimitPrice)

        # in case restart/reuse thread since python not support
        threading.Thread.__init__(self)
        Strategy.strategy_state[self.tick.InstrumentID] = False
Esempio n. 19
0
    def run(self):
        Strategy.strategy_state[self.tick.InstrumentID] = True
        daybar_list = Indicators.getDayBarList(self.tick.InstrumentID)
        if not daybar_list:
            print 'Need one bar at least in database'
            threading.Thread.__init__(self)
            Strategy.strategy_state[self.tick.InstrumentID] = False
            return

        last_daybar = daybar_list[-1]
        #open, high, low, close, volume
        last_high = last_daybar[1]
        last_low = last_daybar[2]

        b_sendorder, s_sendorder = self.getSendOrderCount()

        #print self.tick
        print self.tick.AveragePrice/10

        #b_limit = 0
        if self.tick.LastPrice > (self.tick.AveragePrice/10 + 2) and self.b_limit <3:
            self.PrepareOrder(self.tick.InstrumentID, B, P, s_sendorder, self.tick.LastPrice)  # LastPrice
            print u"buy one."
            self.b_limit += 1



        if self.tick.LastPrice > last_high : # close short and open long

            '''
            if s_sendorder > 0 :
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy, ApiStruct.OF_Close, s_sendorder, self.tick.UpperLimitPrice) # LastPrice
            elif b_sendorder < self.volume :
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy, ApiStruct.OF_Open, self.volume-b_sendorder, self.tick.UpperLimitPrice)
            '''
            if s_sendorder > 0 :
                self.PrepareOrder(self.tick.InstrumentID, B, P, s_sendorder, self.tick.LastPrice) # LastPrice
            elif b_sendorder < self.volume :
                self.PrepareOrder(self.tick.InstrumentID, B, K, self.volume-b_sendorder, self.tick.LastPrice)

        if self.tick.LastPrice < last_low : # close long and open short
            if b_sendorder > 0:
                self.PrepareOrder(self.tick.InstrumentID, S, P, s_sendorder, self.tick.LastPrice)  # LastPrice
            elif s_sendorder < self.volume :
                self.PrepareOrder(self.tick.InstrumentID, S, K, self.volume-s_sendorder, self.tick.LastPrice)

        # in case restart/reuse thread since python not support
        threading.Thread.__init__(self)
        Strategy.strategy_state[self.tick.InstrumentID] = False
Esempio n. 20
0
 def __init__(self, max_position=100, starting_cash=100000):
     self.indutil = IndUtil()
     self.epochMax = 200
     self.epochMin = 20
     self.converged = False
     self.learner = QLearner(
         num_states=self.indutil.get_state_size(),
         num_actions=3,
         alpha=0.2,
         gamma=0.9,
         rar=0.5,
         radr=0.99,
         verbose=False
     )
     self.convergedata = collections.deque(maxlen=10)
     self.numshares = max_position
     self.starting_cash = float(starting_cash)
Esempio n. 21
0
	def ichimokuBullish(df, i:int):
		''' If price is above the Cloud formed by the Senkou Span A and B, 
		and it moves above Tenkansen (from below), that is a buy signal.'''

		if not df.__contains__('tenkansen') or not df.__contains__('kijunsen') or \
			not df.__contains__('senkou_a') or not df.__contains__('senkou_b'):
			Indicators.AddIndicator(df, indicator_name="ichimoku", col_name=None, args=None)

		if i - 1 > 0 and i < len(df):
			if df['senkou_a'][i] is not None and df['senkou_b'][i] is not None:
				if df['tenkansen'][i] is not None and df['tenkansen'][i-1] is not None:
					if df['close'][i-1] < df['tenkansen'][i-1] and \
						df['close'][i] > df['tenkansen'][i] and \
						df['close'][i] > df['senkou_a'][i] and \
						df['close'][i] > df['senkou_b'][i]:
							return df['close'][i]
		
		return False
Esempio n. 22
0
class LoadData:
    path = "../data_set/UGAZ_STOCK.CSV"
    dataset = pandas.read_csv(path)
    converted_dates = list(
        map(datetime.datetime.strptime, dataset['Date'],
            len(dataset['Date']) * ['%m/%d/%Y']))
    indicators = Indicators(dataset)
    elo = indicators.get_elo('1/31/2013')
    elo_ave = elo.ewm(span=9).mean()

    def plot_data(dataset, converted_dates, elo, elo_ave):
        plt.figure(1)
        plt.plot(converted_dates[-200:], dataset['Close'][-200:])

        plt.figure(2)
        plt.plot(converted_dates[-200:], elo[-200:])
        plt.plot(converted_dates[-200:], elo_ave[-200:])
        plt.legend()

        plt.show()

    def prepare_data(dataset, elo, elo_ave):
        print(dataset.shape)
        print(len(elo))
        print(len(elo_ave))
        dataset["Elo"] = elo
        print(dataset)
        drop_data = [
            'Date', 'Open', 'High', 'Low', 'Close', 'Sma', 'Stdev',
            'Adj Close', 'backward_ewm', 'Macd', 'macd_strike'
        ]
        dataset = dataset.drop(drop_data, axis=1)
        dataset = dataset.iloc[1:]
        prediction = Prediction(dataset)
        print(dataset)
        prediction.initiate_training()

    prepare_data(dataset, elo, elo_ave)
    plot_data(dataset, converted_dates, elo, elo_ave)
Esempio n. 23
0
    def run(self):
        Strategy.strategy_state[self.tick.InstrumentID] = True
        daybar_list = Indicators.getDayBarList(self.tick.InstrumentID)
        if len(daybar_list) < self.slow or self.slow_MA is None:
            print 'Need %d bars at least in database' % self.slow
            threading.Thread.__init__(self)
            Strategy.strategy_state[self.tick.InstrumentID] = False
            return

        #print 'self.slow_MA = ' + str(self.slow_MA)
        #atr = Indicators.getATR(self.tick.InstrumentID)
        #print 'self.atr = ' + str(atr)
        #hhv = Indicators.HHV(self.tick.InstrumentID, 20)
        #print 'the hhv = %d, index = %d ' %  hhv
        #llv = Indicators.LLV(self.tick.InstrumentID, 20)
        #print 'the llv = %d, index = %d ' %  llv

        b_sendorder, s_sendorder = self.getSendOrderCount()

        #if self.fast_MA[-1] > self.slow_MA[-1] and self.fast_MA[-2] < self.slow_MA[-2]:
        if self.fast_MA[-1] > self.slow_MA[-1]:
            if s_sendorder > 0 :
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy, ApiStruct.OF_Close, s_sendorder, self.tick.UpperLimitPrice) # LastPrice
            elif b_sendorder < self.volume :
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Buy, ApiStruct.OF_Open, self.volume-b_sendorder, self.tick.UpperLimitPrice)

        #if self.fast_MA[-1] < self.slow_MA[-1] and self.fast_MA[-2] > self.slow_MA[-2]:
        if self.fast_MA[-1] < self.slow_MA[-1]:
            if b_sendorder > 0:
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell, ApiStruct.OF_Close, s_sendorder, self.tick.UpperLimitPrice)  # LastPrice
            elif s_sendorder < self.volume :
                self.PrepareOrder(self.tick.InstrumentID, ApiStruct.D_Sell, ApiStruct.OF_Open, self.volume-s_sendorder, self.tick.LowerLimitPrice)

        # in case restart/reuse thread is not supported by python
        threading.Thread.__init__(self)
        Strategy.strategy_state[self.tick.InstrumentID] = False
Esempio n. 24
0
 def __init__(self):
     self.indicatorClass=Indicators()
Esempio n. 25
0
class Operation:
    indicatorClass=None
    lastSignal=None
    lastSignalT3=None
    def __init__(self):
        self.indicatorClass=Indicators()
        
    def placeOrder(self,exchange, pair, side, amount, price):
        # if side == 'buy':
        #     order = exchange.createLimitBuyOrder(pair, amount, price)
        # elif side == 'sell':
        #     order = exchange.createLimitSellOrder(pair, amount, price)
        if side == 'buy':
            order = exchange.create_order(pair,'market' ,'buy',amount)
        elif side == 'sell':
            order = exchange.create_order(pair,'market' ,'sell',amount)   
        print(order)
        return order

    def buy(self,exchange, pair, amount,conf):
        try:
            order_book = exchange.fetchOrderBook(pair)
            price = order_book['bids'][0][0]
            order = self.placeOrder(exchange, pair, 'buy', amount, price)
            amount = float(amount) - order['filled']
            free = exchange.fetchOrder(order['id'])["price"]*exchange.fetchBalance()[conf['symbol']]['free'];
            free = free + exchange.fetchBalance()['USDT']['free']
            self.writeLogSelBuy("buy",  pair,exchange.fetchOrder(order['id'])["price"],conf,exchange,free)

            while True:
                order = exchange.fetchOrder(order['id'])
                if order['status'] == 'closed':
                    break
                amount = amount - order['filled']
                order_book = exchange.fetchOrderBook(pair)
                price = order_book['bids'][0][0]
                if price != order['price']:
                    print(f'price {price}, order {order["price"]}')
                    exchange.cancelOrder(order['id'])
                    order = self.placeOrder(exchange, pair, 'buy', amount, price)
        except Exception as e:
            print("An exception occurred"+e)
        

    def sell(self,exchange, pair, amount,conf):
        try:
            order_book = exchange.fetchOrderBook(pair)
            price = order_book['asks'][0][0]
            order = self.placeOrder(exchange, pair, 'sell', amount, price)
            amount = float(amount) - order['filled']
            free = exchange.fetchOrder(order['id'])["price"]*exchange.fetchBalance()[conf['symbol']]['free'];
            free = free + exchange.fetchBalance()['USDT']['free']
            self.writeLogSelBuy("sell",  pair,exchange.fetchOrder(order['id'])["price"],conf,exchange,free)
            # while True:
            #     order = exchange.fetchOrder(order['id'])
            #     if order['status'] == 'closed':
            #         break
            #     amount = amount - order['filled']
            #     order_book = exchange.fetchOrderBook(pair)
            #     price = order_book['asks'][0][0]
            #     if price != order['price']:
            #         exchange.cancelOrder(order['id'])
            #         order = placeOrder(exchange, pair, 'sell', amount, price)
        except Exception as e:
            print("An exception occurred"+e)


    def cross(self,long, short):
        position = short > long
        pre_position = position.shift(1)
        result = np.where(position == pre_position, False, True)
        return result

    def cross_over(self,long, short):
        position = short > long
        pre_position = position.shift(1)
        result = np.logical_and(np.where(position == pre_position, False, True), np.equal(position, False))
        return result

    def cross_under(self,long, short):
        position = short > long
        pre_position = position.shift(1)
        result = np.logical_and(np.where(position == pre_position, False, True), np.equal(position, True))
        return result

    def supertrend_signal(self,df, super_trend_column):
        position = df[super_trend_column]
        pre_position = position.shift(1)
        conditions = [
            np.logical_and(np.where(position == pre_position, False, True), np.equal(position, 'up')) == True,
            np.logical_and(np.where(position == pre_position, False, True), np.equal(position, 'down')) == True
        ]
        choices = ['buy', 'sell']
        df['Signal'] = np.select(conditions, choices, default=np.NaN)

        return df

    def tilson_t3_signal(self,df, tilson_t3_column):
        position = df[tilson_t3_column]
        t3_last = position.shift(1)
        t3_previous = position.shift(2)
        t3_prev_previous = position.shift(3)
        
        conditions = [
            np.logical_and(np.where(t3_last > t3_previous, True, False), np.where(t3_previous < t3_prev_previous, True, False)) == True,
            np.logical_and(np.where(t3_last < t3_previous, True, False), np.where(t3_last > t3_previous, True, False)) == True
        ]
        choices = ['buy', 'sell']
        df['Signal'] = np.select(conditions, choices, default=np.NaN)

        return df

    def tilson_t3_strategy(self,df, tilson_t3_column):
        df = tilson_t3_signal(df, tilson_t3_column)
        signal = df['Signal']
        close = df['Close']
        df['buy_price'] = np.select([np.equal(signal, 'buy')], [close], default=np.nan)
        df['sell_price'] = np.select([np.equal(signal, 'sell')], [close], default=np.nan)
        return callculate_strategy_gain(df['Date'], signal, close)

    def supertrend_strategy(self,df, super_trend_column):
        df = self.supertrend_signal(df, super_trend_column)
        signal = df['Signal']
        close = df['Close']
        df['buy_price'] = np.select([np.equal(signal, 'buy')], [close], default=np.nan)
        df['sell_price'] = np.select([np.equal(signal, 'sell')], [close], default=np.nan)
        return self.callculate_strategy_gain(df['Date'], signal, close)

    def callculate_strategy_gain(self,date, signal, close):
        leverage = 1
        print_log = False
        result = pd.Series(np.nan, dtype='float64')
        start_balance = 1000
        balance = start_balance
        #print("balance:" + str(balance))
        last_sell_idx = -1
        last_buy_idx = -1
        for buy_idx in np.where(signal == 'buy')[0]:
            if last_buy_idx == -1 and buy_idx > last_sell_idx:
                last_buy_idx = buy_idx
                for sell_idx in np.where(signal == 'sell')[0]:
                    if last_buy_idx != -1 and sell_idx > buy_idx:
                        delta = (close[sell_idx] - close[buy_idx]) / close[buy_idx]
                        if (delta < -0.01):  # stop loss percentage
                            # stop loss
                            balance = balance + (balance * (delta * leverage))
                            balance = balance * 0.975
                            last_buy_idx = - 1
                            if print_log:
                                print(str(date[sell_idx]) + ' Stop Loss:' + str(balance) + ' -> delta:' + str(delta))

                        if sell_idx > last_buy_idx and last_buy_idx != - 1:
                            # profit sell
                            # print('Pair buy_idx :' + str(buy_idx) + ', sell_idx: ' + str(sell_idx))
                            # print('Pair buy :' + str(df['CLOSE'][buy_idx]) + ', sell: ' + str(df['CLOSE'][sell_idx]))
                            result[sell_idx] = close[sell_idx] - close[buy_idx]
                            balance = balance + (balance * (delta * leverage))
                            balance = balance * 0.975
                            last_sell_idx = sell_idx
                            last_buy_idx = -1
                            if print_log:
                                if delta > 0.025:
                                    print(str(date[sell_idx]) + ' Profit:' + str(balance) + ' -> delta:' + str(delta))
                                else:
                                    print(str(date[sell_idx]) + ' Loss:' + str(balance) + ' -> delta:' + str(delta))

        #print("final balance:" + str(balance))
        profit = (balance) / start_balance * 100
        if  profit < 100:
            profit = profit - 100
        return profit

    def plot_chart(self,chart_name, dataFrame, main_chart_indicators = []):
        fig = make_subplots(rows=1, cols=1, shared_xaxes=True)
        
        fig.add_trace(plt.Candlestick(x     = dataFrame['Date'],
                                    open  = dataFrame['Open'], 
                                    high  = dataFrame['High'],
                                    low   = dataFrame['Low'], 
                                    close = dataFrame['Close'], name = chart_name), row=1, col=1)
        
        for indicator in main_chart_indicators:
            fig.add_trace(plt.Scatter(x=dataFrame['Date'], y=dataFrame[indicator], mode='lines', name= indicator), row=1, col=1)
        

        #fig.add_trace(plt.Scatter(x=dataFrame['Date'], y=dataFrame['MACD'], mode='lines', name='MACD'), row=3, col=1)
        #fig.add_trace(plt.Scatter(x=dataFrame['Date'], y=dataFrame['MACD_SIGNAL'], mode='lines', name='MACD_SIGNAL'), row=3, col=1)
        #fig.add_trace(plt.Bar(x = dataFrame['Date'], y= dataFrame['MACD_HIST'], name = 'MACD_HIST', marker= {'color': 'red'}), row=3, col=1)

        #fig.add_scatter(x=dataFrame['Date'], y=dataFrame['buy_price'], mode="markers", marker=dict(size=20), name="buy", row=1, col=1)
        #fig.add_scatter(x=dataFrame['Date'], y=dataFrame['sell_price'], mode="markers", marker=dict(size=20), name="sell", row=1, col=1)
        
        fig.update_layout(
            yaxis_title= chart_name
        )

        fig.show()

    def find_best_parameter(self,exchange, pair):
        for timeFrame in ['5m','15m','1h','1d']:
            for supertrend_period in range(1, 200, 1):
                for supertrend_factor in np.arange(1, 4, 1):
                    data = exchange.fetch_ohlcv(symbol = pair, timeframe = timeFrame, since=None, limit= 600)
                    header = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']
                    df = pd.DataFrame(data, columns=header)#.set_index('Timestamp')
                    df['Timestamp'] /= 1000
                    df['Date'] = [datetime.fromtimestamp(x) for x in df['Timestamp']]
                    haDf = self.indicatorClass.HA(df)
                    self.indicatorClass.SuperTrend(df, supertrend_period, round(supertrend_factor, 1));
                    supertrend_signal = 'STX_' + str(supertrend_period) + '_' + str(round(supertrend_factor, 1))
                    profit = self.supertrend_strategy(df, supertrend_signal)
                    print(timeFrame + ';' + str(supertrend_period) + ';' + str(round(supertrend_factor, 1)) + ';' + str(profit))

    def limit_buy(self,exchange, api_key, api_secret, pair, amount,conf):

        self.buy(exchange, pair, amount,conf)

    def limit_sell(self,exchange, api_key, api_secret, pair, amount,conf):

        self.sell(exchange, pair, amount,conf)

    def main(self,exchange,conf,use_heikenashi = True):

        pair = conf['symbol']+conf['scr']+conf['quote']

        balance = exchange.fetchBalance()
        free_balance = balance['USDT']['free']
        print('free_balance: ' + str(free_balance) + ' USDT')

        markets = exchange.loadMarkets()
        for market in markets:
            data = markets[market]

        data = exchange.fetch_ohlcv(symbol = pair, timeframe = conf['timeFrame'], since=None, limit=conf['periot'])
        print("data price:", data[-1][4])
        if( conf['appendSubData']):
            subData = exchange.fetch_ohlcv(symbol = pair, timeframe = conf['subTimeFrame'], since=None, limit=60);
            subDataLastIndex= [x[0] for x in subData].index(data[-1][0])
            for x in subData[subDataLastIndex+1:]: 
                data.append(x)
        
        header = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']
        df = pd.DataFrame(data, columns=header)#.set_index('Timestamp')
        df['Timestamp'] /= 1000
        df['Date'] = [datetime.fromtimestamp(x) for x in df['Timestamp']]
        df['Symbol'] = pair
        df['Exchange'] = conf['exchangeId']
        filename = '{}.csv'.format(conf['timeFrame'])
        df = self.indicatorClass.HA(df, use_heikenashi)
        

        if(conf['showGraph']):
            self.plot_chart(pair, df, [supertrend_signal_price, "T3","Signal","buy_price" ]);

        if(conf['indicator']=="t3"):
            tSignal = self.t3getSignal(df["T3"], conf,exchange)
        elif conf['indicator']=="supertred":
            tSignal = (df.tail(1))['Signal'].to_string()
        elif conf["indicator"]=="wave":
            tSignal = self.indicatorClass.wave(data)
        elif conf["indicator"]=="waveWT1":
            tSignal = self.indicatorClass.waveWT1(data)
        print(f"using {conf['indicator']}  signal")
        print("signal",tSignal)
        return tSignal
    def t3getSignal(self,df,conf,exchange):
        status = "None"
        pair = conf['symbol']+conf['scr']+conf['quote']
        if(df[df.index[-1]]>df[df.index[-2]] and df[df.index[-2]]<df[df.index[-3]] and self.lastSignalT3!='buy'):
            status = "buy"
        if(df[df.index[-1]]<df[df.index[-2]] and df[df.index[-2]]>df[df.index[-3]] and self.lastSignalT3!='sell'):
            status = "sell"
        if(status!="None" ):
            now = datetime.now()
            date = now.strftime("%m/%d/%Y, %H:%M:%S")
            with open('output/'+conf['exchangeId']+'_'+conf['symbol']+'_T3_'+str(conf['timeFrame'])+'.csv', 'a+', newline='') as file:
                fieldnames = ['coinName','type', 'price','date']
                writer = DictWriter(file, fieldnames=fieldnames)
                writer.writerow({'coinName':conf['symbol'],'type': status, 'price': exchange.fetchOrderBook(pair)['bids'][0][0],'date':date})
        return status
        
    def start(self,conf,confFile):
        exchange = getattr(ccxt, conf['exchangeId'])({
            'enableRateLimit': True, 
            'apiKey': conf['apiKey'],
            'secret': conf['apiSecret']
        })
        if(conf['subaccount']):
            exchange.headers = {
                'FTX-SUBACCOUNT': 'test',
            }
        pair = conf['symbol']+conf['scr']+conf['quote']
        while True:
            try:
                signal = self.main(exchange,conf)
                self.exchange(signal,exchange,conf,confFile,pair);
                
                if( conf['showGraph']):
                    break
                else:
                    sleep(conf['repeatSecond'])
            except Exception as e:
                print("sel buy problem"+e)    


    def exchange(self,signal,exchange,conf,confFile,pair):
        try:
            if(signal.find("buy")>-1 and self.lastSignal!='buy'):
                self.lastSignal = "buy"
                if(conf['test']==False):
                    amount = exchange.fetch_balance()["USDT"]['free']*(conf['margin']-0.5)/exchange.fetchOrderBook(pair)['asks'][0][0]
                    if(float(exchange.fetch_positions()[-1]['openSize'])>0):
                        self.buy(exchange,  pair, exchange.fetch_positions()[-1]['openSize'],conf)
                    self.buy(exchange,  pair, amount,conf)
                self.writeLog(signal, exchange,conf,confFile,pair)
            if(signal.find("sell")>-1 and self.lastSignal!='sell'):
                self.lastSignal = "sell"
                if(conf['test']==False):
                    #self.limit_sell(exchange, conf['apiKey'], conf['apiSecret'], pair, exchange.fetch_balance()['USDT']['free'],conf)
                    amount = exchange.fetch_balance()["USDT"]['free']*(conf['margin']-0.5)/exchange.fetchOrderBook(pair)['asks'][0][0]

                    if(float(exchange.fetch_positions()[-1]['openSize'])>0):
                        self.sell(exchange,  pair, exchange.fetch_positions()[-1]['openSize'],conf)
                    self.sell(exchange, pair, amount,conf)
                self.writeLog(signal, exchange,conf,confFile,pair)
        except Exception as e: 
            print("sel buy problem"+e)
        
    def writeLog(self,signal,exchange,conf,confFile,pair):
        now = datetime.now()
        date = now.strftime("%m/%d/%Y, %H:%M:%S")
        with open('output/'+conf['exchangeId']+'_'+confFile+'_'+conf['symbol']+'_sellbuycalculation_'+conf['indicator']+"_"+str(conf['timeFrame'])+'.csv', 'a+', newline='') as file:
                fieldnames = ['coinName','type', 'price','date']
                writer = DictWriter(file, fieldnames=fieldnames)
                writer.writerow({'coinName':conf['symbol'],'type': signal, 'price': exchange.fetchOrderBook(pair)['bids'][0][0],'date':date})
    def writeLogSelBuy(self,signal,pair,price,conf,exchange,free):
        now = datetime.now()
        date = now.strftime("%m/%d/%Y, %H:%M:%S")
        with open('output/market_SellBuy'+conf['exchangeId']+'_'+conf['indicator']+"_"+str(conf['timeFrame'])+'.csv', 'a+', newline='') as file:
                fieldnames = ['coinName','type', 'price','date',"free"]
                writer = DictWriter(file, fieldnames=fieldnames)
                writer.writerow({'coinName':pair,'type': signal, 'price': str(price),'date':date,'free':free})
Esempio n. 26
0
 def InitIndicator(self):
     self.fast_MA = Indicators.getMA(self.inst, self.fast)
     self.slow_MA = Indicators.getMA(self.inst, self.slow)
Esempio n. 27
0
class Agent:

    def __init__(self, max_position=100, starting_cash=100000):
        self.indutil = IndUtil()
        self.epochMax = 200
        self.epochMin = 20
        self.converged = False
        self.learner = QLearner(
            num_states=self.indutil.get_state_size(),
            num_actions=3,
            alpha=0.2,
            gamma=0.9,
            rar=0.5,
            radr=0.99,
            verbose=False
        )
        self.convergedata = collections.deque(maxlen=10)
        self.numshares = max_position
        self.starting_cash = float(starting_cash)

    """
    This will determine if the algorithm has converged (internal use only)
    It will look for less than a 5% change in the average of the last 10 port values
    """
    def has_converged(self, reward, epochs):
        self.convergedata.append(reward)
        if self.epochMin > epochs:
            return False
        elif abs(100*(np.average(self.convergedata)-reward)/reward) < 1:
            return True
        elif self.epochMax >= epochs:
            return True
        else:
            return False

    """
    This method is an internal method used by training to keep track of action effects
    """
    def take_action(self, df, symbol, index, action, cash, position, last_port_value):
        # 0 for hold, 1 for buy, 2 for sell
        price = df.loc[index][symbol]

        if action == 1 and position < self.numshares and cash >= self.numshares * price:
            position += self.numshares
            cash -= self.numshares * price
        elif action == 2 and position > 0:
            cash += position * price
            position = 0

        reward = ((cash + position*price)/last_port_value)-1
        port_value = cash + position*price
        return cash, position, reward, port_value

    """
    This will train the agents q-learner
    """
    def train(self, df, symbol):
        states = self.indutil.compute_indicators(df, symbol)
        epoch = 0
        last_epoch_value = self.starting_cash

        while not self.has_converged(last_epoch_value, epoch):
            position = 0
            cash = self.starting_cash
            last_port_value = cash

            action = self.learner.init_state(states.iloc[0].values[0])
            cash, position, reward, port_value \
                = self.take_action(df, symbol, states.index[0], action, cash, position, last_port_value)
            for index, state in states[1:].iterrows():
                action = self.learner.step(state.values[0], reward)
                last_port_value = port_value
                cash, position, reward, port_value \
                    = self.take_action(df, symbol, index, action, cash, position, last_port_value)

            price = df.iloc[-1][symbol]
            last_epoch_value = position * price + cash
            epoch += 1

    """
    This method will be called to test the learned policy.
    """
    def test(self, df, symbol):
        states = self.indutil.compute_indicators(df, symbol)
        trades = df[[symbol, ]]
        trades.values[:, :] = 0
        position = 0
        cash = self.starting_cash

        for index, state in states.iterrows():
            action = self.learner.query(state.values[0])
            price = df.loc[index][symbol]
            if action == 1 and cash >= price*self.numshares and position < self.numshares:
                trades.loc[index][symbol] = self.numshares
                position = self.numshares
                cash -= price*self.numshares
            elif action == 2 and position > 0:
                trades.loc[index][symbol] = -position
                cash += price * position
                position = 0

        return trades
Esempio n. 28
0
today = datetime.date.today()
today = '2016-09-29'
quandlKey = "vXqo1CSCZ6a7eESaKXEu"
benchmark = 'NASDAQOMX/NDX'

hostc = 'localhost'
#hostc='155.246.104.19'
portn = 27017

client = MongoClient(host=hostc, port=portn)
db = client.Project

p = PricesLoading(quandlKey, db)
#p.LoadPricesInMongo()
i = Indicators(db)
#i.CalculateIndicators()

horizon = 15

TIs = [
    'KAMA', 'MACDHIST', 'CCI', 'RSI', 'WILLIAMR', 'MFI', 'EMA', 'ROC',
    'STOCHSLOWD', 'ADX'
]

startDate = '2012-02-08'
endDate = '2015-10-28'
histWindow = 120
rebalanceFrequency = 10
rf = 0.0001
tau = 0.025
Esempio n. 29
0
class Operation:
    indicatorClass=None
    lastSignal=None
    lastSignalT3=None
    def __init__(self):
        self.indicatorClass=Indicators()
        
    def placeOrder(self,exchange, pair, side, amount, price):
        # if side == 'buy':
        #     order = exchange.createLimitBuyOrder(pair, amount, price)
        # elif side == 'sell':
        #     order = exchange.createLimitSellOrder(pair, amount, price)
        if side == 'buy':
            order = exchange.create_order(pair,'market' ,'buy',amount*100)
        elif side == 'sell':
            order = exchange.create_order(pair,'market' ,'sell',amount)   
        print(order)
        return order

    def buy(self,exchange, pair, amount):
        try:
            order_book = exchange.fetchOrderBook(pair)
            price = order_book['bids'][0][0]
            order = self.placeOrder(exchange, pair, 'buy', amount, price)
            amount = amount - order['filled']
            self.writeLogSelBuy("buy",  pair,exchange.fetchOrder(order['id'])["price"])

            while True:
                order = exchange.fetchOrder(order['id'])
                if order['status'] == 'closed':
                    break
                amount = amount - order['filled']
                order_book = exchange.fetchOrderBook(pair)
                price = order_book['bids'][0][0]
                if price != order['price']:
                    print(f'price {price}, order {order["price"]}')
                    exchange.cancelOrder(order['id'])
                    order = self.placeOrder(exchange, pair, 'buy', amount, price)
        except:
            print("An exception occurred")
        

    def sell(self,exchange, pair, amount):
        try:
            order_book = exchange.fetchOrderBook(pair)
            price = order_book['asks'][0][0]
            order = self.placeOrder(exchange, pair, 'sell', amount, price)
            amount = amount - order['filled']
            self.writeLogSelBuy("sell",  pair,exchange.fetchOrder(order['id'])["price"])
            while True:
                order = exchange.fetchOrder(order['id'])
                if order['status'] == 'closed':
                    break
                amount = amount - order['filled']
                order_book = exchange.fetchOrderBook(pair)
                price = order_book['asks'][0][0]
                if price != order['price']:
                    exchange.cancelOrder(order['id'])
                    order = placeOrder(exchange, pair, 'sell', amount, price)
        except:
            print("An exception occurred")


    def cross(self,long, short):
        position = short > long
        pre_position = position.shift(1)
        result = np.where(position == pre_position, False, True)
        return result

    def cross_over(self,long, short):
        position = short > long
        pre_position = position.shift(1)
        result = np.logical_and(np.where(position == pre_position, False, True), np.equal(position, False))
        return result

    def cross_under(self,long, short):
        position = short > long
        pre_position = position.shift(1)
        result = np.logical_and(np.where(position == pre_position, False, True), np.equal(position, True))
        return result

    def supertrend_signal(self,df, super_trend_column):
        position = df[super_trend_column]
        pre_position = position.shift(1)
        conditions = [
            np.logical_and(np.where(position == pre_position, False, True), np.equal(position, 'up')) == True,
            np.logical_and(np.where(position == pre_position, False, True), np.equal(position, 'down')) == True
        ]
        choices = ['buy', 'sell']
        df['Signal'] = np.select(conditions, choices, default=np.NaN)

        return df

    def tilson_t3_signal(self,df, tilson_t3_column):
        position = df[tilson_t3_column]
        t3_last = position.shift(1)
        t3_previous = position.shift(2)
        t3_prev_previous = position.shift(3)
        
        conditions = [
            np.logical_and(np.where(t3_last > t3_previous, True, False), np.where(t3_previous < t3_prev_previous, True, False)) == True,
            np.logical_and(np.where(t3_last < t3_previous, True, False), np.where(t3_last > t3_previous, True, False)) == True
        ]
        choices = ['buy', 'sell']
        df['Signal'] = np.select(conditions, choices, default=np.NaN)

        return df

    def tilson_t3_strategy(self,df, tilson_t3_column):
        df = tilson_t3_signal(df, tilson_t3_column)
        signal = df['Signal']
        close = df['Close']
        df['buy_price'] = np.select([np.equal(signal, 'buy')], [close], default=np.nan)
        df['sell_price'] = np.select([np.equal(signal, 'sell')], [close], default=np.nan)
        return callculate_strategy_gain(df['Date'], signal, close)

    def supertrend_strategy(self,df, super_trend_column):
        df = self.supertrend_signal(df, super_trend_column)
        signal = df['Signal']
        close = df['Close']
        df['buy_price'] = np.select([np.equal(signal, 'buy')], [close], default=np.nan)
        df['sell_price'] = np.select([np.equal(signal, 'sell')], [close], default=np.nan)
        return self.callculate_strategy_gain(df['Date'], signal, close)

    def callculate_strategy_gain(self,date, signal, close):
        leverage = 1
        print_log = False
        result = pd.Series(np.nan, dtype='float64')
        start_balance = 1000
        balance = start_balance
        #print("balance:" + str(balance))
        last_sell_idx = -1
        last_buy_idx = -1
        for buy_idx in np.where(signal == 'buy')[0]:
            if last_buy_idx == -1 and buy_idx > last_sell_idx:
                last_buy_idx = buy_idx
                for sell_idx in np.where(signal == 'sell')[0]:
                    if last_buy_idx != -1 and sell_idx > buy_idx:
                        delta = (close[sell_idx] - close[buy_idx]) / close[buy_idx]
                        if (delta < -0.01):  # stop loss percentage
                            # stop loss
                            balance = balance + (balance * (delta * leverage))
                            balance = balance * 0.975
                            last_buy_idx = - 1
                            if print_log:
                                print(str(date[sell_idx]) + ' Stop Loss:' + str(balance) + ' -> delta:' + str(delta))

                        if sell_idx > last_buy_idx and last_buy_idx != - 1:
                            # profit sell
                            # print('Pair buy_idx :' + str(buy_idx) + ', sell_idx: ' + str(sell_idx))
                            # print('Pair buy :' + str(df['CLOSE'][buy_idx]) + ', sell: ' + str(df['CLOSE'][sell_idx]))
                            result[sell_idx] = close[sell_idx] - close[buy_idx]
                            balance = balance + (balance * (delta * leverage))
                            balance = balance * 0.975
                            last_sell_idx = sell_idx
                            last_buy_idx = -1
                            if print_log:
                                if delta > 0.025:
                                    print(str(date[sell_idx]) + ' Profit:' + str(balance) + ' -> delta:' + str(delta))
                                else:
                                    print(str(date[sell_idx]) + ' Loss:' + str(balance) + ' -> delta:' + str(delta))

        #print("final balance:" + str(balance))
        profit = (balance) / start_balance * 100
        if  profit < 100:
            profit = profit - 100
        return profit

    def plot_chart(self,chart_name, dataFrame, main_chart_indicators = []):
        fig = make_subplots(rows=1, cols=1, shared_xaxes=True)
        
        fig.add_trace(plt.Candlestick(x     = dataFrame['Date'],
                                    open  = dataFrame['Open'], 
                                    high  = dataFrame['High'],
                                    low   = dataFrame['Low'], 
                                    close = dataFrame['Close'], name = chart_name), row=1, col=1)
        
        for indicator in main_chart_indicators:
            fig.add_trace(plt.Scatter(x=dataFrame['Date'], y=dataFrame[indicator], mode='lines', name= indicator), row=1, col=1)
        

        #fig.add_trace(plt.Scatter(x=dataFrame['Date'], y=dataFrame['MACD'], mode='lines', name='MACD'), row=3, col=1)
        #fig.add_trace(plt.Scatter(x=dataFrame['Date'], y=dataFrame['MACD_SIGNAL'], mode='lines', name='MACD_SIGNAL'), row=3, col=1)
        #fig.add_trace(plt.Bar(x = dataFrame['Date'], y= dataFrame['MACD_HIST'], name = 'MACD_HIST', marker= {'color': 'red'}), row=3, col=1)

        #fig.add_scatter(x=dataFrame['Date'], y=dataFrame['buy_price'], mode="markers", marker=dict(size=20), name="buy", row=1, col=1)
        #fig.add_scatter(x=dataFrame['Date'], y=dataFrame['sell_price'], mode="markers", marker=dict(size=20), name="sell", row=1, col=1)
        
        fig.update_layout(
            yaxis_title= chart_name
        )

        fig.show()

    def find_best_parameter(self,exchange, pair):
        for timeFrame in ['5m','15m','1h','1d']:
            for supertrend_period in range(1, 200, 1):
                for supertrend_factor in np.arange(1, 4, 1):
                    data = exchange.fetch_ohlcv(symbol = pair, timeframe = timeFrame, since=None, limit= 600)
                    header = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']
                    df = pd.DataFrame(data, columns=header)#.set_index('Timestamp')
                    df['Timestamp'] /= 1000
                    df['Date'] = [datetime.fromtimestamp(x) for x in df['Timestamp']]
                    haDf = self.indicatorClass.HA(df)
                    self.indicatorClass.SuperTrend(df, supertrend_period, round(supertrend_factor, 1));
                    supertrend_signal = 'STX_' + str(supertrend_period) + '_' + str(round(supertrend_factor, 1))
                    profit = self.supertrend_strategy(df, supertrend_signal)
                    print(timeFrame + ';' + str(supertrend_period) + ';' + str(round(supertrend_factor, 1)) + ';' + str(profit))

    def limit_buy(self,exchange, api_key, api_secret, pair, amount):

        self.buy(exchange, pair, amount)

    def limit_sell(self,exchange, api_key, api_secret, pair, amount):

        self.sell(exchange, pair, amount)

    def main(self,exchange_id, api_key, api_secret, pair, timeFrame, supertrend_period, supertrend_factor, exchange,limit,conf,use_heikenashi = True):

        
        #print(exchange.has)

        balance = exchange.fetchBalance()
        free_balance = balance['USDT']['free']
        print('free_balance: ' + str(free_balance) + ' USDT')
        #buy(exchange, pair, 20)
        #buy(exchange, pair, 100)
        #sell(exchange, pair, 90)

        #order = exchange.createLimitBuyOrder (pair, 0.5, 1.1)##15195897224
        #print(order)
        #print(order['id'])
        
        #order_book = exchange.fetchOrderBook(pair)
        #max_bid = order_book['bids'][0][0]
        #min_ask = order_book['asks'][0][0]
        #print(max_bid)
        #print(min_ask)
        #print(order_book)
        #exchange.cancelOrder(order['id'])
        #exchange.editOrder(id=15195897224, symbol=pair, type='limit', side='buy', amount=0.5, price=1.2)

        #print (exchange.fetchBalance())

        #if (exchange.has['fetchOrder']):
        #    print(exchange.fetchOrder (id=8539938604))
        #print(exchange.fetchOrders (pair))
        #print(exchange.fetchOpenOrders (pair))
        
        markets = exchange.loadMarkets()
        for market in markets:
            data = markets[market]
            if data['symbol'] == pair:
                print("data price:", data['info']['price'])
            #if data['symbol'].endswith(quote):
                #print( data['symbol'] + ' -> change1h  -> %' + str(float(data['info']['change1h'])*100))
                #print( data['symbol'] + ' -> change24h -> %' + str(float(data['info']['change24h'])*100))
                #print( data['symbol'] + ' -> changeBod -> %' + str(float(data['info']['changeBod'])*100))
        
        
        #self.find_best_parameter(exchange, pair)
        """
        """
        data = exchange.fetch_ohlcv(symbol = pair, timeframe = timeFrame, since=None, limit=500)
        header = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']
        df = pd.DataFrame(data, columns=header)#.set_index('Timestamp')
        df['Timestamp'] /= 1000
        df['Date'] = [datetime.fromtimestamp(x) for x in df['Timestamp']]
        df['Symbol'] = pair
        df['Exchange'] = exchange_id
        filename = '{}.csv'.format(timeFrame)
        df = self.indicatorClass.HA(df, use_heikenashi)
        
        self.indicatorClass.SuperTrend(df, supertrend_period, supertrend_factor);
        df["T3"] = self.indicatorClass.generateTillsonT3(df, param=[conf["t3-volume-factor"],conf["t3-period"]])
        #SuperTrend(df, 11, 1);
        supertrend_signal = 'STX_{0}_{1}'.format(supertrend_period, supertrend_factor)
        supertrend_signal_price = 'ST_{0}_{1}'.format(supertrend_period, supertrend_factor)
        profit = self.supertrend_strategy(df, supertrend_signal)
        print('%' + str(profit))
        df = df[(df[supertrend_signal_price] > 0)]
        df = df.tail(150)
        #print(df.tail(50).to_string())
        #df = df.drop(df.index[[0,11]], inplace=True)
        #haDf = super_trend(haDf, 1, 10)
        #print(df.tail(25))
        #print(haDf.tail(25))
        #self.plot_chart(pair, df, [supertrend_signal_price, "T3","Signal","buy_price" ]);
        if(conf["indicator"]=="t3"):
            print("using T3 signal")
            tSignal = self.t3getSignal(df["T3"], conf,exchange)
            print("signal",tSignal)
            return tSignal
        else:
            print("using SuperTrend signal")
            tSignal = (df.tail(1))['Signal'].to_string()
            print("signal",tSignal)
            return tSignal
    def t3getSignal(self,df,conf,exchange):
        status = "None"
        pair = conf['symbol']+"/"+conf['quote']
        if(df[df.index[-1]]>df[df.index[-2]] and df[df.index[-2]]<df[df.index[-3]] and self.lastSignalT3!='buy'):
            status = "buy"
        if(df[df.index[-1]]<df[df.index[-2]] and df[df.index[-2]]>df[df.index[-3]] and self.lastSignalT3!='sell'):
            status = "sell"
        if(status!="None" ):
            pair = conf['symbol']+"/"+conf['quote']
            now = datetime.now()
            date = now.strftime("%m/%d/%Y, %H:%M:%S")
            with open('output/'+conf['exchange-id']+'_'+conf['symbol']+'_T3_'+str(conf['time-frame'])+'.csv', 'a+', newline='') as file:
                    fieldnames = ['coinName','type', 'price','date']
                    writer = DictWriter(file, fieldnames=fieldnames)
                    writer.writerow({'coinName':conf['symbol'],'type': status, 'price': exchange.fetchOrderBook(pair)['bids'][0][0],'date':date})
        return status
        
    def start(self,conf,confFile):
        exchange = getattr(ccxt, conf['exchange-id'])({
            'enableRateLimit': True, 
            'apiKey': conf['api-key'],
            'secret': conf['api-secret']
        })
        if(conf["subaccount"]):
            exchange.headers = {
                'FTX-SUBACCOUNT': 'test',
            }
        pair = conf['symbol']+"/"+conf['quote']
        while True:
            signal = self.main(conf['exchange-id'], conf['api-key'], conf['api-secret'], pair, conf['time-frame'], conf['supertrend-period'], conf['supertrend-factor'], exchange,conf['periot'],conf)
            self.exchange(signal,exchange,conf,confFile,pair);
            
           
            sleep(conf['repeat-second'])


    def exchange(self,signal,exchange,conf,confFile,pair):
        try:
            if(signal.find("buy")>-1 and self.lastSignal!='buy'):
                self.lastSignal = "buy"
                if(conf["test"]==False):
                    self.limit_buy(exchange, conf['api-key'], conf['api-secret'], pair, exchange.fetch_balance()[conf['quote']]['free'])
                self.writeLog(signal, exchange,conf,confFile,pair)
            if(signal.find("sell")>-1 and self.lastSignal!='sell'):
                self.lastSignal = "sell"
                if(conf["test"]==False):
                    self.limit_sell(exchange, conf['api-key'], conf['api-secret'], pair, exchange.fetch_balance()[conf['symbol']]['free'])
                self.writeLog(signal, exchange,conf,confFile,pair)
        except:
            print("sel buy problem")
        
    def writeLog(self,signal,exchange,conf,confFile,pair):
        now = datetime.now()
        date = now.strftime("%m/%d/%Y, %H:%M:%S")
        with open('output/'+conf['exchange-id']+'_'+confFile+'_'+conf['symbol']+'_sellbuycalculation_'+conf["indicator"]+"_"+str(conf['time-frame'])+'.csv', 'a+', newline='') as file:
                fieldnames = ['coinName','type', 'price','date']
                writer = DictWriter(file, fieldnames=fieldnames)
                writer.writerow({'coinName':conf['symbol'],'type': signal[len(signal)-4:len(signal)], 'price': exchange.fetchOrderBook(pair)['bids'][0][0],'date':date})
    def writeLogSelBuy(self,signal,pair,price):
        now = datetime.now()
        date = now.strftime("%m/%d/%Y, %H:%M:%S")
        with open('output/SellBuy.csv', 'a+', newline='') as file:
                fieldnames = ['coinName','type', 'price','date']
                writer = DictWriter(file, fieldnames=fieldnames)
                writer.writerow({'coinName':pair,'type': signal, 'price': str(price),'date':date})
Esempio n. 30
0
 def InitIndicator(self):
     self.fast_MA = Indicators.getMA(self.inst, self.fast)
     self.slow_MA = Indicators.getMA(self.inst, self.slow)