Exemplo n.º 1
0
def analyze():
    analysis = {}
    handler = {}

    handler = TA_Handler(symbol=SYMBOL,
                         exchange=EXCHANGE,
                         screener=SCREENER,
                         interval=INTERVAL,
                         timeout=10)

    try:
        analysis = handler.get_analysis()
    except Exception as e:
        print("pausebotmod:")
        print("Exception:")
        print(e)

    ma_sell = analysis.moving_averages['SELL']
    if ma_sell >= THRESHOLD:
        paused = True
        print(
            f'pausebotmod: Market not looking too good, bot paused from buying {ma_sell}/{THRESHOLD}'
        )
    else:
        print(
            f'pausebotmod: Market looks ok, bot is running {ma_sell}/{THRESHOLD}'
        )
        paused = False

    return paused
def analyze(pairs):
    taMax = 0
    taMaxCoin = 'none'
    signal_coins = {}
    first_analysis = {}
    second_analysis = {}
    first_handler = {}
    second_handler = {}
    if os.path.exists('signals/signalsample.exs'):
        os.remove('signals/signalsample.exs')

    for pair in pairs:
        first_handler[pair] = TA_Handler(
            symbol=pair,
            exchange=MY_EXCHANGE,
            screener=MY_SCREENER,
            interval=MY_FIRST_INTERVAL,
            timeout= 10
        )
        second_handler[pair] = TA_Handler(
            symbol=pair,
            exchange=MY_EXCHANGE,
            screener=MY_SCREENER,
            interval=MY_SECOND_INTERVAL,
            timeout= 10
        )
    
    for pair in pairs:
       
        try:
            first_analysis = first_handler[pair].get_analysis()
            second_analysis = second_handler[pair].get_analysis()
        except Exception as e:
                    print("Exeption:")
                    print(e)
                    print (f'Coin: {pair}')
                    print (f'First handler: {first_handler[pair]}')
                    print (f'Second handler: {second_handler[pair]}')
                    tacheckS = 0
                
        first_tacheck = first_analysis.summary['BUY']
        second_tacheck = second_analysis.summary['BUY']
        if FULL_LOG:
            print(f'{pair} First {first_tacheck} Second {second_tacheck}')
        else:
            print(".", end = '')

        if first_tacheck > taMax:
                taMax = first_tacheck
                taMaxCoin = pair
        if first_tacheck >= TA_BUY_THRESHOLD and second_tacheck >= TA_BUY_THRESHOLD:
                signal_coins[pair] = pair
                print("")
                print(f'Signal detected on {pair}')
                with open('signals/signalsample.exs','a+') as f:
                    f.write(pair + '\n')
    print("")
    print(f'Max signal by {taMaxCoin} at {taMax} on shortest timeframe') 

    return signal_coins
Exemplo n.º 3
0
    def do_GET(self):
        o = urlparse(self.path)
        qParsed = parse_qs(o.query)
        symbol = qParsed['symbol'][0]
        screener = qParsed['screener'][0]
        exchange = qParsed['exchange'][0]
        interval = qParsed['interval'][0]
        tv = TA_Handler(symbol=symbol,
                        screener=screener,
                        exchange=exchange,
                        interval=interval)
        analyse = tv.get_analysis()

        print({symbol, screener, exchange, interval}, analyse)
        self._set_headers()
        self.wfile.write(
            bytes(
                json.dumps({
                    'request': {
                        'symbol': symbol,
                        'screener': screener,
                        'exchange': exchange,
                        'interval': interval
                    },
                    'result': {
                        'summary': analyse.summary,
                        'time': analyse.time.isoformat(),
                        'oscillators': analyse.oscillators,
                        'moving_averages': analyse.moving_averages,
                        'indicators': analyse.indicators
                    }
                }), "utf-8"))
Exemplo n.º 4
0
async def coin(message: types.Message):
    _lang = Lang(_langs, message.from_user.language_code)._lang
    if message.get_args() == "":
        data = ["BTCUSD", "BINANCE"]
    elif re.match(r"^[a-zA-Z]{6,8}$", message.get_args()):
        data = [re.search(r"^[a-zA-Z]{6,8}$", message.get_args()).group(), "BINANCE"]
    elif re.match(r"^[a-zA-Z]{6,8}:[a-zA-Z]{4,}$", message.get_args()):
        data = re.findall(r"^([a-zA-Z]{6,8}):([a-zA-Z]{4,})$", message.get_args())[0]
    else:
        return await message.reply(_lang["FORMAT"])

    try:
        handler = TA_Handler(
            screener= "crypto",
            exchange= data[1],
            symbol= data[0],
            interval= "1d"
        )

        analysis = handler.get_analysis()
        open_price = analysis.indicators["open"]
        close_price = analysis.indicators["close"]
        variance = ((close_price / open_price) -1) * 100

        await message.reply(_lang["SUMMARY"].format(
            pair= data[0],
            exchange= data[1],
            emoji= "⬆️" if variance > 0 else "⬇️",
            variance= format(variance, ".2f"),
            recommended= _lang[analysis.summary["RECOMMENDATION"]],
            open_price= format_price(open_price),
            close_price= format_price(close_price)
        ))
    except:
        return await message.reply(_lang["NOT_FOUND"])
