Search code examples
jsonf#binancetype-providers

Using JsonProvider from Fsharp.Data for Binance-Request


I'm trying to work with the Binance-Connector for .NET. In the F#-Examples, we have the following:

let f = 
    let loggerFactory = LoggerFactory.Create(fun (builder:ILoggingBuilder) -> 
        builder.AddConsole() |> ignore
    )
    let logger = loggerFactory.CreateLogger()

    let loggingHandler = new BinanceLoggingHandler(logger)
    let httpClient = new HttpClient(loggingHandler)
    
    let market = new Market(httpClient)
    
    let result = market.TwentyFourHrTickerPriceChangeStatistics() |> Async.AwaitTask |> Async.RunSynchronously

    0

result is a string and looks something like this:

{"symbol":"ETHBTC","priceChange":"0.00013400","priceChangePercent":"0.179","weightedAvgPrice":"0.07444089","prevClosePrice":"0.07467300","lastPrice":"0.07480700","lastQty":"0.04640000","bidPrice":"0.07480600","bidQty":"6.01380000","askPrice":"0.07480700","askQty":"48.54320000","openPrice":"0.07467300","highPrice":"0.07531600","lowPrice":"0.07357000","volume":"80296.33090000","quoteVolume":"5977.33041290","openTime":1650281947747,"closeTime":1650368347747,"firstId":335177449,"lastId":335313233,"count":135785}

This works as intended, but of course I want to work with the result. So I tried to deserialize it with the JsonProvider:

   type Simple = JsonProvider<result>

Which for some reason doesn't work. The error resides with and it says that the Constructor or value is not defined (FS0039) A sample in the docs for JsonProvider is given as follows:

type Simple = JsonProvider<""" { "name":"John", "age":94 } """>
let simple = Simple.Parse(""" { "name":"Tomas", "age":4 } """)
simple.Age
simple.Name

How can I correctly cast the json to a type?

Best regards


Solution

  • JsonProvider<...> takes a static string parameter which is either a sample string or a sample file (local or online accessible) in order to let the provider infer the types from it.

    So in your case it would be:

    let [<Literal>] BinanceSample = """ [{"symbol":"ETHBTC","priceChange":"-0.00163000"}] """
    
    type Binance = JsonProvider<BinanceSample>
    

    Then you should be able to parse the JSON with:

    let parsed = Binance.Parse(result)
    

    PS: try to provide a JSON sample that is as complete as possible.