skip to Main Content

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


  1. Chosen as BEST ANSWER

    Your code thrown an error like this:

    WebSocket error: WebSocketChannelException: Instance of 'WebSocketException'
    WebSocket closed
    Unhandled exception:
    WebSocketChannelException: Instance of 'WebSocketException'
    

    And my code looks like this:

    import 'dart:convert';
    import 'package:web_socket_channel/web_socket_channel.dart';
    
    class StockService {
      final String accessToken;
      final String instrumentKey;
      final String symbol;
    
      StockService({
        required this.accessToken,
        required this.instrumentKey,
        required this.symbol,
      });
    
      void startListening(void Function(Map<String, String>) onData) {
        final channel = WebSocketChannel.connect(
          Uri.parse('wss://api.upstox.com/websocket/market-quote/quotes?instrument_key=$instrumentKey'),
        );
    
        channel.sink.add(jsonEncode({
          'action': 'subscribe',
          'instrument_key': instrumentKey,
          'symbol': symbol,
          'Authorization': 'Bearer $accessToken',
        }));
    
        channel.stream.listen(
          (message) {
            var data = jsonDecode(message);
            if (data['data'] != null && data['data']["NSE_EQ:$symbol"] != null) {
              Map<String, String> extractData = formatData(data['data']["NSE_EQ:$symbol"]);
              onData(extractData);
            }
          },
          onDone: () {
            print('WebSocket closed');
          },
          onError: (error) {
            print('WebSocket error: $error');
          },
        );
      }
    
      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(),
        };
      }
    }
    
    void main() {
      final stockService = StockService(
        accessToken: "replace my actual access toke",
        instrumentKey: 'NSE_EQ|INE585B01010',
        symbol: 'MARUTI',
      );
    
      stockService.startListening((data) {
        print('Stock data: $data');
      });
    }
    

  2. First you need to add the web_socket_channel package,

    Then you must modify your service :

    import 'dart:convert';
    import 'package:web_socket_channel/web_socket_channel.dart';
    
    class StockService {
      final String accessToken;
      final String instrumentKey;
      final String symbol;
    
      StockService({
        required this.accessToken,
        required this.instrumentKey,
        required this.symbol,
      });
    
      void startListening(void Function(Map<String, String>) onData) {
        final channel = WebSocketChannel.connect(
          Uri.parse('wss://api.upstox.com/websocket/market-quote/quotes?instrument_key=$instrumentKey'),
        );
    
        channel.sink.add(jsonEncode({
          'action': 'subscribe',
          'instrument_key': instrumentKey,
          'symbol': symbol,
          'Authorization': 'Bearer $accessToken',
        }));
    
        channel.stream.listen(
          (message) {
            var data = jsonDecode(message);
            if (data['data'] != null && data['data']["NSE_EQ:$symbol"] != null) {
              Map<String, String> extractData = formatData(data['data']["NSE_EQ:$symbol"]);
              onData(extractData);
            }
          },
          onDone: () {
            print('WebSocket closed');
          },
          onError: (error) {
            print('WebSocket error: $error');
          },
        );
      }
    
      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(),
        };
      }
    }
    

    I’m adding it as void main, you can integrate it into the UI section according to the state management method you use:

    void main() {
      final stockService = StockService(
        accessToken: 'your_access_token',
        instrumentKey: 'your_instrument_key',
        symbol: 'your_symbol',
      );
    
      stockService.startListening((data) {
        print('Stock data: $data');
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search