Ejemplo n.º 1
0
def atr_exits(df, dn_mul=1, up_mul=2, buy_trigger='buy'):
    '''
    
    '''
    df['atr'] = pta.atr(df.high, df.low, df.close)
    df['atr_up'] = df['close'] + (df['atr'] * up_mul)
    df['atr_dn'] = df['close'] - (df['atr'] * up_mul)

    #BUY COLUMN TRIGGERS NEW TARGET AND STOPS TO BE CREATED
    #create placeholders
    df['atr_targ'] = df['atr_up']
    df['atr_stop'] = df['atr_dn']
    #identify
    for i in range(1, len(df)):
        if df[buy_trigger][i] > 0:
            df['atr_targ'][i] = df.atr_up[i]
            df['atr_stop'][i] = df.atr_dn[i]
        else:
            df['atr_targ'][i] = df.atr_targ[i - 1]
            df['atr_stop'][i] = df.atr_stop[i - 1]

    #

    #create exit triggers
    df['stop_hit'] = (df['close'].shift() > df.atr_stop) & (df['close'] <
                                                            df.atr_stop)
    df['targ_hit'] = (df['close'].shift() < df.atr_targ) & (df['close'] >
                                                            df.atr_targ)
    df['atr_sell'] = (df['stop_hit'] == True) | (df['targ_hit'] == True)
    return df
Ejemplo n.º 2
0
 def getSl(candle, candles):
     atr60 = ta.atr(candles["high"],
                    candles["low"],
                    candles["close"],
                    length=60,
                    mamode="ema").iloc[-1]
     return candle['low'] - atr60
Ejemplo n.º 3
0
def super_trend(df, factor=3):
    '''
    takes a dataframe and 
    returns : 
        dataframe with:
            vma         - variable moving avg
            super_upper - ( band)
            super_lower - ( band)
            bullish_supertrend - bool
            super_bull_scale   - bullish_supertrend scaled to
                                 lower_band

    '''

    import pandas_ta as pta

    df['ATR'] = pta.atr(df.high, df.low, df.close)

    # create the vma
    df['vma'] = VMA(df.close, indicator_precision=2)

    # ADD THE BANDS

    df['super_lower'] = df['vma'] - (df['ATR'] * factor)
    df['super_upper'] = df['vma'] + (df['ATR'] * factor)
    df[['bullish_supertrend', 'ATR', 'super_bull_scale']] = ST(df)
    return df  #df[['vma','super_lower','super_upper','bullish_supertrend','super_bull']]
Ejemplo n.º 4
0
 def get_indicators(self, instrument):
     bars = self.ib.reqHistoricalData(contract=instrument,
                                      endDateTime='',
                                      durationStr='6 M',
                                      barSizeSetting='1 day',
                                      whatToShow='MIDPOINT',
                                      useRTH=True)
     df = pd.DataFrame(bars)
     del df['volume']
     del df['barCount']
     del df['average']
     atr = pd.DataFrame(ta.atr(high=df['high'],
                        low=df['low'],
                        close=df['close'],
                        length=20))
     long_donchian = pd.DataFrame(ta.donchian(high=df['high'],
                                              low=df['low'],
                                              upper_length=70,
                                              lower_length=70))
     short_donchian = pd.DataFrame(ta.donchian(high=df['high'],
                                               low=df['low'],
                                               upper_length=8,
                                               lower_length=8))
     df = pd.concat([df, atr, long_donchian, short_donchian],
                    axis=1,
                    join="outer")
     df.columns.values[5] = 'atr'
     df.columns.values[6] = 'long_dcl'
     df.columns.values[7] = 'long_dcm'
     df.columns.values[8] = 'long_dcu'
     df.columns.values[9] = 'short_dcl'
     df.columns.values[10] = 'short_dcm'
     df.columns.values[11] = 'short_dcu'
     # self.log(df.tail())
     return df
