Beispiel #1
0
        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 e)
                {
                    // Login errors can be ignored during initialization
                    // to allow the user to attempt to log in again
                    FDLog.LogError(String.Format("Error Authenticating: {0}", e.Message));
                }
            }
        }
Beispiel #2
0
        public FrmFillDownload()
        {
            var hourago = TT_Info.ToRestTimestamp(DateTime.UtcNow - new TimeSpan(1, 0, 0));

            InitializeComponent();

            InitializeColumnList();

            clbColumns.Items.Clear();
            foreach (FillColumn column in m_TradePaneColumns)
            {
                clbColumns.Items.Add(column, true);
            }

            this.FormClosing += FrmFillDownload_FormClosing;

            cbFileMode.DataSource = Enum.GetValues(typeof(FileMode));

            LoadSettings();

            this.DragOver += FrmFillDownload_DragOver;
            this.DragDrop += Debug_DragDrop;

            FDLog.LogMessage("Starting up C# Fill Downloader v0.0.1");
        }
Beispiel #3
0
        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);
        }
Beispiel #4
0
        protected bool WriteFillsToFile(List <TT_Fill> fills)
        {
            bool errors = false;

            foreach (TT_Fill fill in fills)
            {
                bool   fill_errors = false;
                String row         = "";
                foreach (FillColumn column in m_columns)
                {
                    try
                    {
                        row += column.DisplayField(fill) + ",";
                    }
                    catch (Exception ex)
                    {
                        row += ",";
                        FDLog.LogError("Error parsing fill column " + column.ColumnName + " for fill " + fill.RecordID + Environment.NewLine + ex.Message);
                        fill_errors = true;
                    }
                }
                if (fill_errors)
                {
                    FDLog.LogError("Json for fill " + fill.RecordID + ": " + fill.JsonData() + Environment.NewLine);
                    errors = true;
                }
                row += Environment.NewLine;
                m_outputFile.Write(row.ToString());
            }
            return(errors);
        }
Beispiel #5
0
        private void DebugFillFiles(DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            int      i;
            var      fields = GetReportItems();

            for (i = 0; i < s.Length; i++)
            {
                Console.WriteLine();

                using (StreamReader file = File.OpenText(s[i]))
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        TT_Fill fill = new TT_Fill(JToken.ReadFrom(reader));
                        FDLog.LogMessage(String.Format("Parsing fill from file {0}", s[i]));
                        string row = "";
                        foreach (var field in fields)
                        {
                            try
                            {
                                row += field.DisplayField(fill) + ",";
                            }
                            catch (Exception ex)
                            {
                                row += ",";
                                FDLog.LogError("Error parsing fill column " + field.ColumnName + " for fill " + fill.RecordID + Environment.NewLine + ex.Message);
                            }
                        }
                        FDLog.LogMessage(row);
                    }
            }
        }
Beispiel #6
0
        private void OnError(object sender, string error_message)
        {
            FDLog.LogError(error_message + Environment.NewLine + "--------------------------------------------------" + Environment.NewLine);
            MessageBox.Show(error_message);

            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(this.Close));
            }
            else
            {
                this.Close();
            }
        }
Beispiel #7
0
        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);
                }
            }
        }
Beispiel #8
0
        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);
        }
Beispiel #9
0
        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();
        }
Beispiel #10
0
        private static void privLog(String msg)
        {
            FDLog log = privInstance;

            log.m_logFile.Write(DateTime.UtcNow.ToString() + " | " + msg);
        }
Beispiel #11
0
 public static void LogError(String error_msg)
 {
     FDLog.privLog("ERR | " + error_msg + Environment.NewLine);
 }
Beispiel #12
0
 public static void LogRequest(String request)
 {
     FDLog.privLog("REQ | " + request + Environment.NewLine);
 }
Beispiel #13
0
 public static void LogMessage(String message)
 {
     FDLog.privLog("MSG | " + message + Environment.NewLine);
 }
Beispiel #14
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.

            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);
        }