// Добавление обработчика сообщения
 public void AddMessageHandler(string Command, MessageDelegate Handler)
 {
     if (Handler == null)
         return;
     List<MessageDelegate> msgHandlers;
     lock (messageHandlers)
     {
         if (!messageHandlers.TryGetValue(Command, out msgHandlers))
         {
             lock (messagesList)
             {
                 if (messagesList.Count > 0)
                 {
                     for (var i = messagesList.Count - 1; i >= 0; i--)
                     {
                         Message m = messagesList[i];
                         if (m.Command == Command)
                         {
                             dispatcher.BeginInvoke(new Action(() => Handler(m)));
                             messagesList.Remove(m);
                         }
                     }
                 }
             }
             msgHandlers = new List<MessageDelegate>();
             messageHandlers.Add(Command, msgHandlers);
         }
         msgHandlers.Add(Handler);
     }
 }
 // Установка всех обработчиков событий перед игрой
 public void SetPreGameHandlers(MessageDelegate PlayerAddToTableHandler, MessageDelegate PlayerDeleteFromTableHandler,
     MessageDelegate CreatorLeaveTableHandler, MessageDelegate StartGameHandler)
 {
     AddMessageHandler(Messages.MESSAGE_TABLE_PLAYERS_ADD, PlayerAddToTableHandler);
     AddMessageHandler(Messages.MESSAGE_TABLE_PLAYERS_DELETE, PlayerDeleteFromTableHandler);
     AddMessageHandler(Messages.MESSAGE_TABLE_MODIFY_CREATORLEAVE, CreatorLeaveTableHandler);
     AddMessageHandler(Messages.MESSAGE_GAME_START, StartGameHandler);
 }
Exemple #3
0
        public Timer(int milisecondsDelay, MessageDelegate method)
        {
            this.MilisecondsDelay = milisecondsDelay;
            this.messageDelegate = method;

            //initialize new thread for the Worker method
            Thread th = new Thread(new ThreadStart(NewThreadWorker));
            th.Start();
        }
Exemple #4
0
 public TestMessageHandler(string content, bool isJson = false)
 {
     var stringContent = new StringContent(content);
     if (isJson)
     {
         stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
     }
     this.handlerFunc = _ => new HttpResponseMessage(HttpStatusCode.OK) { Content = stringContent };
 }
Exemple #5
0
        public World(MessageDelegate messageSender)
        {
            bees = new List<Bee>();
            flowers = new List<Flower>();
            Random random = new Random();
            hive = new Hive(this,messageSender);
            for (int i = 0; i < 10; i++)
                AddFlower(random);

        }
        public void MessageBoxShow(string strMessage, string strTitle, MessageDelegate delMsg)
        {
            if (strMessage.Contains("I win."))
            {
                labelComputerScore.Content = (Int32.Parse(labelComputerScore.Content.ToString()) + 1).ToString();
            }

            System.Windows.MessageBox.Show(strMessage, strTitle);
            delMsg();
        }
Exemple #7
0
        public void MessageBoxShow(string strMessage, string strTitle, MessageDelegate delMsg)
        {
            //hack to show score (fastest way)
            if(strMessage.Contains("I win."))
            {
                labelComputerScore.Text = (Int32.Parse(labelComputerScore.Text) + 1).ToString();
            }

            MessageBox.Show(strMessage, strTitle);
            delMsg();
        }
 private void AddTalkMessage(String message)
 {
     if (richTextBoxTalkInfo.InvokeRequired)
     {
         MessageDelegate d = new MessageDelegate(AddTalkMessage);
         richTextBoxTalkInfo.Invoke(d, new object[] { message });
     }
     else
     {
         richTextBoxTalkInfo.AppendText(message+"\n");
         richTextBoxTalkInfo.ScrollToCaret();
     }
 }
 private void AddHistory(string message)
 {
     if (ux_txtSendHistory.InvokeRequired)
     {
         //invoke self on the thread owning this control
         MessageDelegate del = new MessageDelegate(AddHistory);
         ux_txtSendHistory.Invoke(del, message);
     }
     else
     {
         ux_txtSendHistory.AppendText(message + Environment.NewLine);
     }
 }
Exemple #10
0
        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //

            putMessage = new MessageDelegate(PutMessage);
            InitializeComponent();

            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }
Exemple #11
0
        public Bee(int id, Point location, World world, Hive hive,MessageDelegate messageSender)
        {
            this.ID = id;
            this.Age = 0;
            this.location = location;
            this.InsideHive = true;
            this.CurrentState = BeeState.Idle;
            this.destinationFlower = null;
            this.NectarCollected = 0;
            this.world = world;
            this.hive = hive;
            this.ExState = CurrentState;
            this.MessageSender += messageSender;

        }
