示例#1
0
        public static Trade CreateMarketEntry(string broker, decimal entryPrice, DateTime entryTime,
                                              TradeDirection direction, decimal amount, string market,
                                              decimal?stop, decimal?limit,
                                              Timeframe?timeframe = null, string strategies = null, string comments = null, bool alert = false, CalculateOptions calculateOptions = CalculateOptions.Default, TradeUpdateMode updateMode = TradeUpdateMode.Default)
        {
            var trade = new Trade {
                Broker = broker, CalculateOptions = calculateOptions
            };

            if (stop != null)
            {
                trade.AddStopPrice(entryTime, stop.Value);
            }
            if (limit != null)
            {
                trade.AddLimitPrice(entryTime, limit.Value);
            }
            trade.Market         = market;
            trade.TradeDirection = direction;
            trade.EntryPrice     = entryPrice;
            trade.EntryDateTime  = entryTime;
            trade.EntryQuantity  = amount;
            trade.Timeframe      = timeframe;
            trade.Alert          = alert;
            trade.Comments       = comments;
            trade.Strategies     = strategies;
            trade.UpdateMode     = updateMode;
            return(trade);
        }
示例#2
0
        public static Trade CreateOrder(string broker, decimal entryOrder, Candle latestCandle,
                                        TradeDirection direction, decimal amount, string market, DateTime?orderExpireTime,
                                        decimal?stop, decimal?limit, CalculateOptions calculateOptions = CalculateOptions.Default)
        {
            var orderDateTime = latestCandle.CloseTime();

            var trade = new Trade {
                CalculateOptions = calculateOptions
            };

            trade.SetOrder(orderDateTime, entryOrder, market, direction, amount, orderExpireTime);
            if (stop != null)
            {
                trade.AddStopPrice(orderDateTime, stop.Value);
            }
            if (limit != null)
            {
                trade.AddLimitPrice(orderDateTime, limit.Value);
            }
            trade.Broker = broker;

            if (direction == Basics.TradeDirection.Long)
            {
                trade.OrderType = (float)entryOrder <= latestCandle.CloseAsk ? Basics.OrderType.LimitEntry : Basics.OrderType.StopEntry;
            }
            else
            {
                trade.OrderType = (float)entryOrder <= latestCandle.CloseBid ? Basics.OrderType.StopEntry : Basics.OrderType.LimitEntry;
            }
            return(trade);
        }
 public void HitBtcHedgePositionOpen(string clOrdID, TradeDirection direction)
 {
     // New order
     //Int32 b = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
     clOrdID = "123456" + clOrdID;
     _dataService.WebSocket.Send("{\"method\": \"newOrder\",\"params\": {\"clientOrderId\": \"" + clOrdID + "\",\"symbol\": \"ETHUSD\",\"side\": \"" + direction.ToString().ToLower() + "\",\"type\": \"market\",\"price\": \"0.05983\",\"quantity\": \"0.001\"},\"id\": 123}");
 }
示例#4
0
 /// <summary>
 /// Resolve the trade direction to Oanda friendly -/+ units multiplier for trade open
 /// </summary>
 /// <param name="direction">The direction of the trade</param>
 /// <returns>+/-1</returns>
 private int ResolveDiretionToMultiplier(TradeDirection direction)
 {
     return(direction switch
     {
         TradeDirection.Short => - 1,
         _ => 1
     });
示例#5
0
        public void UpdateRecord(string clOrdID, string orderID, TradeDirection direction, double price)
        {
            using (var conn = new MySqlConnection(connectionString))
            {
                if (conn.State == System.Data.ConnectionState.Closed)
                {
                    conn.Open();
                }
                if (direction == TradeDirection.Buy)
                {
                    _sql = string.Format("UPDATE `trades` SET buy_order_id = '{0}', buy_price = {1} where cl_order_id = {2}", orderID, price, clOrdID);
                    using (MySqlCommand cmd = new MySqlCommand(_sql, conn))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }
                else
                {
                    _sql = string.Format("UPDATE `trades` SET sell_order_id = '{0}', sell_price = {1} where cl_order_id = {2}", orderID, price, clOrdID);
                    using (MySqlCommand cmd = new MySqlCommand(_sql, conn))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }

                conn.Close();
            }

            System.Threading.Thread.Sleep(500);             // DELETE! Only for testing
            BitMexProfitCalculate(clOrdID);
        }
示例#6
0
        public void PlaceTradeAsync(int tradingAccountId, int marketId, TradeDirection direction, decimal quantity, decimal bidPrice, decimal offerPrice, int[] close, TradeOrderResponseDelegate callback)
        {
            NewTradeOrderRequestDTO orderRequest;

            lock (_syncObj)
            {
                PriceDTO price;

                _prices.TryGetValue(marketId, out price);

                if (price == null)
                {
                    throw new Exception("you must have a price subscription in order to place a trade");
                }

                orderRequest = new NewTradeOrderRequestDTO
                {
                    AuditId          = price.AuditId,
                    MarketId         = marketId,
                    Direction        = direction.ToString(),
                    BidPrice         = bidPrice,
                    OfferPrice       = offerPrice,
                    Quantity         = quantity,
                    Close            = close,
                    TradingAccountId = tradingAccountId
                };
            }

            PlaceTradeAsync(orderRequest, callback);
        }
示例#7
0
        private static void AddBuySellMarker(
            TradeDirection direction, AnnotationCollection annotations, Trade trade,
            DateTime timeLocal, decimal price, bool makeSmaller, bool isFilled = true, Color?colour = null)
        {
            var buyMarker  = new BuyMarkerAnnotation();
            var sellMarker = new SellMarkerAnnotation();
            var annotation = direction == TradeDirection.Long ? buyMarker : (CustomAnnotation)sellMarker;

            annotation.Width  = makeSmaller ? 12 : 24;
            annotation.Height = makeSmaller ? 12 : 24;
            ((Path)annotation.Content).Stretch = Stretch.Fill;
            annotation.Margin      = new Thickness(0, direction == TradeDirection.Long ? 5 : -5, 0, 0);
            annotation.DataContext = trade;

            var brush = new SolidColorBrush
            {
                Color = colour ?? (direction == TradeDirection.Long ? Colors.Green : Colors.DarkRed)
            };

            if (isFilled)
            {
                ((Path)annotation.Content).Fill = brush;
            }

            buyMarker.StrokeBrush      = brush;
            buyMarker.Opacity          = makeSmaller ? 0.6 : 0.8;
            sellMarker.StrokeBrush     = brush;
            sellMarker.Opacity         = makeSmaller ? 0.6 : 0.8;
            annotation.X1              = timeLocal;
            annotation.BorderThickness = new Thickness(20);
            annotation.Y1              = (double)price;
            annotations.Add(annotation);
        }
        private void ExecuteTrade(TradeDirection direction, double price)
        {
            var quantity = new Random();

            BlotterViewModel.TradeList.Add(new TradeViewModel(DateTime.Now, Environment.UserName, direction, "CADUSD",
                                                              quantity.Next(100, 1000), price));
        }
示例#9
0
        public decimal Short()
        {
            try
            {
                string baseCurrency = Properties.Settings.Default.BaseCurrency;
                string market       = Properties.Settings.Default.Market;
                int    leverage     = int.Parse(Properties.Settings.Default.Leverage);

                decimal balance = this.GetBalance(baseCurrency);
                decimal price   = this.GetCurrentPrice(baseCurrency, market);

                decimal ammountMargin;
                if (Properties.Settings.Default.UsingFixedAmount)
                {
                    ammountMargin = decimal.Parse(Properties.Settings.Default.FixedAmmount.ToString());
                }
                else
                {
                    ammountMargin = Properties.Settings.Default.CapitalPercentageInEachOrder * (balance / price);
                }

                TradeDirection tradeDirection = TradeDirection.Short;

                client.Orders.PostOrder(new Order(market, ammountMargin, tradeDirection, leverage, OrderType.Market));

                return(price);
            }
            catch (Exception ex)
            {
            }
            return(0);
        }
示例#10
0
 public Order(string id, string status, TradeDirection direction, decimal price)
 {
     Id        = id;
     Status    = status;
     Direction = direction;
     Price     = price;
 }
示例#11
0
 private static Order CreateInstance <T>(TradeDirection tradeDirection, OrderType orderType,
                                         bool isReissueOrRepurchase) where T : Order
 {
     if (isReissueOrRepurchase && !repurchaseOrders.Contains(orderType))
     {
         return(new Reissue(tradeDirection, orderType));
     }
     return((T)Activator.CreateInstance(typeof(T), tradeDirection, orderType));
 }
示例#12
0
        public Trade CreateOrder(string broker, decimal entryOrder,
                                 Candle latestCandle, TradeDirection direction, decimal amount,
                                 string market, string baseAsset, DateTime?orderExpireTime, decimal?stop, decimal?limit,
                                 CalculateOptions calculateOptions = CalculateOptions.Default)
        {
            if (broker != "Binance")
            {
                throw new ApplicationException("Incorrect broker");
            }
            if (stop != null)
            {
                throw new ApplicationException("Stop needs to be implemented");
            }
            if (limit != null)
            {
                throw new ApplicationException("Limit needs to be implemented");
            }
            if (orderExpireTime != null)
            {
                throw new ApplicationException("Expire time needs to be implemented");
            }

            var res = _client.Spot.Order.PlaceOrder(
                market,
                direction == TradeDirection.Long ? OrderSide.Buy : OrderSide.Sell,
                OrderType.Limit,
                amount,
                timeInForce: TimeInForce.GoodTillCancel,
                price: entryOrder);

            if (res.Success)
            {
                Log.Info("Order trade created");

                var trade = new Trade
                {
                    Broker           = broker,
                    CalculateOptions = calculateOptions,
                    Market           = market,
                    BaseAsset        = baseAsset,
                    TradeDirection   = direction,
                    Id = res.Data.OrderId.ToString()
                };

                trade.SetOrder(res.Data.CreateTime, entryOrder, market, direction,
                               amount, orderExpireTime);

                return(trade);
            }
            else
            {
                Log.Info($"Failed to create order trade - {res.Error.Message}");

                return(null);
            }
        }
示例#13
0
 public TradeViewModel(DateTime timeStamp, string trader, TradeDirection direction, string ccyPair,
                       double quantity, double price)
 {
     _timeStamp = timeStamp;
     _trader    = trader;
     _direction = direction;
     _ccyPair   = ccyPair;
     _quantity  = quantity;
     _price     = price;
 }
示例#14
0
 public Order(string symbol, double amountMargin, TradeDirection tradeDirection, float leverage, OrderType type, double typeParameter = -1, double?stopLoss = null, double?takeProfit = null)
 {
     Symbol         = symbol;
     AmountMargin   = amountMargin;
     TradeDirection = tradeDirection;
     Leverage       = leverage;
     Type           = type;
     TypeParameter  = typeParameter;
     StopLoss       = stopLoss;
     TakeProfit     = takeProfit;
 }
示例#15
0
 public Order(string symbol, double amountMargin, TradeDirection tradeDirection, float leverage, OrderType type, double typeParameter = -1, double? stopLoss = null, double? takeProfit = null)
 {
     Symbol = symbol;
     AmountMargin = amountMargin;
     TradeDirection = tradeDirection;
     Leverage = leverage;
     Type = type;
     TypeParameter = typeParameter;
     StopLoss = stopLoss;
     TakeProfit = takeProfit;
 }
示例#16
0
 public Trade(string market, string symbol, DateTime time, TradeDirection type, decimal price, decimal amount, Order order)
 {
     Market    = market;
     Symbol    = symbol;
     Time      = time;
     Direction = type;
     Price     = price;
     Amount    = amount;
     Order     = order;
     Id        = (IdCounter++).ToString();
 }
示例#17
0
        public static StopLossDetails GenerateStopLoss(Instrument instrument, TradeDirection direction)
        {
            BetPips = 50;
            SetApiCredentials();

            decimal stopprice = direction == TradeDirection.BUY ? FindStopPointBuy(instrument) : FindStopPointSell(instrument);

            return(new StopLossDetails(instrument)
            {
                price = stopprice
            });
        }
示例#18
0
        public static TakeProfitDetails GenerateTakeProfit(Instrument instrument, TradeDirection direction)
        {
            BetPips = 50;
            SetApiCredentials();

            decimal takeprice = direction == TradeDirection.BUY ? FindTakePointBuy(instrument) : FindTakePointSell(instrument);

            return(new TakeProfitDetails(instrument)
            {
                price = takeprice
            });
        }
示例#19
0
 public Order(string market, string symbol, DateTime time, TradeDirection tradeSide, OrderType orderType, decimal amount, decimal price, string clientId)
 {
     Id        = (idCounter++).ToString();
     ClientId  = clientId;
     Symbol    = symbol;
     Market    = market;
     TradeType = tradeSide;
     Type      = orderType;
     Amount    = amount;
     Price     = price;
     Time      = time;
 }
示例#20
0
        public Trade(string asset, TradeDirection direction, double size, double stopPoints = 0, double takeProfitPoints = 0, string comment = null)
        {
            Asset            = asset;
            Direction        = direction;
            ExecuteOnNextBar = true;
            Size             = size;
            StopPoints       = stopPoints;
            TakeProfitPoints = takeProfitPoints;
            Comment          = comment;

            TradeData = null;
        }
示例#21
0
        public override string ToString()
        {
            //return base.ToString();

            return(String.Format("Trade:  {0}, timestamp:{1}, tradedirection:{2}, No of shares: {3},  price:{4} ",
                                 Stock.Symbol,
                                 TimeStamp.ToString("yyyyMMddHHmmssfff"),
                                 TradeDirection.ToString(),
                                 SharesNumber,
                                 Price.ToString("F")

                                 ));
        }
示例#22
0
        protected decimal CalculateTotalQuantity(TradeDirection direction)
        {
            decimal result = 0m;

            foreach (var eachOrder in _owner.ExecutedAndHasPositionOrders)
            {
                if (direction.SameAs(eachOrder.IsBuy) && eachOrder.IsRisky)
                {
                    result += eachOrder.QuantityBalance;
                }
            }
            return(result);
        }
示例#23
0
        public async Task PricingStructureCorrectValue(UKCompetentAuthority ca, TradeDirection td, int nt, bool isInterim,
                                                       int numberOfShipments, int expectedPrice)
        {
            var result = (await context.PricingStructures.SingleAsync(
                              p => p.CompetentAuthority == ca &&
                              p.Activity.TradeDirection == td &&
                              (int)p.Activity.NotificationType == nt &&
                              p.Activity.IsInterim == isInterim &&
                              (p.ShipmentQuantityRange.RangeFrom <= numberOfShipments &&
                               (p.ShipmentQuantityRange.RangeTo == null || p.ShipmentQuantityRange.RangeTo >= numberOfShipments))))
                         .Price;

            Assert.Equal(expectedPrice, result);
        }
示例#24
0
        static void Main(string[] args)
        {
            BetPips = 50;

            SetApiCredentials();

            WaitForConnection();

            Instrument instrument = GetEUR_USD();

            double lot = GetLotSize(instrument);

            TradeDirection direction = GenerateTradeDirection();
        }
示例#25
0
        public LogicalOrder CreateOrder(StrategyInterface strategy, TradeDirection tradeDirection, OrderType orderType, double price, int position, int strategyPosition)
        {
            LogicalOrder order = Factory.Engine.LogicalOrder(symbol, strategy);

            order.StrategyId       = 1;
            order.StrategyPosition = strategyPosition;
            order.TradeDirection   = tradeDirection;
            order.Type             = orderType;
            order.Price            = price;
            order.Position         = position * lotSize;
            order.Status           = OrderStatus.Active;
            orders.AddLast(order);
            strategy.Position.Change(strategyPosition, 100.00, TimeStamp.UtcNow);
            return(order);
        }
示例#26
0
        internal static IEnumerable <ITrade> RemoveUnselectedTradeDirections(IEnumerable <ITrade> trades,
                                                                             TradeDirection direction)
        {
            var newList = new List <ITrade>();

            foreach (var trade in trades)
            {
                if (direction == TradeDirection.Both || direction == trade.Direction)
                {
                    newList.Add(trade);
                }
            }

            return(newList);
        }
示例#27
0
        //
        //
        #endregion// Instrument Conversions

        #region Order Conversions
        // *****************************************************************
        // ****                Order Conversions Methods                ****
        // *****************************************************************
        //
        //
        /// <summary>
        /// Converts a TT Trade Direction object into a market side integer
        /// </summary>
        /// <param name="tradeDirection"></param>
        /// <returns></returns>
        public static int ToUVMarketSide(TradeDirection tradeDirection)
        {
            if (tradeDirection == TradeDirection.Take)
            {
                return(UVOrder.BuySide);
            }
            else if (tradeDirection == TradeDirection.Hit)
            {
                return(UVOrder.SellSide);
            }
            else if (tradeDirection == TradeDirection.Unknown)
            {
                return(UVOrder.UnknownSide);
            }
            return(UVOrder.UnknownSide);
        }
示例#28
0
 /// <summary>
 /// 记录交易
 /// </summary>
 /// <param name="num">建仓还是平仓(1或者2)</param>
 /// <param name="date">日期</param>
 /// <param name="direction">方向</param>
 /// <param name="price">价格</param>
 /// <param name="amount">数量</param>
 /// <param name="volumecommission">交易佣金</param>
 /// <param name="stampduty">印花税</param>
 public void RecordTrade(int num, DateTime date, TradeDirection direction, double price, int amount, double volumecommission, double stampduty, String reason = "")
 {
     if (num != 1 && num != 2)
     {
         return;
     }
     this.tradeInfos[num - 1] = new TradeInfo()
     {
         Code       = this.code,
         Direction  = direction,
         TradeDate  = date,
         Amount     = amount,
         TradePrice = price,
         Fee        = volumecommission,
         Stamps     = stampduty,
         Reason     = reason
     };
 }
示例#29
0
 public ContractPricingComponent(Money tradeVolume,
                                 Money settlementVolume,
                                 Rate customerSpotRate,
                                 Rate costSpotRate,
                                 RateDirection rateDirection,
                                 TradeDirection tradeDirection,
                                 DateRange startEndDates,
                                 bool isAmountInSettlementCurrency)
 {
     TradeVolume                  = tradeVolume;
     SettlementVolume             = settlementVolume;
     CustomerSpotRate             = customerSpotRate;
     CostSpotRate                 = costSpotRate;
     RateDirection                = rateDirection;
     TradeDirection               = tradeDirection;
     StartEndDates                = startEndDates;
     IsAmountInSettlementCurrency = isAmountInSettlementCurrency;
 }
示例#30
0
 public Filters(IReadOnlyList <ISelectable> markets, IReadOnlyList <ISelectable> strategies,
                IReadOnlyList <ISelectable> assetClasses, IReadOnlyList <ISelectable> days, DateTime startDate,
                DateTime endDate, DateTime startTime, DateTime endTime, double minRiskRewardRatio,
                double maxRiskRewardRatio, TradeStatus status, TradeDirection direction, EntryOrderType orderType)
 {
     Markets            = markets;
     Strategies         = strategies;
     AssetClasses       = assetClasses;
     Days               = days;
     StartDate          = startDate;
     EndDate            = endDate;
     StartTime          = startTime;
     EndTime            = endTime;
     MinRiskRewardRatio = minRiskRewardRatio;
     MaxRiskRewardRatio = maxRiskRewardRatio;
     Status             = status;
     Direction          = direction;
     OrderType          = orderType;
 }
        /// <summary>
        /// Sets and sends an entry order.
        /// </summary>
        bool DoEntryTrade(TradeDirection tradeDir)
        {
            bool responseOK = false;

            double              price;
            OrderDirection      ordDir;
            OperationType       opType;
            MT4Bridge.OrderType type;
            JournalIcons        icon;

            if (timeLastEntryBar != Data.Time[Data.Bars - 1])
                isEnteredLong = isEnteredShort = false;

            if (tradeDir == TradeDirection.Long)
            {   // Buy
                if (isEnteredLong)
                    return false; // Only one long entry is allowed.

                price  = Data.Ask;
                ordDir = OrderDirection.Buy;
                opType = OperationType.Buy;
                type   = MT4Bridge.OrderType.Buy;
                icon   = JournalIcons.OrderBuy;
            }
            else if (tradeDir == TradeDirection.Short)
            {   // Sell
                if (isEnteredShort)
                    return false; // Only one short entry is allowed.

                price  = Data.Bid;
                ordDir = OrderDirection.Sell;
                opType = OperationType.Sell;
                type   = MT4Bridge.OrderType.Sell;
                icon   = JournalIcons.OrderSell;
            }
            else
            {   // Wrong direction of trade.
                return false;
            }

            PosDirection newPosDir = PosDirection.None;
            double size = AnalyseEntrySize(ordDir, ref newPosDir);
            if (size < Data.InstrProperties.MinLot / 2)
            {   // The entry trade is cancelled.
                return false;
            }

            string symbol     = Data.Symbol;
            double lots       = size;
            int    slippage   = Configs.AutoSlippage ? (int)Data.InstrProperties.Spread * 3 : Configs.SlippageEntry;
            double stoploss   = GetStopLossPips(size);
            double takeprofit = GetTakeProfitPips();
            double point      = Data.InstrProperties.Point;

            string sStopLoss = "0";
            if (stoploss > 0)
            {
                double stopLossPrice = 0;
                if (newPosDir == PosDirection.Long)
                    stopLossPrice = Data.Bid - stoploss * point;
                else if (newPosDir == PosDirection.Short)
                    stopLossPrice = Data.Ask + stoploss * point;
                sStopLoss = stopLossPrice.ToString(Data.FF);
            }

            string sTakeProfit  = "0";
            if (takeprofit > 0)
            {
                double takeProfitPrice = 0;
                if (newPosDir == PosDirection.Long)
                    takeProfitPrice = Data.Bid + takeprofit * point;
                else if (newPosDir == PosDirection.Short)
                    takeProfitPrice = Data.Ask - takeprofit * point;
                sTakeProfit = takeProfitPrice.ToString(Data.FF);
            }

            if (Configs.PlaySounds)
                Data.SoundOrderSent.Play();

            JournalMessage jmsg = new JournalMessage(icon, DateTime.Now, string.Format(symbol + " " + Data.PeriodMTStr + " " +
                Language.T("An entry order sent") + ": " + Language.T(ordDir.ToString()) + " {0} " +
                (lots == 1 ? Language.T("lot") : Language.T("lots")) + " " + Language.T("at") + " {1}, " +
                Language.T("Stop Loss") + " {2}, " + Language.T("Take Profit") + " {3}",
                lots, price.ToString(Data.FF), sStopLoss, sTakeProfit));
            AppendJournalMessage(jmsg);

            string parameters = OrderParameters();

            int response = bridge.OrderSend(symbol, type, lots, price, slippage, stoploss, takeprofit, parameters);

            if (response >= 0)
            {   // The order was executed successfully.
                responseOK = true;

                Data.AddBarStats(opType, lots, price);

                timeLastEntryBar = Data.Time[Data.Bars - 1];
                if (type == MT4Bridge.OrderType.Buy)
                    isEnteredLong = true;
                else
                    isEnteredShort = true;

                Data.WrongStopLoss = 0;
                Data.WrongTakeProf = 0;
                Data.WrongStopsRetry = 0;
            }
            else
            {   // Error in operation execution.
                responseOK = false;

                if (Configs.PlaySounds)
                    Data.SoundError.Play();

                if (bridge.LastError == 0)
                    jmsg = new JournalMessage(JournalIcons.Warning, DateTime.Now,
                        Language.T("Operation execution") + ": " + Language.T("MetaTrader is not responding!").Replace("MetaTrader", Data.TerminalName));
                else
                    jmsg = new JournalMessage(JournalIcons.Error, DateTime.Now,
                        Language.T("MetaTrader failed to execute order! Returned").Replace("MetaTrader", Data.TerminalName) + ": " +
                        MT4Bridge.MT4_Errors.ErrorDescription(bridge.LastError));
                AppendJournalMessage(jmsg);

                Data.WrongStopLoss = (int)stoploss;
                Data.WrongTakeProf = (int)takeprofit;
            }

            return responseOK;
        }
示例#32
0
 public static bool SameAs(this TradeDirection direction, bool isBuy)
 {
     return((isBuy && direction == TradeDirection.Buy) || (!isBuy && direction == TradeDirection.Sell));
 }
        /// <summary>
        /// Reduces the status of baseDirection to direction.
        /// </summary>
        private TradeDirection ReduceDirectionStatus(TradeDirection baseDirection, TradeDirection direction)
        {
            if (baseDirection == direction || direction == TradeDirection.Both)
                return baseDirection;

            if (baseDirection == TradeDirection.Both)
                return direction;

            return TradeDirection.None;
        }
        /// <summary>
        /// Sets and sends an entry order.
        /// </summary>
        private void DoEntryTrade(TradeDirection tradeDir)
        {
            double price;
            OrderDirection ordDir;
            OperationType opType;
            OrderType type;
            JournalIcons icon;

            if (_timeLastEntryBar != Data.Time[Data.Bars - 1])
                _isEnteredLong = _isEnteredShort = false;

            switch (tradeDir)
            {
                case TradeDirection.Long: // Buy
                    if (_isEnteredLong)
                        return;
                    price = Data.Ask;
                    ordDir = OrderDirection.Buy;
                    opType = OperationType.Buy;
                    type = OrderType.Buy;
                    icon = JournalIcons.OrderBuy;
                    break;
                case TradeDirection.Short: // Sell
                    if (_isEnteredShort)
                        return;
                    price = Data.Bid;
                    ordDir = OrderDirection.Sell;
                    opType = OperationType.Sell;
                    type = OrderType.Sell;
                    icon = JournalIcons.OrderSell;
                    break;
                default: // Wrong direction of trade.
                    return;
            }

            PosDirection newPosDir = PosDirection.None;
            double size = AnalyseEntrySize(ordDir, ref newPosDir);
            if (size < Data.InstrProperties.MinLot/2)
            {
                // The entry trade is cancelled.
                return;
            }

            string symbol = Data.Symbol;
            double lots = size;
            int slippage = Configs.AutoSlippage ? (int) Data.InstrProperties.Spread*3 : Configs.SlippageEntry;
            double stoploss = GetStopLossPips(size);
            double takeprofit = GetTakeProfitPips();
            double point = Data.InstrProperties.Point;

            string stopLoss = "0";
            if (stoploss > 0)
            {
                double stopLossPrice = 0;
                if (newPosDir == PosDirection.Long)
                    stopLossPrice = Data.Bid - stoploss*point;
                else if (newPosDir == PosDirection.Short)
                    stopLossPrice = Data.Ask + stoploss*point;
                stopLoss = stopLossPrice.ToString(Data.FF);
            }

            string takeProfit = "0";
            if (takeprofit > 0)
            {
                double takeProfitPrice = 0;
                if (newPosDir == PosDirection.Long)
                    takeProfitPrice = Data.Bid + takeprofit*point;
                else if (newPosDir == PosDirection.Short)
                    takeProfitPrice = Data.Ask - takeprofit*point;
                takeProfit = takeProfitPrice.ToString(Data.FF);
            }

            if (Configs.PlaySounds)
                Data.SoundOrderSent.Play();

            string message = string.Format(symbol + " " + Data.PeriodMTStr + " " +
                                           Language.T("An entry order sent") + ": " +
                                           Language.T(ordDir.ToString()) + " {0} " +
                                           LotOrLots(lots) + " " +
                                           Language.T("at") + " {1}, " +
                                           Language.T("Stop Loss") + " {2}, " +
                                           Language.T("Take Profit") + " {3}",
                                           lots, price.ToString(Data.FF), stopLoss,
                                           takeProfit);
            var jmsg = new JournalMessage(icon, DateTime.Now, message);
            AppendJournalMessage(jmsg);
            Log(message);

            string parameters = OrderParameters();
            int response = _bridge.OrderSend(symbol, type, lots, price, slippage, stoploss, takeprofit, parameters);

            if (response >= 0)
            {
                // The order was executed successfully.
                Data.AddBarStats(opType, lots, price);

                _timeLastEntryBar = Data.Time[Data.Bars - 1];
                if (type == OrderType.Buy)
                    _isEnteredLong = true;
                else
                    _isEnteredShort = true;

                Data.WrongStopLoss = 0;
                Data.WrongTakeProf = 0;
                Data.WrongStopsRetry = 0;
            }
            else
            {
                // Error in operation execution.
                ReportOperationError();
                Data.WrongStopLoss = (int) stoploss;
                Data.WrongTakeProf = (int) takeprofit;
            }
        }
示例#35
0
 public void PlaceTradeAsync(int tradingAccountId, int marketId, TradeDirection direction, decimal quantity, decimal bidPrice, decimal offerPrice, TradeOrderResponseDelegate callback)
 {
     PlaceTradeAsync(tradingAccountId, marketId, direction, quantity, bidPrice, offerPrice, new int[] { }, callback);
 }
示例#36
0
        public void PlaceTradeAsync(int tradingAccountId, int marketId, TradeDirection direction, decimal quantity, decimal bidPrice, decimal offerPrice, int[] close, TradeOrderResponseDelegate callback)
        {
            NewTradeOrderRequestDTO orderRequest;
            lock (_syncObj)
            {
                PriceDTO price;

                _prices.TryGetValue(marketId, out price);

                if (price == null)
                {
                    throw new Exception("you must have a price subscription in order to place a trade");
                }

                orderRequest = new NewTradeOrderRequestDTO
                                   {
                                       AuditId = price.AuditId,
                                       MarketId = marketId,
                                       Direction = direction.ToString(),
                                       BidPrice = bidPrice,
                                       OfferPrice = offerPrice,
                                       Quantity = quantity,
                                       Close = close,
                                       TradingAccountId = tradingAccountId
                                   };
            }

            PlaceTradeAsync(orderRequest, callback);


        }
        public async Task PricingStructureCorrectValue(UKCompetentAuthority ca, TradeDirection td, int nt, bool isInterim,
            int numberOfShipments, int expectedPrice)
        {
            var result = (await context.PricingStructures.SingleAsync(
                p => p.CompetentAuthority == ca &&
                     p.Activity.TradeDirection == td &&
                     (int)p.Activity.NotificationType == nt &&
                     p.Activity.IsInterim == isInterim &&
                     (p.ShipmentQuantityRange.RangeFrom <= numberOfShipments &&
                      (p.ShipmentQuantityRange.RangeTo == null || p.ShipmentQuantityRange.RangeTo >= numberOfShipments))))
                .Price;

            Assert.Equal(expectedPrice, result);
        }
        /// <summary>
        /// Adjusts the closing direction.
        /// </summary>
        private TradeDirection GetClosingDirection(TradeDirection baseDirection, IndComponentType compDataType)
        {
            TradeDirection newDirection = baseDirection;

            if (compDataType == IndComponentType.ForceClose)
            {
                newDirection = TradeDirection.Both;
            }
            else if (compDataType == IndComponentType.ForceCloseShort)
            {
                if (baseDirection == TradeDirection.None)
                    newDirection = TradeDirection.Long;
                else if (baseDirection == TradeDirection.Short)
                    newDirection = TradeDirection.Both;
            }
            else if (compDataType == IndComponentType.ForceCloseLong)
            {
                if (baseDirection == TradeDirection.None)
                    newDirection = TradeDirection.Short;
                else if (baseDirection == TradeDirection.Long)
                    newDirection = TradeDirection.Both;
            }

            return newDirection;
        }
        /// <summary>
        /// Increases the status of baseDirection to direction.
        /// </summary>
        private TradeDirection IncreaseDirectionStatus(TradeDirection baseDirection, TradeDirection direction)
        {
            if (baseDirection == direction || direction == TradeDirection.None)
                return baseDirection;

            if (baseDirection == TradeDirection.None)
                return direction;

            return TradeDirection.Both;
        }