Exemplo n.º 5
0
def get_tradingview_recommendation(
    ticker: str, screener: str, exchange: str, interval: str
) -> pd.DataFrame:
    """Get tradingview recommendation based on technical indicators

    Parameters
    ----------
    ticker : str
        Ticker to get the recommendation from tradingview based on technical indicators
    screener : str
        Screener based on tradingview docs https://python-tradingview-ta.readthedocs.io/en/latest/usage.html
    exchange: str
        Exchange based on tradingview docs https://python-tradingview-ta.readthedocs.io/en/latest/usage.html
    interval: str
        Interval time to check technical indicators and correspondent recommendation

    Returns
    -------
    df_recommendation: pd.DataFrame
        Dataframe of tradingview recommendations based on technical indicators
    """

    if not exchange:
        s_req = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={ticker}&apikey={cfg.API_KEY_ALPHAVANTAGE}"
        result = requests.get(s_req, stream=True)
        exchange = result.json()["Exchange"]

    if interval:
        intervals = [interval]
    else:
        intervals = ["1M", "1W", "1d", "4h", "1h", "15m", "5m", "1m"]

    df_recommendation = pd.DataFrame()
    index_recommendation = []
    for an_interval in intervals:
        # If the returned data was successful
        if result.status_code == 200:
            stock_recommendation = TA_Handler(
                symbol=ticker,
                screener=screener,
                exchange=exchange,
                interval=an_interval,
            )
            d_recommendation = stock_recommendation.get_analysis().summary
            df_recommendation = df_recommendation.append(
                d_recommendation, ignore_index=True
            )
            index_recommendation.append(INTERVALS[an_interval])
        df_recommendation.index = index_recommendation
        df_recommendation[["BUY", "NEUTRAL", "SELL"]] = df_recommendation[
            ["BUY", "NEUTRAL", "SELL"]
        ].astype(int)

    df_recommendation.index.name = "Interval"

    return df_recommendation
Exemplo n.º 6
0
 def run(self):
     while 1:
         handler = TA_Handler(
                 symbol="USDTUSD",
                 exchange="KRAKEN",
                 screener="crypto",
                 interval=Interval.INTERVAL_1_MINUTE
                 ) 
         self.lock.acquire()
         self.tether_index[0] = handler.get_analysis().indicators['close']
         self.lock.release()
         time.sleep(2)
Exemplo n.º 7
0
def tradingview_rec(ticker, timeframe):
    try:
        if timeframe == "week":
            handler = TA_Handler(
                symbol=ticker,
                screener="america",
                exchange="NASDAQ",
                interval=Interval.INTERVAL_1_WEEK
            )
        elif timeframe == "month":
            handler = TA_Handler(
                symbol=ticker,
                screener="america",
                exchange="NASDAQ",
                interval=Interval.INTERVAL_1_MONTH
            )
        return handler.get_analysis().summary
    except:
        return "Could not fetch recommendation"
Exemplo n.º 8
0
    def __init__(self, wallet: dict, min_price_change: float) -> None:

        # initialize wallet amounts
        self.tokens = list(wallet.keys())
        self.values = list(wallet.values())
        self.symbol = ''.join(self.tokens)
        self.price_change = min_price_change
        self.current_price = 0

        # initialize price api
        self.api = 'https://min-api.cryptocompare.com/data/pricemulti?fsyms={0}&tsyms={1}&api_key={2}'.format(
            self.tokens[0], self.tokens[1], cfg.CRYPTOCOMPARE_TOKEN)

        # initialize technical analysis api
        self.handler = TA_Handler()
        self.handler.set_symbol_as(self.symbol)
        self.handler.set_exchange_as_crypto_or_stock("BINANCE")
        self.handler.set_screener_as_crypto()
        self.handler.set_interval_as(Interval.INTERVAL_15_MINUTES)
Exemplo n.º 9
0
    def get_macd_indicator(self, symbol):
        _handler = TA_Handler(symbol="{0}".format(symbol),
                              screener="crypto",
                              exchange="binance",
                              interval=MACD_INTERVAL)
        _analysis = _handler.get_analysis()

        _ema10 = _analysis.indicators['EMA10']
        _ema20 = _analysis.indicators['EMA20']

        if _ema10 > _ema20:
            position = 'BUY'

        else:
            position = 'SELL'

        if position != self.tickers['{0}'.format(symbol)]['lastPosition']:
            return position

        return None
Exemplo n.º 10
0
def analyze(pairs):
    signal_coins = {}
    analysis = {}
    handler = {}

    if os.path.exists('signals/custsignalmod.exs'):
        os.remove('signals/custsignalmod.exs')

    for pair in pairs:
        handler[pair] = TA_Handler(symbol=pair,
                                   exchange=EXCHANGE,
                                   screener=SCREENER,
                                   interval=INTERVAL,
                                   timeout=10)

    for pair in pairs:
        try:
            analysis = handler[pair].get_analysis()
        except Exception as e:
            print("Signalsample:")
            print("Exception:")
            print(e)
            print(f'Coin: {pair}')
            print(f'handler: {handler[pair]}')

        oscCheck = 0
        maCheck = 0
        for indicator in OSC_INDICATORS:
            if analysis.oscillators['COMPUTE'][indicator] == 'BUY':
                oscCheck += 1

        for indicator in MA_INDICATORS:
            if analysis.moving_averages['COMPUTE'][indicator] == 'BUY':
                maCheck += 1

        if FULL_LOG:
            print(
                f'Custsignalmod:{pair} Oscillators:{oscCheck}/{len(OSC_INDICATORS)} Moving averages:{maCheck}/{len(MA_INDICATORS)}'
            )

        if oscCheck >= OSC_THRESHOLD and maCheck >= MA_THRESHOLD:
            signal_coins[pair] = pair
            print(
                f'Custsignalmod: Signal detected on {pair} at {oscCheck}/{len(OSC_INDICATORS)} oscillators and {maCheck}/{len(MA_INDICATORS)} moving averages.'
            )
            with open('signals/custsignalmod.exs', 'a+') as f:
                f.write(pair + '\n')

    return signal_coins