Exemple #12
0
        public Hive(World world, MessageDelegate messageSender)
        {
            this.Honey = InitialHoney;
            InitialLocations();
            beeCount = 0;
            Random random = new Random();
            this.world = world;
            this.messageSender = messageSender;
            for (beeCount = 0; beeCount < InitialBees; beeCount++)
            {
                AddBee(random);
            }


        }
Exemple #13
0
 public MainForm()
 {
     //
     // The InitializeComponent() call is required for Windows Forms designer support.
     //
     InitializeComponent();
     //StartServer(49210);
     dsrv = new DataServer(49210);
     ReceiveCallback st = new ReceiveCallback(process);
     dsrv.ClientReceiveCallback = st;
     dsrv.Start();
     putMessage = new MessageDelegate(PutMessage);
     //
     // TODO: Add constructor code after the InitializeComponent() call.
     //
     //
 }
Exemple #14
0
 public LConversation(Conversation conversation, MessageDelegate messageDelegate)
 {
     _msgDelegate = messageDelegate;
     object idValue;
     if (conversation.Properties.TryGetValue(ConversationProperty.Id, out idValue))
         _convId = (string)idValue;
     else
         _convId = "";
     int count = conversation.Participants.Count;
     for (int i = 0; i < count; ++i)
     {
         var p = conversation.Participants[i];
         AddParticipant(p);
     }
     conversation.ParticipantAdded += ParticipantAdded;
     conversation.ParticipantRemoved += ParticipantRemoved;
 }
 // Снятие всех обработчиков событий процесса игры
 public void UnsetGameHandlers(MessageDelegate CardsDistributionHandler, MessageDelegate BazarNextPlayerHandler,
     MessageDelegate BazarPlayerSayHandler, MessageDelegate BazarEndHandler, MessageDelegate BazarPassHandler,
     MessageDelegate GameNextPlayerHandler, MessageDelegate GameRemindCardHandler, MessageDelegate BonusesGetAllHandler,
     MessageDelegate BonusesShowTypesHandler, MessageDelegate BonusesShowWinnerHandler, MessageDelegate GamePlayerQuitHandler,
     MessageDelegate GameEndHandler)
 {
     DeleteMessageHandler(Messages.MESSAGE_GAME_DISTRIBUTIONCARDS, CardsDistributionHandler);
     DeleteMessageHandler(Messages.MESSAGE_GAME_BAZAR_NEXTBETPLAYER, BazarNextPlayerHandler);
     DeleteMessageHandler(Messages.MESSAGE_GAME_BAZAR_SAYBET, BazarPlayerSayHandler);
     DeleteMessageHandler(Messages.MESSAGE_GAME_BAZAR_END, BazarEndHandler);
     DeleteMessageHandler(Messages.MESSAGE_GAME_BAZAR_PASS, BazarPassHandler);
     DeleteMessageHandler(Messages.MESSAGE_GAME_GAMING_NEXTPLAYER, GameNextPlayerHandler);
     DeleteMessageHandler(Messages.MESSAGE_GAME_GAMING_REMINDCARD, GameRemindCardHandler);
     DeleteMessageHandler(Messages.MESSAGE_GAME_BONUSES_ALL, BonusesGetAllHandler);
     DeleteMessageHandler(Messages.MESSAGE_GAME_BONUSES_TYPES, BonusesShowTypesHandler);
     DeleteMessageHandler(Messages.MESSAGE_GAME_BONUSES_WINNER, BonusesShowWinnerHandler);
     DeleteMessageHandler(Messages.MESSAGE_TABLE_PLAYERS_QUIT, GamePlayerQuitHandler);
     DeleteMessageHandler(Messages.MESSAGE_GAME_END, GameEndHandler);
 }
    public PlayClass(GameClass parent)
    {
        this.parent = parent;
        this.peerObject = peerObject;
        this.message = new MessageDelegate(parent.MessageArrived);

        peerObject = new Peer();
        // First set up our event handlers (We only need events for the ones we care about)
        peerObject.PlayerCreated += new PlayerCreatedEventHandler(this.PlayerCreated);
        peerObject.PlayerDestroyed += new PlayerDestroyedEventHandler(this.PlayerDestroyed);
        peerObject.HostMigrated += new HostMigratedEventHandler(this.HostMigrated);
        peerObject.Receive += new ReceiveEventHandler(this.DataReceived);
        peerObject.SessionTerminated += new SessionTerminatedEventHandler(this.SessionTerminated);

        Connect = new ConnectWizard(peerObject, AppGuid, "Step2");
        if (!Connect.StartWizard()) {
            MessageBox.Show("DirectPlay initialization was incomplete. Application will terminate.");
            throw new DirectXException();
        }
    }
