public static IRestResponse GetRequest(string target, string call, params Parameter [] parameters) { RestManager rest_man = privInstance; lock (rest_man) { string endpoint = string.Format("{0}/{1}/{2}", target, rest_man.ApiEnv, call); RestRequest request = new RestRequest(endpoint, Method.GET); request.RequestFormat = DataFormat.Json; request.Parameters.AddRange(parameters); request.Parameters.Add(GetRequestId()); request.AddHeader("Authorization", rest_man.AccessToken); request.AddHeader("x-api-key", rest_man.AppKey); if (privInstance.m_nextRequest > DateTime.Now) { Thread.Sleep(privInstance.m_nextRequest - DateTime.Now); } var response = rest_man.Client.Execute(request); privInstance.m_nextRequest = DateTime.Now + RestManager.MinSpace; LogRequest(request, response); return(response); } }
private static void LogRequest(RestRequest request, RestSharp.IRestResponse result) { RestManager rest_man = privInstance; string log_message = String.Format("{0} - {1} {2}", result.StatusCode.ToString(), request.Method.ToString(), rest_man.Client.BuildUri(request)); FDLog.LogRequest(log_message); }
public static void Init(string app_key, string secret_key, string api_env, string api_url = "https://apigateway.trade.tt/") { RestManager rest_man = privInstance; lock (rest_man) { rest_man.AppKey = app_key; rest_man.SecretKey = secret_key; rest_man.ApiEnv = api_env; rest_man.ApiURL = api_url; rest_man.Client = new RestClient(rest_man.ApiURL); try { TimeSpan renewal_time = RefreshToken() - new TimeSpan(1, 0, 0); renewal_time = new TimeSpan(0, 0, 0, 10); rest_man.TokenTimer = new Timer(TokenTimerHandler, rest_man, renewal_time, renewal_time); } catch (Exception) { // Login errors can be ignored during initialization // to allow the user to attempt to log in again } } }
private static TT_User RequestUser(string user_id) { var result = RestManager.GetRequest("risk", "user/" + user_id); UserResponse usr = JsonConvert.DeserializeObject <UserResponse>(result.Content); return(usr.user[0]); }
private void DownloadFills() { // Perform REST request/response to download fill data, specifying our cached minimum timestamp as a starting point. // On a successful response the timestamp will be updated so we run no risk of downloading duplicate fills. List <TT_Fill> fills = new List <TT_Fill>(); do { var min_param = new RestSharp.Parameter("minTimestamp", TT_Info.ToRestTimestamp(m_minTimeStamp).ToString(), RestSharp.ParameterType.QueryString); RestSharp.IRestResponse result = RestManager.GetRequest("ledger", "fills", min_param); if (result.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception("Request for fills unsuccessful. Status:" + result.StatusCode.ToString() + "Error Message: " + result.ErrorMessage); } JObject json_data = JObject.Parse(result.Content); foreach (var fill in json_data["fills"]) { fills.Add(new TT_Fill(fill)); } fills.Sort((f1, f2) => f1.UtcTimeStamp.CompareTo(f2.UtcTimeStamp)); RaiseFillDownloadEvent(fills); if (fills.Count > 0 && m_running) { m_minTimeStamp = new DateTime(fills[fills.Count - 1].UtcTimeStamp.Ticks + 1); } }while (fills.Count == TT_Info.MAX_RESPONSE_FILLS); }
private static void GetProductData() { var result = RestManager.GetRequest("ttpds", "productdata"); ProductData product_data = JsonConvert.DeserializeObject <ProductData>(result.Content); if (product_data.productTypes != null) { privInstance.dicts.Add("productTypes", CreateDictionary(product_data.productTypes)); } else { throw new Exception("GET ProductData request failed" + Environment.NewLine + result.Content.ToString()); } }
private static void GetMarkets() { var result = RestManager.GetRequest("ttpds", "markets"); TTMarkets markets = JsonConvert.DeserializeObject <TTMarkets>(result.Content); if (markets.Markets != null) { privInstance.dicts.Add("markets", CreateDictionary(markets.Markets)); } else { throw new Exception("GET Market request failed" + Environment.NewLine + result.Content.ToString()); } }
private static void TokenTimerHandler(Object state_info) { RestManager rest_man = (RestManager)state_info; try { TimeSpan renewal_time = RefreshToken() - new TimeSpan(1, 0, 0); rest_man.TokenTimer.Change(renewal_time, renewal_time); } catch (Exception e) { rest_man.TokenTimer.Change(Timeout.Infinite, Timeout.Infinite); RaiseTokenError(e.Message); } }
public static TimeSpan RefreshToken() { RestManager rest_man = privInstance; lock (rest_man) { string endpoint = string.Format("{0}/{1}/{2}", "ttid", rest_man.ApiEnv, "token"); RestRequest request = new RestRequest(endpoint, Method.POST); request.RequestFormat = DataFormat.Json; request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddHeader("x-api-key", rest_man.AppKey); request.AddHeader("Accept", "application/json"); request.AddParameter("grant_type", "user_app"); request.AddParameter("app_key", rest_man.SecretKey); request.AddParameter(GetRequestId()); var response = rest_man.Client.Execute(request); var content = response.Content; LogRequest(request, response); if (response.StatusCode == System.Net.HttpStatusCode.OK) { RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer(); var dict_response = deserial.Deserialize <Dictionary <string, string> >(response); if (dict_response["status"] == "Ok") { rest_man.AccessToken = "Bearer " + dict_response["access_token"]; return(new TimeSpan(0, 0, int.Parse(dict_response["seconds_until_expiry"]))); } else { string err_msg = "Error, POST request for token failed: " + dict_response["status_message"]; FDLog.LogError(err_msg); throw new Exception(err_msg); } } else { string err_msg = "Error, POST request for token failed: " + response.ErrorMessage; FDLog.LogError(err_msg); throw new Exception(err_msg); } } }
private static TT_Account RequestAccount(string account_id) { var result = RestManager.GetRequest("risk", "account/" + account_id); try { AccountResponse acct = JsonConvert.DeserializeObject <AccountResponse>(result.Content); return(acct.account[0]); } catch (Exception) { TT_Account acct = new TT_Account(); acct.id = account_id; acct.name = "PLACEHOLDER"; return(acct); } }
private static void GetInstrumentData() { var result = RestManager.GetRequest("ttpds", "instrumentdata"); InstrumentData instrument_data = JsonConvert.DeserializeObject <InstrumentData>(result.Content); if (instrument_data.optionCodes != null && instrument_data.optionSchemes != null && instrument_data.seriesTerms != null && instrument_data.comboTypes != null) { privInstance.dicts.Add("optionCodes", CreateDictionary(instrument_data.optionCodes)); privInstance.dicts.Add("optionSchemes", CreateDictionary(instrument_data.optionSchemes)); privInstance.dicts.Add("seriesTerms", CreateDictionary(instrument_data.seriesTerms)); privInstance.dicts.Add("comboTypes", CreateDictionary(instrument_data.comboTypes)); } else { throw new Exception("GET InstrumentData request failed" + Environment.NewLine + result.Content.ToString()); } }
private static void GetOrderData() { var result = RestManager.GetRequest("ttledger", "orderdata"); OrderData order_data = JsonConvert.DeserializeObject <OrderData>(result.Content); if (order_data.data != null) { foreach (var entry in order_data.data) { privInstance.dicts.Add(entry.Key, entry.Value); } } else { throw new Exception("GET OrderData request failed" + Environment.NewLine + result.Content.ToString()); } }
public static IRestResponse GetRequest(string target, string call, params Parameter [] parameters) { RestManager rest_man = privInstance; lock (rest_man) { string endpoint = string.Format("{0}/{1}/{2}", target, rest_man.ApiEnv, call); RestRequest request = new RestRequest(endpoint, Method.GET); request.RequestFormat = DataFormat.Json; request.Parameters.AddRange(parameters); request.AddHeader("Authorization", rest_man.AccessToken); request.AddHeader("x-api-key", rest_man.AppKey); var response = rest_man.Client.Execute(request); return(response); } }
private static TT_Instrument RequestInstrument(string instr_id) { var result = RestManager.GetRequest("pds", "instrument/" + instr_id); InstrumentResponse response = JsonConvert.DeserializeObject <InstrumentResponse>(result.Content); if (response.instrument != null) { return(response.instrument[0]); } else { TT_Instrument instr = new TT_Instrument(); instr.id = instr_id; instr.alias = "Permission Denied"; instr.productSymbol = "Permission Denied"; instr.productTypeId = 34; instr.optionCodeId = 2; return(instr); } }
public static IRestResponse GetRequest(string target, string call, int max_retries, params Parameter [] parameters) { RestManager rest_man = privInstance; lock (rest_man) { string endpoint = string.Format("{0}/{1}/{2}", target, rest_man.ApiEnv, call); RestRequest request = new RestRequest(endpoint, Method.GET); request.RequestFormat = DataFormat.Json; request.Parameters.AddRange(parameters); request.Parameters.Add(GetRequestId()); request.AddHeader("Authorization", rest_man.AccessToken); request.AddHeader("x-api-key", rest_man.AppKey); IRestResponse response = null; for (int i = 0; i < max_retries; ++i) { if (privInstance.m_nextRequest > DateTime.Now) { Thread.Sleep(privInstance.m_nextRequest - DateTime.Now); } response = rest_man.Client.Execute(request); privInstance.m_nextRequest = DateTime.Now + RestManager.MinSpace; LogRequest(request, response); if (response.IsSuccessful || (response.StatusCode != System.Net.HttpStatusCode.InternalServerError && response.StatusCode != System.Net.HttpStatusCode.BadRequest && response.ResponseStatus != ResponseStatus.TimedOut)) { break; } } return(response); } }
private static TT_User RequestUser(string user_id) { var result = RestManager.GetRequest("risk", "user/" + user_id); UserResponse response = JsonConvert.DeserializeObject <UserResponse>(result.Content); TT_User usr = null; if (response.Status == "Ok") { usr = response.user[0]; } else { // If the REST API user cannot view this user, make a dummy variable usr = new TT_User(); usr.id = user_id; usr.alias = "user_id:" + user_id; usr.company = new TT_Company(); usr.company.name = "user_id:" + user_id; usr.company.id = -1; usr.company.abbrevName = "user_id:" + user_id; } return(usr); }
private void Debug_DragDrop(object sender, DragEventArgs e) { if (!RestManager.IsAuthorized()) { string app_key = txtSecret.Text.Split(':')[0]; string app_secret = txtSecret.Text; RestManager.Init(app_key, app_secret, txtEnvironment.Text); if (!RestManager.IsAuthorized()) { MessageBox.Show("Rest API was not able to log in with provided App Key and Secret"); return; } else { FDLog.LogMessage("Successfully logged in with app key and secret"); RestManager.OnTokenError += RestManager_OnTokenError; } } string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false); Action debug = () => { DebugFillFiles(e); }; this.BeginInvoke(debug); }
private void btnStart_Click(object sender, EventArgs e) { // Validate our inputs int interval = 0; if (!int.TryParse(txtFrequency.Text, out interval)) { MessageBox.Show("Error parsing frequency \"" + txtFrequency.Text + "\"."); return; } if (interval <= 0) { MessageBox.Show("Frequency must be greater than zero."); return; } TimeSpan start_time = dtpStartTime.Value.TimeOfDay; TimeSpan end_time = dtpEndTime.Value.TimeOfDay; if (start_time > end_time) { MessageBox.Show("Error: Start time must come before end time"); return; } // Try to log in to the REST API RestManager.Init(txtKey.Text, txtSecret.Text, txtEnvironment.Text); if (!RestManager.IsAuthorized()) { MessageBox.Show("Rest API was not able to log in with provided App Key and Secret"); return; } else { RestManager.OnTokenError += RestManager_OnTokenError; } DateTime start_date = default(DateTime); if (dtpStartDate.CustomFormat != " ") { // TimeStamp correction so it properly reflects midnight of // this day in local time start_date = dtpStartDate.Value.Date - TimeZoneInfo.Local.BaseUtcOffset; } else { start_date = DateTime.Today - TimeZoneInfo.Local.BaseUtcOffset; } if (!chkSunday.Checked && !chkMonday.Checked && !chkTuesday.Checked && !chkWednesday.Checked && !chkThursday.Checked && !chkFriday.Checked && !chkSaturday.Checked) { MessageBox.Show("Must select at least one day to run downloader."); return; } bool[] days_to_run = new bool[7]; days_to_run[0] = chkSunday.Checked; days_to_run[1] = chkMonday.Checked; days_to_run[2] = chkTuesday.Checked; days_to_run[3] = chkWednesday.Checked; days_to_run[4] = chkThursday.Checked; days_to_run[5] = chkFriday.Checked; days_to_run[6] = chkSaturday.Checked; try { FileStream fs = File.Create(txtOutput.Text); fs.Close(); m_outputFile = new StreamWriter(txtOutput.Text, true, Encoding.ASCII); m_outputFile.AutoFlush = true; m_outputFile.Write(GetCSVHeader()); } catch (Exception ex) { MessageBox.Show("Error creating output file: " + ex.Message); return; } clbColumns.Enabled = false; btnStart.Text = "Stop Downloading"; btnStart.Click -= btnStart_Click; btnStart.Click += btnStart_Close; btnBrowse.Enabled = false; m_fillThread = new FillDownloadThread(start_time, end_time, new TimeSpan(0, interval, 0), days_to_run, start_date); m_fillThread.FillDownload += fillThread_OnFillDownload; m_fillThread.OnError += OnError; m_fillThread.Start(); }
public static IRestResponse GetRequest(string target, string call, params Parameter[] parameters) { return(RestManager.GetRequest(target, call, 1, parameters)); }
private void DownloadFills() { // Perform REST request/response to download fill data, specifying our cached minimum timestamp as a starting point. // On a successful response the timestamp will be updated so we run no risk of downloading duplicate fills. bool should_continue = false; List <TT_Fill> fills = new List <TT_Fill>(); do { should_continue = false; var min_param = new RestSharp.Parameter("minTimestamp", TT_Info.ToRestTimestamp(m_minTimeStamp).ToString(), RestSharp.ParameterType.QueryString); RestSharp.IRestResponse result = RestManager.GetRequest("ledger", "fills", min_param); if (result.StatusCode == System.Net.HttpStatusCode.GatewayTimeout) { should_continue = true; DateTime max_time = DateTime.Now; int retry_count = 0; for (retry_count = 0; retry_count < max_retries; ++retry_count) { FDLog.LogMessage("Fill request timed out. Retrying...."); max_time = m_minTimeStamp + TimeSpan.FromTicks((max_time - m_minTimeStamp).Ticks / 2); var max_param = new RestSharp.Parameter("maxTimestamp", TT_Info.ToRestTimestamp(max_time).ToString(), RestSharp.ParameterType.QueryString); result = RestManager.GetRequest("ledger", "fills", min_param, max_param); if (result.StatusCode == System.Net.HttpStatusCode.OK) { m_minTimeStamp = max_time; break; } else if (result.StatusCode != System.Net.HttpStatusCode.GatewayTimeout) { throw new Exception(String.Format("Request for fills unsuccessful. (minTimestamp={0}) - Status: {1} - Error Message: {2}", min_param.Value.ToString(), result.StatusCode.ToString(), result.ErrorMessage)); } if (retry_count == max_retries) { throw new Exception("Request for fills unsuccessful. Max Retries exceeded."); } } } else if (result.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception(String.Format("Request for fills unsuccessful. (minTimestamp={0}) - Status: {1} - Error Message: {2}", min_param.Value.ToString(), result.StatusCode.ToString(), result.ErrorMessage)); } JObject json_data = JObject.Parse(result.Content); FDLog.LogMessage(String.Format("Downloaded {0} fills.", json_data["fills"].Count())); foreach (var fill in json_data["fills"]) { fills.Add(new TT_Fill(fill)); } fills.Sort((f1, f2) => f1.UtcTimeStamp.CompareTo(f2.UtcTimeStamp)); RaiseFillDownloadEvent(fills); if (fills.Count > 0) { m_minTimeStamp = new DateTime(fills[fills.Count - 1].UtcTimeStamp.Ticks + 1); } should_continue |= (fills.Count == TT_Info.MAX_RESPONSE_FILLS); should_continue &= m_running; }while (should_continue); }
private void btnStart_Click(object sender, EventArgs e) { // Validate our inputs int interval = 0; if (!int.TryParse(txtFrequency.Text, out interval)) { MessageBox.Show("Error parsing frequency \"" + txtFrequency.Text + "\"."); return; } if (interval <= 0) { MessageBox.Show("Frequency must be greater than zero."); return; } TimeSpan start_time = dtpStartTime.Value.TimeOfDay; TimeSpan end_time = dtpEndTime.Value.TimeOfDay; if (start_time > end_time) { MessageBox.Show("Error: Start time must come before end time"); return; } // Try to log in to the REST API string app_key = txtSecret.Text.Split(':')[0]; string app_secret = txtSecret.Text; RestManager.Init(app_key, app_secret, txtEnvironment.Text, txtURL.Text); if (!RestManager.IsAuthorized()) { MessageBox.Show("Rest API was not able to log in with provided App Key and Secret"); return; } else { FDLog.LogMessage("Successfully logged in with app key and secret"); RestManager.OnTokenError += RestManager_OnTokenError; } DateTime start_date = default(DateTime); if (dtpStartDate.CustomFormat != " ") { // TimeStamp correction so it properly reflects midnight of // this day in local time start_date = dtpStartDate.Value.Date - TimeZoneInfo.Local.BaseUtcOffset; } else { start_date = DateTime.Today - TimeZoneInfo.Local.BaseUtcOffset; } if (!chkSunday.Checked && !chkMonday.Checked && !chkTuesday.Checked && !chkWednesday.Checked && !chkThursday.Checked && !chkFriday.Checked && !chkSaturday.Checked) { MessageBox.Show("Must select at least one day to run downloader."); return; } bool[] days_to_run = new bool[7]; days_to_run[0] = chkSunday.Checked; days_to_run[1] = chkMonday.Checked; days_to_run[2] = chkTuesday.Checked; days_to_run[3] = chkWednesday.Checked; days_to_run[4] = chkThursday.Checked; days_to_run[5] = chkFriday.Checked; days_to_run[6] = chkSaturday.Checked; try { FileMode mode = (FileMode)cbFileMode.SelectedItem; m_outputFile = FillFile.GetFillFile(mode, txtOutput.Text, GetReportItems()); } catch (Exception ex) { MessageBox.Show("Error creating output file: " + ex.Message); return; } clbColumns.Enabled = false; btnStart.Text = "Stop Downloading"; btnStart.Click -= btnStart_Click; btnStart.Click += btnStart_Close; btnBrowse.Enabled = false; FDLog.LogMessage("Beginning downloads..."); m_fillThread = new FillDownloadThread(start_time, end_time, new TimeSpan(0, interval, 0), days_to_run, start_date); m_fillThread.FillDownload += fillThread_OnFillDownload; m_fillThread.OnError += OnError; m_fillThread.Start(); }