keeps disconnecting
Created at 18 May 2023, 12:57
CT
keeps disconnecting
18 May 2023, 12:57
I want to request the data every hour on the hour so that i can create some indicators and plac some buy and sell orders accordingly but t
it keeps disconnecting and saying
Disconnected: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionLost'>: Connection to the other side was lost in a non-clean fashion: Connection lost. ] my code is from twisted.internet import reactor import json import calendar import pandas as pd import numpy as np import pytz from datetime import datetime date= datetime.utcnow() - datetime(1970, 1, 1) seconds =(date.total_seconds()) milliseconds = round(seconds*1000) hourlyBars = [] credentialsFile = open("credentials-dev.json") credentials = json.load(credentialsFile) host = ( EndPoints.PROTOBUF_LIVE_HOST if credentials["HostType"].lower() == "live" else EndPoints.PROTOBUF_DEMO_HOST ) client = Client(host, EndPoints.PROTOBUF_PORT, TcpProtocol) symbolName = "BTCUSD" symbolId = 22395 def transformTrendbar(trendbar): utc_timestamp = trendbar.utcTimestampInMinutes * 60 open_time = datetime.fromtimestamp(utc_timestamp, pytz.utc) open_price = (trendbar.low + trendbar.deltaOpen) / 100000.0 high_price = (trendbar.low + trendbar.deltaHigh) / 100000.0 low_price = trendbar.low / 100000.0 close_price = (trendbar.low + trendbar.deltaClose) / 100000.0 return [open_time, open_price, high_price, low_price, close_price, trendbar.volume] def trendbarsResponseCallback(result): print("\nTrendbars received") trendbars = Protobuf.extract(result) barsData = list(map(transformTrendbar, trendbars.trendbar)) if not barsData: print("No trendbars data received.") return global hourlyBars hourlyBars.clear() hourlyBars.extend(barsData) print("\nhourlyBars length:", len(hourlyBars)) print("\nStopping reactor...") reactor.stop() # Print DataFrame df = pd.DataFrame(np.array(hourlyBars), columns=['Time', 'Open', 'High', 'Low', 'Close', 'Volume']) df["Open"] = pd.to_numeric(df["Open"]) df["High"] = pd.to_numeric(df["High"]) df["Low"] = pd.to_numeric(df["Low"]) df["Close"] = pd.to_numeric(df["Close"]) df["Volume"] = pd.to_numeric(df["Volume"]) print(df.tail()) def symbolsResponseCallback(result): print("\nSymbols received") symbols = Protobuf.extract(result) global symbolName symbolsFilterResult = list(filter(lambda symbol: symbol.symbolName == symbolName, symbols.symbol)) if len(symbolsFilterResult) == 0: raise Exception(f"There is no symbol that matches your defined symbol name: {symbolName}") elif len(symbolsFilterResult) > 1: raise Exception(f"More than one symbol matched your defined symbol name: {symbolName}, match result: {symbolsFilterResult}") symbol = symbolsFilterResult[0] request = ProtoOAGetTrendbarsReq() request.symbolId = symbolId request.ctidTraderAccountId = credentials["AccountId"] request.count = 100 request.period = ProtoOATrendbarPeriod.H1 # Set the period to hourly # We set the from/to time stamps to 50 weeks, you can load more data by sending multiple requests # Please check the ProtoOAGetTrendbarsReq documentation for more detail request.fromTimestamp = milliseconds - 360000000 request.toTimestamp = milliseconds deferred = client.send(request) deferred.addCallbacks(trendbarsResponseCallback, onError) def accountAuthResponseCallback(result): print("\nAccount authenticated") request = ProtoOASymbolsListReq() request.ctidTraderAccountId = credentials["AccountId"] request.includeArchivedSymbols = False deferred = client.send(request) deferred.addCallbacks(symbolsResponseCallback, onError) def applicationAuthResponseCallback(result): print("\nApplication authenticated") request = ProtoOAAccountAuthReq() request.ctidTraderAccountId = credentials["AccountId"] request.accessToken = credentials["AccessToken"] deferred = client.send(request) deferred.addCallbacks(accountAuthResponseCallback, onError) def onError(client, failure): # Callback for errors print("ERROR") print("\nMessage Error: ", failure) def disconnected(client, reason): # Callback for client disconnection print("\nDisconnected: ", reason) def onMessageReceived(client, message): # Callback for receiving all messages if message.payloadType in [ProtoHeartbeatEvent().payloadType, ProtoOAAccountAuthRes().payloadType, ProtoOAApplicationAuthRes().payloadType, ProtoOASymbolsListRes().payloadType, ProtoOAGetTrendbarsRes().payloadType]: return print("\nMessage received: \n", Protobuf.extract(message)) def connected(protocol): print("\nConnected") request = ProtoOAApplicationAuthReq() request.clientId = credentials["ClientId"] request.clientSecret = credentials["Secret"] deferred = protocol.send(request) deferred.addCallbacks(applicationAuthResponseCallback, onError) # Setting optional client callbacks client.setConnectedCallback(connected) client.setDisconnectedCallback(disconnected) client.setMessageReceivedCallback(onMessageReceived) # Starting the client service client.startService() print("running...") # Run Twisted reactor, we imported it earlier reactor.run()