Exemple #17
0
        public Postman(string tegForMessages, dbBind db, string username, string host, string password, string popAdress, int port, string smtpAdress, int smtpPort, MessageDelegate process, sayDel log, Timer mailTimer)
        {
            this.teg = tegForMessages;
            this.readed = new List<string>();
            this.log = log;
            this.MessageRecievedEvent = process;
            this.db = db;
            this.hostUsername = username;
            this.hostAddress = hostUsername + host;
            this.hostPassword = password;
            this.popAddress = popAdress;
            this.popPort = port;
            this.smtpAdress = smtpAdress;
            this.smtpPort = smtpPort;
            this.mailTimer = mailTimer;

            client = new Pop3Client();

            mailTimer.Elapsed += new ElapsedEventHandler(CheckMailBox);
            mailTimer.Start();
        }
Exemple #18
0
 public TestMessageHandler(HttpResponseMessage response)
 {
     this.handlerFunc = _ => response;
 }
Exemple #19
0
 public TestMessageHandler(HttpStatusCode statusCode)
 {
     this.handlerFunc = _ => new HttpResponseMessage(statusCode);
 }
        public static void CsvToBinary(string csvFilename, string binaryFilename, bool hasHeader, MessageDelegate messageDelegate = null)
        {
            //Record start time of process for time taken message
            DateTime now = DateTime.Now;

            //Loads from CSV
            messageDelegate?.Invoke(csvFilename + " reading...", MessageType.Message);
            string[] lines = File.ReadAllLines(csvFilename);

            //skip the header if it has one in the csv
            int startIndex = 0;

            if (hasHeader)
            {
                startIndex = 1;
            }

            //convert the csv into an array of Bar objects OHLC for both bid and ask + volume
            Bar[] dataset = new Bar[lines.Length - startIndex];
            for (int i = startIndex; i < lines.Length; i++)
            {
                dataset[i - startIndex] = new Bar(lines[i]);
            }

            //Remove duplicates and order from oldest to newest
            dataset = dataset.OrderBy(x => x.OpenTime).Distinct(x => x.OpenTime).ToArray();

            //Save it to binary
            DatasetToBinary(binaryFilename, dataset);

            messageDelegate?.Invoke(csvFilename + " csv to binary " + binaryFilename + " took: " + (DateTime.Now - now).TotalSeconds + " secs");
        }
 public static void RemoveObserver(MessageDelegate o)
 {
     MessageEvent -= o;
 }
