I try get realtime data using https api but now i move on to websocket.
and it’s my https api using code look like:
class UpstoxService {
final String accessToken = "token";
final JsonService jsonService;
UpstoxService(this.jsonService);
Future<String?> getInstrumentKey(String tradingSymbol) async {
try {
final List<dynamic> data = await jsonService.loadJsonData();
for (var item in data) {
if (item['trading_symbol'] == tradingSymbol) {
return item['instrument_key'];
}
}
return 'null'; // Return null if no match is found
} catch (e) {
print("Error finding instrument key: $e");
return 'null';
}
}
Future<Map<String, String>> fetchStockData(String instrumentKey,String symbol) async {
final url = Uri.parse('https://api.upstox.com/v2/market-quote/quotes?instrument_key=$instrumentKey');
final headers = {
'Accept': 'application/json',
'Authorization': 'Bearer $accessToken',
};
final response = await http.get(url, headers: headers);
// print(response.statusCode);
// print("${response.statusCode}");
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
Map<String,String> extractData = formatData(data['data']["NSE_EQ:$symbol"]);
return extractData;
} else {
throw Exception('No data available');
}
}
Map<String, String> formatData(var data) {
double open = data['ohlc']!['open'];
String close = data['ohlc']!['close'].toString();
double netChange = data['net_change'];
String percentageChange = ((netChange/open)*100).toStringAsFixed(2);
return {
"currentPrice":close,
"percentageChange":"$percentageChange%",
"amountChange":netChange.toString(),
};
}
}
But How to get real-time stock data in using WebsocketChannel.
Get real time data using WebSocketChannel for upstox api into the flutter.
2
Answers
Your code thrown an error like this:
And my code looks like this:
First you need to add the web_socket_channel package,
Then you must modify your service :
I’m adding it as void main, you can integrate it into the UI section according to the state management method you use: