public BasicPairTradeStrategy(Product productA, Product productB, List<BrokerManager> b, Int32 targetQtyA, 
            Int32 targetQtyB, Double buySpread, Double sellSpread)
        {
            if(productA == null || productB == null || b == null || targetQtyA == null || targetQtyB == null
                || buySpread == null || sellSpread == null)
            {
                String message = "Invalid parameters";
                log.Error(message);
                throw new Exception(message);
            }

            myOrders = new Dictionary<StrategyOrderType, Order>();
            brokers = b;
            this.state = StrategyState.CREATED;
            this.productA = productA;
            this.productB = productB;
            this.targetQtyA = targetQtyA;
            this.targetQtyB = targetQtyB;
            this.buySpread = buySpread;
            this.sellSpread = sellSpread;

            //register to receive events from broker
            foreach(BrokerManager brk in brokers)
            {
                brk.FillUpdate += new FillEventHandler(fillReceived);
                brk.BidUpdate += new BidUpdateEventHandler(bidUpdate);
                brk.AskUpdate += new AskUpdateEventHandler(askUpdate);
                brk.BidQtyUpdate += new BidQtyUpdateEventHandler(bidQtyUpdate);
                brk.AskQtyUpdate += new AskQtyUpdateEventHandler(askQtyUpdate);
                brk.LastUpdate += new LastUpdateEventHandler(lastUpdate);
                brk.LastQtyUpdate += new LastQtyUpdateEventHandler(lastQtyUpdate);
             }
        }
        double VPaiNextState(ChessState state, StrategyState strategy)
        {
            int Tot = 0; bool isKing = state.State[strategy.SlcR][strategy.SlcC] == ChessType.BKing;
            string mstate = ChessState.StateToStr(state);
            string astrategy = StrategyState.StaToStr(strategy);

            //插入决策
            DataOperation.InsertStrategy(astrategy);

            VSTimes[] NsT = new VSTimes[10000];
            NsT = DataOperation.SelectProbTimes(mstate, astrategy);

            //计算V(s+1)
            double NS = 0.0;
            for (int i = 0; i < NsT.Count(); i++)
            {
                NS += NsT[i].Vs * NsT[i].times;
                Tot += NsT[i].times;
            }
            if (Tot > 0) NS /= Tot;

            //从数据库里读出v(s)
            double vs = DataOperation.SelectVState(mstate);

            //从数据库读出瞬时回报值
            double r = DataOperation.SelectReward(mstate, astrategy, isKing);

            //计算现在的v(s)
            vs = vs + a * (r + u * NS - vs);

            return vs;
        }
        StrategyContext(
            StrategyState global,
            Exception exception,
            object message,
            ProcessId sender,
            ProcessId failedProcess,
            ProcessId parentProcess,
            IEnumerable<ProcessId> siblings,
            IEnumerable<ProcessId> affects,
            Time pause,
            Option<Directive> directive,
            Option<MessageDirective> messageDirective
            )
        {
            bool isStop = directive == LanguageExt.Directive.Stop;

            Global = isStop ? StrategyState.Empty : global;
            Exception = exception;
            Message = message;
            Sender = sender;
            Self = failedProcess;
            ParentProcess = parentProcess;
            Siblings = siblings ?? Siblings;
            Affects = affects ?? Affects;
            Pause = isStop ? 0 * s : pause;
            Directive = directive;
            MessageDirective = messageDirective;
        }
        /// <summary>
        /// Closes the trade if price crosses the upper/lower bollinger band.
        /// </summary>
        /// <param name="candles">candle history</param>
        /// <param name="bar">currentcandle</param>
        /// <param name="tradeManager">tradeManager</param>
        private void CloseTradeIfPossible(List <MarketCandle> candles, int bar, ITradeManager tradeManager)
        {
            var candle = candles[bar];
            var bbands = new BollingerBands(candles, bar);

            // for long we close the trade if price  gets above the upper bollinger bands
            if (_trade.TradeType == TradeType.Long && candle.HighPrice > bbands.Upper)
            {
                if (tradeManager.Close(_trade, candle.HighPrice))
                {
                    _state = StrategyState.Scanning;
                    _trade = null;
                    return;
                }
            }

            // for short we close the trade if price  gets below the lowe bollinger bands
            if (_trade.TradeType == TradeType.Short && candle.LowPrice < bbands.Lower)
            {
                if (tradeManager.Close(_trade, candle.LowPrice))
                {
                    _state = StrategyState.Scanning;
                    _trade = null;
                    return;
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// 检测所给IP在指定策略内是否可用
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="strStrategy"></param>
        /// <returns></returns>
        public StrategyState IsAllow(string ip, string strStrategy)
        {
            StrategyState state = StrategyState.DEFAULT;

            if (!String.IsNullOrEmpty(strStrategy))
            {
                string[] strs = strStrategy.Split("|".ToCharArray());
                int      flag = 0;
                for (int i = 0; i < strs.Length; i++)
                {
                    string        str = strs[i];
                    StrategyState s   = CheckIPInStragegy(ip, str);
                    switch (s)
                    {
                    case StrategyState.DEFAULT:
                        break;

                    case StrategyState.ALLOW:
                        return(StrategyState.ALLOW);

                    case StrategyState.DENY:
                        state = StrategyState.DENY;
                        break;
                    }
                }
            }
            return(state);
        }
Exemple #6
0
        public override StrategyState StrategyInit()
        {
            InitUINames();
            var state = new StrategyState(this);

            Strategy = state;
            return(state);
        }
        protected void HandleWeekendRollover(Tick tick)
        {
            var time      = tick.Time;
            var utcTime   = tick.UtcTime;
            var dayOfWeek = time.GetDayOfWeek();

            switch (state)
            {
            default:
                if (dayOfWeek == 5)
                {
                    var hour   = time.Hour;
                    var minute = time.Minute;
                    if (hour == 16 && minute > 30)
                    {
                        beforeWeekendState = state;
                        state = StrategyState.EndForWeek;
                        goto EndForWeek;
                    }
                }
                break;

            case StrategyState.EndForWeek:
EndForWeek:
                if (dayOfWeek == 5)
                {
                    if (Position.Current != 0)
                    {
                        positionPriorToWeekend = Position.Current;
                        if (positionPriorToWeekend > 0)
                        {
                            Orders.Change.ActiveNow.SellMarket(positionPriorToWeekend);
                        }
                        else if (positionPriorToWeekend < 0)
                        {
                            Orders.Change.ActiveNow.BuyMarket(Math.Abs(positionPriorToWeekend));
                        }
                    }
                    return;
                }
                if (Position.Current == positionPriorToWeekend)
                {
                    state = beforeWeekendState;
                }
                else
                {
                    if (positionPriorToWeekend > 0)
                    {
                        Orders.Change.ActiveNow.BuyMarket(positionPriorToWeekend);
                    }
                    if (positionPriorToWeekend < 0)
                    {
                        Orders.Change.ActiveNow.SellMarket(Math.Abs(positionPriorToWeekend));
                    }
                }
                break;
            }
        }
        private int GetVolume(StrategyState ss)
        {
            if (ss.cparam.BasicVolume > 0)
            {
                return(ss.cparam.BasicVolume);
            }

            return((int)Math.Max(10, Meta.AccountEquity() * (-ss.cparam.BasicVolume) / 1000));
        }
        private async Task Loop()
        {
            _state     = _stateStorage.LastState();
            _followers = _state
                         .Stocks
                         .Select(it => new StockFollower(it.CandleData, _contextProvider,
                                                         _state.Orders.Add, it.Status))
                         .ToList();

            while (true)
            {
                Console.WriteLine($"LOOP START {_timeProvider.Now}");
                var lastLoopDate = _state.Time.Date;
                _state.Time = _timeProvider.Now;

                if (lastLoopDate < _timeProvider.Today)
                {
                    _state.DayChanges++;
                    var savedFollowers = _followers
                                         .Where(it => it.Status is WaitingForSell)
                                         .ToList();

                    var stocks = await _stocksProvider.GetStocks(_cancellationTokenSource.Token);

                    _followers = stocks
                                 .Select(it => new StockFollower(it, _contextProvider, _state.Orders.Add))
                                 .ToList();
                    _followers.AddRange(savedFollowers);
                    _state.Stocks = _followers.Select(it => new FollowingStock(it.Stock, it.Status)).ToList();
                }

                if (_followers.Count == 0 && _state.Time.Date == _timeProvider.Today)
                {
                    var tomorrow = _timeProvider.Today.Add(TimeSpan.FromDays(1));
                    var waiting  = tomorrow - _timeProvider.Now + TimeSpan.FromMinutes(5);
                    Console.WriteLine($"GO SLEEPING FOR {waiting}");
                    await Task.Delay(waiting, _cancellationTokenSource.Token);

                    Console.WriteLine("WAKE UP");
                }

                foreach (var follower in _followers)
                {
                    await follower.Perform(_timeProvider.Now, _cancellationTokenSource.Token);
                }

                _state.Stocks = _followers.Select(it => new FollowingStock(it.Stock, it.Status)).ToList();

                _stateStorage.AddState(_state);

                _timeProvider.SaveTime();

                await _contextProvider.Do(it => _state.Dump(it, _cancellationTokenSource.Token));

                _followers.RemoveAll(it => it.Status is Closed);
            }
        }
        public override StrategyState StrategyInit()
        {
            var state = new StrategyState(this);

            state.onStart  += StartState;
            state.onOver   += EndState;
            state.onUpdate += UpdateState;
            return(state);
        }
Exemple #11
0
        /// <summary>
        /// 检测栏目的IP策略
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="columnId">栏目ID</param>
        /// <returns></returns>
        private StrategyState checkChannelStrategyWithCommon(string ip, string columnId)
        {
            StrategyState state = checkChannelStrategy(ip, columnId);

            if (state == StrategyState.DEFAULT)
            {
                state = checkCommonStrategy(ip);
            }
            return(state);
        }
Exemple #12
0
 public OrderInfo(CreateOrderRequest order, StrategyState state)
 {
     Symbol = order.Symbol;
     Side   = order.Side;
     Status = OrderStatus.New;
     if (order.Price != null)
     {
         Price = Convert.ToDecimal(order.Price);
     }
     Qty            = order.Quantity;
     ClientID       = order.NewClientOrderId;
     StratState     = state;
     BaseCurrReturn = null;
 }
Exemple #13
0
        private void handleStateTransition(StateTransition transition)
        {
            // Handle found word
            if (transition.when == StrategyEvent.WordFound)
            {
                var isRealyWordFound   = this.leftWordBorderDetected && this.rightWordBorderDetected && this.currentWord.Length > 1;
                var isWordAlreadyFound = this.foundWords.Contains(this.currentWord);

                // We found all words, finish
                if (isWordAlreadyFound)
                {
                    // Redefine current state by force
                    this.state = StrategyState.Finish;
                    return;
                }

                // Add new word
                if (isRealyWordFound)
                {
                    this.foundWords.Add(this.currentWord);
                }

                // Reset current word
                this.currentWord = String.Empty;
            }

            // Enable movements track and update variables when something detected
            if (transition.to == StrategyState.DetectInitialBorders)
            {
                Utils.clearTable(ref this.buffer);
                this.windowX = bufferWidth / 2;
                this.windowY = bufferHeight / 2;
                this.copyWindowToBuffer();
                this.updateBufferCollapsed();
                this.updateContentRect();
                this.updateWordRect();
                this.updateCharRect();
                this.leftWordBorderDetected   = false;
                this.rightWordBorderDetected  = false;
                this.topWordBorderDetected    = false;
                this.bottomWordBorderDetected = false;
                this.trackMovements           = true;
            }

            // Disable movements track when we walk out, we enable it later when we detected something
            if (transition.to == StrategyState.WalkOutBorders)
            {
                this.trackMovements = false;
            }
        }
Exemple #14
0
        /// <summary>
        /// 检测文章IP策略设置
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="articleId">文章ID</param>
        /// <param name="channelID">栏目ID</param>
        /// <returns></returns>
        private StrategyState checkArticleStrategy(string ip, string articleId, string channelID)
        {
            StrategyState state = StrategyState.DEFAULT;

            if (!String.IsNullOrEmpty(articleId))
            {
                state = StrategyConfigs.Instance.IsAllow(ip, ArticleHelper.QueryStrategy(articleId));
            }

            if (state == StrategyState.DEFAULT)
            {
                state = checkChannelStrategyWithCommon(ip, channelID);
            }
            return(state);
        }
 void CommonGetStra(Boolean[][] whtmp, int i, int j, ref double max, ref double[] VSmax, ref string[] Stra, ref int count, ChessState state)
 {
     for (int row = 0; row < 8; row++)
     {
         for (int col = 0; col < 8; col++)
         {
             if (whtmp[row][col])
             {
                 StrategyState ss = new StrategyState(i, j, row, col);
                 double Ns = VPaiNextState(state, ss);
                 if (Ns > max) { max = Ns; count = 1; VSmax[0] = Ns; Stra[0] = StrategyState.StaToStr(ss); }
                 else if (Ns == max) { VSmax[count] = Ns; Stra[count++] = StrategyState.StaToStr(ss); }
             }
         }
     }
 }
Exemple #16
0
        /// <summary>
        /// 检测IP是否在某一个策略内
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="strStrategy"></param>
        /// <returns></returns>
        public StrategyState CheckIPInStragegy(string ip, string strStrategy)
        {
            Regex reg = new Regex(@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", RegexOptions.Compiled | RegexOptions.Multiline);

            if (!reg.IsMatch(ip))
            {
                throw new Exception("IP格式不正确");
            }

            StrategyState result = StrategyState.DEFAULT;

            if (!String.IsNullOrEmpty(strStrategy))
            {
                StrategyInfo info = this[strStrategy];
                if (info != null && info.Enable)
                {
                    foreach (string rang in info.DenyIPRang)
                    {
                        if (CheckIPInRang(ip, rang))
                        {
                            return(StrategyState.DENY);
                        }
                    }

                    if (info.AllowIPRang.Count == 0)
                    {
                        result = StrategyState.ALLOW;
                    }
                    else
                    {
                        result = Check(delegate(){
                            foreach (string rang in info.AllowIPRang)
                            {
                                if (CheckIPInRang(ip, rang))
                                {
                                    return(true);
                                }
                            }
                            return(false);
                        }) ? StrategyState.ALLOW : StrategyState.DENY;
                    }
                }
            }
            return(result);
        }
Exemple #17
0
        private StrategyState nextState()
        {
            if (this.transitionEvent.HasValue)
            {
                foreach (var transition in transitions)
                {
                    if ((transition.from == this.state) && (transition.when == this.transitionEvent))
                    {
                        this.state  = transition.to;
                        this.action = null;
                        this.handleStateTransition(transition);
                        return(this.state);
                    }
                }
            }

            return(this.state);
        }
Exemple #18
0
        /// <summary>
        /// 检测栏目IP策略设置
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="columnId">栏目ID</param>
        /// <returns></returns>
        private StrategyState checkChannelStrategy(string ip, string columnId)
        {
            StrategyState state = StrategyState.DEFAULT;

            if (!String.IsNullOrEmpty(columnId))
            {
                state = StrategyConfigs.Instance.IsAllow(ip, ChannelHelper.QueryStrategy(columnId));

                if (state == StrategyState.DEFAULT)
                {
                    Channel channel = ChannelHelper.GetChannel(columnId, new string[] { "ParentID" });
                    if (channel != null)
                    {
                        state = checkChannelStrategy(ip, channel.ParentID);
                    }
                }
            }
            return(state);
        }
        double VPaiNextState(ChessState state, StrategyState strategy)
        {
            //int Tot = 0; 
            bool isKing = state.State[strategy.SlcR][strategy.SlcC] == ChessType.WKing;
            string mstate = ChessState.StateToStr(state);
            string astrategy = StrategyState.StaToStr(strategy);

            //插入决策
            DataOperation.InsertStrategy(astrategy);

            // VSTimes[] NsT = new VSTimes[10000];
            //NsT = DataOperation.SelectProbTimes(mstate, astrategy);

            ////计算V(s+1)
            //double NS = 0.0;
            //for (int i = 0; i < NsT.Count(); i++)
            //{
            //    NS += NsT[i].Vs * NsT[i].times;
            //    Tot += NsT[i].times;
            //}
            //if (Tot > 0) NS /= Tot;

            //从数据库里读出Q(s,a)
            double qs = DataOperation.SelectQState(mstate, astrategy);

            //从数据库读出瞬时回报值
            double r = DataOperation.SelectReward(mstate, astrategy, isKing);

            //计算现在的q(s,a)
            qs = qs + a * (r + u * DataOperation.SelectVState(mstate) - qs);

            //把得到的qs存入数据库
            //DataOperation.InsertQState(mstate, astrategy, qs);

            //把得到的qs存入数组
            QState[qcount] = mstate;
            QStrategy[qcount++] = astrategy;

            return qs;
        }
Exemple #20
0
 public Strategy(AbstractClient client)
 {
     this.state                    = StrategyState.FindSomething;
     this.transitionEvent          = null;
     this.action                   = null;
     this.trackMovements           = false;
     this.moveVertical             = false;
     this.step                     = 0;
     this.client                   = client;
     this.buffer                   = Utils.createTable(bufferWidth, bufferHeight, null);
     this.xCollapsedBuff           = new bool?[bufferWidth];
     this.yCollapsedBuff           = new bool?[bufferHeight];
     this.contentRect              = new Utils.Rect();
     this.wordRect                 = new Utils.Rect();
     this.charRect                 = new Utils.Rect();
     this.currentWord              = "";
     this.foundWords               = new HashSet <string>();
     this.leftWordBorderDetected   = false;
     this.rightWordBorderDetected  = false;
     this.topWordBorderDetected    = false;
     this.bottomWordBorderDetected = false;
 }
Exemple #21
0
        private void UpdateRun(string message, StrategyState state)
        {
            try
            {
                _strategyState = state;

                // Trigger update event
                StatusUpdate(this,
                             new StatusUpdateEventArgs()
                {
                    Run        = _run,
                    Message    = message,
                    State      = this._strategyState,
                    UpdateTime = DateTime.Now
                });
            }
            catch
            {
                _strategyState = StrategyState.Stopped;
                //var error = exc.ToString();
            }
        }
        /// <summary>
        /// Scans for possibility to open a new trade.
        /// </summary>
        /// <param name="candles">candle history</param>
        /// <param name="bar">currentcandle</param>
        /// <param name="tradeManager">tradeManager</param>
        private void ScanForEntry(List <MarketCandle> candles, int bar, ITradeManager tradeManager)
        {
            TradeType tradeType;

            if (IsValidEntry(candles, bar, out tradeType))
            {
                var candle     = candles[bar];
                var totalRebuy = 1m;
                if (MaxTimesRebuy >= 1)
                {
                    totalRebuy += FirstRebuyFactor;
                }
                if (MaxTimesRebuy >= 2)
                {
                    totalRebuy += SecondRebuyFactor;
                }
                if (MaxTimesRebuy >= 3)
                {
                    totalRebuy += ThirdRebuyFactor;
                }
                _bundleSize = tradeManager.AccountBalance / totalRebuy;
                var coins = _bundleSize / candle.ClosePrice;
                switch (tradeType)
                {
                case TradeType.Long:
                    _trade = tradeManager.BuyMarket(Symbol, coins);
                    break;

                case TradeType.Short:
                    _trade = tradeManager.SellMarket(Symbol, coins);
                    break;
                }
                if (_trade != null)
                {
                    _state = StrategyState.Opened;
                }
            }
        }
        public StrategyContext With(
            StrategyState Global = null,
            Exception Exception = null,
            object Message = null,
            ProcessId? Sender = null,
            ProcessId? FailedProcess = null,
            ProcessId? ParentProcess = null,
            IEnumerable<ProcessId> Siblings = null,
            IEnumerable<ProcessId> Affects = null,
            Time? Pause = null,
            Option<Directive> Directive = default(Option<Directive>),
            Option<MessageDirective> MessageDirective = default(Option<MessageDirective>)
        ) =>
            new StrategyContext(
                Global ?? this.Global,
                Exception ?? this.Exception,
                Message ?? this.Message,
                Sender ?? this.Sender,
                FailedProcess ?? this.Self,
                ParentProcess ?? this.ParentProcess,
                Siblings ?? this.Siblings,
                Affects ?? this.Affects,
                Pause ?? this.Pause,

                // The following may look like bugs, but it's intentional that when
                // a Directive or MessageDirective is set, they stay set to their first
                // concrete value.  That means the State strategy expression that runs 
                // has the equivalent of an 'early out'.  The whole expression is still
                // processed, but you can't override the earlier value.
                this.Directive.IsSome
                    ? this.Directive
                    : Directive,
                this.MessageDirective.IsSome
                    ? this.MessageDirective
                    : MessageDirective
            );
        //
        // *****************************************
        // ****         Setup Begin()           ****
        // *****************************************
        /// <summary>
        /// This is called after all Engines have been created, and added to the master
        /// list inside the Strategy (IEngineContainer).
        /// As a convenience, the PricingEngine class locates useful Engines and keeps
        /// pointers to them.
        /// </summary>
        /// <param name="myEngineHub"></param>
        /// <param name="engineContainer"></param>
        public override void SetupBegin(IEngineHub myEngineHub, IEngineContainer engineContainer)
        {
            base.SetupBegin(myEngineHub, engineContainer);

            //
            // Subscribe to economic numbers of legs.
            //
            List <InstrumentName> instruments = new List <InstrumentName>();

            foreach (IEngine iEngine in engineContainer.GetEngines())
            {
                if (iEngine is PricingEngine)
                {
                    PricingEngine pricingEngine = (PricingEngine)iEngine;
                    foreach (Lib.MarketHubs.PriceLeg leg in pricingEngine.m_Legs)
                    {
                        if (!instruments.Contains(leg.InstrumentName))
                        {
                            instruments.Add(leg.InstrumentName);
                        }
                    }
                }
            }
            //QueryBase query = null;
            //this.ParentStrategy.StrategyHub.RequestQuery(query, this.QueryResponseHandler, this.ParentStrategy);

            //
            // Subscribe to start/end trading times
            //
            // If StartTime=EndTime => strategy never shuts off.
            if (ParentStrategy.QueryItem != null && ParentStrategy.StrategyHub.m_Alarm != null &&
                ParentStrategy.QueryItem.StartTime.CompareTo(ParentStrategy.QueryItem.EndTime) != 0)
            {
                Random            random       = new Random();
                StrategyQueryItem strategyItem = ParentStrategy.QueryItem;
                Alarm             alarm        = ParentStrategy.StrategyHub.m_Alarm;

                // Collect today's time/date
                DateTime today = ParentStrategy.StrategyHub.GetLocalTime().Date;       // collect nearest day
                DateTime day   = today;
                if (day.CompareTo(strategyItem.StartDate) < 0)
                {
                    day = strategyItem.StartDate;
                }
                AlarmEventArg eventArg;                                         // my callback event arg.
                while (day.CompareTo(strategyItem.EndDate) <= 0)                // Loop thru each day and set start/end alarms.
                {
                    // Create start event.
                    DateTime dt = day.Add(strategyItem.StartTime);
                    eventArg       = new AlarmEventArg();
                    eventArg.State = StrategyState.Normal;
                    double secs = m_StartTimeSeconds + m_StartTimeSeconds * (0.01 * random.Next(0, m_RandomSlopPercent[0]));
                    eventArg.TimeStemp = dt.AddSeconds(secs);                   // start at start time or after.
                    alarm.Set(dt, this.AlarmEventHandler, eventArg);

                    // Create stop event.
                    dt = day.Add(strategyItem.EndTime);                         // exit time (or earlier)
                    double lastSecs = double.MaxValue;
                    for (int i = 0; i < m_ExitTimeSeconds.Length; ++i)
                    {
                        if (m_ExitTimeSeconds[i] != double.NaN)
                        {
                            StrategyState state = (StrategyState)(i + (int)StrategyState.ExitOnly);
                            eventArg       = new AlarmEventArg();
                            eventArg.State = state;
                            secs           = m_ExitTimeSeconds[i] + m_ExitTimeSeconds[i] * (0.01 * random.Next(0, m_RandomSlopPercent[i]));
                            secs           = Math.Max(0, Math.Min(secs, lastSecs)); // don't allow this exit level to be earlier than previous one.
                            lastSecs       = secs - 1.0;                            // therefore, states padding is strictly decreasing in seconds!
                            DateTime dt2 = dt.AddSeconds(-secs);
                            alarm.Set(dt, this.AlarmEventHandler, eventArg);
                        }
                    }

                    // Increment day
                    day = day.AddDays(1.0).Date;                                // increment until past endDate or ...
                    if (day.DayOfWeek == DayOfWeek.Saturday && day != today)    // ... its Saturday (but continue if today is Sat.).
                    {
                        break;
                    }
                } //wend day
            }
        }         //SetupBegin()
Exemple #25
0
 public ConsistencyEvent(ConsistencyError errorCode, string symbol, bool toSendEmail = true, StrategyState state = null)
 {
     ErrorCode = errorCode;
     Symbol    = symbol;
     Status    = ConsistencyStatus.NOT_VERIFIED;
     if (errorCode != ConsistencyError.CONSISTENT && toSendEmail)
     {
         if (state != null)
         {
             EmailSender.SendEmail("Consistency Error", ToString() + "\r\n" + state.ToString());
         }
         else
         {
             EmailSender.SendEmail("Consistency Error", ToString());
         }
     }
 }
        private void checkForExitCondition()
        {
            if(true) //TODO: replace with real condition
            {
                state = StrategyState.EXITING;
                unwindTrades();

                //Reinitialize system to begining state
                setup();
            }
        }
        //Sends in the initial orders so that we can begin waiting for the signal
        private void setup()
        {
            if(myOrders != null && myOrders.Count() > 0)
                unwindTrades();

            this.state = StrategyState.INITIALIZING;

            //enter initial trades, two for each product
            BrokerManager brk = getFirstBroker();
            
            //We don't want anyone else submitting orders at this time, so that we limit the time 
            //in between the submission of these four orders.
            lock(brk)
            {
                //enter A side based on B price
                LimitOrder sellAOrd = new LimitOrder(productA, bidQtyA, Order.Side.SELL, askB + sellSpread);
                LimitOrder buyAOrd = new LimitOrder(productA, bidQtyA, Order.Side.BUY, bidB + buySpread);

                //submit A side orders
                brk.submitOrder(sellAOrd);
                brk.submitOrder(buyAOrd);

                //Keep track of the A side orders
                myOrders.Add(StrategyOrderType.SELL_A, sellAOrd);
                myOrders.Add(StrategyOrderType.BUY_A, buyAOrd);
                myFills.Add(sellAOrd.internalId, 0);
                myFills.Add(buyAOrd.internalId, 0);

                //enter B side based on A price
                LimitOrder sellBOrd = new LimitOrder(productB, bidQtyB, Order.Side.SELL, askA + sellSpread);
                LimitOrder buyBOrd = new LimitOrder(productB, bidQtyB, Order.Side.BUY, bidA + buySpread);

                //submit B side orders
                brk.submitOrder(sellAOrd);
                brk.submitOrder(buyAOrd);

                //Keep track of the B side orders
                myOrders.Add(StrategyOrderType.SELL_B, sellBOrd);
                myOrders.Add(StrategyOrderType.BUY_B, buyBOrd);
                myFills.Add(sellBOrd.internalId, 0);
                myFills.Add(buyBOrd.internalId, 0);

                this.state = StrategyState.READY;
            }
        }
        public override bool onStart(int ticks)
        {
            for (int i = 1; i < 100; i++)
            {
                string paramName = string.Format("P{0}String", i);
                if (this.param.ContainsString(paramName))
                {
                    StrategyState ssNew = new StrategyState();

                    ssNew.cparam = new PipsovikWeekendParam();
                    string[] paramStr = this.param.GetStringParameter(paramName).Split(new char[] { ',' });
                    ssNew.cparam.Symbol           = paramStr[0];
                    ssNew.cparam.OpenOrderShift   = Int32.Parse(paramStr[1]);
                    ssNew.cparam.BasicVolume      = Int32.Parse(paramStr[2]);
                    ssNew.cparam.HappyHour        = Int32.Parse(paramStr[3]);
                    ssNew.cparam.HappyMinute      = Int32.Parse(paramStr[4]);
                    ssNew.cparam.InitPeriodMinute = Int32.Parse(paramStr[5]);
                    ssNew.cparam.TradeDuration    = Int32.Parse(paramStr[6]);
                    ssNew.cparam.ClosingDuration  = Int32.Parse(paramStr[7]);
                    ssNew.cparam.WorkingDay       = Int32.Parse(paramStr[8]);
                    ssNew.cparam.ID = i;

                    int tradeMinuteTotal = (ssNew.cparam.HappyHour * 60 + ssNew.cparam.HappyMinute + ssNew.cparam.InitPeriodMinute);
                    int startHour        = tradeMinuteTotal / 60;
                    if (startHour >= 24)
                    {
                        startHour -= 24;
                    }
                    int startMinute = tradeMinuteTotal % 60;
                    ssNew.tradeTime.Init(startHour, startMinute, ssNew.cparam.TradeDuration, 0, ssNew.cparam.WorkingDay, 12);
                    ssNew.closeAllTime.Init(startHour, startMinute, ssNew.cparam.TradeDuration + ssNew.cparam.ClosingDuration, 0, ssNew.cparam.WorkingDay, 12);

                    ssList.Add(ssNew);
                }
            }

            if (!ssList.Any())
            {
                StrategyState ssNew = new StrategyState();

                ssNew.cparam                  = new PipsovikWeekendParam();
                ssNew.cparam.Symbol           = base.Symbol;
                ssNew.cparam.OpenOrderShift   = param["OpenOrderShift"];
                ssNew.cparam.BasicVolume      = param["BasicVolume"];
                ssNew.cparam.HappyHour        = param["HappyHour"];
                ssNew.cparam.HappyMinute      = param["HappyMinute"];
                ssNew.cparam.InitPeriodMinute = param["InitPeriodMinute"];
                ssNew.cparam.TradeDuration    = param["TradeDuration"];
                ssNew.cparam.ClosingDuration  = param["ClosingDuration"];
                ssNew.cparam.WorkingDay       = param["WorkingDay"];
                ssNew.cparam.ID               = 0;

                int tradeMinuteTotal = (ssNew.cparam.HappyHour * 60 + ssNew.cparam.HappyMinute + ssNew.cparam.InitPeriodMinute);
                int startHour        = tradeMinuteTotal / 60;
                if (startHour >= 24)
                {
                    startHour -= 24;
                }
                int startMinute = tradeMinuteTotal % 60;
                ssNew.tradeTime.Init(startHour, startMinute, ssNew.cparam.TradeDuration, 0, ssNew.cparam.WorkingDay, 12);
                ssNew.closeAllTime.Init(startHour, startMinute, ssNew.cparam.TradeDuration + ssNew.cparam.ClosingDuration, 0, ssNew.cparam.WorkingDay, 12);

                ssList.Add(ssNew);
            }


            return(true);
        }
Exemple #29
0
        private string GetBestSolution(ResultCollection results)
        {
            string result = string.Empty;

            try
            {
                if (results["Best VRP Solution"] == null)
                {
                    return(null);
                }

                // otherwise we have a valid solution, so update the database
                VRPSolution solution = results["Best VRP Solution"].Value as VRPSolution;

                var tours = solution.Solution.GetTours();

                bool firstDriver = true;

                for (int i = 0; i < tours.Count; i++)
                {
                    if (firstDriver)
                    {
                        firstDriver = false;
                    }
                    else
                    {
                        result += "|";
                    }

                    int tourIndex = solution.Solution.GetTourIndex(tours[i]);
                    int vehicle   = solution.Solution.GetVehicleAssignment(tourIndex);
                    int depot     = _vehicleAssignment[vehicle];

                    //result += _driverIds[depot].ToString() + ":";
                    result += _drivers[depot].name + ":";

                    var stops = string.Empty;

                    bool first = true;

                    foreach (var s in tours[i].Stops)
                    {
                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            stops += ",";
                        }

                        //stops += _stopIds[s - 1].ToString();
                        stops += _tasks[s - 1].name;

                        var penalty = _mutipliers.Where(x => x.DriverName == _drivers[depot].name && x.TaskName == _tasks[s - 1].name).FirstOrDefault();

                        if (penalty.AdjustmentMultiplier >= 1000)
                        {
                            stops += "~2";
                        }
                        else if (penalty.AdjustmentMultiplier > 1)
                        {
                            stops += "~1";
                        }
                        else
                        {
                            stops += "~0";
                        }

                        if (_drivers[depot].name == "2" && _tasks[s - 1].stop.name == "100")
                        {
                            var debug = true;
                        }
                    }

                    result += stops;
                }
            }
            catch
            {
                //alg.Stop();
                _strategyState = StrategyState.Stopped;
                return(null);
            }

            return(result);
        }
        /// <summary>
        /// Perform strategy
        /// </summary>
        /// <param name="candles">candle history</param>
        /// <param name="bar">currentcandle</param>
        /// <param name="tradeManager">tradeManager</param>
        public void OnCandle(List <MarketCandle> candles, int bar, ITradeManager tradeManager)
        {
            switch (_state)
            {
            case StrategyState.Scanning:
                ScanForEntry(candles, bar, tradeManager);
                break;

            case StrategyState.Opened:
                CloseTradeIfPossible(candles, bar, tradeManager);
                if (_trade == null)
                {
                    return;
                }

                if (MaxTimesRebuy >= 1)
                {
                    if (CanRebuy(candles, bar))
                    {
                        var candle = candles[bar];
                        if (DoRebuy(candle, FirstRebuyFactor, tradeManager))
                        {
                            _state = StrategyState.Rebuy1;
                        }
                    }
                }
                break;

            case StrategyState.Rebuy1:
                CloseTradeIfPossible(candles, bar, tradeManager);
                if (_trade == null)
                {
                    return;
                }

                if (MaxTimesRebuy >= 2)
                {
                    if (CanRebuy(candles, bar))
                    {
                        var candle = candles[bar];
                        if (DoRebuy(candle, SecondRebuyFactor, tradeManager))
                        {
                            _state = StrategyState.Rebuy2;
                        }
                    }
                }
                break;

            case StrategyState.Rebuy2:
                CloseTradeIfPossible(candles, bar, tradeManager);
                if (_trade == null)
                {
                    return;
                }

                if (MaxTimesRebuy >= 3)
                {
                    if (CanRebuy(candles, bar))
                    {
                        var candle = candles[bar];
                        if (DoRebuy(candle, ThirdRebuyFactor, tradeManager))
                        {
                            _state = StrategyState.Waiting;
                        }
                    }
                }
                break;

            case StrategyState.Waiting:
                CloseTradeIfPossible(candles, bar, tradeManager);
                break;
            }
        }
        private bool UpdateHappyPrice(Tick <int> currTick, StrategyState ss)
        {
            string id = ss.cparam.ID.ToString();

            if (TestingMode)
            {
                if (currTick.DateTime.Hour == ss.cparam.HappyHour && currTick.DateTime.Minute == ss.cparam.HappyMinute)
                {
                    int averagePrice = (currTick.Ask + currTick.Bid) / 2;
                    if (testingLow > averagePrice)
                    {
                        testingLow = averagePrice;
                    }
                    if (testingHigh < averagePrice)
                    {
                        testingHigh = averagePrice;
                    }

                    ss.happyPrice = (testingLow + testingHigh) / 2;
                }
                else
                {
                    testingLow  = Int32.MaxValue;
                    testingHigh = 0;
                }

                if (ss.happyPrice == 0)
                {
                    return(false);
                }
                return(true);
            }
            if ((currTick.DateTime - ss.happyPriceInitializationDateTime).TotalMinutes > 60 * 24)
            {
                ss.happyPrice = 0;
            }

            if (currTick.DateTime.Hour == ss.cparam.HappyHour && currTick.DateTime.Minute == ss.cparam.HappyMinute)
            {
                ss.happyPrice = 0;
                return(false);
            }
            if (ss.happyPrice == 0)
            {
                AddComment(ss.cparam.ID, "Initializing happy price\n");

                DateTime happyDateTime = new DateTime(currTick.DateTime.Year, currTick.DateTime.Month, currTick.DateTime.Day,
                                                      ss.cparam.HappyHour, ss.cparam.HappyMinute, 0);

                int happyTotalMinute   = ss.cparam.HappyHour * 60 + ss.cparam.HappyMinute;
                int currentTotalMinute = currTick.DateTime.Hour * 60 + currTick.DateTime.Minute;
                if (currentTotalMinute < happyTotalMinute)
                {
                    happyDateTime = happyDateTime.AddDays(-1);
                }
                int shift = Meta.iBarShift(GetNameAverageSymbol(ss.cparam.Symbol), GraphPeriod.PERIOD_M1, happyDateTime, true);
                if (shift == -1)
                {
                    for (int i = 0; i < 5; i++)
                    {
                        happyDateTime = happyDateTime.AddMinutes(-1);
                        shift         = Meta.iBarShift(GetNameAverageSymbol(ss.cparam.Symbol), GraphPeriod.PERIOD_M1, happyDateTime, true);
                    }

                    AddComment(GetNameAverageSymbol(ss.cparam.Symbol) + ": can`t get shift for this symbol.");
                    Meta.RefreshRates();
                    return(false);
                }

                int high = Meta.iHigh(GetNameAverageSymbol(ss.cparam.Symbol), GraphPeriod.PERIOD_M1, shift);
                int low  = Meta.iLow(GetNameAverageSymbol(ss.cparam.Symbol), GraphPeriod.PERIOD_M1, shift);
                if (high == 0 || low == 0)
                {
                    AddComment(GetNameAverageSymbol(ss.cparam.Symbol) + ": can`t get iHigh or iLow from Meta\n");
                    Meta.RefreshRates();
                    return(false);
                }
                ss.happyPrice = (high + low) / 2;
                ss.happyPriceInitializationDateTime = happyDateTime;
            }
            AddComment(ss.cparam.Symbol + string.Format("  happyPrice={0}   ", ss.happyPrice));

            return(true);
        }
Exemple #32
0
        public Message MakeDecisionNonLeader(AgentInfo agent)
        {
            Message msg = null;

            if (agent.AlliesIds.Count() >= 1 && agent.IsLeader)
            {
                foreach (var v in agentsToAskForLeader.Keys.ToList())
                {
                    agentsToAskForLeader[v]++;
                }
                var firstOrNull = agentsToAskForLeader.FirstOrDefault(x => x.Value > Math.Min(Math.Max((Board.NumberOfFilledRows() * 2), 3), 8));
                if (firstOrNull.Key != 0)
                {
                    agentsToAskForLeader.Remove(firstOrNull.Key);
                    return(LogMessage(new Message <ExchangeInformationRequest>(new ExchangeInformationRequest()
                    {
                        AskedAgentId = firstOrNull.Key
                    })));
                }
            }
            if (agent.ExchangeInfoRequests.Count() != 0)
            {
                var tmp = agent.ExchangeInfoRequests[0];
                agent.ExchangeInfoRequests.RemoveAll(x => x.AskingId == tmp.AskingId);
                if (agent.AlliesIds.Count() >= 1 && agent.IsLeader)
                {
                    agentsToAskForLeader[tmp.AskingId.Value] = 0;
                }

                return(LogMessage(GiveInfo(tmp.AskingId.Value)));
            }

            MessageType last = History.Peek();

            if (last == MessageType.MoveError)
            {
                return(LogMessage(RandomMove()));
            }

            if (last == MessageType.PutPieceError)
            {
                strategyState = StrategyState.FindPiece;
                return(LogMessage(RandomMove()));//dont know when and what to do
            }
            switch (strategyState)
            {
            case StrategyState.FindPiece:
                if (agent.HasPiece)
                {
                    return(LogMessage(new Message <CheckHoldedPieceRequest>(new CheckHoldedPieceRequest())));
                }
                else
                {
                    return(LogMessage(FindPieceAction(agent)));
                }

            case StrategyState.CheckSham:
                return(LogMessage(new Message <CheckHoldedPieceRequest>(new CheckHoldedPieceRequest())));

            case StrategyState.BringToGoalArea:
                if (!agent.HasPiece)
                {
                    strategyState = StrategyState.FindPiece;
                    return(LogMessage(FindPiece(agent)));
                }
                if (!Board.InGoalArea(agent.Position))
                {
                    return(LogMessage(MoveToGoals(agent)));
                }

                var nearest  = Board.FindUndiscoveredGoalCoordinates(agent.Position);
                int distance = Math.Abs(nearest.Item1 - agent.Position.X) + Math.Abs(nearest.Item2 - agent.Position.Y);
                if (distance > 1)
                {
                    return(LogMessage(MoveToGoals(agent)));
                }
                else if (agent.AlliesIds.Count() >= 1 && !agent.IsLeader)
                {
                    strategyState = StrategyState.ExchangeInfo;
                    return(LogMessage(new Message <ExchangeInformationRequest>(new ExchangeInformationRequest()
                    {
                        AskedAgentId = agent.LeaderId
                    })));
                }
                else if (nearest != (agent.Position.X, agent.Position.Y))
                {
                    return(LogMessage(MoveToGoals(agent)));
                }
                else
                {
                    return(LogMessage(new Message <PutPieceRequest>(new PutPieceRequest())));
                }
        public string GetStrategy(ChessState state, Boolean isWhite)
        {
            int i, j, count = 0;
            double max = 0.0;
            double[] VSmax = new double[10000];
            string[] Stra = new string[10000];
            Boolean[][] whtmp;

            //插入状态
            DataOperation.InsertState(ChessState.StateToStr(state));

            for (i = 0; i < 8; i++)
            {
                for (j = 0; j < 8; j++)
                {
                    if (state.State[i][j] >= ChessType.BPawn && state.State[i][j] <= ChessType.BKing)
                    {
                        switch (state.State[i][j])
                        {
                            case ChessType.BPawn:
                                whtmp = ChessLawExe.PawnStep(state, j, i);
                                for (int row = 0; row < 8; row++)
                                {
                                    for (int col = 0; col < 8; col++)
                                    {
                                        if (whtmp[row][col])
                                        {
                                            StrategyState ss = new StrategyState(i, j, row, col);
                                            if (row == 7) ss.Conv = ChessType.BQueen;
                                            double Ns = VPaiNextState(state, ss);
                                            if (Ns > max) { max = Ns; count = 1; VSmax[0] = Ns; Stra[0] = StrategyState.StaToStr(ss); }
                                            else if (Ns == max) { VSmax[count] = Ns; Stra[count++] = StrategyState.StaToStr(ss); }

                                            if (row == 7) ss.Conv = ChessType.BKnight;
                                            Ns = VPaiNextState(state, ss);
                                            if (Ns > max) { max = Ns; count = 1; VSmax[0] = Ns; Stra[0] = StrategyState.StaToStr(ss); }
                                            else if (Ns == max) { VSmax[count] = Ns; Stra[count++] = StrategyState.StaToStr(ss); }
                                        }
                                    }
                                }
                                break;

                            case ChessType.BKnight:
                                whtmp = ChessLawExe.KnightStep(state, j, i);
                                CommonGetStra(whtmp, i, j, ref max, ref VSmax, ref Stra, ref count, state);
                                break;

                            case ChessType.BBishop:
                                whtmp = ChessLawExe.BishopStep(state, j, i);
                                CommonGetStra(whtmp, i, j, ref max, ref VSmax, ref Stra, ref count, state);
                                break;

                            case ChessType.BRook:
                                whtmp = ChessLawExe.RookStep(state, j, i);
                                CommonGetStra(whtmp, i, j, ref max, ref VSmax, ref Stra, ref count, state);
                                break;

                            case ChessType.BQueen:
                                whtmp = ChessLawExe.QueenStep(state, j, i);
                                CommonGetStra(whtmp, i, j, ref max, ref VSmax, ref Stra, ref count, state);
                                break;

                            case ChessType.BKing:
                                whtmp = ChessLawExe.KingStep(state, j, i);
                                CommonGetStra(whtmp, i, j, ref max, ref VSmax, ref Stra, ref count, state);
                                break;
                        }
                    }
                }
            }

            Random rand = new Random();
            int key = rand.Next(0, count);

            double CurrVs = VSmax[key];
            string CurrStr = Stra[key];

            //把得到的qs存入数据库
            for (i = 0; i < qcount; i++)
                DataOperation.InsertQState(QState[i], QStrategy[i], CurrVs);

            QState = new string[10000];
            QStrategy = new string[10000];
            qcount = 0;

            //把状态和决策存入数组
            State[tcount] = ChessState.StateToStr(state);
            Strategy[tcount++] = CurrStr;

            return CurrStr;
        }
Exemple #34
0
        private string GetBestSolution(ResultCollection results)
        {
            string result = string.Empty;

            try
            {
                if (results["Best VRP Solution"] == null)
                {
                    return(null);
                }

                // otherwise we have a valid solution, so update the database
                VRPSolution solution = results["Best VRP Solution"].Value as VRPSolution;

                var tours = solution.Solution.GetTours();

                bool firstDriver = true;

                for (int i = 0; i < tours.Count; i++)
                {
                    if (firstDriver)
                    {
                        firstDriver = false;
                    }
                    else
                    {
                        result += "|";
                    }

                    int tourIndex = solution.Solution.GetTourIndex(tours[i]);
                    int vehicle   = solution.Solution.GetVehicleAssignment(tourIndex);
                    int depot     = _vehicleAssignment[vehicle];

                    result += _driverIds[depot].ToString() + ":";

                    var stops = string.Empty;

                    bool first = true;

                    foreach (var s in tours[i].Stops)
                    {
                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            stops += ",";
                        }

                        stops += _stopIds[s - 1].ToString();
                    }

                    result += stops;
                }
            }
            catch (Exception exc)
            {
                //alg.Stop();
                _strategyState = StrategyState.Stopped;
                return(null);
            }

            return(result);
        }