Exemple #22
0
        public static IForm <PizzaOrder> BuildForm(bool noNumbers = false, bool ignoreAnnotations = false, bool localize = false, ChoiceStyleOptions style = ChoiceStyleOptions.AutoText)
        {
            var builder = new FormBuilder <PizzaOrder>(ignoreAnnotations);

            ActiveDelegate <PizzaOrder> isBYO       = (pizza) => pizza.Kind == PizzaOptions.BYOPizza;
            ActiveDelegate <PizzaOrder> isSignature = (pizza) => pizza.Kind == PizzaOptions.SignaturePizza;
            ActiveDelegate <PizzaOrder> isGourmet   = (pizza) => pizza.Kind == PizzaOptions.GourmetDelitePizza;
            ActiveDelegate <PizzaOrder> isStuffed   = (pizza) => pizza.Kind == PizzaOptions.StuffedPizza;

            // form.Configuration().DefaultPrompt.Feedback = FeedbackOptions.Always;
            if (noNumbers)
            {
                builder.Configuration.DefaultPrompt.ChoiceFormat = "{1}";
                builder.Configuration.DefaultPrompt.ChoiceCase   = CaseNormalization.Lower;
                builder.Configuration.DefaultPrompt.ChoiceParens = BoolDefault.False;
            }
            else
            {
                builder.Configuration.DefaultPrompt.ChoiceFormat = "{0}. {1}";
            }
            builder.Configuration.DefaultPrompt.ChoiceStyle = style;
            Func <PizzaOrder, double> computeCost = (order) =>
            {
                double cost = 0.0;
                switch (order.Size)
                {
                case SizeOptions.Medium: cost = 10; break;

                case SizeOptions.Large: cost = 15; break;

                case SizeOptions.Family: cost = 20; break;
                }
                return(cost);
            };
            MessageDelegate <PizzaOrder> costDelegate = async(state) =>
            {
                double cost = 0.0;
                switch (state.Size)
                {
                case SizeOptions.Medium: cost = 10; break;

                case SizeOptions.Large: cost = 15; break;

                case SizeOptions.Family: cost = 20; break;
                }
                cost *= state.NumberOfPizzas;
                return(new PromptAttribute(string.Format(DynamicPizza.Cost, cost)));
            };
            var form = builder
                       .Message("Welcome to the pizza bot!!!")
                       .Message("Lets make pizza!!!")
                       .Field(nameof(PizzaOrder.NumberOfPizzas))
                       .Field(nameof(PizzaOrder.Size))
                       .Field(nameof(PizzaOrder.Kind))
                       .Field(new FieldReflector <PizzaOrder>(nameof(PizzaOrder.Specials))
                              .SetType(null)
                              .SetDefine(async(state, field) =>
            {
                var specials = field
                               .SetFieldDescription(DynamicPizza.Special)
                               .SetFieldTerms(DynamicPizza.SpecialTerms.SplitList())
                               .RemoveValues();
                if (state.NumberOfPizzas > 1)
                {
                    specials
                    .SetAllowsMultiple(true)
                    .AddDescription("special1", DynamicPizza.Special1)
                    .AddTerms("special1", DynamicPizza.Special1Terms.SplitList());
                }
                specials
                .AddDescription("special2", DynamicPizza.Special2)
                .AddTerms("special2", DynamicPizza.Special2Terms.SplitList());
                return(true);
            }))
                       .Field("BYO.HalfAndHalf", isBYO)
                       .Field("BYO.Crust", isBYO)
                       .Field("BYO.Sauce", isBYO)
                       .Field("BYO.Toppings", isBYO)
                       .Field("BYO.HalfToppings", (pizza) => isBYO(pizza) && pizza.BYO != null && pizza.BYO.HalfAndHalf)
                       .Message("Almost there!!! {*filled}", isBYO)
                       .Field(nameof(PizzaOrder.GourmetDelite), isGourmet)
                       .Field(nameof(PizzaOrder.Signature), isSignature)
                       .Field(nameof(PizzaOrder.Stuffed), isStuffed)

                       .Message("What we have is a {?{Signature} signature pizza} {?{GourmetDelite} gourmet pizza} {?{Stuffed} {&Stuffed}} {?{?{BYO.Crust} {&BYO.Crust}} {?{BYO.Sauce} {&BYO.Sauce}} {?{BYO.Toppings}}} pizza")
                       .Field("DeliveryAddress", validate:
                              async(state, value) =>
            {
                var result = new ValidateResult {
                    IsValid = true, Value = value
                };
                var str = value as string;
                if (str.Length == 0 || str[0] < '1' || str[0] > '9')
                {
                    result.Feedback = DynamicPizza.AddressHelp;
                    result.IsValid  = false;
                }
                else
                {
                    result.Feedback = DynamicPizza.AddressFine;
                    if (str == "1")
                    {
                        // Test to see if step is skipped
                        state.Phone = "111-1111";
                    }
                    else if (str == "2")
                    {
                        result.Choices = new List <Choice> {
                            new Choice {
                                Description = new DescribeAttribute("2 Iowa St"), Terms = new TermsAttribute("iowa"), Value = "2 Iowa St"
                            },
                            new Choice {
                                Description = new DescribeAttribute("2 Kansas St"), Terms = new TermsAttribute("kansas"), Value = "2 Kansas St"
                            }
                        };
                        result.IsValid = false;
                    }
                    else if (str == "3")
                    {
                        result.FeedbackCard = new FormPrompt()
                        {
                            Prompt      = "Secret place",
                            Description = new DescribeAttribute(image: @"https://placeholdit.imgix.net/~text?txtsize=12&txt=secret&w=80&h=40&txttrack=0&txtclr=000&txtfont=bold")
                        };
                    }
                }
                return(result);
            })
                       .Message(costDelegate)
                       .Confirm(async(state) =>
            {
                var cost = computeCost(state);
                return(new PromptAttribute(string.Format(DynamicPizza.CostConfirm, cost)));
            })
                       .AddRemainingFields()
                       .Message("Rating = {Rating:F1} and [{Rating:F2}]")
                       .Confirm("Would you like a {Size}, {[{BYO.Crust} {BYO.Sauce} {BYO.Toppings}]} pizza delivered to {DeliveryAddress}?", isBYO)
                       .Confirm("Would you like a {Size}, {&Signature} {Signature} pizza delivered to {DeliveryAddress}?", isSignature, dependencies: new string[] { "Size", "Kind", "Signature" })
                       .Confirm("Would you like a {Size}, {&GourmetDelite} {GourmetDelite} pizza delivered to {DeliveryAddress}?", isGourmet)
                       .Confirm("Would you like a {Size}, {&Stuffed} {Stuffed} pizza delivered to {DeliveryAddress}?", isStuffed)
                       .OnCompletion(async(session, pizza) => Console.WriteLine("{0}", pizza))
                       .Build();

            if (localize)
            {
                using (var stream = new FileStream("pizza-" + Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName + ".resx", FileMode.Open))
                    using (var reader = new ResXResourceReader(stream))
                    {
                        IEnumerable <string> missing, extra;
                        form.Localize(reader.GetEnumerator(), out missing, out extra);
                    }
            }
            return(form);
        }
Exemple #23
0
        public void Add(MessageDelegate processor)
        {
            Message m = new Message(processor, null);

            Messages.Add(m);
        }
 private static extern void FIZZUnityKeyboard_CustomMessageInput(bool enable, MessageDelegate messageDelegate, StickerDelegate stickerDelegate);
Exemple #25
0
 public static void Register(Page window, MessageDelegate handler)
 {
     View    = window;
     Message = handler;
 }
Exemple #26
0
 public void Register(Command cmd, MessageDelegate @delegate)
 {
     messageDelegate[cmd] = @delegate;
 }
Exemple #27
0
        public void RecvMessage()
        {
            while (true)
            {   //loop till read nothing
                int size = 0;
                if (socket == null)
                {
                    return;
                }
                if (readSize < 4)
                {
                    // read message header ...
                    if (socket.Available < unreadSize)
                    {
                        return;
                    }
                    size = socket.Receive(buffer, offset, unreadSize, SocketFlags.None);
                    if (size <= 0)
                    {
                        return;
                    }
                    readSize   += size;
                    offset     += size;
                    unreadSize -= size;
                    if (unreadSize != 0)
                    {
                        return;
                    }

                    command    = (Command)BitConverter.ToUInt16(buffer, 0);
                    unreadSize = (int)BitConverter.ToUInt16(buffer, 2) - 4;
                    offset     = 0;
                }

                // read message body ...
                if (socket.Available < unreadSize)
                {
                    return;
                }
                size = socket.Receive(buffer, offset, Math.Min(BufferSize - offset, unreadSize), SocketFlags.None);
                if (size <= 0)
                {
                    return;
                }
                readSize   += size;
                offset     += size;
                unreadSize -= size;
                stream.Write(buffer, 0, size);
                offset = 0;

                if (unreadSize == 0)
                {// finish read a message, deserialize message to a class, invoke message receive callback
                    stream.Seek(0, SeekOrigin.Begin);
                    Message msg = (Message)formatter.Deserialize(stream);
                    if (command != Command.S_PLAYER_MOVE)
                    {
                        UnityEngine.Debug.Log(string.Format("Message {0}", command.ToString()));
                    }
                    try
                    {
                        MessageDelegate @delegate = messageDelegate[command];
                        @delegate.Invoke(this, msg);
                    }
                    catch (KeyNotFoundException e)
                    {
                        Trace.WriteLine(string.Format("catch KeyNotFoundException {0} when calling invoke", e.ToString()));
                    }
                    catch (SystemException)
                    {
                    }
                    // clear the receive strean and reset receive state
                    stream.Seek(0, SeekOrigin.End);
                    stream.Position = 0;
                    offset          = 0;
                    command         = Command.NONE;
                    readSize        = 0;
                    unreadSize      = 4;
                }
            }
        }
Exemple #28
0
 //register delegate
 public void RegisterMessageDelegate(MessageDelegate mes)
 {
     mesDel = mes;
 }
Exemple #29
0
        //abstract public void AsyncConnect(string ip, short port, ChannelDelegate @delegate);

        abstract public void RegisterMessageRecv(Command cmd, MessageDelegate @delegate);
Exemple #30
0
 // threaded message listener
 public OpenFaceAnimatorListener(MessageDelegate messageDelegate)
 {
     _messageDelegate = messageDelegate;
     _listenerWorker  = new Thread(ListenerWork);
 }
 public void Error(string strMessage, string strTitle, MessageDelegate delMsg)
 {
     throw new NotImplementedException();
 }
