Skip to content

Instantly share code, notes, and snippets.

@NVentimiglia
Created May 4, 2021 00:44
Show Gist options
  • Save NVentimiglia/15a0d66fd61e12e55cc9bd38c902460c to your computer and use it in GitHub Desktop.
Save NVentimiglia/15a0d66fd61e12e55cc9bd38c902460c to your computer and use it in GitHub Desktop.
TDAmeritrade SignIn Unity3d / DotNet / C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using UnityEngine;
using UnityEngine.Networking;
namespace TDAmeritrade
{
[Serializable]
public class SignInResult
{
public string security_code;
public string access_token;
public string refresh_token;
public string scope;
public int expires_in;
public int refresh_token_expires_in;
public string token_type;
}
/// <summary>
/// https://www.reddit.com/r/algotrading/comments/c81vzq/td_ameritrade_api_access_2019_guide/
/// https://www.reddit.com/r/algotrading/comments/914q22/successful_access_to_td_ameritrade_api/
/// </summary>
public class TDClientAlpha : MonoBehaviour
{
public string ConsumerKey = "";
public string RedirectUri = "http://localhost";
[Header("Paste from code={code} address bar result in step 1")]
public string SecurityCode = "";
public SignInResult Result;
private void Awake()
{
SecurityCode = string.Empty;
Load();
}
private void Load()
{
Result = JsonUtility.FromJson<SignInResult>(PlayerPrefs.GetString("TDClientAlpha.SignInResult"));
}
private void Save()
{
var json = JsonUtility.ToJson(Result);
PlayerPrefs.SetString("TDClientAlpha.SignInResult", json);
PlayerPrefs.Save();
}
[ContextMenu("1 StartSignIn")]
public void StartSignIn()
{
var encodedKey = HttpUtility.UrlEncode(ConsumerKey);
var encodedUri = HttpUtility.UrlEncode(RedirectUri);
var path = $"https://auth.tdameritrade.com/auth?response_type=code&redirect_uri={encodedUri}&client_id={encodedKey}%40AMER.OAUTHAP";
Application.OpenURL(path);
}
[ContextMenu("2 CompleteSignIn")]
public void CompleteSignIn()
{
StartCoroutine(CompleteSignInAsync());
}
IEnumerator CompleteSignInAsync()
{
var decoded = HttpUtility.UrlDecode(SecurityCode);
var path = "https://api.tdameritrade.com/v1/oauth2/token";
WWWForm form = new WWWForm();
form.AddField("grant_type", "authorization_code");
form.AddField("access_type", "offline");
form.AddField("client_id", $"{ConsumerKey}@AMER.OAUTHAP");
form.AddField("redirect_uri", RedirectUri);
form.AddField("code", decoded);
var webRequest = UnityWebRequest.Post(path, form);
yield return webRequest.SendWebRequest();
switch (webRequest.result)
{
case UnityWebRequest.Result.ConnectionError:
case UnityWebRequest.Result.DataProcessingError:
Debug.LogError("Error: " + webRequest.error);
break;
case UnityWebRequest.Result.ProtocolError:
Debug.LogError("HTTP Error: " + webRequest.error);
break;
case UnityWebRequest.Result.Success:
var r = webRequest.downloadHandler.text;
Debug.Log(r);
Debug.LogWarning("HTTP Success, Received Access Token");
Result = JsonUtility.FromJson<SignInResult>(r);
Result.security_code = SecurityCode;
Save();
break;
}
}
[ContextMenu("3 RefreshSignIn")]
public void RefreshSignIn()
{
StartCoroutine(RefreshSignInAsync());
}
IEnumerator RefreshSignInAsync()
{
var decoded = HttpUtility.UrlDecode(Result.security_code);
var path = "https://api.tdameritrade.com/v1/oauth2/token";
WWWForm form = new WWWForm();
form.AddField("grant_type", "refresh_token");
form.AddField("access_type", "");
form.AddField("client_id", $"{ConsumerKey}@AMER.OAUTHAP");
form.AddField("redirect_uri", RedirectUri);
form.AddField("refresh_token", Result.refresh_token);
form.AddField("code", decoded);
var webRequest = UnityWebRequest.Post(path, form);
yield return webRequest.SendWebRequest();
switch (webRequest.result)
{
case UnityWebRequest.Result.ConnectionError:
case UnityWebRequest.Result.DataProcessingError:
Debug.LogError("Error: " + webRequest.error);
break;
case UnityWebRequest.Result.ProtocolError:
Debug.LogError("HTTP Error: " + webRequest.error);
break;
case UnityWebRequest.Result.Success:
var r = webRequest.downloadHandler.text;
Debug.Log(r);
var better = JsonUtility.FromJson<SignInResult>(r);
Result.access_token = better.access_token;
Save();
Debug.LogWarning("HTTP Success, Refreshed Access Token");
break;
}
}
[ContextMenu("GetQuote")]
public void GetQuote()
{
StartCoroutine(GetQuoteAsync());
}
IEnumerator GetQuoteAsync()
{
var symbol = "SPY";
var key = HttpUtility.UrlEncode(ConsumerKey);
var path = $"https://api.tdameritrade.com/v1/marketdata/{symbol}/quotes?apikey={key}";
var webRequest = UnityWebRequest.Get(path);
yield return webRequest.SendWebRequest();
switch (webRequest.result)
{
case UnityWebRequest.Result.ConnectionError:
case UnityWebRequest.Result.DataProcessingError:
Debug.LogError("Error: " + webRequest.error);
break;
case UnityWebRequest.Result.ProtocolError:
Debug.LogError("HTTP Error: " + webRequest.error);
break;
case UnityWebRequest.Result.Success:
var r = webRequest.downloadHandler.text;
Debug.Log(r);
Debug.LogWarning("HTTP Success, GetQuote");
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment