Beispiel #1
0
        /// <summary>
        /// 停止平仓追单对齐。
        /// </summary>
        public void StopCloseChaseOrder()
        {
            if (m_backgroundWorkerType != AutoTraderWorkType.CloseChaseOrder ||
                m_backgroundRunFlag == false)
            {
                string           text   = "当前未进行平仓追单";
                AutoTraderNotice notice = CreateTraderNotice(text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
                return;
            }

            {
                string           text   = "停止平仓追单";
                AutoTraderNotice notice = CreateTraderNotice(text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
            }

            lock (m_syncObj)
            {
                if (m_backgroundWorkerType == AutoTraderWorkType.CloseChaseOrder)
                {
                    m_backgroundRunFlag = false;
                }
            }

            m_operatorEvent.Reset();
        }
        /// <summary>
        /// 委托回报变更。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OrderDriver_OnOrderBookChanged(object sender, USeOrderBookChangedEventArgs e)
        {
            try
            {
                OrderBookUpdateResult result = null;
                lock (m_syncObj)
                {
                    result = m_arbitrageOrder.UpdateOrderBook(e.OrderBook);
                    if (result != null)
                    {
                        result.Task.UpdateTaskState();

                        m_arbitrageOrder.UpdataArbitrageOrderState();
                        m_operatorEvent.Set();
                    }
                }

                if (result != null)
                {
                    //委托更新触发流程监控运行
                    m_operatorEvent.Set();
                    SafeFireArbitrageOrderChanged();

                    AutoTraderNotice tradeNotice = result.CreateNotice(this.TraderIdentify, this.Alias);
                    if (tradeNotice != null)
                    {
                        SafeFireAutoTraderNotice(tradeNotice);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Assert(false, ex.Message);
            }
        }
Beispiel #3
0
        /// <summary>
        /// 强制平仓完成。
        /// </summary>
        public void ForceCloseFinish()
        {
            CheckBackgroundWorker("强制平仓完成");

            lock (m_syncObj)
            {
                if (m_arbitrageOrder.HasUnFinishOrderBook)
                {
                    throw new Exception(string.Format("{0}有未完成委托单", this));
                }

                if (m_arbitrageOrder.State != ArbitrageOrderState.Closeing)
                {
                    throw new Exception(string.Format("{0}为{1}状态,不能强制设定为平仓完成", this, this.ArbitrageOrderState.ToDescription()));
                }

                m_arbitrageOrder.State = ArbitrageOrderState.Closed;
            }

            SafeFireArbitrageOrderChanged();

            {
                string           text   = "强制平仓完成";
                AutoTraderNotice notice = CreateTraderNotice(text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
            }
        }
Beispiel #4
0
        /// <summary>
        /// 停止开仓对齐。
        /// </summary>
        public void StopOpenAlignment()
        {
            if (m_backgroundWorkerType != AutoTraderWorkType.OpenAlignment ||
                m_backgroundRunFlag == false)
            {
                string           text   = "当前未进行开仓对齐操作";
                AutoTraderNotice notice = CreateTraderNotice(text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
                return;
            }

            {
                string           text   = "停止开仓对齐";
                AutoTraderNotice notice = CreateTraderNotice(text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
            }
            lock (m_syncObj)
            {
                if (m_backgroundWorkerType == AutoTraderWorkType.OpenAlignment)
                {
                    m_backgroundRunFlag = false;
                }
            }

            m_operatorEvent.Reset();
        }
Beispiel #5
0
        /// <summary>
        /// 记录通知日志。
        /// </summary>
        /// <param name="notice"></param>
        public void WriteTraderNoticeLog(AutoTraderNotice notice)
        {
            string text = string.Format("[Notice][Alias:{1}][NoticeType:{2}][Message:{3}][TradeIdentity:{0}]",
                                        notice.TradeIdentity, notice.Alias, notice.NoticeType, notice.Message);

            m_recordLogger.WriteInformation(text);
        }
Beispiel #6
0
        /// <summary>
        /// 开始平仓。
        /// </summary>
        public void BeginClose()
        {
            lock (m_syncObj)
            {
                Debug.Assert(m_arbitrageOrder.Argument != null);
                Debug.Assert(m_arbitrageOrder.Argument.CloseArg != null);
                //Debug.Assert(m_arbitrageOrder.Argument.StopLossArg != null);

                if (m_arbitrageOrder.State != ArbitrageOrderState.Opened)
                {
                    throw new Exception(string.Format("{0}为{1}状态,不能进入平仓状态", this, m_arbitrageOrder.State.ToDescription()));
                }
                string errorMessage = string.Empty;
                if (VerfiyArbitrageArgument(m_arbitrageOrder.Argument, out errorMessage) == false)
                {
                    throw new Exception(string.Format("{0}平仓参数错误,{1}", this, errorMessage));
                }

                //创建平仓任务组
                ArbitrageTaskGroup closeTaskGroup = CreateCloseTaskGroup(m_arbitrageOrder.OpenTaskGroup, m_arbitrageOrder.Argument);

                m_arbitrageOrder.CloseTaskGroup = closeTaskGroup;
                m_arbitrageOrder.State          = ArbitrageOrderState.Closeing;
            }

            m_operatorEvent.Set();

            SafeFireArbitrageOrderChanged();

            string           text   = "进入平仓流程";
            AutoTraderNotice notice = CreateTraderNotice(text);

            SafeFireAutoTraderNotice(notice);
            WriteTraderNoticeLog(notice);
        }
Beispiel #7
0
        /// <summary>
        /// 转移为历史记录(不在更改)。
        /// </summary>
        public void TransferToHistoryArbitrage()
        {
            lock (m_syncObj)
            {
                if (m_arbitrageOrder.State != ArbitrageOrderState.Closed)
                {
                    throw new Exception(string.Format("{0}为{1}状态,未结束不能转移", this, this.ArbitrageOrderState.ToDescription()));
                }
            }

            ArbitrageOrderSettlement settlemetResult = CalculateSettlementResult();

            lock (m_syncObj)
            {
                m_arbitrageOrder.State            = ArbitrageOrderState.Finish;
                m_arbitrageOrder.FinishTime       = DateTime.Now;
                m_arbitrageOrder.SettlementResult = settlemetResult;
            }

            SafeFireArbitrageOrderChanged();

            string           text   = "交易结束,转移到历史记录";
            AutoTraderNotice notice = CreateTraderNotice(text);

            SafeFireAutoTraderNotice(notice);
            WriteTraderNoticeLog(notice);
        }
Beispiel #8
0
        private BackgroundWorker m_worker = null;  //工作线程
        #endregion

        #region 开平仓
        /// <summary>
        /// 开仓/平仓监控下单。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WorkerDoWorkForOpenAndClose(object sender, DoWorkEventArgs e)
        {
            string           text   = string.Format("启动跟单流程,当前状态为{0}", this.ArbitrageOrderState.ToDescription());
            AutoTraderNotice notice = CreateTraderNotice(text);

            SafeFireAutoTraderNotice(notice);
            WriteTraderNoticeLog(notice);

            SafeFireAutoTraderStateChanged(AutoTraderWorkType.OpenOrClose, AutoTraderState.Enable);

            lock (m_syncObj)
            {
                m_arbitrageOrder.ResetTryOrderErrorCount();
            }
            while (true)
            {
                ArbitrageOrderState arbitrageOrderState = ArbitrageOrderState.None;

                lock (m_syncObj)
                {
                    if (m_backgroundRunFlag == false)
                    {
                        break;                                // 退出跟单
                    }
                    arbitrageOrderState = m_arbitrageOrder.State;
                }

                switch (arbitrageOrderState)
                {
                case ArbitrageOrderState.Opening:
                    //建仓中
                    ProcessArbitrageOrderOpenTask();
                    break;

                case ArbitrageOrderState.Closeing:
                    ProcessArbitrageOrderCloseTask();
                    //平仓中
                    break;

                case ArbitrageOrderState.None:
                    //无下一步指示,等待
                    m_operatorEvent.WaitOne(EVENT_WAIT_Time);
                    break;

                case ArbitrageOrderState.Opened:
                    BeginClose();
                    return;

                case ArbitrageOrderState.Closed:
                    //已结束,流程退出
                    return;

                default:
                    Debug.Assert(false, "未知类型的套利单状态");
                    return;
                }
            }
        }
        private void AutoTraderManager_OnAutoTraderNotify(AutoTraderNotice notice)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new AutoTraderNotifyEventHandle(AutoTraderManager_OnAutoTraderNotify), notice);
                return;
            }

            string text = string.Format("套利单<{0}>{1}", notice.Alias, notice.Message);

            this.lblAutoTradeInfo.Text = text;
        }
Beispiel #10
0
        /// <summary>
        /// 安全触发报告事件。
        /// </summary>
        /// <param name="notice">通知。</param>
        private void SafeFireAutoTraderNotice(AutoTraderNotice notice)
        {
            AutoTraderNotifyEventHandle handle = this.OnAutoTraderNotify;

            if (handle != null)
            {
                try
                {
                    handle(notice);
                }
                catch (Exception ex)
                {
                    Debug.Assert(false, ex.Message);
                }
            }
        }
        private void AutoTraderManager_OnNotify(AutoTraderNotice notice)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new AutoTraderNotifyEventHandle(AutoTraderManager_OnNotify), notice);
                return;
            }

            ArbitrageLogViewModel log = new ArbitrageLogViewModel()
            {
                TraderIdentify = notice.TradeIdentity,
                Alias          = notice.Alias,
                LogTime        = notice.NoticeTime,
                Message        = notice.Message,
                NoticeType     = notice.NoticeType
            };

            m_dataSource.Insert(0, log);
        }
Beispiel #12
0
        /// <summary>
        /// 移除自动下单机。
        /// </summary>
        /// <param name="traderIdentify">自动下单机标识。</param>
        public void RemoveAutoTrader(Guid traderIdentify)
        {
            AutoTrader trader = null;

            lock (m_syncObj)
            {
                if (m_autoTraderDic.TryGetValue(traderIdentify, out trader) == false)
                {
                    Debug.Assert(false);
                    return;
                }
            }

            if (trader.State == AutoTraderState.Enable)
            {
                throw new Exception(string.Format("套利单[{0}]为运行状态,请先停止在移除", trader.Alias));
            }
            if (trader.IsFinish == false)
            {
                throw new Exception(string.Format("套利单[{0}]当前状态为 {1} ,不能移除", trader, trader.ArbitrageOrderState.ToDescription()));
            }
            if (trader.HasUnFinishOrderBook)
            {
                throw new Exception(string.Format("套利单[{0}]有未完成委托单 ,不能移除", trader));
            }

            trader.OnNotify -= AutoTrader_OnNotify;
            trader.OnAlarm  -= AutoTrader_OnAlarm;
            trader.OnArbitrageOrderChanged -= AutoTrader_OnArbitrageOrderChanged;

            lock (m_syncObj)
            {
                m_autoTraderDic.Remove(traderIdentify);
            }

            string           text   = "移除套利单成功";
            AutoTraderNotice notice = new AutoTraderNotice(trader.TraderIdentify, trader.Alias, AutoTraderNoticeType.Infomation, text);

            SafeFireAutoTraderNotice(notice);
            trader.WriteTraderNoticeLog(notice);

            SafeFireRemoveAutoTrader(traderIdentify);
        }
Beispiel #13
0
        /// <summary>
        /// 检查后台流程是否在运行。
        /// </summary>
        /// <returns></returns>
        private bool CheckBackgroundWorker(string action)
        {
            if (m_initialized == false)
            {
                throw new ApplicationException(string.Format("{0}未初始化", this));
            }

            if (this.BackgroundWorkerIsBusy)
            {
                string           text   = string.Format("{0}正在进行{1}操作,请先停止后台流程在进行{2}操作", this, this.BackgroundWorkerType.ToDescription(), action);
                AutoTraderNotice notice = CreateTraderNotice(text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);

                throw new ApplicationException(text);
            }

            return(true);
        }
Beispiel #14
0
        /// <summary>
        /// 撤销挂单。
        /// </summary>
        public void CancelOpenHangingOrder()
        {
            CheckBackgroundWorker("未成交撤单");

            if (m_arbitrageOrder.HasUnFinishOrderBook == false)
            {
                AutoTraderNotice notice = CreateTraderNotice(AutoTraderNoticeType.Order, "没有未完成委托单,无需撤单");
                SafeFireAutoTraderNotice(notice);
                return;
            }
            else
            {
                string           text   = "正在进行撤单操作";
                AutoTraderNotice notice = CreateTraderNotice(text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
            }

            //未完成单先撤单
            foreach (ArbitrageTask task in m_arbitrageOrder.OpenTaskGroup.TaskList)
            {
                if (task.HasUnFinishOrderBook)
                {
                    List <USeOrderBook> unFinishOrderBooks = task.UnFinishOrderBooks;
                    foreach (USeOrderBook orderBook in unFinishOrderBooks)
                    {
                        string message      = string.Empty;
                        bool   cancelResult = m_orderDriver.CancelOrder(orderBook.OrderNum, orderBook.Instrument, out message);
                        if (cancelResult == false)
                        {
                            AutoTraderNotice errorNotice = CreateTraderNotice(AutoTraderNoticeType.Order, "撤单失败");
                            SafeFireAutoTraderNotice(errorNotice);
                        }
                    }
                }
            }

            {
                AutoTraderNotice notice = CreateTraderNotice("撤单完成,等待撤单结果");
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
            }
        }
Beispiel #15
0
        /// <summary>
        /// 创建新的套利订单。
        /// </summary>
        /// <param name="argument">套利单参数。</param>
        /// <param name="currentInvestor">当前投资者帐号。</param>
        public AutoTrader CreateNewAutoTrader(ArbitrageArgument argument, InvestorAccount currentInvestor)
        {
            Guid traderIdentify = CreateNewAutoTraderIdentify();
            int  aliasNum       = CreateNewAutoTraderAliasNum();

            USeArbitrageOrder arbitrageOrder = new USeArbitrageOrder();

            arbitrageOrder.TraderIdentify = traderIdentify;
            arbitrageOrder.AliasNum       = aliasNum;
            arbitrageOrder.State          = ArbitrageOrderState.None;
            arbitrageOrder.BrokerId       = currentInvestor.BrokerId;
            arbitrageOrder.Account        = currentInvestor.Account;
            arbitrageOrder.Argument       = argument.Clone();
            arbitrageOrder.CreateTime     = DateTime.Now;

            TaskOrderSetting taskOrderSetting = m_systemConfigManager.GetTaskOrderSetting();
            //任务组待开仓或者平仓时在创建
            AutoTrader trader = new AutoTrader();

            trader.SetRecordLogger(USeManager.Instance.CommandLogger);
            trader.SetTryOrderCondition(taskOrderSetting.TaskMaxTryCount, taskOrderSetting.TryOrderMinInterval);
            trader.Initialize(arbitrageOrder, m_orderDriver, m_quoteDriver, m_alarmManager);

            trader.OnNotify += AutoTrader_OnNotify;
            trader.OnAlarm  += AutoTrader_OnAlarm;
            trader.OnArbitrageOrderChanged += AutoTrader_OnArbitrageOrderChanged;
            trader.OnStateChanged          += AutoTrader_OnStateChanged;

            lock (m_syncObj)
            {
                m_autoTraderDic.Add(traderIdentify, trader);
            }

            SafeFireAddAutoTrader(traderIdentify);
            string           text   = "创建套利单成功";
            AutoTraderNotice notice = new AutoTraderNotice(trader.TraderIdentify, trader.Alias, AutoTraderNoticeType.Infomation, text);

            SafeFireAutoTraderNotice(notice);
            trader.WriteTraderNoticeLog(notice);

            return(trader);
        }
        public AutoTraderNotice CreateNotice(Guid traderIdentify, string alias)
        {
            AutoTraderNotice notice = null;

            if (this.CancelQty > 0)
            {
                string text = string.Format("{0} {1}撤单{2}手", this.TaskDesc, this.Instrument, this.CancelQty);
                notice = new AutoTraderNotice(traderIdentify, alias, AutoTraderNoticeType.Trade, text);
            }
            else if (this.BlankQty > 0)
            {
                string text = string.Format("{0} {1}废单{2}手", this.TaskDesc, this.Instrument, this.BlankQty);
                notice = new AutoTraderNotice(traderIdentify, alias, AutoTraderNoticeType.Trade, text);
            }
            else if (this.TradeQty > 0)
            {
                string text = string.Format("{0} {1}成交{2}手", this.TaskDesc, this.Instrument, this.TradeQty);
                notice = new AutoTraderNotice(traderIdentify, alias, AutoTraderNoticeType.Trade, text);
            }

            return(notice);
        }
Beispiel #17
0
        /// <summary>
        /// 开平仓流程结束。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WorkerForOpenAndCloseCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (m_worker != null)
            {
                m_worker.ProgressChanged    -= WorkerForOpenAndCloseProgressChanged;
                m_worker.RunWorkerCompleted -= WorkerForOpenAndCloseCompleted;
                m_worker.DoWork             -= WorkerDoWorkForOpenAndClose;

                m_worker = null;
            }

            //流程结束,置位运行标识
            m_backgroundRunFlag    = false;
            m_backgroundWorkerType = AutoTraderWorkType.None;

            string           text   = "下单机已停止";
            AutoTraderNotice notice = CreateTraderNotice(text);

            SafeFireAutoTraderNotice(notice);
            WriteTraderNoticeLog(notice);

            SafeFireAutoTraderStateChanged(AutoTraderWorkType.None, AutoTraderState.Disable);
        }
Beispiel #18
0
        /// <summary>
        /// 设定流程进入开仓流程。
        /// </summary>
        public void BeginOpen()
        {
            lock (m_syncObj)
            {
                if (m_arbitrageOrder.OpenArgument == null)
                {
                    throw new Exception(string.Format("{0}开仓参数未设定", this));
                }

                if (m_arbitrageOrder.State != ArbitrageOrderState.None)
                {
                    throw new Exception(string.Format("{0}为{1}状态,不能进入开仓状态", this, m_arbitrageOrder.State.ToDescription()));
                }

                string errorMessage = string.Empty;
                if (VerfiyOpenArgument(m_arbitrageOrder.OpenArgument, out errorMessage) == false)
                {
                    throw new Exception(string.Format("{0}开仓参数错误,{1}", this, errorMessage));
                }

                //创建开仓任务组
                ArbitrageTaskGroup openTaskGroup = CreateOpenTaskGroup(m_arbitrageOrder.Argument);

                m_arbitrageOrder.OpenTaskGroup = openTaskGroup;
                m_arbitrageOrder.State         = ArbitrageOrderState.Opening;
            }

            m_operatorEvent.Set();

            SafeFireArbitrageOrderChanged();

            string           text   = "进入开仓流程";
            AutoTraderNotice notice = CreateTraderNotice(text);

            SafeFireAutoTraderNotice(notice);
            WriteTraderNoticeLog(notice);
        }
Beispiel #19
0
        /// <summary>
        /// 平仓追单。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WorkerDoWorkForCloseChaseOrder(object sender, DoWorkEventArgs e)
        {
            {
                AutoTraderNotice notice = CreateTraderNotice("平仓追单对齐操作");
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
            }

            //开仓追单
            //1.撤销掉当前所有未成交委托单
            //2.检查不对齐欠缺仓位,对欠缺仓位进行开仓追单
            //3.开仓以市价委托,尽量保证成交
            Debug.Assert(m_arbitrageOrder.State == ArbitrageOrderState.Closeing);

            if (m_arbitrageOrder.HasUnFinishOrderBook)
            {
                string           text   = "平仓追单有未完成委托单正在撤单";
                AutoTraderNotice notice = CreateTraderNotice(AutoTraderNoticeType.Order, text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);

                List <USeOrderBook> unFinishOrderBook = m_arbitrageOrder.GetAllUnfinishOrderBooks();
                foreach (USeOrderBook orderBook in unFinishOrderBook)
                {
                    string errorMessage = string.Empty;
                    bool   cancelResult = m_orderDriver.CancelOrder(orderBook.OrderNum, orderBook.Instrument, out errorMessage);
                    if (cancelResult == false)
                    {
                        text   = string.Format("平仓追单{0} 撤单失败", orderBook.OrderNum);
                        notice = CreateTraderNotice(AutoTraderNoticeType.Order, text);
                        SafeFireAutoTraderNotice(notice);
                        WriteTraderNoticeLog(notice);

                        return;   // 退出流程,触发预警
                    }
                }

                text   = "平仓追单操作完成,等待撤单成功";
                notice = CreateTraderNotice(AutoTraderNoticeType.Order, text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);

                while (true)
                {
                    //等待撤单完成
                    m_operatorEvent.WaitOne(EVENT_WAIT_Time);

                    if (m_backgroundRunFlag == false)
                    {
                        text   = string.Format("平仓追单流程退出");
                        notice = CreateTraderNotice(AutoTraderNoticeType.Infomation, text);
                        SafeFireAutoTraderNotice(notice);
                        WriteTraderNoticeLog(notice);
                        return;
                    }

                    if (m_arbitrageOrder.HasUnFinishOrderBook == false)
                    {
                        text   = string.Format("平仓追单已完成撤单");
                        notice = CreateTraderNotice(AutoTraderNoticeType.Order, text);
                        SafeFireAutoTraderNotice(notice);
                        WriteTraderNoticeLog(notice);
                        break;
                    }
                }
            }

            List <OrderCommand> commandList = new List <OrderCommand>();

            // 对欠缺仓位进行补单
            foreach (ArbitrageTask task in m_arbitrageOrder.CloseTaskGroup.TaskList)
            {
                if (task.FirstSubTask.TradeQty == task.SecondSubTask.TradeQty)
                {
                    continue;
                }

                Debug.Assert(task.FirstSubTask.TradeQty > task.SecondSubTask.TradeQty);

                //追单
                USeInstrument instrument = task.SecondSubTask.Instrument;
                USeOrderSide  orderSide  = task.SecondSubTask.OrderSide;
                int           orderQty   = task.FirstSubTask.TradeQty - task.SecondSubTask.TradeQty;
                Debug.Assert(orderQty > 0);
                decimal orderPrice = GetFirstInstrumentOrderPrice(instrument, ArbitrageOrderPriceType.OpponentPrice, orderSide);
                Debug.Assert(orderPrice > 0);
                USeOffsetType offsetType = USeOffsetType.Close;

                List <OrderCommand> subCommandList = CreateOrderCommands(task.TaskId, instrument, orderSide, offsetType, orderQty, orderPrice, "平仓追单");
                foreach (OrderCommand command in subCommandList)
                {
                    bool orderResult = PlaceOrderForOrderCommand(command);
                    if (orderResult)
                    {
                        task.SecondSubTask.AddPositiveOrderBook(command.CreateOrignalOrderBook());
                        task.UpdateTaskState();
                        //task.TaskState = ArbitrageTaskState.FirstPlaceOrder;
                    }
                }

                commandList.AddRange(subCommandList);
            }

            #region 通知
            foreach (OrderCommand command in commandList)
            {
                AutoTraderNotice notice = CreateTraderNotice(AutoTraderNoticeType.Order, command.ToDescription());
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
            }
            #endregion

            {
                string           text   = "平仓追单已完成追单,等待成交";
                AutoTraderNotice notice = CreateTraderNotice(AutoTraderNoticeType.Order, text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
            }
        }
        /// <summary>
        /// 套利单任务 -- 优先合约下单。
        /// </summary>
        /// <param name="taskGroup">开仓/平仓 任务组。</param>
        /// <param name="differentialUnit">最大仓差。</param>
        /// <returns></returns>
        private bool ProcessFirstSubTask(ArbitrageTaskGroup taskGroup, int differentialUnit)
        {
            #region 校验
            PriceSpreadCheckResult priceSpeadResult = CheckPriceSpread(taskGroup.OpenCloseType, m_arbitrageOrder.Argument);
            if (priceSpeadResult.OrderReason == TaskOrderReason.None)
            {
                WriteTraderDebugInfo("优先合约检查,不满足价差条件");
                return(false);
            }

            int firstUnExeTaskIndex = taskGroup.GetFirstTaskUnExecutIndex();
            if (firstUnExeTaskIndex < 0)
            {
                // 优先合约全部完成下单
                return(false);
            }

            bool secondTaskIsPlaceOrder = taskGroup.CheckSecondTaskIsPlaceOrder(firstUnExeTaskIndex);
            if (secondTaskIsPlaceOrder == false)
            {
                WriteTraderDebugInfo("反手合约还未下单,不许下单");
                return(false);
            }

            //反手仓位未成交任务数
            int secondUnTradeTaskCount = taskGroup.GetUnTradeSecondTaskCount(firstUnExeTaskIndex);
            if (secondUnTradeTaskCount >= differentialUnit)
            {
                WriteTraderDebugInfo("优先合约反手合约任务仓差大于等于允许最大仓差,不许下单");
                return(false);
            }

            ArbitrageTask task = taskGroup.TaskList[firstUnExeTaskIndex];
            Debug.Assert(task != null && task.TaskState == ArbitrageTaskState.None);
            ArbitrageSubTask firstSubTask = task.FirstSubTask;

            if (firstSubTask.TryOrderCount >= m_tryOrderCondition.MaxTryOrderCount)
            {
                m_backgroundRunFlag = false;

                string text = string.Format("流程暂停,{2}下单任务[{0}]超出最大尝试下单次数{1}次",
                                            task.TaskId, m_tryOrderCondition.MaxTryOrderCount, firstSubTask.Instrument.InstrumentCode);
                AutoTraderNotice notice = CreateTraderNotice(AutoTraderNoticeType.Order, text);
                SafeFireAutoTraderNotice(notice);

                AlarmNotice alarm = new AlarmNotice(AlarmType.AutoTraderWarning, text);
                SafeFireAutoTraderAlarm(alarm);

                WriteTraderNoticeLog(notice);

                return(false);
            }

            if (firstSubTask.CanPlaceNextOrder(m_tryOrderCondition.NextOrderInterval) == false)
            {
                WriteTraderDebugInfo("优先合约检查,距离上次下单时间过近,暂时不下单");
                return(false);
            }
            #endregion

            #region  单

            Debug.Assert(priceSpeadResult.OrderReason == TaskOrderReason.Open ||
                         priceSpeadResult.OrderReason == TaskOrderReason.Close ||
                         priceSpeadResult.OrderReason == TaskOrderReason.StopLoss);
            task.OrderReason = priceSpeadResult.OrderReason;
            task.PriceSpread = priceSpeadResult.PriceSpreadThreshold;

            //获取优先合约下单价格
            decimal orderPrice = GetFirstInstrumentOrderPrice(firstSubTask.Instrument, firstSubTask.OrderPriceType, firstSubTask.OrderSide);
            Debug.Assert(orderPrice > 0);
            int orderQty = firstSubTask.UnOrderQty;
            Debug.Assert(orderQty > 0);

            USeInstrument instrument = firstSubTask.Instrument;
            USeOffsetType offsetType = firstSubTask.OffsetType;
            USeOrderSide  orderSide  = firstSubTask.OrderSide;

            List <OrderCommand> commandList = null;
            lock (ms_orderSyncObj)
            {
                commandList = CreateOrderCommands(task.TaskId, instrument, orderSide, offsetType, orderQty, orderPrice, "优先合约");
                Debug.Assert(commandList != null && commandList.Count > 0);

                foreach (OrderCommand command in commandList)
                {
                    bool orderResult = PlaceOrderForOrderCommand(command);
                    if (orderResult)
                    {
                        firstSubTask.AddPositiveOrderBook(command.CreateOrignalOrderBook());
                        task.UpdateTaskState();
                        //task.TaskState = ArbitrageTaskState.FirstPlaceOrder;
                    }
                }
            }
            firstSubTask.AddTryOrderCount();  // 下单累加1次
            #endregion

            #region 通知
            foreach (OrderCommand command in commandList)
            {
                AutoTraderNotice notice = CreateTraderNotice(AutoTraderNoticeType.Order, command.ToDescription());
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
            }
            #endregion

            return(true);
        }
        /// <summary>
        /// 套利单任务--反手合约下单(优先合约已成交)
        /// </summary>
        /// <param name="taskGroup">开仓/平仓 任务组。</param>
        private bool ProcessSecondSubTask(ArbitrageTaskGroup taskGroup)
        {
            for (int i = 0; i < taskGroup.TaskList.Count; i++)
            {
                #region 校验
                ArbitrageTask task = taskGroup.TaskList[i];

                if (task.TaskState != ArbitrageTaskState.FirstTradeFinish)
                {
                    //优先合约未成交,无需做反手合约检查
                    continue;
                }

                ArbitrageSubTask secondSubTask = task.SecondSubTask;

                if (secondSubTask.TryOrderCount >= m_tryOrderCondition.MaxTryOrderCount)
                {
                    m_backgroundRunFlag = false;

                    string text = string.Format("流程暂停,{2}下单任务[{0}]超出最大尝试下单次数{1}次",
                                                task.TaskId, m_tryOrderCondition.MaxTryOrderCount, secondSubTask.Instrument.InstrumentCode);
                    AutoTraderNotice notice = CreateTraderNotice(AutoTraderNoticeType.Order, text);
                    SafeFireAutoTraderNotice(notice);

                    AlarmNotice alarm = new AlarmNotice(AlarmType.AutoTraderWarning, text);
                    SafeFireAutoTraderAlarm(alarm);

                    WriteTraderNoticeLog(notice);

                    return(false);
                }

                if (secondSubTask.CanPlaceNextOrder(m_tryOrderCondition.NextOrderInterval) == false)
                {
                    WriteTraderDebugInfo("反手合约检查,距离上次下单时间过近,暂时不下单");
                    continue;
                }
                #endregion

                #region  单
                //获取反手合约下单价格
                decimal orderPrice = GetSecondTaskOrderPrice(taskGroup.OperationSide, taskGroup.PreferentialSide, task.FirstSubTaskAvgTradePrice, task.PriceSpread);

                orderPrice = TrimOrderPrice(secondSubTask.Instrument, orderPrice, secondSubTask.OrderSide);
                int orderQty = secondSubTask.UnOrderQty;
                Debug.Assert(orderQty > 0);

                USeInstrument instrument = secondSubTask.Instrument;
                USeOffsetType offsetType = secondSubTask.OffsetType;
                USeOrderSide  orderSide  = secondSubTask.OrderSide;

                List <OrderCommand> commandList = null;
                lock (ms_orderSyncObj)
                {
                    commandList = CreateOrderCommands(task.TaskId, instrument, orderSide, offsetType, orderQty, orderPrice, "反手合约");
                    Debug.Assert(commandList != null && commandList.Count > 0);

                    foreach (OrderCommand command in commandList)
                    {
                        bool orderResult = PlaceOrderForOrderCommand(command);
                        if (orderResult)
                        {
                            secondSubTask.AddPositiveOrderBook(command.CreateOrignalOrderBook());
                            task.UpdateTaskState();
                            //task.TaskState = ArbitrageTaskState.FirstPlaceOrder;
                        }
                    }
                }
                secondSubTask.AddTryOrderCount();  // 下单累加1次
                #endregion

                #region 通知
                foreach (OrderCommand command in commandList)
                {
                    AutoTraderNotice notice = CreateTraderNotice(AutoTraderNoticeType.Order, command.ToDescription());
                    SafeFireAutoTraderNotice(notice);
                    WriteTraderNoticeLog(notice);
                }
                #endregion
            }

            return(false);
        }
Beispiel #22
0
        /// <summary>
        /// 安全触发报告事件。
        /// </summary>
        /// <param name="tradeIdentity"></param>
        /// <param name="alias"></param>
        /// <param name="noticeType">通知类型。</param>
        /// <param name="message">通知消息。</param>
        private void SafeFireAutoTraderNotice(Guid tradeIdentity, string alias, AutoTraderNoticeType noticeType, string message)
        {
            AutoTraderNotice notice = new AutoTraderNotice(tradeIdentity, alias, noticeType, message);

            SafeFireAutoTraderNotice(notice);
        }
Beispiel #23
0
        private AutoTraderNotice CreateTraderNotice(string message)
        {
            AutoTraderNotice notice = new AutoTraderNotice(this.TraderIdentify, this.Alias, AutoTraderNoticeType.Infomation, message);

            return(notice);
        }
Beispiel #24
0
 private void AutoTrader_OnNotify(AutoTraderNotice notice)
 {
     SafeFireAutoTraderNotice(notice);
 }
Beispiel #25
0
        private AutoTraderNotice CreateTraderNotice(AutoTraderNoticeType noticeType, string message)
        {
            AutoTraderNotice notice = new AutoTraderNotice(this.TraderIdentify, this.Alias, noticeType, message);

            return(notice);
        }
Beispiel #26
0
        /// <summary>
        /// 初始化套利下单机。
        /// </summary>
        /// <param name="arbitrageOrder">套利单信息。</param>
        /// <param name="orderDriver">下单驱动。</param>
        /// <param name="quoteDriver">行情驱动。</param>
        /// <param name="alarmManager">预警管理类。</param>
        public void Initialize(USeArbitrageOrder arbitrageOrder, USeOrderDriver orderDriver, USeQuoteDriver quoteDriver, AlarmManager alarmManager)
        {
            if (m_initialized)
            {
                throw new ApplicationException(string.Format("{0} already initialized.", this));
            }

            if (arbitrageOrder == null)
            {
                throw new ArgumentNullException("arbitrageOrder", "arbitrageOrder is null");
            }

            if (orderDriver == null)
            {
                throw new ArgumentNullException("orderDriver", "orderDriver is null");
            }

            if (quoteDriver == null)
            {
                throw new ArgumentNullException("quoteDrvier", "quoteDrvier is null");
            }

            if (alarmManager == null)
            {
                throw new ArgumentNullException("alarmManager", "alarmManager is null");
            }

            try
            {
                lock (m_syncObj)
                {
                    m_arbitrageOrder = arbitrageOrder.Clone();

                    m_orderDriver = orderDriver;
                    m_quoteDriver = quoteDriver;
                }

                m_orderDriver.OnOrderBookChanged  += OrderDriver_OnOrderBookChanged;
                m_quoteDriver.OnMarketDataChanged += QuoteDriver_OnMarketDataChanged;

                if (arbitrageOrder.OpenArgument != null)
                {
                    m_quoteDriver.Subscribe(arbitrageOrder.OpenArgument.BuyInstrument);
                    m_quoteDriver.Subscribe(arbitrageOrder.OpenArgument.SellInstrument);
                }

                string           text   = string.Format("初始化套利单完成,当前状态为[{0}]", arbitrageOrder.State.ToDescription());
                AutoTraderNotice notice = CreateTraderNotice(text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);
            }
            catch (Exception ex)
            {
                string           text   = string.Format("初始化套利单失败,原因:{0}", ex.Message);
                AutoTraderNotice notice = CreateTraderNotice(text);
                SafeFireAutoTraderNotice(notice);
                WriteTraderNoticeLog(notice);

                throw new Exception("初始化自定下单机失败");
            }
            m_initialized = true;
        }