Exemple #32
0
        public static void StartListening(string eventName, MessageDelegate listener)
        {
            List <MessageDelegate> listeners = Instance.eventDictonary.SafeGetOrInitialize(eventName);

            listeners.AddIfUnique(listener);
        }
 public NetMqPair(MessageDelegate messageDelegate, bool createConnection = false)
 {
     _createConnection = createConnection;
     _messageDelegate  = messageDelegate;
     _connectionWorker = new Thread(ConnectionWork);
 }
        //This is very similar to the back test but decided to duplicate the code because the BackTest needs to very fast and didn't want to build timeframes and then backtest
        //instead backtesting builds the timeframes as it goes.
        public static Dictionary <int, Bar[]> BuildTimeFrames(Asset asset, int[] requiredTimeframes, MessageDelegate messageDelegate = null)
        {
            //Record start time of process for time taken message
            DateTime now = DateTime.Now;

            ///Can run this on separate threads per asset if we aren;t worried about drawdown calculations ect..
            messageDelegate?.Invoke(asset.Name + " Building timeframes ...");

            //key is the timeframe in minutes
            Dictionary <int, List <Bar> > datasets = new Dictionary <int, List <Bar> >();


            //Read all the bytes from the datapath from the 1 min timeframe if the data is not already loaded
            //this is very fast about 0.9 seconds for 10 years of minute data
            if (asset.Dataset == null)
            {
                asset.Dataset = DataBuilder.LoadBinary(asset.DataPath);
            }

            byte[] bytes = asset.Dataset;

            //add in the required minute bars with a 1 bar lookback
            //If a strategy needs these bars it will be overwritted in the next foreach loop
            datasets.Add(1, new List <Bar>());

            foreach (int timeframe in requiredTimeframes)
            {
                //overwrite the minute bar details if the strategy requires this
                if (timeframe != 1)
                {
                    datasets.Add(timeframe, new List <Bar>());
                }
            }

            //keep a pointer of the last added bar and date so this can be modified while building up the higher timeframes
            Dictionary <int, Bar>      lastAddedBars  = new Dictionary <int, Bar>();
            Dictionary <int, DateTime> lastAddedDates = new Dictionary <int, DateTime>();


            //Traverse the byte array to build the bars - this can be done on separate threads for each asset for maximum speed
            int i = 0;

            while (i < bytes.Length)
            {
                Bar bar = DataBuilder.ReadBinaryBar(bytes, (i / 44));
                //move to next line in byte array - 1 bar is 44 bytes
                i += 44;

                //go through each timeframe and either create a new bar or increment the current bar
                foreach (KeyValuePair <int, List <Bar> > barSet in datasets)
                {
                    //create a bardate pegged to the nearest timeframe
                    DateTime barDate;
                    if (barSet.Key == 1)
                    {
                        barDate = bar.OpenTime;
                    }
                    else
                    {
                        //Peg the bar to the start of the timeframe
                        TimeSpan d = TimeSpan.FromMinutes(barSet.Key);
                        barDate = (new DateTime((bar.OpenTime.Ticks + d.Ticks) / d.Ticks * d.Ticks, bar.OpenTime.Kind)).AddMinutes(-barSet.Key);
                    }

                    //Keep a record of the last added bars date or set it to the current bar date on the first run
                    DateTime lastAddedDate;
                    if (lastAddedDates.ContainsKey(barSet.Key))
                    {
                        lastAddedDate = lastAddedDates[barSet.Key];
                    }
                    else
                    {
                        lastAddedDate = barDate;
                    }

                    DateTime nextBar = ((DateTime)lastAddedDate).AddMinutes(barSet.Key);

                    //add the bar to all timeframes if it doesnt exist
                    if ((nextBar <= barDate) || !lastAddedDates.ContainsKey(barSet.Key))
                    {
                        //need a new bar for each time frame so we don't have the same pointer in each timeframe
                        Bar setBar = new Bar(bar);

                        //Add to the bar list
                        barSet.Value.Add(setBar);

                        lastAddedBars[barSet.Key]  = setBar;
                        lastAddedDates[barSet.Key] = barDate;
                    }
                    //don't need to increment bars on the 1 minute time frame
                    else if (barSet.Key > 1)
                    {
                        //get the lastAdded bar which is the start of this timeframe
                        Bar lastAdded = lastAddedBars[barSet.Key];

                        //We adjust the bar for the max,min,vol and close
                        if (bar.BidHigh > lastAdded.BidHigh)
                        {
                            lastAdded.BidHigh = bar.BidHigh;
                        }
                        if (bar.BidLow < lastAdded.BidLow)
                        {
                            lastAdded.BidLow = bar.BidLow;
                        }
                        if (bar.AskHigh > lastAdded.AskHigh)
                        {
                            lastAdded.AskHigh = bar.AskHigh;
                        }
                        if (bar.AskLow < lastAdded.AskLow)
                        {
                            lastAdded.AskLow = bar.AskLow;
                        }
                        lastAdded.BidClose = bar.BidClose;
                        lastAdded.AskClose = bar.AskClose;
                        lastAdded.Volume  += bar.Volume;
                    }
                }
            }

            //remove any duplicates and order from oldest to newest
            Dictionary <int, Bar[]> sortedData = new Dictionary <int, Bar[]>();

            foreach (KeyValuePair <int, List <Bar> > barSet in datasets)
            {
                //don't need the minute bar - that was just used for the bar build process
                if (barSet.Key != 1)
                {
                    sortedData.Add(barSet.Key, barSet.Value.OrderBy(x => x.OpenTime).Distinct(x => x.OpenTime).ToArray());
                }
            }

            messageDelegate?.Invoke(asset.Name + " timeframe build took: " + (DateTime.Now - now).TotalSeconds + " secs");


            return(sortedData);
        }
 public void Subscribe(MessageDelegate messageHandler)
 {
     messageHandlers += messageHandler;
 }
