首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TD Ameritrade .NET

TD Ameritrade .NET
EN

Stack Overflow用户
提问于 2020-04-25 06:25:45
回答 5查看 3.7K关注 0票数 2

有没有人让TD美国流媒体API与C#一起工作?这里有一些文档和JavaScript示例,https://developer.tdameritrade.com/content/streaming-data。我已经让JavaScript示例在https://js.do/上工作,但是无法获得任何类似于在.NET中工作的东西,这是我想要做的一个简短的版本。我不能确切地包括我发送的内容,因为我试图发送包含帐户信息的登录消息,但我可以说,我复制并粘贴了在我的JavaScript测试中工作的确切JSON消息到本例中的文件LoginJSON.txt中。在本例中,套接字将在我发送消息后立即关闭,根本没有文本响应。但是,如果我发送一条故意设置错误格式的消息,我实际上会得到文本响应,表示消息格式不正确,然后得到一个套接字断开连接。他们的支持一直没有反应,我理解这是正常的。这里有一些python示例,https://www.youtube.com/channel/UCBsTB02yO0QGwtlfiv5m25Q,但是我已经看过它们了,但是我还没有学到任何东西来帮助我的代码工作。

代码语言:javascript
复制
        ClientWebSocket socket = new ClientWebSocket();
        var connectAsync = socket.ConnectAsync(new Uri("wss://streamer-ws.tdameritrade.com/ws"), CancellationToken.None);
        string loginRequest;
        using (StreamReader re = new StreamReader("LoginJSON.txt")) {
            loginRequest = re.ReadToEnd();
        }

        connectAsync.Wait();

        Thread readThread = new Thread(
            delegate(object obj)
            {
                while (true) {
                    if (socket.State == WebSocketState.Open) {
                        Console.Out.WriteLine("Waiting");
                        byte[] recBytes = new byte[1024];
                        var clientBuffer = new ArraySegment<byte>(recBytes);
                        var receiveAsync = socket.ReceiveAsync(clientBuffer, CancellationToken.None);
                        receiveAsync.Wait();
                        switch (receiveAsync.Result.MessageType) {
                            case WebSocketMessageType.Text:
                                var s = Encoding.UTF8.GetString(recBytes);
                                Console.Out.WriteLine(s.Trim());
                                break;
                            case WebSocketMessageType.Close:
                                Console.Out.WriteLine("Close message received");
                                break;
                            default:
                                throw new ArgumentOutOfRangeException();
                        }
                    }
                }
            });

        readThread.Start();
        socket.SendAsync(Encoding.UTF8.GetBytes(loginRequest), WebSocketMessageType.Text, true, CancellationToken.None);
        Console.ReadLine();
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2020-05-22 23:30:09

我尝试了WebSocketClient方法,但始终没有成功。我和你犯的错误完全一样。一点儿没错。我发现WebSocketClient实际上使在javascript中实现非常简单的内容变得复杂。只需让您的C#调用一个javascript函数来执行javascript并将响应发送回您。我已经让它的工作方式,使用C#在一个Blazor应用程序,它的无缝工作。

票数 0
EN

Stack Overflow用户

发布于 2020-06-23 12:59:44

我面临着同样的问题,我设法解决了这个问题。在我的示例中,时间戳没有正确准备,因此需要计算时间戳才能得到TokenTimestamp属性,应该将其转换为通用时间。抱歉,我的英语来自谷歌翻译公司。)这是正确的代码:

代码语言:javascript
复制
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime tokenDate = Convert.ToDateTime(userPrincipal.StreamerInfo.TokenTimestamp);
TimeSpan tokenEpoch = tokenDate.ToUniversalTime() - epoch;
long timestamp = (long)Math.Floor(tokenEpoch.TotalMilliseconds);

var credentials = new Credentials
{
    userid = userPrincipal.Accounts[0].AccountId,
    token = userPrincipal.StreamerInfo.Token,
    company = userPrincipal.Accounts[0].Company,
    segment = userPrincipal.Accounts[0].Segment,
    cddomain = userPrincipal.Accounts[0].AccountCdDomainId,
    usergroup = userPrincipal.StreamerInfo.UserGroup,
    accesslevel = userPrincipal.StreamerInfo.AccessLevel,
    authorized = "Y",
    timestamp = timestamp,
    appid = userPrincipal.StreamerInfo.AppId,
    acl = userPrincipal.StreamerInfo.Acl
};
var credentialArr = credentials.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Select(p => new KeyValuePair<string, string>(p.Name, p.GetValue(credentials, null).ToString()));
var loginRequest = new Request
{
    service = "ADMIN",
    command = "LOGIN",
    requestid = "0",
    account = userPrincipal.Accounts[0].AccountId,
    source = userPrincipal.StreamerInfo.AppId,
    parameters = new Parameters
    {
        credential = string.Join("&", credentialArr.Where(c => !string.IsNullOrWhiteSpace(c.Value)).Select(c => string.Format("{0}={1}", HttpUtility.UrlEncode(c.Key, Encoding.UTF8), HttpUtility.UrlEncode(c.Value, Encoding.UTF8)))),
        token = userPrincipal.StreamerInfo.Token,
        version = "1.0",
        qoslevel = "0"
    }
};
var req = JsonConvert.SerializeObject(Requests.ToRequests(loginRequest), Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
socketClient = new WebSocket(string.Format("wss://{0}/ws", userPrincipal.StreamerInfo.StreamerSocketUrl));
if(Environment.OSVersion.Version.Major > 5)
{
    socketClient.SslConfiguration.EnabledSslProtocols = (System.Security.Authentication.SslProtocols)3072;
    socketClient.SslConfiguration.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
}
socketClient.Connect();
socketClient.Send(req);
票数 2
EN

Stack Overflow用户

发布于 2021-05-19 21:00:19

@Mikhail,您能分享一下获取用户主体的代码吗?这是我的代码,但我得到了status=401,即使我的访问令牌是有效的(我已经通过API页面测试了它):

代码语言:javascript
复制
    using System;
    using WebSocketSharp;
    using System.Net.Http;
    using System.Threading.Tasks;

namespace TdLogin
{
    class Program
    {
        static async Task  Main(string[] args)
        {
            string accessToken = util.accessToken; // get the access token from util 
            Console.WriteLine("Hello World!");
            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accessToken);
            var result = await client.GetAsync("https://api.tdamer`enter code here`itrade.com/v1/userprincipals?fields=streamerSubscriptionKeys%2CstreamerConnectionInfo");
            Console.WriteLine("status= {0}", result.StatusCode);
            Console.WriteLine(result.Content);
            Console.ReadKey();
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61421801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档