все значения данных, показывающие ноль после обновления через webscoket из API брокера в python print содержат 0,0,0,0,0 - PullRequest
0 голосов
/ 02 мая 2020
 import time,os,datetime,math
 from time import sleep
 import logging
 from alice_blue import *
 import pandas as pd

 username = "AAAAAA"
 password = "AAAAAAA"
 api_secret = "AAAAAAA"
 twoFA = "AAAAAA"

access_token=
AliceBlue.login_and_get_access_token(username=username,password=password,twoFA=twoFA,api_se 
cret=api_secret)
alice = 
AliceBlue(username=username,password=password,access_token=access_token,master_contracts_to_download= 
['NSE'])

print("Master contract loaded succesfully")
print("\n")

print("Getting Profile Details ")
print("\n")
profile = alice.get_profile()
profile_data=(profile['data'])
exchange = profile_data['exchanges']
print("Name: ",profile_data['name']," Client Id: ",profile_data['login_id']," Pan card: ",profile_data["pan_number"],"Exchange : ",exchange[1])
print("\n")
balance = alice.get_balance()
balance_data = balance['data']
cash_position = balance_data['cash_positions']
print("Balance available is : ",cash_position[0]['utilized']['var_margin'])

print("Wait for breakout Time\n")

socket_opened = False
token = 0
open_price=0
high_price=0
low_price=0
close_price=0

def event_handler_quote_update(message):
    global token
    global open_price
    global high_price
    global close_price
    global low_price
    token = message['token']
    open_price = message['open']
    high_price = message['high']
    low_price = message['low']
    close_price = message['close']
def open_callback():
    global socket_opened
    socket_opened = True

alice.start_websocket(subscribe_callback=event_handler_quote_update,
                  socket_open_callback=open_callback,
                  run_in_background=True)
while(socket_opened==False):
    pass
alice.subscribe(alice.get_instrument_by_symbol("NSE","ONGC"), LiveFeedType.FULL_SNAPQUOTE)
print(token,open_price,high_price,low_price,close_price)
sleep(10)

Пожалуйста, кто-нибудь, помогите, я новичок в python и трейдинге al go. Я ожидаю обновления значения от websocket и печати, но он не может обновлять и печатать одно и то же. Пожалуйста, помогите кому-нибудь. Это alice blue api для индийского фондового рынка, который помогает в торговле go. Все работает нормально, кроме обновленных данных

1 Ответ

1 голос
/ 02 мая 2020

Попробуйте заснуть прямо за подпиской. Это похоже на асинхронный вызов, и ваша функция обратного вызова, вероятно, срабатывает после того, как вы напечатаете результаты.

Вы уверены, что ваш сон находится в правильной строке?

Редактировать:

Возможно, вам следует просто использовать класс queue.Queue. Я надеюсь, что это решит вашу проблему. Вы можете использовать Очередь просто как обычный список. Например:

from concurrent.futures import ThreadPoolExecutor
from queue import Queue
from time import sleep

def write_in_Queue(some_message, seconds):
    print("Wait {} seconds".format(seconds))
    sleep(seconds)
    queue.put(some_message)
    print('message put into Queue')

if __name__ == "__main__":
    queue = Queue()
    threadpool = ThreadPoolExecutor()
    threadpool.submit(write_in_Queue, "Hallo", 2)
    threadpool.submit(write_in_Queue, "End", 4)

    print("Waiting for first message")
    message_1 = queue.get()
    print("Wait for second message")
    message_2 = queue.get()
    print(message_2)
    print("Finish this thread")

Вы получите вывод:

Wait 2 seconds
Wait 4 seconds
 Waiting for first message
message put into Queue
Wait for second message
message put into Queue
End
Finish this thread

queue.get позаботится о том, чтобы вы подождали, пока что-то будет записано в очередь. Я пытался решить эту проблему с помощью библиотеки Asyncio, но не смог найти решение, чтобы получить эту работу так быстро.

Вы просто пишете свои сообщения в очередь. Надеюсь, это поможет.

...