B4J Code Snippet Get Stock Data

All,

B4J NON-UI application snippet to get stock data from Yahoo Finance using HTTP and JSON.

Example Result for YHOO
B4X:
LastTradePrice: 36.61
LastTradeTime: 1:02pm
Change: -0.22
ChangeinPercent: -0.60%

B4J Code
B4X:
Sub Process_Globals
   Private StockIndicator As String
End Sub

Sub AppStart (Args() As String)
  If Args.Length = 0 Then
    Log("Abort: Argument missing. Example Yahoo: YHOO")
    ExitApplication2(1)
  End If
  StockIndicator = Args(0).ToUpperCase
  Dim url As String = $"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22${StockIndicator}%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="$
  Dim j As HttpJob
  j.Initialize("j", Me)
  j.Download(url)
  StartMessageLoop
End Sub

Sub JobDone(Job As HttpJob)
   If Job.Success Then
     Dim parser As JSONParser
     parser.Initialize(Job.GetString)
     Dim root As Map = parser.NextObject
     Dim qquery As Map = root.Get("query")
     Dim qresults As Map = qquery.Get("results")
     Dim qquote As Map = qresults.Get("quote")
     Log($"LastTradePrice: ${qquote.Get("LastTradePriceOnly")}"$)
     Log($"LastTradeTime: ${qquote.Get("LastTradeTime")}"$)
     Log($"Change: ${qquote.Get("Change")}"$)
     Log($"ChangeinPercent: ${qquote.Get("ChangeinPercent")}"$)
   Else
     Log("Error: " & Job.ErrorMessage)
   End If
   Job.Release
   ExitApplication2(0)
End Sub
 

Attachments

  • B4JHowToStockData.zip
    4.3 KB · Views: 474
Top