IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Python Discussion :

IndexError: List index out of range


Sujet :

Python

  1. #1
    Membre à l'essai
    Homme Profil pro
    Administrateur de base de données
    Inscrit en
    Mai 2014
    Messages
    33
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Hauts de Seine (Île de France)

    Informations professionnelles :
    Activité : Administrateur de base de données
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Mai 2014
    Messages : 33
    Points : 13
    Points
    13
    Par défaut IndexError: List index out of range
    Bonjour à tous !

    Pour vous expliquez brièvement, j'ai trouvez un bot sur twitter qui référence le RSI (indicateur utilisé dans le trading) c'est une valeur de type float.

    Toute les 5 minutes le Bot poste les RSI les plus bas des crypto monnaies. Mon but étant de réussir a "grab" les RSI des crypto monnaies pour pouvoir ensuite les analyser. Je récupère aussi le Volume des crypto monnaies grâce à un module développé grâce a une API sur le site bittrex.com. Pour cette étape tout marche très bien je n'ai aucun problème.

    J'utilise tweepy pour le stream listener twitter.

    Voici un exemple de format de tweet qui est poster:

    5 min #RSI Signals:

    $BTC - $SLR: 35.85
    $BTC - $VRM: 36.5
    $BTC - $BCC: 36.52
    $BTC - $ENG: 37.81
    $BTC - $WAVES: 39.8

    $ZCL $CLOAK $PKB $SC
    J'arrive à récupérer le coin en question et le RSI aucun soucis.

    Le problème est que je lance ça sur mon serveur OVH (sous Linux) et que je le laisse tourner 24/24 en permanence grâce à screen.

    En faisant ça je me suis rendu compte que parfois j'obtenais cette erreur de manière récurrente que je n'ai pas réussis à résoudre.

    Je ne sais pas pourquoi mais parfois sans raison j'obtient un List index out of range.

    Je ne sais pas de quelle ligne provient l'erreur puisque il m'indique l'erreur a la fin du fichier.


    Nom : 4299927D957D9F1F804938B24E3EA7EA14F477.png