Exemplo n.º 11
0
async def recom(ctx, stock_name):
    """Shows what you should do with a stock, buy or sell"""
    """try:
		ticker = yf.Ticker(str(stock_name))
		rec = pd.DataFrame(ticker.recommendations)
	except:
		return
	await ctx.send("```" + str(rec.tail(1)) + "```")"""
    try:  #see if the stock is in NASDAQ
        handler = TA_Handler(symbol=str(stock_name),
                             screener="america",
                             exchange="NASDAQ",
                             interval=Interval.INTERVAL_1_DAY)
        analysis = handler.get_analysis()  #get the analysis of the stock
    except:
        try:  #see if the stock is in the NYSE
            handler = TA_Handler(symbol=str(stock_name),
                                 screener="america",
                                 exchange="NYSE",
                                 interval=Interval.INTERVAL_1_DAY)
            analysis = handler.get_analysis()
        except:
            try:  #else check if its a crypto

                handler = TA_Handler(symbol=str(stock_name),
                                     screener="crypto",
                                     exchange="binance",
                                     interval=Interval.INTERVAL_1_DAY)
                analysis = handler.get_analysis()
            except:
                return  #if none of the above end the function
    await ctx.send(
        "```You should {0} {1} right NOW!```".format(
            ''.join(analysis.summary['RECOMMENDATION'].replace('_', ' ')),
            stock_name)
    )  #tells the user what they should do with the stock or crypto
Exemplo n.º 12
0
print("Testing {}Tradingview-TA{} v{}{}".format(Fore.CYAN, Fore.MAGENTA,
                                                tradingview_ta.__version__,
                                                Style.RESET_ALL))
print(
    "This test is {}semi-automatic{}. Please compare with tradingview's data manually."
    .format(Fore.LIGHTRED_EX, Style.RESET_ALL))
print("------------------------------------------------")

COUNT = 5
success = 0

print("{}#0{} {}Testing invalid symbol{}".format(Fore.BLUE, Style.RESET_ALL,
                                                 Fore.LIGHTBLUE_EX,
                                                 Style.RESET_ALL))
handler = TA_Handler(symbol="ThisSymbolIsInvalid",
                     interval="1m",
                     screener="america",
                     exchange="NASDAQ")
try:
    analysis = handler.get_analysis()
    if analysis:
        print("{}#0{} Invalid symbol test {}failed{}. No exception occured.".
              format(Fore.BLUE, Style.RESET_ALL, Fore.RED, Style.RESET_ALL))
except Exception as e:
    if str(e) == "Exchange or symbol not found.":
        print("{}#0{} Invalid symbol test {}success{}.".format(
            Fore.BLUE, Style.RESET_ALL, Fore.GREEN, Style.RESET_ALL))
        success += 1
    else:
        print(
            "{}#0{} Invalid symbol test {}failed{}. An exception occured, but the symbol is valid."
            .format(Fore.BLUE, Style.RESET_ALL, Fore.RED, Style.RESET_ALL))
Exemplo n.º 13
0
#print(tradingview_ta.__version__)

intervals = [
    '1m',  #Interval.INTERVAL_1_MINUTE,
    '5m',  #Interval.INTERVAL_5_MINUTES,
    '15m',  #Interval.INTERVAL_15_MINUTES,
    '1h',  #Interval.INTERVAL_1_HOUR,
    '4h',  #Interval.INTERVAL_4_HOURS,
    '1d',  #Interval.INTERVAL_1_DAY,
    '1W',  #Interval.INTERVAL_1_WEEK,
    '1M'  #Interval.INTERVAL_1_MONTH,
]
summary = {'BUY': 0, 'SELL': 0, 'NEUTRAL': 0}
keys = ['BUY', 'SELL', 'NEUTRAL']
handler = TA_Handler(symbol='VUG',
                     screener='america',
                     exchange='AMEX',
                     interval=intervals[0])
#help(TA_Handler)
print(handler.symbol)
for intervali in intervals:
    handler.set_interval_as(intervali)
    analysis = handler.get_analysis()
    print('  ', analysis.interval, analysis.summary)
    #print(analysis.interval)
    #print(intervali,analysis.oscillators)
    #print(intervali,analysis.moving_averages)
    #keys = [key for key in analysis.indicators.keys() if 'Pivot' in key]
    #for key in analysis.indicators.keys():
    #if 'Pivot' in key:
    #print(intervali,key,analysis.indicators[key])
    #print('  ',summary+analysis.summary)
Exemplo n.º 14
0
import datetime
from time import sleep