Ejemplo n.º 5
0
def ST(
    df,
    f=3,
    n=7
):  #df is the dataframe, n is the period, f is the factor; f=3, n=7 are commonly used.
    #Calculation of SuperTrend
    '''
    makes a strawberrie supertrend on your dataframe
    df= dataframe
    n = periods
    f = factor
    
    '''
    import pandas_ta as pta

    df['ATR'] = pta.atr(df.high, df.low, df.close)
    df['Upper Basic'] = (df['high'] + df['low']) / 2 + (f * df['ATR'])
    df['lower Basic'] = (df['high'] + df['low']) / 2 - (f * df['ATR'])
    df['Upper Band'] = df['Upper Basic']
    df['lower Band'] = df['lower Basic']
    for i in range(n, len(df)):
        if df['close'][i - 1] <= df['Upper Band'][i - 1]:
            df['Upper Band'][i] = min(df['Upper Basic'][i],
                                      df['Upper Band'][i - 1])
        else:
            df['Upper Band'][i] = df['Upper Basic'][i]
    for i in range(n, len(df)):
        if df['close'][i - 1] >= df['lower Band'][i - 1]:
            df['lower Band'][i] = max(df['lower Basic'][i],
                                      df['lower Band'][i - 1])
        else:
            df['lower Band'][i] = df['lower Basic'][i]
    df['SuperTrend'] = np.nan
    for i in df['SuperTrend']:
        if df['close'][n - 1] <= df['Upper Band'][n - 1]:
            df['SuperTrend'][n - 1] = df['Upper Band'][n - 1]
        elif df['close'][n - 1] > df['Upper Band'][i]:
            df['SuperTrend'][n - 1] = df['lower Band'][n - 1]
    for i in range(n, len(df)):
        if df['SuperTrend'][i - 1] == df['Upper Band'][
                i - 1] and df['close'][i] <= df['Upper Band'][i]:
            df['SuperTrend'][i] = df['Upper Band'][i]
        elif df['SuperTrend'][i - 1] == df['Upper Band'][
                i - 1] and df['close'][i] >= df['Upper Band'][i]:
            df['SuperTrend'][i] = df['lower Band'][i]
        elif df['SuperTrend'][i - 1] == df['lower Band'][
                i - 1] and df['close'][i] >= df['lower Band'][i]:
            df['SuperTrend'][i] = df['lower Band'][i]
        elif df['SuperTrend'][i - 1] == df['lower Band'][
                i - 1] and df['close'][i] <= df['lower Band'][i]:
            df['SuperTrend'][i] = df['Upper Band'][i]
    df['bullish_supertrend'] = df['SuperTrend'] < df['close']

    # scale the bool to lower band

    df['super_bull'] = df['bullish_supertrend'].replace(True, 1).replace(
        1, df.super_lower)
    return df[['bullish_supertrend', 'ATR', 'super_bull']]
Ejemplo n.º 6
0
 def getDayAtr(self, period):
   day_candles = self.trader.getPriceHistory(epic=self.symbol, resolution='DAY', max=period)
   atr_dict = map(lambda c: {
     'high':  c['highPrice']['ask'],
     'low': c['lowPrice']['bid'],
     'close': c['closePrice']['bid']
   }, day_candles)
   atr_df = pd.DataFrame(atr_dict)
   return ta.atr(atr_df['high'], atr_df['low'], atr_df['close'], length=period, mamode="ema").iloc[-1]
Ejemplo n.º 7
0
    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        self.cancel_all()

        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        high = pd.Series(am.high_array)
        low = pd.Series(am.low_array)
        close = pd.Series(am.close_array)

        atr_array = ta.atr(
            high, low, close,
            self.atr_length)  #am.atr(self.atr_length, array=True)
        self.atr_value = atr_array.iloc[-1]
        self.atr_ma = atr_array.iloc[-self.atr_ma_length:].mean()
        self.rsi_value = ta.rsi(close, self.rsi_length).iloc[-1]

        if self.pos == 0:
            self.intra_trade_high = bar.high_price
            self.intra_trade_low = bar.low_price

            if self.atr_value > self.atr_ma:
                if self.rsi_value > self.rsi_buy:
                    self.buy(bar.close_price + 5, self.fixed_size)
                elif self.rsi_value < self.rsi_sell:
                    self.short(bar.close_price - 5, self.fixed_size)

        elif self.pos > 0:
            self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
            self.intra_trade_low = bar.low_price

            long_stop = self.intra_trade_high * \
                (1 - self.trailing_percent / 100)
            self.sell(long_stop, abs(self.pos), stop=True)

        elif self.pos < 0:
            self.intra_trade_low = min(self.intra_trade_low, bar.low_price)
            self.intra_trade_high = bar.high_price

            short_stop = self.intra_trade_low * \
                (1 + self.trailing_percent / 100)
            self.cover(short_stop, abs(self.pos), stop=True)

        self.put_event()
Ejemplo n.º 8
0
    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        self.cancel_all()

        self.am.update_bar(bar)
        if not self.am.inited:
            return

        high = pd.Series(self.am.high_array)
        low = pd.Series(self.am.low_array)
        close = pd.Series(self.am.close_array)

        if not self.pos:
            self.entry_up, self.entry_down = high.rolling(
                self.entry_window).max().iloc[-1], low.rolling(
                    self.entry_window).min().iloc[-1]

        self.exit_up, self.exit_down = high.rolling(self.exit_window).max().iloc[-1], \
                                       low.rolling(self.entry_window).min().iloc[-1]

        if not self.pos:

            self.atr_value = ta.atr(
                high, low, close,
                self.atr_window).iloc[-1]  # self.am.atr(self.atr_window)

            self.long_entry = 0
            self.short_entry = 0
            self.long_stop = 0
            self.short_stop = 0

            self.send_buy_orders(self.entry_up)
            self.send_short_orders(self.entry_down)
        elif self.pos > 0:
            self.send_buy_orders(self.entry_up)

            sell_price = max(self.long_stop, self.exit_down)
            self.sell(sell_price, abs(self.pos), True)

        elif self.pos < 0:
            self.send_short_orders(self.entry_down)

            cover_price = min(self.short_stop, self.exit_up)
            self.cover(cover_price, abs(self.pos), True)

        self.put_event()
Ejemplo n.º 9
0
    def on_15min_bar(self, bar: BarData):
        """"""
        self.cancel_all()

        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        close = pd.Series(am.close_array)
        high = pd.Series(am.high_array)
        low = pd.Series(am.low_array)

        standard_deviation = ta.stdev(close=close, length=self.boll_window)
        deviations = self.boll_dev * standard_deviation

        mid = ta.sma(close=close, length=self.boll_window)

        self.boll_up, self.boll_down = (mid + deviations).iloc[-1],  (mid - deviations).iloc[-1]
        self.cci_value = ta.cci(high, low, close, self.cci_window).iloc[-1]
        self.atr_value = ta.atr(high, low, close, self.atr_window).iloc[-1]

        if self.pos == 0:
            self.intra_trade_high = bar.high_price
            self.intra_trade_low = bar.low_price

            if self.cci_value > 0:
                self.buy(self.boll_up, self.fixed_size, True)
            elif self.cci_value < 0:
                self.short(self.boll_down, self.fixed_size, True)

        elif self.pos > 0:
            self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
            self.intra_trade_low = bar.low_price

            self.long_stop = self.intra_trade_high - self.atr_value * self.sl_multiplier
            self.sell(self.long_stop, abs(self.pos), True)

        elif self.pos < 0:
            self.intra_trade_high = bar.high_price
            self.intra_trade_low = min(self.intra_trade_low, bar.low_price)

            self.short_stop = self.intra_trade_low + self.atr_value * self.sl_multiplier
            self.cover(self.short_stop, abs(self.pos), True)

        self.put_event()