Affichages : 884
Taille : 105,4 Ko


    Voici le code en question:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
     
    import tweepy
    import sys, signal, json, time
    from bittrex import bittrex
    import datetime
    import urllib
    import urllib2
    import yagmail
     
     
    # Specify the account credentials in the following variables:
    consumer_key = ''
    consumer_secret = ''
    access_token = ''
    access_token_secret = ''
    gmail_user = ''  
    gmail_password = ''
     
     
    target_user = 909009874498940928
    api = bittrex('KEY', 'SECRET')
     
     
     
    def sigint_handler(signum, frame):
        """Handler for ctrl+c"""
        print '\n[!] CTRL+C pressed. Exiting...'
        sys.exit(0)
     
    signal.signal(signal.SIGINT, sigint_handler)
     
     
     
     
    def SplitTweet(twt):
    	file = open("logs.txt","a")
    	coin =''
    	rsi = 0
    	first_letter = twt[:1]
    	#if it's 5min RSI
    	if '5' in first_letter:
    		#before read line per line
    		lines = twt.split('\n')
    		#Read line per line
    		for line in lines:
    			btc_balance  = api.getbalance("BTC")['Available']
    			#Split to get $BTC and the rest
    			split = line.split("-", 1)
    			if '$BTC' in split[0]:
    				#Split into all things
    				split_coin = split[1].split("$", 1)
    				#Only coin and RSI
    				coin_et_rsi = split_coin[1]
    				coin_et_rsi_split = coin_et_rsi.split(": ", 1)
    				coin = coin_et_rsi_split[0]
    				rsi_string = coin_et_rsi_split[1]
    				rsi = float(rsi_string)
    				open_order = api.getopenorders("BTC-" + coin)
    				if coin != 'MTL' and coin != 'TRIG':
    					if not open_order:
    						market = "BTC-" + coin
    						marketsummary = api.getmarketsummary(market)
    						volume_str = marketsummary[0]['BaseVolume']
    						volume = float(volume_str)
    						if rsi< 24.1 and volume >=200:
    							if btc_balance > 0.028:
    								print '\n[+] {} has a RSI of {} '.format(coin, rsi)
    								print 'BTC Balance {} BTC\n\n'.format(btc_balance)							
    								file.write(" %s %s RSI: %s " % (market, datetime.datetime.now(), rsi))
    								pricecoin = api.getticker("BTC-" + coin)
    								pricebuy = pricecoin['Last']
    								pricesell = pricebuy + (0.036 * pricebuy)
    								stoploss = pricebuy - (0.04 * pricebuy)
    								subject = '%s RSI: %s' %(coin, rsi)  
    								body = '%s RSI is: %s\nPlaced a buy order at %s and sell order at %s\nYou should place a stop loss at %s\n' %(coin, rsi,pricebuy, pricesell, stoploss)
    								yag = yagmail.SMTP(gmail_user, gmail_password)
    								yag.send("zidanesignal@gmail.com", subject, body)
    							else:
    								print 'BTC balance < 0 : {}\n\n'.format(btc_balance)
    	file.close()
     
     
    # This listener will print out all Tweets it receives
    class PrintListener(tweepy.StreamListener):
        def on_data(self, data):
            # Decode the JSON data
            tweet = json.loads(data)
    	#Reading tweet
    	twt = (tweet['text'].encode('ascii', 'ignore'))
    	SplitTweet(twt)
     
        def on_error(self, status):
            print(status)
     
     
    if __name__ == '__main__':
        listener = PrintListener()
     
        # Show system message
        print('Waiting for tweets ...')
     
        # Authenticate
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
     
        # Connect the stream to our listener
        stream = tweepy.Stream(auth, listener)
        stream.filter(follow=[unicode(target_user)])
    Et voici le bittrex.py

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
     
    #!/usr/bin/env python
    import urllib
    import urllib2
    import json
    import time
    import hmac
    import hashlib
     
    class bittrex(object):
     
        def __init__(self, key, secret):
            self.key = key
            self.secret = secret
            self.public = ['getmarkets', 'getcurrencies', 'getticker', 'getmarketsummaries', 'getmarketsummary', 'getorderbook', 'getmarkethistory']
            self.market = ['buylimit', 'buymarket', 'selllimit', 'sellmarket', 'cancel', 'getopenorders']
            self.account = ['getbalances', 'getbalance', 'getdepositaddress', 'withdraw', 'getorder', 'getorderhistory', 'getwithdrawalhistory', 'getdeposithistory']
     
     
        def query(self, method, values={}):
            if method in self.public:
                url = 'https://bittrex.com/api/v1.1/public/'
            elif method in self.market:
                url = 'https://bittrex.com/api/v1.1/market/'
            elif method in self.account: 
                url = 'https://bittrex.com/api/v1.1/account/'
            else:
                return 'Something went wrong, sorry.'
     
            url += method + '?' + urllib.urlencode(values)
     
            if method not in self.public:
                url += '&apikey=' + self.key
                url += '&nonce=' + str(int(time.time()))
                signature = hmac.new(self.secret, url, hashlib.sha512).hexdigest()
                headers = {'apisign': signature}
            else:
                headers = {}
     
            req = urllib2.Request(url, headers=headers)
            response = json.loads(urllib2.urlopen(req).read())
     
            if response["result"]:
                return response["result"]
            else:
                return response["message"]
     
     
        def getmarkets(self):
            return self.query('getmarkets')
     
        def getcurrencies(self):
            return self.query('getcurrencies')
     
        def getticker(self, market):
            return self.query('getticker', {'market': market})
     
        def getmarketsummaries(self):
            return self.query('getmarketsummaries')
     
        def getmarketsummary(self, market):
            return self.query('getmarketsummary', {'market': market})
     
        def getorderbook(self, market, type, depth=20):
            return self.query('getorderbook', {'market': market, 'type': type, 'depth': depth})
     
        def getmarkethistory(self, market, count=20):
            return self.query('getmarkethistory', {'market': market, 'count': count})
     
        def buylimit(self, market, quantity, rate):
            return self.query('buylimit', {'market': market, 'quantity': quantity, 'rate': rate})
     
        def buymarket(self, market, quantity):
            return self.query('buymarket', {'market': market, 'quantity': quantity})
     
        def selllimit(self, market, quantity, rate):
            return self.query('selllimit', {'market': market, 'quantity': quantity, 'rate': rate})
     
        def sellmarket(self, market, quantity):
            return self.query('sellmarket', {'market': market, 'quantity': quantity})
     
        def cancel(self, uuid):
            return self.query('cancel', {'uuid': uuid})
     
        def getopenorders(self, market):
            return self.query('getopenorders', {'market': market})
     
        def getopenorders_special(self):
            return self.query('getopenorders')
     
        def getbalances(self):
            return self.query('getbalances')
     
        def getbalance(self, currency):
            return self.query('getbalance', {'currency': currency})
     
        def getdepositaddress(self, currency):
            return self.query('getdepositaddress', {'currency': currency})
     
        def withdraw(self, currency, quantity, address):
            return self.query('withdraw', {'currency': currency, 'quantity': quantity, 'address': address})
     
        def getorder(self, uuid):
            return self.query('getorder', {'uuid': uuid})
     
        def getorderhistory(self, market, count):
            return self.query('getorderhistory', {'market': market, 'count': count})
     
        def getwithdrawalhistory(self, currency, count):
            return self.query('getwithdrawalhistory', {'currency': currency, 'count': count})
     
        def getdeposithistory(self, currency, count):
            return self.query('getdeposithistory', {'currency': currency, 'count': count})
    Je vous remercie d'avance pour vos réponses

  2. #2
    Expert éminent sénior
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 287
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 287
    Points : 36 776
    Points
    36 776
    Par défaut
    Salut,

    Même réponse que pour le post précédent: fabriquez un code plus robuste ou simplifiez.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

Discussions similaires

  1. IndexError: list index out of range
    Par Ouled dans le forum Général Python
    Réponses: 2
    Dernier message: 25/05/2017, 18h58
  2. Tache cron IndexError: list index out of range
    Par rene2200 dans le forum Général Python
    Réponses: 3
    Dernier message: 20/11/2009, 14h02
  3. IndexError: string index out of range
    Par nina08 dans le forum Général Python
    Réponses: 2
    Dernier message: 04/08/2008, 09h27
  4. un impossible "list index out of range" alors que si !
    Par guiguizekid dans le forum Général Python
    Réponses: 3
    Dernier message: 18/05/2008, 04h04
  5. list index out of range
    Par watcha2020 dans le forum Général Python
    Réponses: 2
    Dernier message: 29/06/2006, 09h59

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo