bool check_session(XDocument doc)
 {
     try
     {
         var error_node = doc.Descendants("Error").Single();
         if (error_node == null)
         {
             return(false);
         }
         if (error_node.Element("ErrorTxt").Value.Trim() != "")
         {
             return(false);
         }
         return(true);
     }
     catch (Exception ex)
     {
         MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace);
         MainApp.g_working = false;
         return(false);
     }
 }
Exemple #2
0
        void init_dynamic()
        {
            panel_wait.BringToFront();
            new System.Threading.Tasks.Task(async() =>
            {
                try
                {
                    bool _login = await m_dyn.login();
                    if (_login == false)
                    {
                        MainApp.log_info("Dynamic Odds API connection failed.");
                        if (MessageBox.Show("Failed to log in to Dynamic Odds XML feed service.\nDo you want to continue without live alert?", "OddAlert", MessageBoxButtons.YesNo) == DialogResult.No)
                        {
                            Close();
                            return;
                        }
                    }

                    play_sound();
                    MainApp.log_info("Dynamic Odds API connected.");
                    m_agency_lookup = await m_dyn.get_agencies();

                    load_events();

                    this.InvokeOnUiThreadIfRequired(() =>
                    {
                        panel_wait.SendToBack();
                    });

                    m_timer_alert.Start();
                }
                catch (Exception ex)
                {
                    MainApp.log_error("Exception in init_dynamic\n" + ex.Message + "\n" + ex.StackTrace);
                }
            }).Start();
        }
        public async System.Threading.Tasks.Task <Dictionary <string, string> > get_agencies()
        {
            try
            {
                Dictionary <string, string> agency = new Dictionary <string, string>();
                string endpoint = $"{ep}GetData.asp?SessionID={session_id}&Method=GetBettingAgencies";
                string res      = await WRequest.get_response(endpoint);

                XDocument doc = XDocument.Parse(res);
                if (check_session(doc) == false)
                {
                    if (res.Contains("Request Limit Exceeded"))
                    {
                        await Task.Delay(1000);

                        return(await get_agencies());
                    }
                    MainApp.log_error("Error getting agencies");
                    MainApp.log_error(res);
                    MainApp.g_working = false;
                    return(null);
                }

                foreach (var node in doc.Descendants("BA"))
                {
                    agency.Add(node.Attribute("ID").Value, node.Element("Name").Value);
                }
                MainApp.g_working = true;
                return(agency);
            }
            catch (Exception ex)
            {
                MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace);
                MainApp.g_working = false;
                return(null);
            }
        }
Exemple #4
0
        private async void M_timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                {
                }
                if (m_dyn.Ready())
                {
                    if (m_cur_date.ToString("yyyy-MM-dd") != DateTime.Now.ToString("yyyy-MM-dd"))
                    {
                        load_events();
                    }

                    foreach (var eve in m_event_list)
                    {
                        if (m_event_status[eve] == 0)
                        {
                            var au_now = MainApp.AuNow();
                            if (eve.StartTime < au_now)
                            {
                                m_event_status[eve] = 2; // ended
                                continue;
                            }

                            m_event_status[eve] = 1; // busy
                            new Thread(async() =>
                            {
                                var odd_view = await m_dyn.get_runner_odds(eve.ID);
                                // Check delta and raise the alert
                                if (eve.OddView != null && odd_view != null)
                                {
                                    MainApp.log_info($"Odds for {eve.State} - {eve.Venue} - {eve.EventNo} updated.");
                                    foreach (var runner in odd_view.RName)
                                    {
                                        foreach (var bookie in m_monitor_bookies)
                                        {
                                            decimal pre_price = eve.OddView.get_odd_for_bookie(bookie, runner);
                                            decimal cur_price = odd_view.get_odd_for_bookie(bookie, runner);

                                            if (pre_price < 2M || cur_price == 0)
                                            {
                                                continue;
                                            }

                                            int pre_point = PriceTable.get_point(pre_price);
                                            int cur_point = PriceTable.get_point(cur_price);
                                            int delta     = cur_point - pre_point;
                                            if (delta <= -MainApp.g_setting.alert_level && -delta <= 13)
                                            {
                                                play_sound();
                                                MainApp.log_info("Notification triggered.");

                                                int idx = odd_view.RName.IndexOf(runner);
                                                // get top prices
                                                List <KeyValuePair <string, decimal> > odd_dict = new List <KeyValuePair <string, decimal> >();
                                                foreach (var one_bookie in odd_view.Odds)
                                                {
                                                    odd_dict.Add(new KeyValuePair <string, decimal>(one_bookie.Bookie, one_bookie.Odds[idx]));
                                                }
                                                odd_dict.Sort((pair1, pair2) => - pair1.Value.CompareTo(pair2.Value));

                                                // new notification
                                                Notification note    = new Notification();
                                                note.event_id        = eve.ID;
                                                note.datetime        = au_now.ToString("yyyy-MM-dd hh:mm:ss");
                                                note.time_to_jump    = eve.StartTime.Subtract(au_now).ToString("h'h 'm'm 's's'");
                                                note.degree          = delta;
                                                note.state           = eve.State;
                                                note.venue           = eve.Venue;
                                                note.race_number     = int.Parse(eve.EventNo);
                                                note.horse_number    = int.Parse(odd_view.RNo[idx]);
                                                note.horse_name      = runner;
                                                note.previous_price  = pre_price;
                                                note.current_price   = cur_price;
                                                note.bookie          = bookie;
                                                note.suggested_stake = suggest_stake(pre_price, delta);
                                                note.max_profit      = note.suggested_stake * (pre_price - 1);
                                                note.top_price_1     = $"${odd_dict[0].Value} {odd_dict[0].Key}";
                                                note.top_price_2     = $"${odd_dict[1].Value} {odd_dict[1].Key}";
                                                note.top_price_3     = $"${odd_dict[2].Value} {odd_dict[2].Key}";
                                                note.top_price_4     = $"${odd_dict[3].Value} {odd_dict[3].Key}";
                                                note.status          = 0; // pending
                                                note.result          = "-";
                                                add_note_to_db(note);
                                                refresh_in_delay = true;
                                                //refresh_grid();
                                            }
                                        }
                                    }
                                }

                                eve.OddView         = odd_view;
                                m_event_status[eve] = 0; // idle
                            }).Start();
                        }
                    }

                    foreach (var pair in m_event_status)
                    {
                        if (pair.Value == 2)
                        {
                            m_event_list.Remove(pair.Key);
                        }
                    }

                    if (m_event_list.Count == 0)
                    {
                        MainApp.log_info("No active events are left today. " + m_cur_date.ToString("yyyy-MM-dd"));
                    }
                }

                if (MainApp.g_working)
                {
                    img_status.BackgroundImage = Properties.Resources.Circle_ON;
                }
                else
                {
                    img_status.BackgroundImage = Properties.Resources.Circle_OFF;
                }
            }
            catch (Exception ex)
            {
                MainApp.log_error("Exception in timer\n" + ex.Message + "\n" + ex.StackTrace);
            }
            m_timer_alert.Start();
        }
        public async System.Threading.Tasks.Task <RaceEvent> get_event(RaceEvent ref_eve, string eve_id)
        {
            try
            {
                RaceEvent eve      = new RaceEvent();
                string    endpoint = $"{ep}GetData.asp?SessionID={session_id}&Method=GetEvent&EventID={eve_id}&Runners=true";
                string    res      = await WRequest.get_response(endpoint);

                XDocument doc = XDocument.Parse(res);
                if (check_session(doc) == false)
                {
                    if (res.Contains("Request Limit Exceeded"))
                    {
                        await Task.Delay(1000);

                        return(await get_event(ref_eve, eve_id));
                    }
                    MainApp.g_working = false;
                    return(null);
                }

                MainApp.g_working = true;
                XElement elem = null;
                try
                {
                    elem = doc.Element("Data").Element("GetEvent").Element("Event");
                }
                catch (Exception e)
                {
                    return(null);
                }
                if (elem == null)
                {
                    return(null);
                }
                eve.ID           = elem.Attribute("ID").Value;
                eve.EventNo      = elem.Element("EventNo").Value;
                eve.Name         = elem.Element("Name").Value;
                eve.Distance     = elem.Element("Distance").Value;
                eve.Track        = elem.Element("Track").Value;
                eve.TrackRtg     = elem.Element("TrackRtg").Value;
                eve.Starters     = elem.Element("Starters").Value;
                eve.StartTime_Au = elem.Element("StartTime").Value;
                eve.Class        = elem.Element("Class").Value;
                eve.Prizemoney   = elem.Element("Prizemoney").Value;
                eve.Status       = elem.Element("Status").Value;
                if (eve.Status.ToUpper() == "FINAL")
                {
                    eve.Status = "PAYING";
                }
                eve.WeatherTC = elem.Element("WeatherTC").Value;
                WeatherConditions con = new WeatherConditions();
                con.TempC      = elem.Element("WeatherCondtions").Element("TempC").Value;
                con.Humidity   = elem.Element("WeatherCondtions").Element("Humidity").Value;
                con.WindSpeed  = elem.Element("WeatherCondtions").Element("WindSpeed").Value;
                con.WindDir    = elem.Element("WeatherCondtions").Element("WindDir").Value;
                eve.WeatherCon = con;
                eve.Rail       = elem.Element("Rail").Value;
                eve.CodeAAP    = elem.Element("CodeAAP").Value;
                eve.CodeBF     = elem.Element("CodeBF").Value;
                eve.Runners    = new List <Runner>();
                foreach (var node in elem.Elements("Runner"))
                {
                    Runner runner = new Runner();
                    runner.Name      = node.Element("Name").Value;
                    runner.Jockey    = node.Element("Jockey").Value;
                    runner.Trainer   = node.Element("Trainer").Value;
                    runner.Bar       = node.Element("Bar").Value;
                    runner.Hcp       = node.Element("Hcp").Value;
                    runner.Scr       = node.Element("Scr").Value;
                    runner.Emergency = node.Element("Emergency").Value;
                    eve.Runners.Add(runner);
                }

                eve.Venue         = ref_eve.Venue;
                eve.EventCode     = ref_eve.EventCode;
                eve.Type          = ref_eve.Type;
                eve.State         = ref_eve.State;
                eve.StartTime     = ref_eve.StartTime;
                eve.Date          = ref_eve.Date;
                MainApp.g_working = true;
                return(eve);
            }
            catch (Exception ex)
            {
                MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace);
                MainApp.g_working = false;
                return(null);
            }
        }
        public async System.Threading.Tasks.Task <List <RaceEvent> > get_event_schedule(DateTime date)
        {
            try
            {
                DateTime         au_now   = date.Subtract(MainApp.g_time_diff);
                List <RaceEvent> schedule = new List <RaceEvent>();
                string           date_str = date.ToString("yyyy-MM-dd");
                string           endpoint = $"{ep}GetData.asp?SessionID={session_id}&Method=GetEventSchedule&Date={date_str}&Types=R,H,G&Limit=999";
                string           res      = await WRequest.get_response(endpoint);

                XDocument doc = XDocument.Parse(res);
                if (check_session(doc) == false)
                {
                    if (res.Contains("Request Limit Exceeded"))
                    {
                        await Task.Delay(1000);

                        return(await get_event_schedule(date));
                    }
                    MainApp.log_error("Error getting event schedule");
                    MainApp.log_error(res);
                    MainApp.g_working = false;
                    return(null);
                }

                var all_events = doc.Descendants("Event");
                foreach (var node in all_events)
                {
                    RaceEvent eve = new RaceEvent();
                    eve.ID           = node.Attribute("ID").Value;
                    eve.Date         = date;
                    eve.EventCode    = node.Attribute("EventCode").Value;
                    eve.StartTime_Au = node.Attribute("StartTime").Value;
                    eve.Type         = node.Attribute("Type").Value;
                    if (eve.Type == "T")
                    {
                        eve.Type = "H";
                    }
                    eve.Venue   = node.Attribute("Venue").Value;
                    eve.EventNo = node.Attribute("EventNo").Value;
                    eve.Status  = node.Attribute("EventStatus").Value;
                    if (eve.Status.ToUpper() == "FINAL")
                    {
                        eve.Status = "PAYING";
                    }
                    eve.State = node.Attribute("State").Value;

                    if (au_states.Contains(eve.State) == false ||
                        eve.Status.ToUpper() != "OPEN" ||
                        eve.Type != "R")
                    {
                        continue;
                    }

                    if (!MainApp.DEBUG && eve.StartTime_Au.CompareTo(au_now.ToString("HH:mm:ss")) < 0)
                    {
                        continue;
                    }

                    string[] fields = eve.StartTime_Au.Split(':');
                    eve.StartTime = new DateTime(au_now.Year, au_now.Month, au_now.Day, int.Parse(fields[0]), int.Parse(fields[1]), int.Parse(fields[2]));

                    //MainApp.log_info(eve.ToString());
                    schedule.Add(eve);
                }
                MainApp.g_working = true;
                return(schedule);
            }
            catch (Exception ex)
            {
                MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace);
                MainApp.g_working = false;
                return(null);
            }
        }
        public async Task <OddOverview> get_runner_odds(string event_id)
        {
            XDocument doc;
            string    res;

            try
            {
                OddOverview overview = new OddOverview();
                overview.EveID = event_id;

                string endpoint = $"{ep}GetData.asp?SessionID={session_id}&Method=GetRunnerOdds&EventID={event_id}";
                res = await WRequest.get_response(endpoint);

                doc = XDocument.Parse(res);
                if (check_session(doc) == false)
                {
                    if (res.Contains("Request Limit Exceeded"))
                    {
                        await Task.Delay(1000);

                        return(await get_runner_odds(event_id));
                    }
                    MainApp.log_error("Error getting running odds");
                    MainApp.log_error(res);
                    MainApp.g_working = false;
                    return(null);
                }

                IEnumerable <XElement> elems;
                try
                {
                    elems = doc.Element("Data").Element("RunnerOdds").Elements();
                }
                catch (Exception ee)
                {
                    MainApp.log_error("DynHelperError: " + ee.Message + "\n" + ee.StackTrace);
                    MainApp.g_working = false;
                    return(null);
                }
                overview.Odds = new List <OddOneBookie>();
                foreach (var elem in elems)
                {
                    string name = elem.Name.ToString();
                    string val  = elem.Value.ToString();
                    if (name == "RNo")
                    {
                        overview.RNo = new List <string>(val.Split(','));
                    }
                    else if (name == "RName")
                    {
                        overview.RName = new List <string>(val.Split(','));
                    }
                    else
                    {
                        string bookie;
                        if (OddBookieMap.map.TryGetValue(name, out bookie))
                        {
                            OddOneBookie odd_one = new OddOneBookie();
                            odd_one.OddName = name;
                            odd_one.Bookie  = bookie;
                            odd_one.Odds    = new List <decimal>(val.Split(',').Select(x => x.ToString() == "" ? 0 : decimal.Parse(x)));
                            overview.Odds.Add(odd_one);
                        }
                    }
                }
                MainApp.g_working = true;
                return(overview);
            }
            catch (Exception ex)
            {
                MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace);
                MainApp.g_working = false;
                return(null);
            }
        }