if len(argv) != 7:
    print("Usage: {} symbol webdriver c_key c_secret a_token a_secret".format(
        argv[0]))
    print("Symbol: Trading pair/symbol (ex: BTCUSDT).")
    print("Webdriver: Selenium webdriver (ex: chrome, firefox, edge).")
    print("c_key: Twitter consumer key.")
    print("c_secret: Twitter consumer secret.")
    print("a_token: Twitter access token.")
    print("a_secret: Twitter access token secret.")
    exit(1)

# Tradingview Settings
handler = TA_Handler()
handler.symbol = argv[1]
handler.interval = "1h"
handler.driver = argv[2]
handler.start_driver()

# Tweepy and Twitter Settings
auth = tweepy.OAuthHandler(argv[3], argv[4])
auth.set_access_token(argv[5], argv[6])

up = "📈"
down = "📉"
last_price = 0

# Create API object
api = tweepy.API(auth)
Exemplo n.º 15
0
def get_stock_indicators_manual(
):  #Get sell/buy indicators from tradingview_ta for one stock, with user input and print the result
    handler = TA_Handler()
    symbol = loop_simples_de_coleta(configleng[4], configleng[0],
                                    configleng[2])
    handler.set_symbol_as(symbol)
    exchange = loop_simples_de_coleta(configleng[5], configleng[0],
                                      configleng[2])
    handler.set_exchange_as_crypto_or_stock(exchange)
    handler.set_screener_as_stock(
        loop_simples_de_coleta(configleng[8], configleng[0], configleng[2]))
    r = str(interval_options())
    handler.set_interval_as(r)
    stock = handler.get_analysis().summary
    stock_table = []
    for i in stock.items():
        stock_table.append(i)
    stock_table.insert(0, ["Company: " + symbol.upper(), "Result"])
    stock_table = AsciiTable(stock_table)
    print(stock_table.table)
from tradingview_ta import TA_Handler, Interval
symbol = 'BTCUSDT'

exchange = 'BINANCE'
pair = TA_Handler()
pair.set_symbol_as(symbol)
pair.set_exchange_as_crypto_or_stock(exchange)
pair.set_screener_as_crypto()
pair.set_interval_as(Interval.INTERVAL_1_DAY)
print(pair.get_analysis().summary)
# Example output: {"RECOMMENDATION": "BUY", "BUY": 8, "NEUTRAL": 6, "SELL": 3}
print(pair.get_analysis().oscillators)
print(pair.get_analysis().moving_averages)
print(pair.get_analysis().indicators)
Exemplo n.º 17
0
from tradingview_ta import TA_Handler, Interval
import time
from datetime import datetime
import config
from binance.client import Client
from binance.enums import *

client = Client(config.API_KEY, config.API_SECRET, tld='com')

now = datetime.now()
fecha = now.strftime("%d-%m-%y %H:%M:%S")
lista = client.get_all_tickers()
strongBuy_list = []
strongSell_list = []
for i in lista:
    tesla = TA_Handler()
    tesla.set_symbol_as(i['symbol'])
    tesla.set_exchange_as_crypto_or_stock("BINANCE")
    tesla.set_screener_as_crypto()
    tesla.set_interval_as(Interval.INTERVAL_1_HOUR)
    print(i['symbol'])
    try:
        print(tesla.get_analysis().summary)
    except Exception as e:
        print("No Data")
        continue
    if ((tesla.get_analysis().summary)["RECOMMENDATION"]) == "STRONG_BUY":
        print(f" Compar más fuerte {i}", fecha)
        strongBuy_list.append(i['symbol'])
    elif ((tesla.get_analysis().summary)["RECOMMENDATION"]) == "STRONG_SELL":
        print(f" Compar más fuerte {i}", fecha)