Exemple #36
0
		protected virtual Message Add(MessageDelegate processor, DictParams parameters)
		{
			return Add(processor, parameters, 0, false);
		}
Exemple #37
0
 public void SetSelectChangeHandler(MessageDelegate func)
 {
     selectChangeHandler = new MessageDelegate(func);
 }
Exemple #38
0
		protected virtual Message Add(MessageDelegate processor, DictParams parameters, int priority, bool isParallel)
		{
			Message m = new Message(processor, parameters, priority, isParallel);
			int i = GetIndex(priority);
			if (i < 0)
			{
				Messages.Add(m);
			}
			else
			{
				Messages.Insert(i, m);
			}
			return m;
		}
Exemple #39
0
 /// <summary>
 /// Adds a route
 /// </summary>
 public static void Subscribe(MessageDelegate handler)
 {
     OnMessage += handler;
 }
 // Удаление обработчика сообщения
 public void DeleteMessageHandler(string Command, MessageDelegate Handler)
 {
     ServerConnection.DeleteMessageHandler(Command, Handler);
 }
 public static void RegisterObserver(MessageDelegate o)
 {
     MessageEvent += o;
 }
        public static void PythonFeatureBuilder(PythonBridge pb, Asset asset, ExternalFeatureData externalFeatureData, MessageDelegate messageDelegate = null)
        {
            messageDelegate?.Invoke(asset.Name + " Precalcualting Features ...");

            //Record start time of process for time taken message
            DateTime now = DateTime.Now;

            //build the features into a semicolon sepearated string
            string featureCommand = externalFeatureData.FeatureCommands;

            //get the dataset for this timeframe
            Dictionary <int, Bar[]> timeframes = DataBuilder.BuildTimeFrames(asset, new int[] { externalFeatureData.Timeframe });

            //Use a temporary Share directory for this data
            string filename = asset.DataPath.Replace(".bin", "_Share.bin");

            //Generate a tempory binary file containing the datafeed to be used for calculation and save to disk
            string datasetType = "single";

            if (externalFeatureData.CalculateOn == DataFeedType.Ask || externalFeatureData.CalculateOn == DataFeedType.Bid) //otherwise include all bid or ask OHLC and volume.
            {
                datasetType = "whole";
                DataBuilder.DatasetToBinary(filename, timeframes[externalFeatureData.Timeframe], externalFeatureData.CalculateOn);
            }
            else  //Faster way if just need a single data feed
            {
                DataBuilder.DatasetToBinarySingle(filename, timeframes[externalFeatureData.Timeframe], externalFeatureData.CalculateOn);
            }

            //[ASSET] is a placeholder
            string transformedFilename = externalFeatureData.BinaryFilepath.Replace("[ASSET]", asset.Name);

            //Bridge python to calculate the data
            string[] commands = new string[] { datasetType, filename, transformedFilename,
                                               externalFeatureData.FeatureCommands };
            pb.RunScript(FeatureBuildPath, commands);

            File.Delete(filename);

            messageDelegate?.Invoke(asset.Name + " feature calculations took: " + (DateTime.Now - now).TotalSeconds + " secs");
        }
Exemple #43
0
 public TestMessageHandler(MessageDelegate handlerFunc)
 {
     this.handlerFunc = handlerFunc;
 }
 public virtual IFormBuilder <T> Message(MessageDelegate <T> generateMessage, ActiveDelegate <T> condition = null, IEnumerable <string> dependencies = null)
 {
     _form._steps.Add(new MessageStep <T>(generateMessage, condition, dependencies, _form));
     return(this);
 }
Exemple #45
0
		public void Add(MessageDelegate processor)
		{
			Message m = new Message(processor, null);
			Messages.Add(m);
		}
Exemple #46
0
 public void SetButtonClickHandler(MessageDelegate func)
 {
     buttonClickHandler = new MessageDelegate(func);
 }
Exemple #47
0
 /// <summary> 在R_ReceiveMessage中追加聊天信息</summary>
 private void AddTalkMessage(string message)
 {
     if (R_ReceiveMessage.InvokeRequired)
     {
         MessageDelegate d = new MessageDelegate(AddTalkMessage);
         R_ReceiveMessage.Invoke(d, new object[] { message });
     }
     else
     {
         R_ReceiveMessage.AppendText(message + Environment.NewLine);
         R_ReceiveMessage.ScrollToCaret();
     }
 }
Exemple #48
0
 public static void UnregisterMessage(int id, MessageDelegate messageDelegate)
 {
     register.Unregister(id, messageDelegate);
 }
