Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

python - Creating a function from current source code "list comprehension"

Outcome 1 required:

The first batch of code below is in its working form. Please assist in creating a function " def Calculations():" inclusive of all the list calculations to return the same results with the static list. With the calculations in proper functions I will be able to refine the problem and might be able to move forward ...

Outcome 2 required for those that want to go in depth...: When I run the code on a live list that appends every x intervals it stalls the information feed. I believe it could be the creating of the appending lists in batches of increasing numbers... but I don't have a solution for it... Below is the working code...

I am getting my live data from Binance in a appending list of closes only for those who would like to test it in the live status... The data could be coming from any source , does not need to be Binance as long as its an appending list of closes in float format...

See code below...

import itertools

l = [16.329,16.331, 16.3705, 16.3965, 16.44, 16.4227, 16.4028, 16.37, 16.3829, 16.3482, 16.3614, 16.4191, 16.4008, 16.4048, 16.4076, 16.3724, 16.3599, 16.3872, 16.3794, 16.3528, 16.3886, 16.3904, 16.3815, 16.3864, 16.4254, 16.4411, 16.4151, 16.4338, 16.4212, 16.3819, 16.2857, 16.2703, 16.2408, 16.1938, 16.2038, 16.2035, 16.217, 16.2374, 16.2414, 16.2238, 16.1787, 16.2725, 16.2964, 16.3155, 16.238, 16.2149, 16.2992, 16.3568, 16.2793, 16.2467, 16.312, 16.3117, 16.3017, 16.3465, 16.3882, 16.3698, 16.307, 16.3328, 16.3311, 16.3466, 16.3382, 16.3703, 16.3502, 16.3661, 16.38, 16.3972, 16.4141, 16.393, 16.3769, 16.3683, 16.4136, 16.3774, 16.3709, 16.3179, 16.3019, 16.3149, 16.2838, 16.2689, 16.2602, 16.2679, 16.2921, 16.312, 16.3158, 16.3198, 16.2955, 16.303, 16.327, 16.356, 16.313, 16.3, 16.2806, 16.2634, 16.2856, 16.2702, 16.2136, 16.2782, 16.276, 16.2231, 16.2255, 16.1314, 16.0796, 16.1192, 16.0977, 16.1358, 16.1408, 16.1703]


####  VARIABLES & SETTINGS  ####
dataingestperiod = 17
original_list_count = len(l)
timeframed_list = l[-dataingestperiod:]
timeframed_list_count = len(timeframed_list)

def groupSequence(x): 
    it = iter(x) 
    prev, res = next(it), [] 
  
    while prev is not None: 
        start = next(it, None) 
  
        if start and start > prev: 
            res.append(prev) 
        elif res: 
            yield list(res + [prev]) 
            res = [] 
        prev = start 

def divbyZero(increasingcount,decreasingcount):
    try: return increasingcount/decreasingcount
    except ZeroDivisionError: return 0
    
def divbyZeroMain(increasingcountMain,decreasingcountMain):
    try: return increasingcountMain/decreasingcountMain
    except ZeroDivisionError: return 0


#### TIMEFRAMED LIST CALCULATIONS#####
listA_1 = (list(groupSequence(timeframed_list))) # obtain numbers in increasing sequence
# print(len(listA_1)) # number of increases in mixed format
listA = list(itertools.chain.from_iterable(listA_1)) # remove double brackets to enable list count
increasingcount = len(listA)
decreasingcount = timeframed_list_count - increasingcount
trend = divbyZero(increasingcount,decreasingcount)


#### MAIN APPENDING LIST CALCULATIONS #####
listMain_1 = (list(groupSequence(l)))
listMain = list(itertools.chain.from_iterable(listMain_1))
increasingcountMain = len(listMain)
decreasingcountMain = original_list_count - increasingcountMain
trendMain = divbyZeroMain(increasingcountMain,decreasingcountMain)

###Timeframed list increases-only appending to max last"dataingestperiod" perhaps problem on live feed data....###
increase_list_timeframed = []
for x in listA: 
        increase_list_timeframed.append(x)

### Main list increases only appending...####
increase_list_Main = []
for x in listMain: 
        increase_list_Main.append(x)


###Prints ON TIMEFRAMED LIST ####
print ("---------------")
print ("---------------")
print ("Timeframed list count set at max {}".format(timeframed_list_count))
print ("Count of decreases in timeframed list is {}".format(decreasingcount))
print ("Count of increases in timeframed list is {}".format(increasingcount))
print ("Current timeframed trend is {}".format(trend))
print ("---------------")
print ("---------------")


###Prints ON MAIN LIST ####
print ("Main appending list count so far is {}".format(original_list_count))
print ("Count of decreases in Main appending list is {}".format(decreasingcountMain))
print ("Count of increases in Main appending list is {}".format(increasingcountMain))
print ("Current Main trend is {}".format(trendMain))

The actual code as live to binance is listed below with the above code included. You also need to install "pip install python-binance" and "pip install websocket_client" got the binance access code from ParttimeLarry

Outcome 2 required: When run live that all calculations run uninterruptedly...

import itertools
import copy
import websocket, json, pprint, talib, numpy
from binance.client import Client
from binance.enums import *

#DATA FROM WEBSOCKETS########
SOCKET = "wss://stream.binance.com:9443/ws/linkusdt@kline_1m"


API_KEY = 'yourAPI_KEY'
API_SECRET ='yourAPI_Secret'

closes = []   # created for RSI indicator only using closes
in_position = False


client = Client(API_KEY, API_SECRET) # tld='us'

def order(side, quantity, symbol,order_type=ORDER_TYPE_MARKET):
    try:
        print("sending order")
        order = client.create_order(symbol=symbol, side=side, type=order_type, quantity=quantity)
        print(order)
    except Exception as e:
        print("an exception occured - {}".format(e))
        return False

    return True

    
def on_open(ws):
    print('opened connection')
   # start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
    # try:
    #     file = open("C:/GITPROJECTS/binance-bot/csvstats.txt","+a")
    #     file.write("New Session Open Connection Start at time {}
".format(datetime.datetime.now())))
    
    # finally:
    #     file.close()

def on_close(ws):
    print('closed connection')
   
def on_message(ws, message):
    global closes, in_position
    
    print('received message')
    json_message = json.loads(message)
    pprint.pprint(json_message)

    candle = json_message['k']

    is_candle_closed = candle['x']
    close = candle['c']
    
     
    if is_candle_closed:
        print("candle closed at {}".format(close))
        closes.append(float(close))
              
        print("closes")
        print(closes)
        
        
        
                  
####################################################################################
########CALCULATIONS ON INDICATORS #################################################        
        
        # dataingestperiod = 5
        l = copy.deepcopy(closes)
        maincountofcloses = len(l)
        print ("Total count of closes so far {}".format(maincountofcloses))
                    
        ####  VARIABLES & SETTINGS  ####
        l = copy.deepcopy(closes)        
        dataingestperiod = 3
        original_list_count = len(l)
        #print ("Main list count so far is {}".format(original_list_count))
        timeframed_list = l[-dataingestperiod:]
        timeframed_list_count = len(timeframed_list)
        #print ("Timeframed list count set at max {}".format(timeframed_list_count))


        def groupSequence(x):
            it = iter(x)
            prev, res = next(it), []
            
            while prev is not None:
                start = next(it, None)
                
                if start and start > prev:
                    res.append(prev) 
                
                elif res:
                    yield list(res + [prev]) 
                    res = [] 
                    prev = start 

        def divbyZero(increasingcount,decreasingcount):
            try: return increasingcount/decreasingcount
            except ZeroDivisionError: return 0
    
        def divbyZeroMain(increasingcountMain,decreasingcountMain):
            try: return increasingcountMain/decreasingcountMain
            except ZeroDivisionError: return 0


        #### TIMEFRAMED LIST CALCULATIONS#####
        listA_1 = (list(groupSequence(timeframed_list))) # obtain numbers in increasing sequence
        # print(len(listA_1)) # number of increases in mixed format
        listA = list(itertools.chain.from_iterable(listA_1)) # remove double brackets to enable list count
        increasingcount = len(listA)
        decreasingcount = timeframed_list_count - increasingcount
        trend = divbyZero(increasingcount,decreasingcount)
        

        #### MAIN APPENDING LIST CALCULATIONS #####
        listMain_1 = (list(groupSequence(l)))
        listMain = list(itertools.chain.from_iterable(listMain_1))
        increasingcountMain = len(listMain)
        decreasingcountMain = original_list_count - increasingcountMain
        trendMain = divbyZeroMain(increasingcountMain,decreasingcountMain)
        

        increase_list_timeframed = []

        for x in listA: 
                increase_list_timeframed.append(x)

      
        increase_list_Main = []
        for x in listMain: 
                increase_list_Main.append(x)

        ###Prints ON TIMEFRAMED LIST ####
        print ("---------------")
        print ("---------------")
        print ("Timeframed list count set at max {}".format(timeframed_list_count))
        print ("Count of decreases in timeframed list is {}".format(decreasingcount))
        print ("Count of increases in timeframed list is {}".format(increasingcount))
        print ("Current timeframed trend is {}".format(trend))
        print ("---------------")
        print ("---------------")

        ###Prints ON MAIN LIST ####
        print ("Main appending list count so far is {}".format(original_list_count))
        print ("Count of decreases in Main appending list is {}".format(decreasingcountMain))
        print ("Count of increases in Main appending list is {}".format(increasingcountMain))
        print ("Current Main trend is {}".format(trendMain))
        # threading.Timer(10.0, divbyZeroMain).start()         
        # threading.Timer(10.0, divbyZero).start()            
                 
                 
# ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)
# ws.run_forever()
ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)
ws.run_forever()

question from:https://stackoverflow.com/questions/65859053/creating-a-function-from-current-source-code-list-comprehension

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...