Exemplo n.º 18
0
def get_buy_or_sell(ticker_exchange, intervals, ratio):
    keys = ['BUY', 'SELL', 'NEUTRAL']
    handler = TA_Handler(symbol='VUG',
                         screener='america',
                         exchange='AMEX',
                         interval=intervals[0])
    print(bcolors.NEUTRAL, '  {:10s}  {:15s}  '.format('Ticker',
                                                       'Recommendation'),
          'Summary of Technical Analysis', bcolors.ENDC)
    print(
        '--------------------------------------------------------------------------'
    )
    tickers_to_buy = []
    tickers_to_sell = []
    for symbol, exchange in ticker_exchange.items():
        handler.set_symbol_as(symbol)
        handler.exchange = exchange
        summary = {'BUY': 0, 'SELL': 0, 'NEUTRAL': 0}
        for intervali in intervals:
            handler.set_interval_as(intervali)
            analysis = handler.get_analysis()
            #print('  ',analysis.interval,analysis.summary)
            #print(analysis.interval)
            #print(intervali,analysis.oscillators)
            #print(intervali,analysis.moving_averages)
            #keys = [key for key in analysis.indicators.keys() if 'Pivot' in key]
            #for key in analysis.indicators.keys():
            #if 'Pivot' in key:
            #print(intervali,key,analysis.indicators[key])
            #print('  ',summary+analysis.summary)
            for key, val in summary.items():
                summary[key] += analysis.summary[key]
            #print(analysis.time)
            #print(analysis.oscillators)
            #print(analysis.indicators)
        #print('  ',summary)
        num_tests = 0
        for summary_key, summary_val in summary.items():
            num_tests += summary_val
        shaun_recommendation = 'NEUTRAL'
        for summary_key, summary_val in summary.items():
            if summary_val > ratio * num_tests:
                shaun_recommendation = summary_key
        if shaun_recommendation == 'BUY':
            #print(bcolors.BUY+handler.symbol,shaun_recommendation,summary,bcolors.ENDC)
            print(
                bcolors.BUY,
                '  {:10s}  {:15s}  '.format(handler.symbol,
                                            shaun_recommendation), summary,
                bcolors.ENDC)
            tickers_to_buy.append(handler.symbol)
        elif shaun_recommendation == 'SELL':
            #print(bcolors.SELL,handler.symbol,shaun_recommendation,summary,bcolors.ENDC)
            print(
                bcolors.SELL,
                '  {:10s}  {:15s}  '.format(handler.symbol,
                                            shaun_recommendation), summary,
                bcolors.ENDC)
            tickers_to_sell.append(handler.symbol)
        elif shaun_recommendation == 'NEUTRAL':
            #print(bcolors.NEUTRAL,handler.symbol,shaun_recommendation,summary,bcolors.ENDC)
            print(
                bcolors.NEUTRAL,
                '  {:10s}  {:15s}  '.format(handler.symbol,
                                            shaun_recommendation), summary,
                bcolors.ENDC)
    #print(help(handler))
    #print(help(handler.get_analysis()))
    #print(handler.get_indicators())

    print(bcolors.BUY + 'recommended to buy ', tickers_to_buy, bcolors.ENDC)
    print(bcolors.SELL + 'recommended to sell ', tickers_to_sell, bcolors.ENDC)
    return tickers_to_buy, tickers_to_sell
Exemplo n.º 19
0
def tech():
    id_focus = input("ID action > ")
    symbol = input("entreprise symbole > ")
    exchange = input("place bourisère > ")
    country = input("pays > ")

    print("Analyse technique :")

    try:
        _object = TA_Handler()
        _object.set_symbol_as(symbol)
        _object.set_exchange_as_crypto_or_stock(exchange)
        _object.set_screener_as_stock(country)
        _object.set_interval_as(Interval.INTERVAL_1_DAY)
        tradingview_result = _object.get_analysis().summary
        print("1 jour >", tradingview_result)

        _object.set_interval_as(Interval.INTERVAL_1_WEEK)
        tradingview_result = _object.get_analysis().summary
        print("1 sem >", tradingview_result)

        _object.set_interval_as(Interval.INTERVAL_1_MONTH)
        tradingview_result = _object.get_analysis().summary
        print("1 mois >", tradingview_result)

        print("Infos ajoutée en DB")
        with connexion:
            c.execute(
                f"UPDATE ACTIONS SET tec_exchange = '{exchange}', tec_country = '{country}' WHERE id = {id_focus};"
            )
    except:
        print("ERREUR > une ou plusieures données sont érronées.")
Exemplo n.º 20
0
def cls():
    os.system('cls' if os.name == 'nt' else 'clear')


cls()

print("Bienvenue sur Tradyglo v.BETA")
while i == 0:
    symbol = input("entreprise symbole > ")
    exchange = input("place bourisère > ")
    country = input("pays > ")

    print("-" * 100)
    print("Résultats analyses techniques", symbol, ":")

    _object = TA_Handler()
    _object.set_symbol_as(symbol)
    _object.set_exchange_as_crypto_or_stock(exchange)
    _object.set_screener_as_stock(country)
    _object.set_interval_as(Interval.INTERVAL_1_DAY)
    test = _object.get_analysis().summary

    print("1 jour >", test)

    _object.set_interval_as(Interval.INTERVAL_1_WEEK)
    test = _object.get_analysis().summary
    print("1 sem >", test)

    _object.set_interval_as(Interval.INTERVAL_1_MONTH)
    test = _object.get_analysis().summary
    print("1 mois >", test)
Exemplo n.º 21
0
 def get_data_from_tradingView(self):
     # dataframeSPY = pd.read_csv("data/SPY.csv")
     # dataframeSPY['time'] = pd.to_datetime(dataframeSPY['time'], unit='s')
     # print(dataframeSPY.tail())
     tesla = TA_Handler()
     tesla.set_symbol_as("TSLA")
     tesla.set_exchange_as_crypto_or_stock("NASDAQ")
     tesla.set_screener_as_stock("america")
     tesla.set_interval_as(Interval.INTERVAL_1_DAY)
     print(tesla.get_analysis().summary)