Ejemplo n.º 10
0
def main(ticker_name, date_from, param_atr, param_cci_length=28):
    init_activity_log(ticker_name)

    df = new_prepare_data_today(ticker_name)[date_from:]
    df_atr = ta.atr(df['high'], df['low'], df['close'], length=14)
    df_atr.name = 'atr'
    df = df.join(df_atr)
    df_cci = ta.cci(df['high'],
                    df['low'],
                    df['close'],
                    length=param_cci_length)
    df_cci.name = 'cci'
    df = df.join(df_cci)
    print(df.tail(10))
    trade_init()

    indexmax = len(df)
    for i in range(0, indexmax):
        close = df.iloc[i]['close']
        high = df.iloc[i]['high']
        low = df.iloc[i]['low']
        env_datetime = df.iloc[i]['datetime']
        atr = df.iloc[i]['atr']
        cci = df.iloc[i]['cci']
        prev_cci = df.iloc[i - 1]['cci']

        prev_close = df.iloc[i - 1]['close']
        is_trade_closed = False

        actual_atr = atr * param_atr

        update_trade(ticker_name, close, high, low, env_datetime, actual_atr,
                     prev_close)
        #print(str(prev_cci))
        #print(str(cci))
        if prev_cci < 0 and cci >= 0:
            if trade_type != '':
                close_trade(ticker_name, close, env_datetime)
                is_trade_closed = True

            new_env_datetime = env_datetime
            if is_trade_closed == True:
                new_env_datetime = datetime.strptime(
                    env_datetime,
                    '%Y-%m-%dT%H:%M:%S.%f000Z') + timedelta(minutes=1)
                new_env_datetime = datetime.strftime(
                    new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')
            open_trade(ticker_name, 'long', close, new_env_datetime,
                       actual_atr)
        if prev_cci >= 0 and cci < 0:
            if trade_type != '':
                close_trade(ticker_name, close, env_datetime)
                is_trade_closed = True

            new_env_datetime = env_datetime
            if is_trade_closed == True:
                new_env_datetime = datetime.strptime(
                    env_datetime,
                    '%Y-%m-%dT%H:%M:%S.%f000Z') + timedelta(minutes=1)
                new_env_datetime = datetime.strftime(
                    new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')
            open_trade(ticker_name, 'short', close, new_env_datetime,
                       actual_atr)

    print('---')
    print('from ' + date_from + ' to ' +
          datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'))
    print('trades sum result: ' + str(trade_sum))
    print('trades count: ' + str(trade_count))

    persist_activity_log(ticker_name)
    """
Ejemplo n.º 11
0
def atr_back_test(m,
                  df,
                  to_plot=False,
                  up_multiple=2,
                  dn_multiple=2,
                  plot_trac=False):
    '''
    this function does the backtest things
    m is for model
    '''
    df['atr'] = pta.atr(df.High, df.Low, df.Close)
    bdf = df[[m, 'atr', 'High', 'Low', 'Close']].dropna(axis=0)
    #sns.heatmap(bdf.isnull())

    bdf['atr_up'] = (bdf['Close'] + bdf['atr'] * up_multiple)
    bdf['atr_down'] = (bdf['Close'] - bdf['atr'] * dn_multiple)

    ##### later create a function that makes variations of ups and downs

    #### to_be an ATR -LOOP

    # STRAT FUNCTION
    ### starts here...
    '''llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll'''
    '''inputs'''
    buy = m  #'Tree165473'
    t_up = 'atr_up'
    t_dn = 'atr_down'
    #SO this needs to go into a function and will be part of the backtest loop for each model
    # atr_targs and stop will be inputs so i can iterate through
    #if bdf.index.name == 'date':
    #    bdf = bdf.reset_index()

    bdf['trac'] = False
    bdf['targ'] = bdf[t_up]
    bdf['stop'] = bdf[t_dn]

    for i in range(1, len(bdf)):
        if (bdf[buy][i] == True) & (bdf['trac'][i - 1] == False):
            bdf['trac'][i] = True
            bdf['targ'][i] = bdf[t_up][i]
            bdf['stop'][i] = bdf[t_dn][i]
        elif (bdf['trac'][i - 1] == True) & (
            (bdf['Low'][i] < bdf['stop'][i - 1]) |
            (bdf['High'][i] > bdf['targ'][i - 1])):
            bdf['trac'][i] = False
        else:
            bdf['trac'][i] = bdf['trac'][i - 1]
            bdf['targ'][i] = bdf['targ'][i - 1]
            bdf['stop'][i] = bdf['stop'][i - 1]
    #hl(bdf)

    #print(s)
    #tit = (s + '_'+m)

    if to_plot == True:
        #sola(bdf[['stop','Close','targ']])#,title=tit)
        bdf[['stop', 'Close', 'targ']].iplot(theme='solar', fill=True)

    ## todo- replace 'strat' with a varable

    bdf['strat'] = 0
    for i in range(1, len(bdf)):
        if (bdf['trac'][i - 1] == False) & (bdf['trac'][i] == True):
            bdf['strat'][i] = 1
        elif (bdf['trac'][i - 1] == True) & (bdf['trac'][i] == False):
            bdf['strat'][i] = -1

    #hl(bdf)

    #bdf  =bdf.set_index('date')#.drop(['level_0','index'],axis=1)
    bdf

    #%matplotlib
    results, history = backtest('ternary',
                                bdf,
                                custom_column='strat',
                                init_cash=1000,
                                plot=plot_trac,
                                verbose=False,
                                return_history=True)
    #results['model'] = buy
    #results['target']= target
    #results['sheet'] = s
    results['strat_type'] = 'atr_smacks'
    results['up_multiple'] = up_multiple
    results['dn_multiple'] = dn_multiple
    #results = results.set_index('custom_column')
    #results['buy'] = buy
    #se

    if plot_trac:
        bdf['trac'] = bdf['trac'].replace(True, 1).replace(1, bdf.Close)
        bdf[['Close', 'High', 'trac']].iplot(theme='solar', fill=True)

    return results
Ejemplo n.º 12
0
def back_test_things(m, to_plot=False, up_multiple=2, dn_multiple=2):
    '''
    this function does the backtest things
    m is for model
    '''
    df['atr'] = pta.atr(df.High, df.Low, df.Close)
    bdf = df[[m, 'atr', 'High', 'Low', 'Close']].dropna(axis=0)
    #sns.heatmap(bdf.isnull())

    bdf['atr_up'] = (bdf['Close'] + bdf['atr'] * up_multiple)
    bdf['atr_down'] = (bdf['Close'] - bdf['atr'] * dn_multiple)

    ##### later create a function that makes variations of ups and downs

    #### to_be an ATR -LOOP

    # STRAT FUNCTION
    ### starts here...
    '''llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll'''
    '''inputs'''
    buy = m  #'Tree165473'
    t_up = 'atr_up'
    t_dn = 'atr_down'
    #SO this needs to go into a function and will be part of the backtest loop for each model
    # atr_targs and stop will be inputs so i can iterate through
    if bdf.index.name == 'date':
        bdf = bdf.reset_index()

    bdf['trac'] = False
    bdf['targ'] = bdf[t_up]
    bdf['stop'] = bdf[t_dn]

    for i in range(1, len(bdf)):
        if (bdf[buy][i] == True) & (bdf['trac'][i - 1] == False):
            bdf['trac'][i] = True
            bdf['targ'][i] = bdf[t_up][i]
            bdf['stop'][i] = bdf[t_dn][i]
        elif (bdf['trac'][i - 1] == True) & (
            (bdf['Low'][i] < bdf['stop'][i - 1]) |
            (bdf['High'][i] > bdf['targ'][i - 1])):
            bdf['trac'][i] = False
        else:
            bdf['trac'][i] = bdf['trac'][i - 1]
            bdf['targ'][i] = bdf['targ'][i - 1]
            bdf['stop'][i] = bdf['stop'][i - 1]
    #hl(bdf)

    print(s)
    tit = (s + '_' + m)

    #if to_plot==True:
    #sola(bdf[['stop','Close','targ']],title=tit)

    ## todo- replace 'strat' with a varable

    bdf['strat'] = 0
    for i in range(1, len(bdf)):
        if (bdf['trac'][i - 1] == False) & (bdf['trac'][i] == True):
            bdf['strat'][i] = 1
        elif (bdf['trac'][i - 1] == True) & (bdf['trac'][i] == False):
            bdf['strat'][i] = -1

    #hl(bdf)

    bdf = bdf.set_index('date')  #.drop(['level_0','index'],axis=1)
    bdf

    #%matplotlib
    results, history = backtest('ternary',
                                bdf,
                                custom_column='strat',
                                init_cash=1000,
                                plot=to_plot,
                                verbose=False,
                                return_history=True)
    results['model'] = buy
    results['target'] = target
    results['sheet'] = s
    results['up_multiple'] = up_multiple
    results['dn_multiple'] = dn_multiple
    #results = results.set_index('custom_column')
    #results['buy'] = buy
    #se
    results.T

    ### so now i need to rename the thing after the strat and atr paramaters

    ####

    #####  this is ready to become a save_function... but

    btpath = 'backtest_data/'
    if not os.path.exists(btpath):
        os.mkdir(btpath)
    fname = 'results.csv'
    if not os.path.exists(btpath + fname):
        print('dosnt exitst')
        rdf = results
        rdf.to_csv(btpath + fname)
        print('results.csv created')
    else:
        rdf = pd.read_csv(btpath + fname).drop('Unnamed: 0', axis=1)
        print('already exists')
        rdf = rdf.append(results)
        print('apending')
        rdf.to_csv(btpath + fname)
        print('results.csv UPDATED!')
Ejemplo n.º 13
0
    def on_candle(self, symbol, candles, db):
        candle = candles.iloc[-1]
        prevCandle = candles.iloc[-2]
        hours = int(datetime.strftime(candle.date, '%H'))
        mins = int(datetime.strftime(candle.date, '%M'))
        donchian_low = ta.donchian(candles["high"], candles["low"], 20,
                                   20).iloc[-1]["DCL_20_20"]
        self.plotter.addPtToLine(symbol, 'Donchian Low', candle.date,
                                 donchian_low)
        self.checkOrders(candle, candles)
        if self.state == 'BEFORE_RANGE':
            if hours > 22:
                self.state = 'RANGE_CALC'
                self.rangeMax = candle.high
                self.rangeMin = candle.low
                self.overnightDateStart = candle.date
        if self.state == 'RANGE_CALC':
            if candle.low < self.rangeMin:
                self.rangeMin = candle.low
            elif candle.high > self.rangeMax:
                self.rangeMax = candle.high
            if hours == 7 and mins == 55:
                self.trader.closeAllPositions(candle)
                self.isPosOpen = False
            if hours == 8 and mins == 0:
                self.tradedToday = False
                self.state = 'TRADING_OPEN'
                atr_period = 14
                table_name = f'ib_{symbol}_1D'
                dayCandles = db.getLastCandles(table_name,
                                               candle.date.to_pydatetime(),
                                               atr_period)
                #myAtr = self.atr(candles["high"], candles["low"], candles["close"], 4032).iloc[-1]
                self.dayAtr = ta.atr(dayCandles["high"],
                                     dayCandles["low"],
                                     dayCandles["close"],
                                     length=atr_period,
                                     mamode="ema").iloc[-1]
                #avg = AverageTrueRange(high=candles["high"], low=candles["low"], close=candles["close"], window=288)
                #print('Trading Open:', candle.date, 'ATR:', avg.average_true_range().iloc[-1], dayAtr, myAtr)
                print('Trading Open:', candle.date, 'Total R:',
                      self.trader.total_r)
                rect_name = f'Overnight Range {datetime.strftime(candle.date, "%Y-%m-%d")}'
                self.plotter.createLine(symbol, rect_name, 'grey')
                self.plotter.addPtToLine(symbol, rect_name,
                                         self.overnightDateStart,
                                         self.rangeMin)
                self.plotter.addPtToLine(symbol, rect_name,
                                         self.overnightDateStart,
                                         self.rangeMax)
                self.plotter.addPtToLine(symbol, rect_name, candle.date,
                                         self.rangeMax)
                self.plotter.addPtToLine(symbol, rect_name, candle.date,
                                         self.rangeMin)
                self.plotter.addPtToLine(symbol, rect_name,
                                         self.overnightDateStart,
                                         self.rangeMin)

                #print('\nReady to trade. Max:', self.rangeMax, 'Min:', self.rangeMin, candle.date)
        if self.state == 'TRADING_OPEN':
            #print('prevCandle.close:', prevCandle.close, self.rangeMax, 'Is greater than max:', prevCandle.close > self.rangeMax)
            if prevCandle.close > self.rangeMax and not self.tradedToday and not self.isPosOpen:
                #slLength = (self.rangeMax - self.rangeMin) / 2
                # rAbsolute = slLength + candle.open - self.rangeMax
                #sl = candle.open - slLength # Place sl at half the range height
                sl = donchian_low

                self.slLength = candle.open - sl
                #print('don:', don)
                tp = candle.open + (self.tpR * self.slLength)
                actual_range = (self.slLength + candle.open - self.rangeMin)
                valid_session = self.dayAtr > actual_range
                # print('    Valid:', valid_session)
                if valid_session:
                    self.trader.placeMktBracketOrder(symbol, 'BUY',
                                                     self.amtPerTrade,
                                                     candle.open, tp, sl,
                                                     candle.date)
                    #print('Trade placed.', candle.open, candle.date)
                    self.isPosOpen = True
                self.tradedToday = True
            if prevCandle.close < self.rangeMin and not self.tradedToday and not self.isPosOpen:
                self.tradedToday = True
            if hours == 21 and mins == 0:
                self.state = 'BEFORE_RANGE'
Ejemplo n.º 14
0
def main(ticker_name, date_from, param_atr, param_st_near_length=10, param_st_near_m = 3, param_st_far_length = 24, param_st_far_m = 6, granularity='H1'):
    init_activity_log(ticker_name, granularity)
    df = new_prepare_data_today(ticker_name, granularity)
    df_near = ta.supertrend(df['high'], df['low'], df['close'], length=param_st_near_length, multiplier=param_st_near_m)
    df_near.columns = ['SUPERT_near',  'SUPERTd_near',  'SUPERTl_near',  'SUPERTs_near']
    df = df.join(df_near)

    df_far = ta.supertrend(df['high'], df['low'], df['close'], length=param_st_far_length, multiplier=param_st_far_m)
    df_far.columns = ['SUPERT_far',  'SUPERTd_far',  'SUPERTl_far',  'SUPERTs_far']
    df = df.join(df_far)

    df_atr = ta.atr(df['high'], df['low'], df['close'], length=14)
    df_atr.name = 'atr'

    df = df.join(df_atr)
    print(df.tail(10))

    df = df[date_from:]
    trade_init()

    indexmax = len(df)
    for i in range (0, indexmax):
        close = df.iloc[i]['close']
        high = df.iloc[i]['high']
        low = df.iloc[i]['low']

        env_datetime = df.iloc[i]['datetime']
        #SUPERT_near = df.iloc[i]['SUPERT_near'] 
        SUPERTd_near = df.iloc[i]['SUPERTd_near']
        #SUPERTl_near = df.iloc[i]['SUPERTl_near']
        #SUPERTs_near = df.iloc[i]['SUPERTs_near']
        #SUPERT_far = df.iloc[i]['SUPERT_far']
        SUPERTd_far = df.iloc[i]['SUPERTd_far']
        #SUPERTl_far = df.iloc[i]['SUPERTl_far']
        #SUPERTs_far = df.iloc[i]['SUPERTs_far']
        atr = df.iloc[i]['atr']
        
        prev_close = df.iloc[i-1]['close']
        is_trade_closed = False


        actual_atr = atr * param_atr

        update_trade(ticker_name, close, high, low, env_datetime, actual_atr, prev_close)

        prev_SUPERTd_near = df.iloc[i-1]['SUPERTd_near']
        if prev_SUPERTd_near != SUPERTd_near:
            #near changed
            if SUPERTd_near == 1:
                if SUPERTd_far == 1:
                    if trade_type != '' and trade_type == 'short':
                        new_env_datetime = datetime.strptime(env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')+ timedelta(minutes=1)
                        new_env_datetime = datetime.strftime(new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')
                        close_trade(ticker_name, close, new_env_datetime)
                        is_trade_closed = True
                        
                    new_env_datetime = env_datetime
                    if is_trade_closed == True:
                        new_env_datetime = datetime.strptime(env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')+ timedelta(minutes=2)
                        new_env_datetime = datetime.strftime(new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')
                    if trade_type == '':
                        open_trade(ticker_name, 'long', close, new_env_datetime, actual_atr)
                    

            if SUPERTd_near == -1:
                if SUPERTd_far == -1:
                    if trade_type != ''  and trade_type == 'long':
                        new_env_datetime = datetime.strptime(env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')+ timedelta(minutes=1)
                        new_env_datetime = datetime.strftime(new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')
                        close_trade(ticker_name, close, new_env_datetime)
                        is_trade_closed = True

                    new_env_datetime = env_datetime
                    if is_trade_closed == True:
                        new_env_datetime = datetime.strptime(env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')+ timedelta(minutes=2)
                        new_env_datetime = datetime.strftime(new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')
                    if trade_type == '':
                        open_trade(ticker_name, 'short', close, new_env_datetime, actual_atr)

        if is_trade_closed == False:
            prev_SUPERTd_far = df.iloc[i-1]['SUPERTd_far']
            if prev_SUPERTd_far != SUPERTd_far:
                #far changed
                if SUPERTd_far == 1:
                    if SUPERTd_near == 1:
                        if trade_type != '':
                            new_env_datetime = datetime.strptime(env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')+ timedelta(minutes=1)
                            new_env_datetime = datetime.strftime(new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')
                            close_trade(ticker_name, close, new_env_datetime)
                            is_trade_closed = True
                        new_env_datetime = env_datetime
                        if is_trade_closed == True:
                            new_env_datetime = datetime.strptime(env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')+ timedelta(minutes=2)
                            new_env_datetime = datetime.strftime(new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')
                        open_trade(ticker_name, 'long', close, new_env_datetime, actual_atr)


                if SUPERTd_far == -1:
                    if SUPERTd_near == -1:
                        if trade_type != '':
                            new_env_datetime = datetime.strptime(env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')+ timedelta(minutes=1)
                            new_env_datetime = datetime.strftime(new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')
                            close_trade(ticker_name, close, new_env_datetime)
                            is_trade_closed = True

                        new_env_datetime = env_datetime
                        if is_trade_closed == True:
                            new_env_datetime = datetime.strptime(env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')+ timedelta(minutes=2)
                            new_env_datetime = datetime.strftime(new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z')
                        open_trade(ticker_name, 'short', close, new_env_datetime, actual_atr)

    
    print('---')
    print('from ' + date_from + ' to '+datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'))
    print('trades sum result: '+str(trade_sum))
    print('trades count: '+str(trade_count))
    persist_activity_log(ticker_name, granularity)

    """