Running code separately to collect live stock data from API WebSocket to provide it to main code in Python

54 views Asked by At

I have a code which has a loop which collects data from API WebSocket continuously, after end of the time set for a timeframe, like 1-minute, 3-minute, 5-minute etc. After collecting data, it is sorted for open, high, low after that condition is checked for the next action, after completing the action, control goes back to the loop which collects the data. My problem is, while processing the data for sorting and condition-check, there is a fraction loss of time which causes errors, some data is missed. How to avoid this? Will it help if I have a separate module which can be accessed by a different module which does data-sorting and checks for condition. How to do this?

def ohlc(checkInstrument,timeframe):
    global Call
    global Put
    global sl
    global target
    global CallBuyValue
    global PutBuyValue
    global ADXatCallBuy
    global ADXatPutBuy
    global first
    global exitTimeCall
    global exitTimePut
    global flag
    global wait
    date=pd.to_datetime(datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S'))
    while(str(date)[-2::]!='00' and first == 0):
        date=pd.to_datetime(datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S'))
        print(date)
    first=1
    date=date+timedelta(minutes=timeframe)
    sec = date.second
    if(sec > 0):
        date = date-timedelta(seconds=sec)
    print(date)
    l=[]
    while(pd.to_datetime(datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S'))<date):
        x=getLTP("NSE", checkInstrument)
        # time.sleep(1)
        if(Call==1 and Put==0 and wait == 0):
            if (sl>=x):
                print("x : ", x)
                print("Stop loss hit")
                oidexit=exitPosition(tradeCEoption)
                CallBuyValue=0
                target=0
                sl=0
                Call=0
                flag=0
                wait=1
            elif (x>target):
                sl=CallBuyValue
                CallBuyValue=target
                target = target + 14
                print("New Target :", target)
                print("New Stop Loss: ", sl)
                print("New Trailing Stop Loss :", CallBuyValue)
        elif(Put==1 and Call==0 and wait == 0):
            if(sl<=x):
                print("x : ", x)
                print("Stop loss hit")
                oidexit=exitPosition(tradePEoption)
                PutBuyValue=0
                target=0
                sl=0
                Put=0
                flag=0
                wait=1
            elif(x<=target):
                sl=PutBuyValue
                PutBuyValue=target
                target = target - 14
                print("Target :", target)
                print("Stop Loss: ", sl)
                print("Trailing Stop Loss :", PutBuyValue)
        if x!=-1:
            print(x)
            l.append(x)

This is the code block which collects data in a loop through API websocket, it also checks for stop loss and target and after the time end reaches the control goes to condition to check for next action like whether to buy a call or a put.

while z == 1:
    #global x
    data=ohlc(checkInstrument,1)  #[9:20, 17000, 17870, 16780, 17220] timeframe
    dt1 = datetime.now()
    print(dt1)
    print(StopEntryTime)
    if data[0]!=-1:
        opens.append(data[1])
        high.append(data[2])
        low.append(data[3])
        close.append(data[-1])
        ttime.append(data[0])
        st=''
        if op!=[]:
            #if op[0]=='sma':
            value=ta.trend.SMAIndicator(pd.Series(close),op[1]).sma_indicator().iloc[-1]
            value1=ta.trend.ADXIndicator(pd.Series(high), pd.Series(low), pd.Series(close), op[2], False).adx().iloc[-1]
            value2[0]=ta.trend.ADXIndicator(pd.Series(high), pd.Series(low), pd.Series(close), op[2], False).adx().iloc[-2]
            value2[1]=ta.trend.ADXIndicator(pd.Series(high), pd.Series(low), pd.Series(close), op[2], False).adx().iloc [-3]
            value2[2]=ta.trend.ADXIndicator(pd.Series(high), pd.Series(low), pd.Series(close), op[2], False).adx().iloc[-4]
            if value!=0 and value1!=0 and wait==0:
                if value1 > 42 and value1 > value2[0]+2 and value < close[-1] and close[-1] > close[-2]+5 and Call==0 and Put == 0 and close[-1] > opens[-1]+5.5 and dt1 <= StopEntryTime:# and opens[-1] < close[-2]+50 and opens[-2] < close[-3]+50 and opens[-3] < close[-4]+50:
                    oidentry = findStrikePriceATM('NIFTY','CE')
                    Call=1
                    CallBuyValue=close[-1]
                    target = CallBuyValue + 1
                    sl = CallBuyValue - 24
                    print("set sl: ",sl)
                    print("set target: ",target)
                    print("ADX :", value1)
                    print("ADX -2 :", value2[1])
                    flag=1
                if value1 > 42 and value1 > value2[0]+2 and value > close[-1] and close[-1] < close[-2]-5 and Put==0 and Call == 0 and opens[-1]-5.5 > close[-1] and dt1 <= StopEntryTime:# and opens[-1] > close[-2]-50 and opens[-2 ] > close[-3]-50 and opens[-3] > close[-4]-50:
                    oidentry = findStrikePriceATM('NIFTY','PE')
                    Put=1
                    PutBuyValue = close[-1]
                    sl = PutBuyValue + 24
                    target = PutBuyValue - 1
                    print("set sl: ",sl)
                    print("set target: ",target)
                    print("ADX :", value1)
                    print("ADX -2 :", value2[1])
                    flag=0
        data.append(value)
        if (dt1 >= closeTime):
            if Call == 1:
                print("EOD.")
                #Exit Position
                oidexit = exitPosition(tradeCEoption)
            elif Put == 1:
                print("EOD.")
                #Exit position
                oidexit = exitPosition(tradePEoption)
            print('End Of the Day')
            z = 2
            break
    wait=0

This is the block which calsl the earlier block (OHLC Function) and decides whether Call should be bought, Put should be bought or no action. Now as the control gos to-fro some data is missed out. Today I missed a spike which caused error in the output. How to separate data collection and provider as well separately? I want to have stop loss and target on live data though.

0

There are 0 answers