Exemplo n.º 22
0
class Trader:
    def __init__(self, wallet: dict, min_price_change: float) -> None:

        # initialize wallet amounts
        self.tokens = list(wallet.keys())
        self.values = list(wallet.values())
        self.symbol = ''.join(self.tokens)
        self.price_change = min_price_change
        self.current_price = 0

        # initialize price api
        self.api = 'https://min-api.cryptocompare.com/data/pricemulti?fsyms={0}&tsyms={1}&api_key={2}'.format(
            self.tokens[0], self.tokens[1], cfg.CRYPTOCOMPARE_TOKEN)

        # initialize technical analysis api
        self.handler = TA_Handler()
        self.handler.set_symbol_as(self.symbol)
        self.handler.set_exchange_as_crypto_or_stock("BINANCE")
        self.handler.set_screener_as_crypto()
        self.handler.set_interval_as(Interval.INTERVAL_15_MINUTES)

    def check_recommendation(self) -> str:
        return self.handler.get_analysis().summary['RECOMMENDATION']

    def get_price(self) -> float:
        response = requests.request("GET", self.api)
        json_resp = json.loads(response.text)
        return json_resp[self.tokens[0]][self.tokens[1]]

    def buy(self, percent) -> float:
        quantity = self.values[1] * percent
        self.values[0] += quantity / self.current_price
        self.values[1] -= quantity

        return quantity / self.current_price

    def sell(self, percent) -> float:
        quantity = self.values[0] * percent
        self.values[1] += quantity * self.current_price
        self.values[0] -= quantity

        return quantity
        # return'SOLD '+str(quantity) +' '+self.trading_pair[0]+' for ' + str(price)

    def handle_status_change(self, curr) -> float:
        if curr == 'STRONG_BUY' and self.values[1] > 0:
            return (self.buy(1), 'BUY')
        elif curr == 'BUY' and self.values[1] > 0:
            return (self.buy(0.4), 'BUY')
        elif curr == 'SELL' and self.values[0] > 0:
            return (self.sell(0.4), 'SELL')
        elif curr == 'STRONG_SELL' and self.values[0] > 0:
            return (self.sell(1), 'SELL')
        else:
            return (0, None)

    def wallet_pretty(self) -> str:
        w = emoji.emojize(
            ':credit_card:\n{:.4f} {}\n{:.4f} {}\n\nTotal:\n{:.4f} {}'.format(
                self.values[0], self.tokens[0], self.values[1], self.tokens[1],
                self.values[1] + self.values[0] * self.current_price,
                self.tokens[1]))
        return w

    def trade_pretty(self, quantity, side) -> str:
        if side == 'SELL':
            return emoji.emojize(
                ':left_arrow: Sold {:.4f} {} for {:.4f}'.format(
                    quantity, self.tokens[0], self.current_price))
        else:
            return emoji.emojize(
                ':right_arrow: Bought {:.4f} {} for {:.4f}'.format(
                    quantity, self.tokens[0], self.current_price))

    def persist(self) -> None:
        with open('./saved.pickle', 'wb') as f:
            pickle.dump(self, f)

    def run(self) -> str:
        logging.info('Started trading ' + self.symbol)
        # prev_rec = 'NONE'
        prev_price = self.current_price

        while True:
            try:
                rec = self.check_recommendation()
                self.current_price = self.get_price()

                price_change = abs(1 - (prev_price / self.current_price))

                if price_change > self.price_change or 'STRONG' in rec:
                    traded = self.handle_status_change(rec)

                    self.persist()
                    if traded[0] <= 0:
                        continue

                    prev_price = self.current_price
                    # prev_rec = rec

                    tradedstr = self.trade_pretty(*traded)
                    walletstr = self.wallet_pretty()

                    yield tradedstr

                    logging.info(tradedstr)
                    logging.info(walletstr)

                    self.persist()
            except:
                logging.exception('Error occurred')
            finally:
                time.sleep(30)
Exemplo n.º 23
0
if args.secureproxy:
    proxies["https"] = args.secureproxy

print("------------------------------------------------")
print("Testing {}Tradingview-TA{} v{}{}".format(Fore.CYAN, Fore.MAGENTA, tradingview_ta.__version__, Style.RESET_ALL))
print("This test is {}semi-automatic{}. Please compare with tradingview's data manually.".format(Fore.LIGHTRED_EX, Style.RESET_ALL))
print("------------------------------------------------")

COUNT = 7
success = 0

print("{}#0{} {}Testing invalid symbol{}".format(Fore.BLUE, Style.RESET_ALL, Fore.LIGHTBLUE_EX, Style.RESET_ALL))
handler = TA_Handler(
    symbol="ThisSymbolIsInvalid",
    interval="1m",
    screener="america",
    exchange="NASDAQ",
    proxies = proxies
)
try:
    analysis = handler.get_analysis()
    if analysis:
        print("{}#0{} Invalid symbol test {}failed{}. No exception occured.".format(Fore.BLUE, Style.RESET_ALL, Fore.RED, Style.RESET_ALL))
except Exception as e:
    if str(e) == "Exchange or symbol not found.":
        print("{}#0{} Invalid symbol test {}success{}.".format(Fore.BLUE, Style.RESET_ALL, Fore.GREEN, Style.RESET_ALL))
        success += 1
    else:
        print("{}#0{} Invalid symbol test {}failed{}. An exception occured, but the symbol is valid.".format(Fore.BLUE, Style.RESET_ALL, Fore.RED, Style.RESET_ALL))

Exemplo n.º 24
0
from django.contrib.auth.decorators import login_required
from django.db.models import F
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Shares
from .forms import SharesForm
from django.contrib import messages
from django.core.paginator import Paginator
from tradingview_ta import TA_Handler, Interval

tesla = TA_Handler()
tesla.set_symbol_as("TSLA")
tesla.set_exchange_as_crypto_or_stock("NASDAQ")
tesla.set_screener_as_stock("america")
tesla.set_interval_as(Interval.INTERVAL_1_DAY)
print(tesla.get_analysis().summary)
# Example output: {"RECOMMENDATION": "BUY", "BUY": 8, "NEUTRAL": 6, "SELL": 3}


@login_required
def index(request, message=messages):

    all_shares = Shares.objects.filter()
    paginator = Paginator(all_shares, 10)
    page = request.GET.get('pg')
    all_shares = paginator.get_page(page)
    return render(request, 'index.html', {'all_shares': all_shares})


@login_required
def add_shares(request):
Exemplo n.º 25
0
def get_tradingview_recommendation(ticker: str, screener: str, exchange: str,
                                   interval: str) -> str:
    """Get tradingview recommendation based on technical indicators

    Parameters
    ----------
    ticker : str
        Ticker to get the recommendation from tradingview based on technical indicators
    screener : str
        Screener based on tradingview docs https://python-tradingview-ta.readthedocs.io/en/latest/usage.html
    exchange: str
        Exchange based on tradingview docs https://python-tradingview-ta.readthedocs.io/en/latest/usage.html
    interval: str
        Interval time to check technical indicators and correspondent recommendation

    Returns
    -------
    str
        tradingview recommendation based on technical indicators
    """

    if not exchange:
        s_req = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={ticker}&apikey={cfg.API_KEY_ALPHAVANTAGE}"
        result = requests.get(s_req, stream=True)
        exchange = result.json()["Exchange"]

    if not interval:
        df_recommendation = pd.DataFrame()
        index_recommendation = list()
        for interv in ["1M", "1W", "1d", "4h", "1h", "15m", "5m", "1m"]:
            # If the returned data was successful
            if result.status_code == 200:
                stock_recommendation = TA_Handler(
                    symbol=ticker,
                    screener=screener,
                    exchange=exchange,
                    interval=interv,
                )
                d_recommendation = stock_recommendation.get_analysis().summary
                df_recommendation = df_recommendation.append(d_recommendation,
                                                             ignore_index=True)
                index_recommendation.append(INTERVALS[interv])
            df_recommendation.index = index_recommendation
            df_recommendation[["BUY", "NEUTRAL", "SELL"]] = df_recommendation[[
                "BUY", "NEUTRAL", "SELL"
            ]].astype(int)
        df_recommendation["-----"] = "-----"
        df_recommendation.index.name = "Interval"
        recommendation = df_recommendation[[
            "RECOMMENDATION", "-----", "BUY", "NEUTRAL", "SELL"
        ]].to_string()

    else:
        stock_recommendation = TA_Handler(symbol=ticker,
                                          screener=screener,
                                          exchange=exchange,
                                          interval=interval)
        d_recommendation = stock_recommendation.get_analysis().summary
        recommendation = f"Interval: {INTERVALS[interval]}\n"
        recommendation += f"Recommendation: {d_recommendation['RECOMMENDATION']}\n"
        recommendation += f"{int(d_recommendation['BUY'])} BUY, {int(d_recommendation['NEUTRAL'])} NEUTRAL"
        recommendation += f", {int(d_recommendation['SELL'])} SELL"

    return recommendation
Exemplo n.º 26
0
def root():
    if request.method == "GET":
        return render_template("index.html",
                               version=tradingview_ta.__version__,
                               captcha_sitekey=hcaptcha_sitekey)
    elif request.method == "POST":
        try:
            # hCaptcha
            # hcaptcha_response = request.form["h-captcha-response"]
            # captchaReq = requests.post("https://hcaptcha.com/siteverify", data={"secret": hcaptcha_secret, "response": hcaptcha_response})
            # if captchaReq.json()["success"] == False:
            #     return render_template("error.html", version=tradingview_ta.__version__, error="Error: Invalid captcha", captcha_sitekey=hcaptcha_sitekey)

            # TradingView Technical Analysis
            handler = TA_Handler()
            handler.set_symbol_as(request.form["symbol"])
            handler.set_exchange_as_crypto_or_stock(request.form["exchange"])
            handler.set_screener_as_stock(request.form["screener"])
            handler.set_interval_as(request.form["interval"])
            analysis = handler.get_analysis()
            return render_template("success.html",
                                   version=tradingview_ta.__version__,
                                   symbol=analysis.symbol,
                                   exchange=analysis.exchange,
                                   screener=analysis.screener,
                                   interval=analysis.interval,
                                   time=analysis.time.astimezone(timezone.utc),
                                   summary=analysis.summary,
                                   oscillators=analysis.oscillators,
                                   moving_averages=analysis.moving_averages,
                                   indicators=analysis.indicators,
                                   captcha_sitekey=hcaptcha_sitekey)
        except Exception as e:
            return render_template("error.html",
                                   version=tradingview_ta.__version__,
                                   error=e,
                                   captcha_sitekey=hcaptcha_sitekey)
Exemplo n.º 27
0
def get_stock_indicators_list(
    lista=list
):  #Get sell/buy indicators for multiple stocks from a list, and print the results
    handler = TA_Handler()
    for i in range(len(lista)):
        handler.set_symbol_as(lista[i][0])
        handler.set_exchange_as_crypto_or_stock("NASDAQ")
        handler.set_screener_as_stock("america")
        handler.set_interval_as(Interval.INTERVAL_1_HOUR)
        stock = handler.get_analysis().summary
        stock_table = []
        for b in stock.items():
            stock_table.append(b)
        stock_table.insert(0, ["Company: " + lista[i][0].upper(), "Result"])
        stock_table = AsciiTable(stock_table)
        print(stock_table.table)