Exemple #49
0
 /// <summary>
 /// Register a handler for a particular message type.
 /// <para>There are several system message types which you can add handlers for. You can also add your own message types.</para>
 /// </summary>
 /// <typeparam name="T">Message type</typeparam>
 /// <param name="handler">Function handler which will be invoked for when this message type is received.</param>
 public void RegisterHandler <T>(MessageDelegate <T> handler)
 {
     RegisterHandler <T>((_, value) => { handler(value); });
 }
Exemple #50
0
 public TestMessageHandler(MessageDelegate handlerFunc)
 {
     this.handlerFunc = handlerFunc;
 }
Exemple #51
0
 public NetMqListener(MessageDelegate messageDelegate)
 {
     _messageDelegate = messageDelegate;
     _listenerWorker  = new Thread(ListenerWork);
 }
        public static void LoadExternalFeatureBinary(Asset asset, ExternalFeatureData externalFeature, MessageDelegate messageDelegate)
        {
            //Read the results into the bars from the binary file that python has written over
            PreCalculatedFeatures pcFeatures = new PreCalculatedFeatures();

            //[ASSET] is used as a placeholder so insert the assetname here
            string filename = externalFeature.BinaryFilepath.Replace("[ASSET]", asset.Name);

            byte[] bytes = File.ReadAllBytes(filename);

            //Traverse the byte array to add in the values to the Data attribute of the corresponding bar
            int i = 0;

            while (i < bytes.Length)
            {
                //Read the required data from the byte array and increment the index
                long timestamp = BitConverter.ToInt64(bytes, i);
                i += 8;
                //convert from python to .net date
                DateTime dt = DateTime.FromBinary(timestamp / 100).AddYears(1969);

                //Add a new bar
                Dictionary <string, double?> barData = new Dictionary <string, double?>();
                pcFeatures.Data.Add(dt, barData);

                foreach (string field in externalFeature.FieldNames)
                {
                    double val = BitConverter.ToDouble(bytes, i);
                    barData.Add(field, val);
                    i += 8;
                }
            }

            //add this data to the asset (or overwrite if exists)
            if (!asset.Data.ContainsKey(externalFeature.Timeframe))
            {
                asset.Data.Add(externalFeature.Timeframe, pcFeatures);
            }
            else
            {
                asset.Data[externalFeature.Timeframe] = pcFeatures;
            }
        }
 /// <summary>
 /// Add a delegate which controls how packets with certain data will be handled.
 /// </summary>
 /// <param name="identifier">If the data in a packet starts with this string the delegate will be called.</param>
 /// <param name="handler">The delegate that is called if the packet data starts with identifier.</param>
 protected void AddPacketDelegate(string identifier, MessageDelegate handler)
 {
     packetDelegates[identifier] = handler;
 }
Exemple #54
0
 static public void Register(Command command, MessageDelegate @delegate)
 {
     Client.Instance.Register(command, @delegate);
 }
Exemple #55
0
		protected virtual Message Add(MessageDelegate processor, DictParams parameters, bool isParallel)
		{
			return Add(processor, parameters, 0, isParallel);
		}
Exemple #56
0
 /// <summary>
 /// Adds a terminal middleware delegate to the application's message pipeline.
 /// </summary>
 public static IPipelineBuilder Run(this IPipelineBuilder builder, MessageDelegate handler)
 {
     builder.Use(_ => handler);
     return(builder);
 }
            public virtual bool PreProcessWmKeyDown(ref Message m)
            {
                System.Diagnostics.Debug.WriteLine("PreProcessWmKeyDown(ref Message m)", "KeyInterpreter");

                Keys vc = (Keys)m.WParam.ToInt32();

                Keys keyData = vc | Control.ModifierKeys;

                // detect whether key down event should be raised
                var hasMessageHandler = this.MessageHandlers.ContainsKey(keyData);
                if (hasMessageHandler && RaiseKeyDown(keyData))
                    return true;

                MessageDelegate messageHandler = hasMessageHandler
                    ? this.MessageHandlers[keyData]
                    : messageHandler = new MessageDelegate(PreProcessWmKeyDown_Default);

                return messageHandler(ref m);
            }
Exemple #58
0
 public virtual void Action(MessageDelegate callback)
 {
     callback("Message1");
 }
 // Удаление обработчика сообщения
 public void DeleteMessageHandler(string Command, MessageDelegate Handler)
 {
     if (Handler == null)
         return;
     List<MessageDelegate> msgHandlers;
     lock (messageHandlers)
     {
         if (messageHandlers.TryGetValue(Command, out msgHandlers))
         {
             msgHandlers.Remove(Handler);
             if (msgHandlers.Count == 0)
             {
                 messageHandlers.Remove(Command);
             }
         }
     }
 }
Exemple #60
0
 override public void RegisterMessageRecv(Command cmd, MessageDelegate @delegate)
 {
     onMessageRecv[cmd] = @delegate;
 }