Beispiel #1
0
 internal override ThreeValuedLogic Evaluate(Strategy strategy)
 {
     var association = strategy.GetCompositeAssociation(this.associationType);
     return (association != null && association.Equals(this.equals))
                ? ThreeValuedLogic.True
                : ThreeValuedLogic.False;
 }
Beispiel #2
0
        internal override ThreeValuedLogic Evaluate(Strategy strategy)
        {
            var compareValue = this.compare;

            var compareRole = this.compare as IRoleType;
            if (compareRole != null)
            {
                compareValue = strategy.GetInternalizedUnitRole(compareRole);
            }
            else
            {
                if (this.roleType.ObjectType is IUnit)
                {
                    compareValue = this.roleType.Normalize(this.compare);
                }
            }

            var comparable = strategy.GetInternalizedUnitRole(this.roleType) as IComparable;

            if (comparable == null)
            {
                return ThreeValuedLogic.Unknown;
            }

            return comparable.CompareTo(compareValue) < 0
                       ? ThreeValuedLogic.True
                       : ThreeValuedLogic.False;
        }
Beispiel #3
0
        internal override ThreeValuedLogic Evaluate(Strategy strategy)
        {
            bool unknown = false;
            foreach (Predicate filter in this.Filters)
            {
                if (filter.Include)
                {
                    switch (filter.Evaluate(strategy))
                    {
                        case ThreeValuedLogic.True:
                            return ThreeValuedLogic.True;
                        case ThreeValuedLogic.Unknown:
                            unknown = true;
                            break;
                    }
                }
            }

            if (unknown)
            {
                return ThreeValuedLogic.Unknown;
            }

            return ThreeValuedLogic.False;
        }
 public void Record(IMdsDescriptor sequence, Strategy strategy )
 {
     Total++;
     if(sequence.IsSuccessful) {
         Successful++;
     }
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="StrategyNameGenerator"/>.
		/// </summary>
		/// <param name="strategy">Strategy.</param>
		public StrategyNameGenerator(Strategy strategy)
		{
			if (strategy == null)
				throw new ArgumentNullException("strategy");

			_strategy = strategy;
			_strategy.SecurityChanged += () =>
			{
				if (_selectors.Contains("Security"))
					Refresh();
			};
			_strategy.PortfolioChanged += () =>
			{
				if (_selectors.Contains("Portfolio"))
					Refresh();
			};

			ShortName = new string(_strategy.GetType().Name.Where(char.IsUpper).ToArray());

			_formatter = Smart.CreateDefaultSmartFormat();
			_formatter.SourceExtensions.Add(new Source(_formatter, new Dictionary<string, string>
			{
				{ "FullName", _strategy.GetType().Name },
				{ "ShortName", ShortName },
			}));

			_selectors = new SynchronizedSet<string>();

			AutoGenerateStrategyName = true;
			Pattern = "{ShortName}{Security:_{0.Security}|}{Portfolio:_{0.Portfolio}|}";
		}
        internal override ThreeValuedLogic Evaluate(Strategy strategy)
        {
            if (this.associationType.IsMany)
            {
                var associations = strategy.GetCompositeAssociations(this.associationType);
                foreach (var assoc in associations)
                {
                    if (this.containingExtent.Contains(assoc))
                    {
                        return ThreeValuedLogic.True;
                    }
                }

                return ThreeValuedLogic.False;
            }

            var association = strategy.GetCompositeAssociation(this.associationType);
            if (association != null)
            {
                return this.containingExtent.Contains(association)
                           ? ThreeValuedLogic.True
                           : ThreeValuedLogic.False;
            }

            return ThreeValuedLogic.False;
        }
        public UIController(List<BrokerManager> b, PositionManager pos, MainWindow w)
        {
            runningStrategy = null;
            cummulativePnL = 0;
            win = w;
            brokers = b;
            pos.PositionChange += new PositionChangedEventHandler(positionChange);
            pos.TradeMatched += new TradeMatchedEventHandler(tradeMatched);
            win.StrategyStart += new StrategyStartDelegate(startStrategy);
            win.StrategyStop += new StrategyStopDelegate(stopStrategy);

            //register to receive events from brokers
            foreach (BrokerManager brk in brokers)
            {
                brk.FillUpdate += new FillEventHandler(fillReceived);
                brk.OrderConfirmed += new OrderConfirmEventHandler(orderConfirmed);
                brk.RiskFilterFailure += new RiskFilterFailureEventHandler(riskFilterFailed);
                brk.LastUpdate += new LastUpdateEventHandler(lastUpdate);
            }

            Dictionary<int, String> strategyMap = new Dictionary<int, String>();
            strategyMap.Add(0, "Buy & Hold");
            strategyMap.Add(1, "Pair Trade");
            win.availableStrategies = strategyMap;
        }
Beispiel #8
0
		private void OnChildStrategiesAdded(Strategy strategy)
		{
			var rule = strategy
				.WhenStopped()
				.Do(s =>
				{
					if (FinishMode == BasketStrategyFinishModes.First)
					{
						if (FirstFinishStrategy == null)
						{
							FirstFinishStrategy = s;
							Stop();
						}
					}
					else
					{
						if (ChildStrategies.SyncGet(c => c.All(child => child.ProcessState != ProcessStates.Started)))
							Stop();
					}
				})
				.Once()
				.Apply(this);

			rule.UpdateName(rule.Name + " (BasketStrategy.OnChildStrategiesAdded)");
		}
        internal override ThreeValuedLogic Evaluate(Strategy strategy)
        {
            var containing = new HashSet<IObject>(this.containingEnumerable);

            if (this.associationType.IsMany)
            {
                var associations = strategy.GetCompositeAssociations(this.associationType);
                foreach (var assoc in associations)
                {
                    if (containing.Contains((IObject)assoc))
                    {
                        return ThreeValuedLogic.True;
                    }
                }

                return ThreeValuedLogic.False;
            }

            var association = strategy.GetCompositeAssociation(this.associationType);
            if (association != null)
            {
                return containing.Contains(association)
                           ? ThreeValuedLogic.True
                           : ThreeValuedLogic.False;
            }

            return ThreeValuedLogic.False;
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="run">Run</param>
        /// <param name="strategy">Strategy</param>
        public BackoffRunner(IDynamicRuns run, Strategy strategy = Strategy.Exponential)
            : base(run.MinimumPeriodInSeconds, run.MaximumPeriodInSeconds, strategy)
        {
            this.run = run;

            base.Name = string.Format("{0}+{1}", this.GetType(), this.run.GetType());
        }
Beispiel #11
0
        public static void Main(string[] args)
        {
            string inputname = args[0];
            string outputname = args[1];

            string[] lines = File.ReadAllLines(inputname);

            int ncases = int.Parse(lines[0]);
            IList<string> results = new List<string>();
            Strategy strat = new Strategy();
            int nline = 0;

            for (int k = 0; k < ncases; k++)
            {
                nline++;
                int nnumbers = int.Parse(lines[nline].Trim());
                nline++;
                var first = lines[nline].Trim().Split(' ').Select(n => double.Parse(n)).ToList();
                nline++;
                var second = lines[nline].Trim().Split(' ').Select(n => double.Parse(n)).ToList();

                int nwinwar = strat.CalculateWar(first, second);
                int nwindwar = strat.CalculateDeceitfulWar(first, second);

                results.Add(string.Format("Case #{0}: {1} {2}", k + 1, nwindwar, nwinwar));
            }

            File.WriteAllLines(outputname, results.ToArray());
        }
			public StrategyItem(Strategy strategy)
			{
				if (strategy == null)
					throw new ArgumentNullException(nameof(strategy));

				Strategy = strategy;
			}
Beispiel #13
0
        internal override ThreeValuedLogic Evaluate(Strategy strategy)
        {
            var value = strategy.GetInternalizedUnitRole(this.roleType);

            if (value == null)
            {
                return ThreeValuedLogic.Unknown;
            }

            var equalsValue = this.equals;

            if (this.equals is IRoleType)
            {
                var equalsRole = (IRoleType)this.equals;
                equalsValue = strategy.GetInternalizedUnitRole(equalsRole);
            }
            else
            {
                if (this.roleType.ObjectType is IUnit)
                {
                    equalsValue = RoleTypeExtensions.Normalize(this.roleType, this.@equals);
                }
            }

            if (equalsValue == null)
            {
                return ThreeValuedLogic.False;
            }

            return value.Equals(equalsValue)
                       ? ThreeValuedLogic.True
                       : ThreeValuedLogic.False;
        }
Beispiel #14
0
        internal override ThreeValuedLogic Evaluate(Strategy strategy)
        {
            object value = strategy.GetCompositeRole(this.roleType);

            if (value == null)
            {
                return ThreeValuedLogic.False;
            }

            object equalsValue = this.equals;

            if (this.equals is IRoleType)
            {
                var equalsRole = (IRoleType)this.equals;
                equalsValue = strategy.GetCompositeRole(equalsRole);
            }

            if (equalsValue == null)
            {
                return ThreeValuedLogic.False;
            }

            return value.Equals(equalsValue)
                       ? ThreeValuedLogic.True
                       : ThreeValuedLogic.False;
        }
        public static void Main(string[] args)
        {
            var strategy = new Strategy(5);
            var result = strategy.Go().Result;

            Console.WriteLine($"Result: {result}");

        }
Beispiel #16
0
        public void CalculateSimpleWarWin()
        {
            Strategy strat = new Strategy();

            var result = strat.CalculateWar(new double[] { 0.2 }, new double[] { 0.1 });

            Assert.AreEqual(1, result);
        }
Beispiel #17
0
        public void CalculateWarCaseFour()
        {
            Strategy strat = new Strategy();

            var result = strat.CalculateWar(new double[] { 0.186, 0.389, 0.907, 0.832, 0.959, 0.557, 0.300, 0.992, 0.899 }, new double[] { 0.916, 0.728, 0.271, 0.520, 0.700, 0.521, 0.215, 0.341, 0.458 });

            Assert.AreEqual(4, result);
        }
Beispiel #18
0
        public void CalculateDeceitfulWarCaseTwo()
        {
            Strategy strat = new Strategy();

            var result = strat.CalculateDeceitfulWar(new double[] { 0.7, 0.2 }, new double[] { 0.8, 0.3 });

            Assert.AreEqual(1, result);
        }
 public void Record(IMdsDescriptor sequence, Strategy strategy )
 {
     if(writer!=null) {
         writer.WriteLine("{0} {1} => {2}", sequence.IsSuccessful?"SUCCESS":"FAILURE", strategy, sequence);
     }
     if(wrappedLogger==null) return;
     wrappedLogger.Record(sequence,strategy);
 }
Beispiel #20
0
        public void CalculateDeceitfulWarCaseThree()
        {
            Strategy strat = new Strategy();

            var result = strat.CalculateDeceitfulWar(new double[] { 0.5, 0.1, 0.9 }, new double[] { 0.6, 0.4, 0.3 });

            Assert.AreEqual(2, result);
        }
Beispiel #21
0
	public static void setStrategy(Strategy s ){
		BallScript.strategy = s;

		if (s.GetType()== new secondStrategy().GetType()) {
			Debug.Log("sec strategy");
			BallScript.strategy=new secondStrategy();
		}
	}
Beispiel #22
0
        public void CalculateDeceitfulWarCaseOne()
        {
            Strategy strat = new Strategy();

            var result = strat.CalculateDeceitfulWar(new double[] { 0.5 }, new double[] { 0.6 });

            Assert.AreEqual(0, result);
        }
 public MsilSymbolManager(ICommandLine commandLine, IFilter filter, log4net.ILog logger, Strategy.ITrackedMethodStrategyManager trackedMethodStrategyManager)
 {
     _commandLine = commandLine;
     _filter = filter;
     _logger = logger;
     _trackedMethodStrategyManager = trackedMethodStrategyManager;
     _methods = new Dictionary<int, MethodDefinition>();
 }
Beispiel #24
0
 private void ResetTree()
 {
     currentStrategy = null;
     currentState = Names.STATE_IDLE;
     treeLevel = 0;
     jobDone = false;
     //Debug.Log("Reset Tree.");
 }
Beispiel #25
0
 public BaseEnemy(string name, int attack, Strategy strategy) 
 {
     this.health = 20;
     this.name = name;
     this.attack = attack;
     this.strategy = strategy;
     this.speed = Random.Range(9, 15); //TODO: CHANGE THIS
     this.xp = 20;
 }
 /// <summary>
 /// Finds the first child element matching the given mechanism and value.
 /// </summary>
 /// <param name="strategy">The mechanism by which to find the elements.</param>
 /// <param name="value">The value to use to search for the elements.</param>
 /// <param name="timeout">Optional timeout in milliseconds</param>
 /// <param name="raise"></param>
 /// <returns>WebElement</returns>
 public WebElement FindElementBy(Strategy strategy, string value, int timeout = -1, bool raise = true) {
     try {
         return FindFirstElement(strategy, value, timeout);
     } catch (Errors.NoSuchElementError) {
         if (raise)
             throw new Errors.NoSuchElementError(strategy, value);
         return null;
     }
 }
Beispiel #27
0
        internal override ThreeValuedLogic Evaluate(Strategy strategy)
        {
            var roles = strategy.GetCompositeRoles(this.roleType);
            if (roles != null)
            {
                return roles.Contains(this.containedObject) ? ThreeValuedLogic.True : ThreeValuedLogic.False;
            }

            return ThreeValuedLogic.False;
        }
 /// <summary>
 /// Constructor for use in code when optimizing remapping.
 /// </summary>
 /// <param name="character">Character information</param>
 /// <param name="plan">Plan to optimize for</param>
 /// <param name="strategy">Optimization strategy</param>
 /// <param name="name">Title of this form</param>
 /// <param name="description">Description of the optimization operation</param>
 public AttributesOptimizationForm(Character character, BasePlan plan, Strategy strategy, string name, string description)
     : this()
 {
     m_character = character;
     m_baseCharacter = character.After(plan.ChosenImplantSet);
     m_strategy = strategy;
     m_plan = plan;
     m_description = description;
     Text = name;
 }
Beispiel #29
0
        internal override ThreeValuedLogic Evaluate(Strategy strategy)
        {
            if (this.equals == null)
            {
                return ThreeValuedLogic.False;
            }

            return this.equals.Equals(strategy.GetObject())
                       ? ThreeValuedLogic.True
                       : ThreeValuedLogic.False;
        }
Beispiel #30
0
 public BackgroundObject(Texture2D texture, Vector2 position, float rotation, float size, Strategy strategy)
 {
     _sprite = new Sprite(texture);
     Position = position;
     _sprite.Position = position;
     _sprite.Scale = new Vector2(size);
     _sprite.Color = ColorFromSize(size);
     _sprite.CenterOrigin();
     _rotation = rotation;
     _strategy = strategy;
 }
Beispiel #31
0
 public Stop(Strategy strategy, Position position, double level, StopType type, StopMode mode)
     : this(strategy, position, DateTime.MinValue, level, type, mode)
 {
 }
Beispiel #32
0
 public Stop(Strategy strategy, Position position, DateTime time)
     : this(strategy, position, time, 0, StopType.Trailing, StopMode.Percent)
 {
 }
Beispiel #33
0
        public ProcessSystemConfigParser(string nodeName, Types typeDefs, IEnumerable <FuncSpec> strategyFuncs)
        {
            strategyFuncs     = strategyFuncs ?? new FuncSpec[0];
            this.nodeName     = nodeName;
            this.types        = typeDefs;
            this.clusterType  = types.Register(BuildClusterType());
            this.processType  = types.Register(BuildProcessType());
            this.routerType   = types.Register(BuildRouterType());
            this.strategyType = types.Register(BuildStrategySpec(types, strategyFuncs));

            var opChars = ":!%&*+.<=>\\^|-~";

            // Process config definition
            Definition = GenLanguageDef.Empty.With(
                CommentStart: "/*",
                CommentEnd: "*/",
                CommentLine: "//",
                NestedComments: true,
                OpStart: oneOf(opChars),
                OpLetter: oneOf(opChars),
                IdentStart: letter,
                IdentLetter: either(alphaNum, oneOf("-_")),
                ReservedNames: List("if", "then", "else").AddRange(types.AllInOrder.Map(t => t.Name)),
                ReservedOpNames: List("-", "+", "/", "*", "==", "!=", ">", "<", "<=", ">=", "||", "&&", "|", "&", "%", "!", "~", "^")
                );

            // Token parser
            // This builds the standard token parser from the definition above
            TokenParser   = makeTokenParser(Definition);
            identifier    = TokenParser.Identifier;
            stringLiteral = TokenParser.StringLiteral;
            integer       = TokenParser.Integer;
            floating      = TokenParser.Float;
            natural       = TokenParser.Natural;
            whiteSpace    = TokenParser.WhiteSpace;
            symbol        = TokenParser.Symbol;
            reserved      = TokenParser.Reserved;
            reservedOp    = TokenParser.ReservedOp;

            // Binary operator parser
            Func <string, Assoc, Operator <ValueToken> > binary =
                (name, assoc) =>
                Operator.Infix(assoc,
                               from x in reservedOp(name)
                               select ValueToken.BinaryOp(name));

            // Prefix operator parser
            Func <string, Operator <ValueToken> > prefix =
                (name) =>
                Operator.Prefix(
                    from x in reservedOp(name)
                    select ValueToken.PrefixOp(name));

            // Postfix operator parser
            Func <string, Operator <ValueToken> > postfix =
                (name) =>
                Operator.Postfix(
                    from x in reservedOp(name)
                    select ValueToken.PostfixOp(name));

            // Operator table
            Operator <ValueToken>[][] table =
            {
                new [] { prefix("-"), prefix("+"), prefix("!") },
                new [] { binary("*",  Assoc.Left), binary("/", Assoc.Left), binary("%", Assoc.Left)},
                new [] { binary("+",  Assoc.Left), binary("-", Assoc.Left)},
                new [] { binary("<",  Assoc.Left), binary(">", Assoc.Left), binary(">=", Assoc.Left), binary("<=", Assoc.Left)},
                new [] { binary("==", Assoc.Left), binary("!=", Assoc.Left)},
                new [] { binary("&",  Assoc.Left) },
                new [] { binary("^",  Assoc.Left) },
                new [] { binary("|",  Assoc.Left) },
                new [] { binary("&&", Assoc.Left) },
                new [] { binary("||", Assoc.Left) },
            };


            Func <Option <string>, TypeDef, Parser <ValueToken> > valueInst = null;
            Parser <TypeDef> typeName = null;

            // ProcessId parser
            processId =
                token(
                    from xs in many1(choice(lower, digit, oneOf("@/[,-_]{}: ")))
                    let r                     = (new string(xs.ToArray())).Trim()
                                      let pid = ProcessId.TryParse(r)
                                                from res in pid.Match(
                        Right: x => result(x),
                        Left: ex => failure <ProcessId>($"{ex.Message} '({r})'"))
                                                select res);

            // ProcessName parser
            processName =
                token(
                    from o in symbol("\"")
                    from xs in many1(choice(lower, digit, oneOf("@/[,-_]{.}: ")))
                    from c in symbol("\"")
                    let r                 = (new string(xs.ToArray())).Trim()
                                    let n = ProcessName.TryParse(r)
                                            from res in n.Match(
                        Right: x => result(x),
                        Left: ex => failure <ProcessName>(ex.Message))
                                            select res);

            // Attribute parser
            Func <string, Parser <ValueToken>, Parser <NamedValueToken> > attr =
                (name, p) =>
                from x in reserved(name)
                from _ in symbol("=")
                from v in p
                select new NamedValueToken(name, v, None);

            // Type name parser
            Parser <Type> type =
                from x in letter
                from xs in many1(choice(letter, ch('.'), ch('_')))
                select Type.GetType(new string(x.Cons(xs).ToArray()));

            var directive    = types.Directive.ValueParser(this).Map(x => (Directive)x);
            var msgDirective = types.MessageDirective.ValueParser(this).Map(x => (MessageDirective)x);

            Parser <State <Exception, Option <Directive> > > exceptionDirective =
                from b in symbol("|")
                from t in token(type)
                from a in symbol("->")
                from d in directive
                select Strategy.With(d, t);

            Parser <State <Exception, Option <Directive> > > otherwiseDirective =
                from b in symbol("|")
                from t in symbol("_")
                from a in symbol("->")
                from d in directive
                select Strategy.Otherwise(d);

            Parser <State <Directive, Option <MessageDirective> > > matchMessageDirective =
                from b in symbol("|")
                from d in token(directive)
                from a in symbol("->")
                from m in token(msgDirective)
                select Strategy.When(m, d);

            Parser <State <Directive, Option <MessageDirective> > > otherwiseMsgDirective =
                from b in symbol("|")
                from t in symbol("_")
                from a in symbol("->")
                from d in token(msgDirective)
                select Strategy.Otherwise(d);

            // Strategy exception -> directive parser
            match =
                from _ in attempt(reserved("match"))
                from direx in many(attempt(exceptionDirective))
                from other in optional(otherwiseDirective)
                let dirs = direx.Append(other.AsEnumerable()).ToArray()
                           from ok in dirs.Length > 0
                    ? result(dirs)
                    : failure <State <Exception, Option <Directive> >[]>("'match' must be followed by at least one clause")
                           select new ValueToken(types.Get("strategy"), Strategy.Match(dirs));

            Parser <State <StrategyContext, Unit> > redirectMatch =
                from direx in many(attempt(matchMessageDirective))
                from other in optional(otherwiseMsgDirective)
                let dirs = direx.Append(other.AsEnumerable()).ToArray()
                           from ok in dirs.Length > 0
                    ? result(dirs)
                    : failure <State <Directive, Option <MessageDirective> >[]>("'redirect when' must be followed by at least one clause")
                           select Strategy.Redirect(dirs);

            // Strategy directive -> message-directive matching parser
            redirect =
                from n in attempt(reserved("redirect"))
                from t in either(attempt(symbol(":")), reserved("when"))
                from r in t == ":"
                   ? from d in token(msgDirective)
                select Strategy.Redirect(d)
                   : redirectMatch
                select new ValueToken(types.Get("strategy"), r);

            // Type name parser
            typeName = choice(Seq(types.AllInOrder.Map(t => reserved(t.Name).Map(_ => t))));

            // cluster.<alias>.<property> parser -- TODO: generalise
            Parser <ValueToken> clusterVar =
                attempt(
                    from _ in reserved("cluster")
                    from tup in either(
                        attempt(
                            from d1 in symbol(".")
                            from alias in identifier
                            from d2 in symbol(".")
                            from id in identifier
                            select Tuple(alias, id)),
                        attempt(
                            from d in symbol(".")
                            from id in identifier
                            select Tuple("", id)))
                    from sub in optional(from d2 in symbol(".")
                                         from id2 in identifier
                                         select id2).Map(x => x.IfNone("value"))
                    from state in getState <ParserState>()                              // TODO: This can be generalised into an object walking system
                    from v in state.Clusters.Find(tup.Item1).Match(                     //       where an object (in this case the cluster), is in 'scope'
                        Some: cluster =>                                                //       and recursive walking of the dot operator will find the
                        cluster.Settings.Find(tup.Item2).Match(                         //       value.
                            Some: local => result(local),
                            None: () => failure <ValueToken>($"unknown identifier 'cluster.{tup.Item2}'")),
                        None: () => failure <ValueToken>($"cluster.{tup.Item2} used when a cluster with a node-name attribute set to '{nodeName}' hasn't been defined.  Or the cluster called '{nodeName}' exists and is aliased, and you're not providing the variable in the form: cluster.<alias>.<property-name>"))
                    select v
                    );

            // Variable of unknown type parser
            Parser <ValueToken> variable =
                either(
                    clusterVar,
                    attempt(
                        from id in identifier
                        from state in getState <ParserState>()
                        from v in state.Local(id).Match(
                            Some: v => result(v),
                            None: () => failure <ValueToken>($"unknown identifier '{id}' "))
                        select v
                        )
                    );

            // Variable of known type parser
            Func <TypeDef, Parser <ValueToken> > variableOfType =
                expect =>
                from v in variable
                from r in v.Type == expect
                        ? result(v)
                        : expect.Convert(v).Match(
                    Some: x => result(x),
                    None: () => failure <ValueToken>($"type mismatch {v.Type} found, expected {expect}")
                    )
                select r;

            Parser <ValueToken> ternary =
                token(
                    from __ in attempt(reserved("if"))
                    from eb in exprUnknownType
                    from ex in eb.Type == types.Bool
                        ? result(eb)
                        : failure <ValueToken>("ternary expressions must evaluate to a boolean value")
                    from th in reserved("then")
                    from te in exprUnknownType
                    from el in reserved("else")
                    from ee in exprUnknownType
                    select((bool)ex.Value) ? te : ee
                    );

            valueUntyped = choice(
                variable,
                choice(Seq(types.AllInOrder.Map(typ => attempt(typ.ValueParser(this).Map(val => new ValueToken(typ, typ.Ctor(None, val)))))))
                );

            // Expression term parser
            Parser <ValueToken> termUnknownType =
                choice(
                    parens(lazyp(() => exprUnknownType)),
                    ternary,
                    valueUntyped);

            // Expression parser
            exprUnknownType =
                buildExpressionParser(table.Reverse().ToArray(), termUnknownType);

            // Variable declaration parser
            valueDef =
                from typ in either(
                    attempt(reserved("let")).Map(x => Option <TypeDef> .None),
                    typeName.Map(Option <TypeDef> .Some)
                    )
                from arr in optional(symbol("[]"))
                from _ in arr.IsSome && typ.IsNone
                    ? failure <Unit>("when declaring an array you must specify the type, you can't use 'let'")
                    : result <Unit>(unit)
                from id in identifier.label("identifier")
                from alias in optional(
                    from a_ in reserved("as")
                    from nm in identifier
                    select nm)
                from __ in symbol(":")
                from v in arr.IsSome
                    ? either(
                    attempt(valueInst(alias, TypeDef.Map(() => typ.IfNone(TypeDef.Unknown)))),
                    valueInst(alias, TypeDef.Array(() => typ.IfNone(TypeDef.Unknown))))
                    : typ.Map(t => expr(alias, t))
                .IfNone(() => exprUnknownType)
                from nv in result(new NamedValueToken(id, v, alias))
                from state in getState <ParserState>()
                from res in state.LocalExists(id)
                    ? failure <ParserState>($"A value with the name '{id}' already declared")
                    : result(state.AddLocal(id, v))
                from ___ in setState(res)
                select nv;

            // Value or variable parser
            valueInst = (alias, typ) => either(variableOfType(typ), typ.ValueParser(this).Map(value => new ValueToken(typ, typ.Ctor(alias, value))));

            // Expression term parser
            term =
                (alias, expected) =>
                choice(
                    parens(lazyp(() => expr(alias, expected))),
                    valueInst(alias, expected),
                    from val in exprUnknownType
                    from res in val.Type == expected
                            ? result(val)
                            : failure <ValueToken>($"expression must evaluate to {expected}, it actually evaluates to {val.Type}")
                    select res
                    );

            // Expression parser
            expr =
                (alias, expected) =>
                buildExpressionParser(table, term(alias, expected));

            // Parses a named argument: name = value
            namedArgument =
                (settingName, spec) =>
                attempt(token(attr(spec.Name, expr(None, spec.Type()))));

            // Parses a single non-named argument
            argument =
                (settingName, spec) =>
                attempt(token(expr(None, spec.Type()).Map(x => new NamedValueToken(spec.Name, x, None))));

            // Parses many arguments, wrapped in ( )
            argumentMany =
                (settingName, spec) =>
                from a in commaSep1(choice(Seq(spec.Map(arg => namedArgument(settingName, arg)))))
                from r in a.Count == spec.Length
                        ? result(a)
                        : failure <Seq <NamedValueToken> >("Invalid arguments for " + settingName)
                select r;

            // Parses the arguments for a setting
            arguments =
                (settingName, spec) =>
                spec.Length == 0
                        ? failure <Seq <NamedValueToken> >("Invalid arguments spec, has zero arguments")
                        : spec.Length == 1
                            ? from a in argument(settingName, spec.Head())
                select Seq1(a)
                            : argumentMany(settingName, spec);

            // Declare the global type
            var globalType = new TypeDef("global", (_, x) => x, typeof(Lst <NamedValueToken>), nodeName, 0);

            // Global namespace
            parser = from ws in whiteSpace
                     from __ in setState(ParserState.Empty)
                     from ss in globalType.ValueParser(this)
                     select(Lst <NamedValueToken>) ss;
        }
 public InitializeStrategyCommand(Strategy strategy, DateTime from, DateTime to)
 {
     Strategy = strategy;
     FromDate = from;
     ToDate   = to;
 }
Beispiel #35
0
        // Parse the pairs data from PT to our own common data structure.
        private List <DCALogData> ParsePairsData(dynamic pairsData, bool processBuyStrategies)
        {
            List <DCALogData> pairs = new List <DCALogData>();

            foreach (var pair in pairsData)
            {
                DCALogData dcaLogData = new DCALogData();
                dcaLogData.Amount             = pair.totalAmount;
                dcaLogData.BoughtTimes        = pair.boughtTimes;
                dcaLogData.Market             = pair.market;
                dcaLogData.ProfitPercent      = pair.profit;
                dcaLogData.AverageBuyPrice    = pair.avgPrice;
                dcaLogData.TotalCost          = pair.totalCost;
                dcaLogData.BuyTriggerPercent  = pair.buyProfit;
                dcaLogData.CurrentLowBBValue  = pair.bbLow == null ? 0 : pair.bbLow;
                dcaLogData.CurrentHighBBValue = pair.highBb == null ? 0 : pair.highBb;
                dcaLogData.BBTrigger          = pair.bbTrigger == null ? 0 : pair.bbTrigger;
                dcaLogData.CurrentPrice       = pair.currentPrice;
                dcaLogData.SellTrigger        = pair.triggerValue == null ? 0 : pair.triggerValue;
                dcaLogData.PercChange         = pair.percChange;
                dcaLogData.Leverage           = pair.leverage == null ? 0 : pair.leverage;
                dcaLogData.BuyStrategy        = pair.buyStrategy == null ? "" : pair.buyStrategy;
                dcaLogData.SellStrategy       = pair.sellStrategy == null ? "" : pair.sellStrategy;
                dcaLogData.IsTrailing         = false;

                if (pair.buyStrategies != null && processBuyStrategies)
                {
                    foreach (var bs in pair.buyStrategies)
                    {
                        Strategy buyStrategy = new Strategy();
                        buyStrategy.Type                   = bs.type;
                        buyStrategy.Name                   = bs.name;
                        buyStrategy.EntryValue             = bs.entryValue;
                        buyStrategy.EntryValueLimit        = bs.entryValueLimit;
                        buyStrategy.TriggerValue           = bs.triggerValue;
                        buyStrategy.CurrentValue           = bs.currentValue;
                        buyStrategy.CurrentValuePercentage = bs.currentValuePercentage;
                        buyStrategy.Decimals               = bs.decimals;
                        buyStrategy.IsTrailing             = ((string)bs.positive).IndexOf("trailing", StringComparison.InvariantCultureIgnoreCase) > -1;
                        buyStrategy.IsTrue                 = ((string)bs.positive).IndexOf("true", StringComparison.InvariantCultureIgnoreCase) > -1;

                        dcaLogData.BuyStrategies.Add(buyStrategy);
                    }
                }

                if (pair.sellStrategies != null)
                {
                    foreach (var ss in pair.sellStrategies)
                    {
                        Strategy sellStrategy = new Strategy();
                        sellStrategy.Type                   = ss.type;
                        sellStrategy.Name                   = ss.name;
                        sellStrategy.EntryValue             = ss.entryValue;
                        sellStrategy.EntryValueLimit        = ss.entryValueLimit;
                        sellStrategy.TriggerValue           = ss.triggerValue;
                        sellStrategy.CurrentValue           = ss.currentValue;
                        sellStrategy.CurrentValuePercentage = ss.currentValuePercentage;
                        sellStrategy.Decimals               = ss.decimals;
                        sellStrategy.IsTrailing             = ((string)ss.positive).IndexOf("trailing", StringComparison.InvariantCultureIgnoreCase) > -1;
                        sellStrategy.IsTrue                 = ((string)ss.positive).IndexOf("true", StringComparison.InvariantCultureIgnoreCase) > -1;

                        dcaLogData.SellStrategies.Add(sellStrategy);

                        // Find the target percentage gain to sell.
                        if (sellStrategy.Name.Contains("GAIN", StringComparison.InvariantCultureIgnoreCase))
                        {
                            if (!dcaLogData.TargetGainValue.HasValue || dcaLogData.TargetGainValue.Value > sellStrategy.EntryValue)
                            {
                                // Set the target sell percentage
                                dcaLogData.TargetGainValue = sellStrategy.EntryValue;
                            }
                        }
                    }
                }

                // Calculate current value
                dcaLogData.CurrentValue = dcaLogData.CurrentPrice * dcaLogData.Amount;

                // Convert Unix Timestamp to Datetime
                System.DateTime rdldDateTime = new DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
                rdldDateTime = rdldDateTime.AddSeconds((double)pair.firstBoughtDate).ToUniversalTime();

                // Profit Trailer bought times are saved in UTC
                if (pair.firstBoughtDate > 0)
                {
                    DateTimeOffset ptFirstBoughtDate = DateTimeOffset.Parse(rdldDateTime.Year.ToString() + "-" + rdldDateTime.Month.ToString("00") + "-" + rdldDateTime.Day.ToString("00") + "T" + rdldDateTime.Hour.ToString("00") + ":" + rdldDateTime.Minute.ToString("00") + ":" + rdldDateTime.Second.ToString("00"), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

                    // Convert UTC bought time to local offset time
                    ptFirstBoughtDate = ptFirstBoughtDate.ToOffset(OffsetTimeSpan);

                    dcaLogData.FirstBoughtDate = ptFirstBoughtDate.DateTime;
                }
                else
                {
                    dcaLogData.FirstBoughtDate = Constants.confMinDate;
                }

                _dcaLog.Add(dcaLogData);
            }

            return(pairs);
        }
Beispiel #36
0
 public Rewriter(Strategy strategy)
 {
     CurrentStrategy = strategy;
 }
Beispiel #37
0
        TypeDef BuildStrategySpec(Types types, IEnumerable <FuncSpec> strategyFuncs)
        {
            TypeDef strategy = null;

            Func <Lst <NamedValueToken>, Lst <State <StrategyContext, Unit> > > compose =
                items => items.Map(x => (State <StrategyContext, Unit>)x.Value.Value);

            var oneForOne = FuncSpec.Property("one-for-one", () => strategy, () => strategy, value => Strategy.OneForOne((State <StrategyContext, Unit>)value));
            var allForOne = FuncSpec.Property("all-for-one", () => strategy, () => strategy, value => Strategy.AllForOne((State <StrategyContext, Unit>)value));

            var always   = FuncSpec.Property("always", () => strategy, () => types.Directive, value => Strategy.Always((Directive)value));
            var pause    = FuncSpec.Property("pause", () => strategy, () => types.Time, value => Strategy.Pause((Time)value));
            var retries1 = FuncSpec.Property("retries", () => strategy, () => types.Int, value => Strategy.Retries((int)value));

            var retries2 = FuncSpec.Attrs(
                "retries",
                () => strategy,
                locals => Strategy.Retries((int)locals["count"], (Time)locals["duration"]),
                new FieldSpec("count", () => types.Int),
                new FieldSpec("duration", () => types.Time)
                );

            var backoff1 = FuncSpec.Attrs(
                "backoff",
                () => strategy,
                locals => Strategy.Backoff((Time)locals["min"], (Time)locals["max"], (Time)locals["step"]),
                new FieldSpec("min", () => types.Time),
                new FieldSpec("max", () => types.Time),
                new FieldSpec("step", () => types.Time)
                );

            var backoff2 = FuncSpec.Attrs(
                "backoff",
                () => strategy,
                locals => Strategy.Backoff((Time)locals["min"], (Time)locals["max"], (double)locals["scalar"]),
                new FieldSpec("min", () => types.Time),
                new FieldSpec("max", () => types.Time),
                new FieldSpec("scalar", () => types.Double)
                );

            var backoff3 = FuncSpec.Property("backoff", () => strategy, () => types.Time, value => Strategy.Backoff((Time)value));

            // match
            // | exception -> directive
            // | _         -> directive
            var match = FuncSpec.Special("match", () => strategy);

            // redirect when
            // | directive -> message-directive
            // | _         -> message-directive
            var redirect = FuncSpec.Special("redirect", () => strategy);

            strategy = new TypeDef(
                "strategy",
                typeof(State <StrategyContext, Unit>),
                (_, s) => Strategy.Compose(compose((Lst <NamedValueToken>)s).ToArray().ToArray()),
                20,
                new[] { oneForOne, allForOne, always, pause, retries1, retries2, backoff1, backoff2, backoff3, match, redirect }.Append(strategyFuncs).ToArray()
                );

            return(strategy);
        }
Beispiel #38
0
 /// <summary>
 /// Constructor: Creates a tree for a given strategy
 /// </summary>
 /// <param name="strategy">reference strategy.
 /// </param>
 public Tree(Strategy strategy)
 {
     this._parentStrategy = strategy;
 }
 // Constructor
 public Context(Strategy strategy)
 {
     this._strategy = strategy;
 }
Beispiel #40
0
        /// <summary>
        /// Function: recursive helper function for cloning process.
        /// </summary>
        /// <param name="initialDate">Clone's initialDate</param>
        /// <param name="finalDate">Clone's finalDate</param>
        /// <param name="clones">internal table of previously cloned base ids and respective cloned strategies</param>
        /// <param name="initial_values">internal table of initial values for the new cloned strategies</param>
        /// <param name="simulated">true if the strategy is simulated and not persistent</param>
        private Tree Clone_Internal(DateTime initialDate, DateTime finalDate, Dictionary <int, Strategy> clones, Dictionary <int, double> initial_values, bool simulated)
        {
            Dictionary <int, Strategy> clones_internal = new Dictionary <int, Strategy>();

            foreach (Strategy strat in _strategyDB.Values.ToList())
            {
                Tree tree_clone = strat.Tree.Clone_Internal(initialDate, finalDate, clones, initial_values, simulated);
                if (tree_clone != null)
                {
                    if (!clones.ContainsKey(strat.ID))
                    {
                        clones.Add(strat.ID, tree_clone.Strategy);
                    }
                    clones_internal.Add(strat.ID, tree_clone.Strategy);
                }
            }

            foreach (Strategy strategy in _strategyDB.Values.ToList())
            {
                if (strategy.Portfolio == null)
                {
                    if (!clones.ContainsKey(strategy.ID))
                    {
                        Strategy subclone = strategy.Clone(null, initialDate, finalDate, clones, simulated);

                        if (!clones.ContainsKey(strategy.ID))
                        {
                            clones.Add(strategy.ID, subclone);
                        }

                        clones_internal.Add(strategy.ID, subclone);

                        initial_values.Add(subclone.ID, strategy.GetTimeSeries(TimeSeriesType.Last).Values[0]);
                    }
                    else
                    {
                        clones_internal.Add(strategy.ID, clones[strategy.ID]);
                    }
                }
            }

            if (_parentStrategy.Portfolio != null)
            {
                Portfolio portfolioClone = _parentStrategy.Portfolio.Clone(simulated);
                foreach (int[] ids in _parentStrategy.Portfolio.ReserveIds.ToList())
                {
                    Currency   ccy          = Currency.FindCurrency(ids[0]);
                    Instrument longReserve  = Instrument.FindInstrument(ids[1]);
                    Instrument shortReserve = Instrument.FindInstrument(ids[2]);

                    portfolioClone.AddReserve(ccy, longReserve.InstrumentType == InstrumentType.Strategy ? clones[longReserve.ID] : longReserve, shortReserve.InstrumentType == InstrumentType.Strategy ? clones[shortReserve.ID] : shortReserve);
                }

                Strategy strategyClone = _parentStrategy.Clone(portfolioClone, initialDate, finalDate, clones, simulated);
                if (!clones.ContainsKey(_parentStrategy.ID))
                {
                    clones.Add(_parentStrategy.ID, strategyClone);
                }

                initial_values.Add(strategyClone.ID, _parentStrategy.GetAUM(DateTime.Now, TimeSeriesType.Last));

                Tree clone = strategyClone.Tree;
                foreach (Strategy st in clones_internal.Values.ToList())
                {
                    if (st.Portfolio != null)
                    {
                        st.Portfolio.ParentPortfolio = clone.Strategy.Portfolio;
                    }

                    clone.AddSubStrategy(st);
                }

                return(clone);
            }
            return(null);
        }
Beispiel #41
0
 public static string GenerateBotName(string nameFormula, string symbol, Strategy strategy)
 {
     return(nameFormula
            .Replace("{pair}", symbol)
            .Replace("{strategy}", strategy.ToString()));
 }
        public override void AddStrategy(Strategy strategy)
        {
            switch (((CostBudgetBackupSetStrategyName)strategy.Name))
            {
            case CostBudgetBackupSetStrategyName.CostBudgetBackupSetCode:
                strategy.RelationFieldName = "CostBudgetBackupSetCode";
                strategy.Type = StrategyType.StringEqual;
                break;

            case CostBudgetBackupSetStrategyName.CostBudgetBackupCode:
                strategy.RelationFieldName = "CostBudgetBackupCode";
                strategy.Type = StrategyType.StringEqual;
                break;

            case CostBudgetBackupSetStrategyName.CostBudgetSetCode:
                strategy.RelationFieldName = "CostBudgetSetCode";
                strategy.Type = StrategyType.StringEqual;
                break;

            case CostBudgetBackupSetStrategyName.ProjectCode:
                strategy.RelationFieldName = "ProjectCode";
                strategy.Type = StrategyType.StringEqual;
                break;

            case CostBudgetBackupSetStrategyName.CostBudgetSetName:
                strategy.RelationFieldName = "CostBudgetSetName";
                strategy.Type = StrategyType.StringEqual;
                break;

            case CostBudgetBackupSetStrategyName.CostBudgetSetNameLike:
                strategy.RelationFieldName = "CostBudgetSetName";
                strategy.Type = StrategyType.StringLike;
                strategy.SetParameter(0, "%" + strategy.GetParameter(0) + "%");
                break;

            case CostBudgetBackupSetStrategyName.UnitCode:
                strategy.RelationFieldName = "UnitCode";
                strategy.Type = StrategyType.StringEqual;
                break;

            case CostBudgetBackupSetStrategyName.GroupCode:
                strategy.RelationFieldName = "GroupCode";
                strategy.Type = StrategyType.StringEqual;
                break;

            case CostBudgetBackupSetStrategyName.CostCode:
                strategy.RelationFieldName = "CostCode";
                strategy.Type = StrategyType.StringEqual;
                break;

            case CostBudgetBackupSetStrategyName.PBSType:
                strategy.RelationFieldName = "PBSType";
                strategy.Type = StrategyType.StringEqual;
                break;

            case CostBudgetBackupSetStrategyName.PBSCode:
                strategy.RelationFieldName = "PBSCode";
                strategy.Type = StrategyType.StringEqual;
                break;

            case CostBudgetBackupSetStrategyName.BackupPerson:
                strategy.RelationFieldName = "BackupPerson";
                strategy.Type = StrategyType.StringEqual;
                break;

            case CostBudgetBackupSetStrategyName.BackupDateRange:
                strategy.RelationFieldName = "BackupDate";
                strategy.Type = StrategyType.DateTimeRangeOnlyDate;
                break;

            default:
                strategy.Type = StrategyType.Other;
                break;
            }
            base.AddStrategy(strategy);
        }
Beispiel #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StrategyParam"/>.
 /// </summary>
 /// <param name="strategy">Strategy.</param>
 /// <param name="id">Parameter identifier.</param>
 /// <param name="name">Parameter name.</param>
 public StrategyParam(Strategy strategy, string id, string name)
     : base(strategy, id, name, typeof(T), default)
 {
 }
Beispiel #44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StrategyParam"/>.
 /// </summary>
 /// <param name="strategy">Strategy.</param>
 /// <param name="name">Parameter name.</param>
 public StrategyParam(Strategy strategy, string name)
     : base(strategy, name, name, typeof(T))
 {
 }
Beispiel #45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StrategyParam"/>.
 /// </summary>
 /// <param name="strategy">Strategy.</param>
 /// <param name="id">Parameter identifier.</param>
 /// <param name="name">Parameter name.</param>
 /// <param name="initialValue">The initial value.</param>
 public StrategyParam(Strategy strategy, string id, string name, T initialValue)
     : base(strategy, id, name, typeof(T), initialValue)
 {
 }
        public override int GetHashCode()
        {
            int hash = 1;

            if (TradeId.Length != 0)
            {
                hash ^= TradeId.GetHashCode();
            }
            if (ExchangeOrderId.Length != 0)
            {
                hash ^= ExchangeOrderId.GetHashCode();
            }
            if (System.Length != 0)
            {
                hash ^= System.GetHashCode();
            }
            if (Counterparty.Length != 0)
            {
                hash ^= Counterparty.GetHashCode();
            }
            if (PortfolioId.Length != 0)
            {
                hash ^= PortfolioId.GetHashCode();
            }
            if (Volume != 0D)
            {
                hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(Volume);
            }
            if (InstrumentId.Length != 0)
            {
                hash ^= InstrumentId.GetHashCode();
            }
            if (Price != 0D)
            {
                hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(Price);
            }
            if (Currency.Length != 0)
            {
                hash ^= Currency.GetHashCode();
            }
            if (timestamp_ != null)
            {
                hash ^= Timestamp.GetHashCode();
            }
            hash ^= AdditionalData.GetHashCode();
            if (SystemTradeId.Length != 0)
            {
                hash ^= SystemTradeId.GetHashCode();
            }
            if (UniqueTradeId.Length != 0)
            {
                hash ^= UniqueTradeId.GetHashCode();
            }
            if (Desk.Length != 0)
            {
                hash ^= Desk.GetHashCode();
            }
            if (ExchangeTradeId.Length != 0)
            {
                hash ^= ExchangeTradeId.GetHashCode();
            }
            if (MarketTrade != false)
            {
                hash ^= MarketTrade.GetHashCode();
            }
            if (AlgoId.Length != 0)
            {
                hash ^= AlgoId.GetHashCode();
            }
            if (Strategy.Length != 0)
            {
                hash ^= Strategy.GetHashCode();
            }
            if (Owner.Length != 0)
            {
                hash ^= Owner.GetHashCode();
            }
            if (ClearerAccount.Length != 0)
            {
                hash ^= ClearerAccount.GetHashCode();
            }
            if (Depot.Length != 0)
            {
                hash ^= Depot.GetHashCode();
            }
            if (Safekeeping.Length != 0)
            {
                hash ^= Safekeeping.GetHashCode();
            }
            if (Deleted != false)
            {
                hash ^= Deleted.GetHashCode();
            }
            if (FundingCurrency.Length != 0)
            {
                hash ^= FundingCurrency.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Beispiel #47
0
 public virtual OptimizationParameterSet Optimize(Strategy strategy, OptimizationUniverse universe = null)
 {
     return(null);
 }
Beispiel #48
0
 private By(params By[] locators)
 {
     _strategy = Strategy.Any;
     _value    = locators;
 }
Beispiel #49
0
 private void Optimize(Strategy strategy, InstrumentList instruments, OptimizationUniverse universe,
                       int nFrameworks, int nStrategies)
 {
     throw new NotImplementedException();
 }
Beispiel #50
0
 public InternalOrders(Strategy strategy, TradeDirection direction)
 {
     this.strategy  = strategy;
     this.direction = direction;
 }
Beispiel #51
0
 /// <summary>
 /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
 /// </summary>
 /// <returns>
 /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
 /// </returns>
 public override string ToString()
 {
     return(string.Format("Ур{0} Пер{1} {2} {3} ",
                          Level, MinResalesCount, Strategy.GetDescription(), Price));
 }
Beispiel #52
0
 private By(Strategy strategy, string value)
 {
     _strategy = strategy;
     _value    = value;
 }
Beispiel #53
0
 private void SetStrategy(ref Strategy stratToSet, Strategy strat)
 {
     stratToSet = strat;
 }
        public override void Save(SettingsStorage storage)
        {
            Strategy?.Save(storage);

            base.Save(storage);
        }