Exemplo n.º 28
0
"""Using the tradingview-ta package to get ethereum data from binance in 15 minute intervals"""

from tradingview_ta import TA_Handler, Interval

handler = TA_Handler(symbol="ETHUSD",
                     screener="crypto",
                     exchange="binance",
                     interval=Interval.INTERVAL_15_MINUTES)

analysis = handler.get_analysis()
Exemplo n.º 29
0
# coding: utf-8

# In[ ]:
import pandas as pd
from tradingview_ta import TA_Handler, Interval
from tqdm import trange
import time
import datetime as dt
#########
tickers = pd.read_csv('dataset/ind_nifty50list.csv')
tickers = pd.DataFrame(tickers.Symbol)
########
dictionary = {'-': '_', '&': '_'}
tickers.replace(dictionary, regex=True, inplace=True)
Stock = {}
handler = TA_Handler()
handler.set_exchange_as_crypto_or_stock("NSE")
handler.set_screener_as_stock("india")
tickers['Strength'] = 0
while True:
    handler.set_interval_as(Interval.INTERVAL_1_HOUR)
    # tickers.shape[0]
    for i in trange(tickers.shape[0]):
        try:
            handler.set_symbol_as(tickers.Symbol[i])
            Stock[tickers.Symbol[i]] = [
                handler.get_analysis().summary['RECOMMENDATION'],
                handler.get_analysis().indicators['close']
            ]
            #print([i],tickers[i],handler.get_analysis().summary['RECOMMENDATION'])
Exemplo n.º 30
0
def analyse_technique(id_infos):

    print("Analyse technique :")

    try:
        with connexion:
            c.execute(
                f"SELECT tec_symbol, tec_exchange, tec_country FROM actions where id = {id_infos};"
            )
            result = c.fetchone()
            tec_symbol = result[0]
            tec_exchange = result[1]
            tec_country = result[2]

            try:  #1- on tente avec ce qui est stocké en db
                _object = TA_Handler()
                _object.set_symbol_as(tec_symbol)
                _object.set_exchange_as_crypto_or_stock(tec_exchange)
                _object.set_screener_as_stock(tec_country)

                _object.set_interval_as(Interval.INTERVAL_1_DAY)
                tradingview_result = _object.get_analysis().summary

                _object.set_interval_as(Interval.INTERVAL_1_WEEK)
                tradingview_result2 = _object.get_analysis().summary

                _object.set_interval_as(Interval.INTERVAL_1_MONTH)
                tradingview_result3 = _object.get_analysis().summary

                c.execute(
                    f"UPDATE ACTIONS SET tec_exchange = '{tec_exchange}', tec_country = '{tec_country}' WHERE id = {id_infos};"
                )

                print("1 jour >", tradingview_result)
                print("1 sem >", tradingview_result2)
                print("1 mois >", tradingview_result3)
            except:
                tec_country = "AMERICA"
                tec_exchange = "NYSE"

                try:
                    _object = TA_Handler()
                    _object.set_symbol_as(tec_symbol)
                    _object.set_exchange_as_crypto_or_stock(tec_exchange)
                    _object.set_screener_as_stock(tec_country)

                    _object.set_interval_as(Interval.INTERVAL_1_DAY)
                    tradingview_result = _object.get_analysis().summary

                    _object.set_interval_as(Interval.INTERVAL_1_WEEK)
                    tradingview_result2 = _object.get_analysis().summary

                    _object.set_interval_as(Interval.INTERVAL_1_MONTH)
                    tradingview_result3 = _object.get_analysis().summary

                    c.execute(
                        f"UPDATE ACTIONS SET tec_exchange = '{tec_exchange}', tec_country = '{tec_country}' WHERE id = {id_infos};"
                    )

                    print("1 jour >", tradingview_result)
                    print("1 sem >", tradingview_result2)
                    print("1 mois >", tradingview_result3)

                except:
                    tec_country = "AMERICA"
                    tec_exchange = "NASDAQ"
                    try:
                        _object = TA_Handler()
                        _object.set_symbol_as(tec_symbol)
                        _object.set_exchange_as_crypto_or_stock(tec_exchange)
                        _object.set_screener_as_stock(tec_country)

                        _object.set_interval_as(Interval.INTERVAL_1_DAY)
                        tradingview_result = _object.get_analysis().summary

                        _object.set_interval_as(Interval.INTERVAL_1_WEEK)
                        tradingview_result2 = _object.get_analysis().summary

                        _object.set_interval_as(Interval.INTERVAL_1_MONTH)
                        tradingview_result3 = _object.get_analysis().summary

                        c.execute(
                            f"UPDATE ACTIONS SET tec_exchange = '{tec_exchange}', tec_country = '{tec_country}' WHERE id = {id_infos};"
                        )

                        print("1 jour >", tradingview_result)
                        print("1 sem >", tradingview_result2)
                        print("1 mois >", tradingview_result3)

                    except:
                        print(
                            "Aucune donnée d'analyse technique, utilisez .tech"
                        )

    except:
        print("ERROR 14")