private void aToBSideRb_CheckedChanged(object sender, EventArgs e)
 {
     if (aToBSideRb.Checked)
     {
         tradeSide = TradeSide.A_TO_B;
     }
 }
Пример #2
0
 public GameEventAddToTrade(Session session, uint objectGuid, TradeSide tradeSide)
     : base(GameEventType.AddToTrade, GameMessageGroup.UIQueue, session)
 {
     Writer.Write(objectGuid);
     Writer.Write((uint)tradeSide);
     Writer.Write(0);    // location / slot
 }
 private void bToASideRb_CheckedChanged(object sender, EventArgs e)
 {
     if (bToASideRb.Checked)
     {
         tradeSide = TradeSide.B_TO_A;
     }
 }
Пример #4
0
        public bool TrySetWorkingTrailingStopPrice(TradeSide tradeSide, int level, double workingTrailingStopPrice)
        {
            bool isSuccess = false;

            switch (tradeSide)
            {
            case TradeSide.Unknown:
                break;

            case TradeSide.Buy:
                if (m_WorkingBuyNodes.ContainsKey(level))
                {
                    m_WorkingBuyNodes[level].WorkingTrailingStopPrice = workingTrailingStopPrice;
                    isSuccess = true;
                }
                break;

            case TradeSide.Sell:
                if (m_WorkingSellNodes.ContainsKey(level))
                {
                    m_WorkingSellNodes[level].WorkingTrailingStopPrice = workingTrailingStopPrice;
                    isSuccess = true;
                }
                break;
            }
            return(isSuccess);
        }
Пример #5
0
        /// <summary>
        /// Argument Constructor
        /// </summary>
        /// <param name="tradeSide">Represents the side which was responsible for starting the Trade</param>
        /// <param name="tradeSize">Size of Trade depending upon the Order Size which strated the Trade</param>
        /// <param name="executionPrice">Price at which the order is executed</param>
        /// <param name="executionProvider">Order Execution Provider On which the executions take place</param>
        /// <param name="executionId">Execution ID for Order which initiated the Trade</param>
        /// <param name="security">Security/Symbol for which the Order Executions are occuring</param>
        /// <param name="startTime">Execution time to be used for Trade Start Time</param>
        public Trade(TradeSide tradeSide, int tradeSize, decimal executionPrice, string executionProvider, string executionId, Security security, DateTime startTime)
        {
            // Save Information
            _tradeSide         = tradeSide;
            _tradeSize         = tradeSize;
            _executionProvider = executionProvider;
            _security          = security;
            _startTime         = startTime;

            // Initialize
            _executionDetails = new Dictionary <string, int>();

            // Set initial Position value
            _position = tradeSize;

            // Set initial PnL value
            _profitAndLoss = executionPrice * tradeSize;

            // Set value to 'Negative' if the Trade side is 'SELL'
            if (tradeSide.Equals(Constants.TradeSide.Sell))
            {
                _position      *= -1;
                _tradeSize     *= -1;
                _profitAndLoss *= -1;
            }

            // Add initial values to the local Map
            _executionDetails.Add(executionId, _position);
        }
Пример #6
0
        public bool TrySetWorkingExitQty(TradeSide tradeSide, int level, int workingQty)
        {
            bool isSuccess = false;

            switch (tradeSide)
            {
            case TradeSide.Unknown:
                break;

            case TradeSide.Buy:
                if (m_WorkingBuyNodes.ContainsKey(level))
                {
                    m_WorkingBuyNodes[level].WorkingExitQty = workingQty;
                    isSuccess = true;
                }
                break;

            case TradeSide.Sell:
                if (m_WorkingSellNodes.ContainsKey(level))
                {
                    m_WorkingSellNodes[level].WorkingExitQty = workingQty;
                    isSuccess = true;
                }
                break;
            }
            return(isSuccess);
        }
Пример #7
0
 public GameEventAddToTrade(Session session, ObjectGuid item, TradeSide tradeSide)
     : base(GameEventType.AddToTrade, GameMessageGroup.UIQueue, session)
 {
     Writer.WriteGuid(item);
     Writer.Write((uint)(tradeSide));
     Writer.Align();
 }
Пример #8
0
        public bool TrySetWorkingEnterFlag(TradeSide tradeSide, int level, bool workingEnterFlag)
        {
            bool isSuccess = false;

            switch (tradeSide)
            {
            case TradeSide.Unknown:
                break;

            case TradeSide.Buy:
                if (m_WorkingBuyNodes.ContainsKey(level))
                {
                    m_WorkingBuyNodes[level].IsEnterEnable = workingEnterFlag;
                    isSuccess = true;
                }
                break;

            case TradeSide.Sell:
                if (m_WorkingSellNodes.ContainsKey(level))
                {
                    m_WorkingSellNodes[level].IsEnterEnable = workingEnterFlag;
                    isSuccess = true;
                }
                break;
            }
            return(isSuccess);
        }
Пример #9
0
        public async Task <Binance.Blank> TestPlaceOrderAsync(string symbol, TradeSide side, Binance.OrderType type, decimal amount, decimal?price = null, decimal?stopPrice = null, Binance.TimeInForce tif = Binance.TimeInForce.GTC, string newClientOrderId = null)
        {
            var serverTime = await GetServerTime();

            var offset  = serverTime - DateTime.UtcNow;
            var request = new RestSharp.RestRequest(TestPlaceOrderEndpoint, RestSharp.Method.POST);

            request.AddQueryParameter("symbol", symbol);
            request.AddQueryParameter("side", side.ToString().ToUpper());
            request.AddQueryParameter("type", type.ToString().ToUpper());
            request.AddQueryParameter("quantity", amount.ToString());
            request.AddQueryParameter("newOrderRespType", "RESULT");
            request.AddQueryParameter("timeInForce", tif.ToString().ToUpper());
            //request.AddQueryParameter("recvWindow", 60000);
            if (price != null)
            {
                request.AddQueryParameter("price", price.Value.ToString());
            }
            if (newClientOrderId != null)
            {
                request.AddQueryParameter("newClientOrderId", newClientOrderId);
            }
            var result = await RequestSignedApiAsync <Binance.Blank>(request, TestPlaceOrderWeight, offset);

            return(result);
        }
Пример #10
0
 public void SetTrade(TradeSide side, long lPrice, int size)
 {
     IsTrade      = true;
     binary.Side  = (byte)side;
     binary.Price = lPrice;
     binary.Size  = size;
 }
Пример #11
0
        //
        //
        /// <summary>
        /// Setup stop loss timers if stop orders signals are triggered.
        /// </summary>
        /// <param name="side"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public bool SetUpStopLossTimer(TradeSide side, int time)
        {
            switch (side)
            {
            case TradeSide.Unknown:
                break;

            case TradeSide.Buy:
                if (m_StopLossTimers[OrderSide.BuySide] == null)
                {
                    m_StopLossTimers[OrderSide.BuySide]          = new Timer(time);
                    m_StopLossTimers[OrderSide.BuySide].Elapsed += new ElapsedEventHandler(StopLossTimer_OnTick);
                }
                if (m_StopLossTriggered[OrderSide.BuySide] == false)
                {
                    m_StopLossTriggered[OrderSide.BuySide] = true;
                    m_StopLossTimers[OrderSide.BuySide].Start();
                }
                break;

            case TradeSide.Sell:
                if (m_StopLossTimers[OrderSide.SellSide] == null)
                {
                    m_StopLossTimers[OrderSide.SellSide]          = new Timer(time);
                    m_StopLossTimers[OrderSide.SellSide].Elapsed += new ElapsedEventHandler(StopLossTimer_OnTick);
                }
                if (m_StopLossTriggered[OrderSide.SellSide] == false)
                {
                    m_StopLossTriggered[OrderSide.SellSide] = true;
                    m_StopLossTimers[OrderSide.SellSide].Start();
                }
                break;
            }
            return(true);
        }
Пример #12
0
        public void SetAttributes(Dictionary <string, string> attributes)
        {
            TradeSide tradeSide;
            int       qty;

            foreach (KeyValuePair <string, string> att in attributes)
            {
                if (att.Key.Equals("TradeLevelName"))
                {
                    m_TradeLevelName = att.Value;
                }
                else if (att.Key.Equals("IsEnterEnable") && att.Value.Equals(bool.TrueString))
                {
                    m_IsEnterEnable = true;
                }
                else if (att.Key.Equals("TradeLevel") && int.TryParse(att.Value, out qty))
                {
                    m_TradeLevel = qty;
                }
                else if (att.Key.Equals("TradeSide") && Enum.TryParse(att.Value, out tradeSide))
                {
                    m_TradeSide = tradeSide;
                }
                else if (att.Key.Equals("WorkingEnterQty") && int.TryParse(att.Value, out qty))
                {
                    m_WorkingEnterQty = qty;
                }
                else if (att.Key.Equals("WorkingExitQty") && int.TryParse(att.Value, out qty))
                {
                    m_WorkingExitQty = qty;
                }
            }
        }
Пример #13
0
        private IEnumerable <OrderBookEntry> AggregateOrderBook(ICollection <OrderBookEntry> orderBook)
        {
            TradeSide side             = TradeSide.Sell;
            decimal   priceLevel       = decimal.Zero;
            decimal   volumeAggregated = decimal.Zero;
            var       result           = new List <OrderBookEntry>();

            foreach (var entry in orderBook)
            {
                if (priceLevel == decimal.Zero)
                {
                    side             = entry.Side;
                    priceLevel       = MergePrice(entry.Price, factor, entry.Side);
                    volumeAggregated = entry.Quantity;
                }
                else if (side == entry.Side && priceLevel == MergePrice(entry.Price, factor, entry.Side))
                {
                    volumeAggregated += entry.Quantity;
                }
                else
                {
                    result.Add(new OrderBookEntry()
                    {
                        Price = priceLevel, Quantity = volumeAggregated, Side = side
                    });
                    priceLevel       = MergePrice(entry.Price, factor, entry.Side);
                    volumeAggregated = entry.Quantity;
                    side             = entry.Side;
                }
            }

            return(result);
        }
        /// <summary>
        /// Get the flag of whether any of the entry level is allowed.
        /// </summary>
        /// <param name="tradeSide"></param>
        /// <returns></returns>
        public bool GetEntryAllowFlag(TradeSide tradeSide)
        {
            switch (tradeSide)
            {
            case TradeSide.Unknown:
                break;

            case TradeSide.Buy:
                foreach (TradingNode tradingNode in m_WorkingBuyNodes.Values)
                {
                    if (tradingNode.IsEnterEnable == true)
                    {
                        return(true);
                    }
                }
                break;

            case TradeSide.Sell:
                foreach (TradingNode tradingNode in m_WorkingSellNodes.Values)
                {
                    if (tradingNode.IsEnterEnable == true)
                    {
                        return(true);
                    }
                }
                break;
            }
            return(false);
        }
Пример #15
0
        private void UpdateTrendState(TrendInfo trendInfo, TradeSide side, ILocalSnapshotService localSnapshotService)
        {
            var pricesOpt = CalculatePrices(trendInfo.TargetEis, trendInfo.ReferenceEis, side, localSnapshotService);

            if (pricesOpt == null)
            {
                return;
            }
            var prices = pricesOpt.Value;

            var referenceDeltaPrice = PriceTrendCalculator.CalcPriceOffset(prices.ReferencePrice, prices.TargetPrice, 0);

            lock (trendInfo.Sync)
            {
                var mutTrendInfoBySide = trendInfo.GetMutable(side);

                var now = _dateTimeService.UtcNow;
                mutTrendInfoBySide.UpdateStateIncrementally(referenceDeltaPrice, now);

                var isReset = prices.TargetSpread > TargetSpreadThreshold ||
                              Math.Abs(referenceDeltaPrice) > ReferenceDeltaPriceThreshold;

                var exceededDeltaPriceStartTime = trendInfo.ExceededDeltaPriceStartTime;
                if (exceededDeltaPriceStartTime != null)
                {
                    if (isReset)
                    {
                        trendInfo.TryResetProhibitionPeriod(now, ResetPeriod);
                    }
                    else
                    {
                        trendInfo.AbortReset();
                        if (exceededDeltaPriceStartTime + WindowPeriod <= now)
                        {
                            // prohibition period is ended
                            trendInfo.ExceededDeltaPriceStartTime = null;

                            var buyTrendInfo = trendInfo.GetMutable(TradeSide.Buy);
                            buyTrendInfo.Equilibrium = buyTrendInfo.CalcMeanDeltaPrice();

                            var sellTrendInfo = trendInfo.GetMutable(TradeSide.Sell);
                            sellTrendInfo.Equilibrium = sellTrendInfo.CalcMeanDeltaPrice();
                        }
                    }
                }
                else
                {
                    if (isReset)
                    {
                        trendInfo.TryResetProhibitionPeriod(now, ResetPeriod);
                    }
                    else
                    {
                        trendInfo.AbortReset();
                        mutTrendInfoBySide.Equilibrium = mutTrendInfoBySide.CalcMeanDeltaPrice();
                    }
                }
            }
        }
Пример #16
0
 public MutableTrendInfoBySide GetMutable(TradeSide side)
 {
     return(side switch
     {
         TradeSide.Buy => _buyMutable,
         TradeSide.Sell => _sellMutable,
         _ => throw new ArgumentOutOfRangeException(nameof(side), side, null)
     });
 private void aBBFSideRb_CheckedChanged(object sender, EventArgs e)
 {
     if (aBBFSideRb.Checked)
     {
         tradeSide   = TradeSide.BOTH_A_B_B_FIRST;
         tradeMethod = TradeMethod.B_TO_A;
     }
 }
Пример #18
0
 private static TradeSide GetSide(bool reverse, TradeSide providerSide)
 {
     if (!reverse)
     {
         return(providerSide);
     }
     return(providerSide == TradeSide.Buy ? TradeSide.Sell : TradeSide.Buy);
 }
 private CryptoTradeSide ConvertSide(TradeSide tradeSide)
 {
     if (tradeSide == TradeSide.Undefined)
     {
         return(CryptoTradeSide.Undefined);
     }
     return(tradeSide == TradeSide.Buy ? CryptoTradeSide.Buy : CryptoTradeSide.Sell);
 }
Пример #20
0
 internal Order(SingleAdviser <int> adviser, string symbol, double requestedPrice, double requestedVolume, OrderType type, TradeSide side)
 {
     m_volume         = requestedVolume;
     m_adviser        = adviser;
     m_symbol         = symbol;
     m_requestedPrice = requestedPrice;
     m_type           = type;
     m_side           = side;
 }
Пример #21
0
Файл: Order.cs Проект: ifzz/FDK
		internal Order(SingleAdviser<int> adviser, string symbol, double requestedPrice, double requestedVolume, OrderType type, TradeSide side)
		{
			m_volume = requestedVolume;
			m_adviser = adviser;
			m_symbol = symbol;
			m_requestedPrice = requestedPrice;
			m_type = type;
			m_side = side;
		}
Пример #22
0
        private void ManageOverSize(Tick tick)
        {
            var lots = Position.Size / lotSize;

            if (Position.IsShort)
            {
                if (lots >= maxLots)
                {
                    SellSize     = 0;
                    BuySize      = lots; // Math.Max(1, maxLots / 20);
                    state        = StrategyState.OverSize;
                    oversizeSide = TradeSide.Sell;
                }
                else if (state == StrategyState.OverSize)
                {
                    if (Position.IsFlat || oversizeSide == TradeSide.Buy)
                    {
                        state = StrategyState.Active;
                    }
                    else
                    {
                        SellSize = 0;
                        BuySize  = Math.Max(1, maxLots / 20);
                        BuySize  = Math.Min(lots, BuySize);
                    }
                }
            }

            if (Position.IsLong)
            {
                if (lots != lastLots)
                {
                    lastLots = lots;
                }
                if (lots >= maxLots)
                {
                    BuySize      = 0;
                    SellSize     = lots; // Math.Max(1, maxLots / 20);
                    state        = StrategyState.OverSize;
                    oversizeSide = TradeSide.Buy;
                }
                else if (state == StrategyState.OverSize)
                {
                    if (Position.IsFlat || oversizeSide == TradeSide.Sell)
                    {
                        state = StrategyState.Active;
                    }
                    else
                    {
                        BuySize  = 0;
                        SellSize = Math.Max(1, maxLots / 20);
                        SellSize = Math.Min(lots, SellSize);
                    }
                }
            }
        }
Пример #23
0
 public TradeCoinRequest(string fromCoin, string toCoin, TradeType tradeType, TradeSide tradeSide, decimal tradePrice, decimal units, TradeLevel tradeLevel)
 {
     this.FromCoinSymbol = fromCoin;
     this.ToCoinSymbol = toCoin;
     this.TradeType = (int)tradeType;
     this.TradeSide = (int)tradeSide;
     this.TradePrice = tradePrice;
     this.Units = units;
     this.TradeLevel = (int)tradeLevel;
 }
 public Order(string tradeId, string stockId, TradeSide side, double originalQuantity, decimal price, DateTimeOffset timeIssued, IImmutableList <Fill> fills)
 {
     OrderId          = tradeId;
     StockId          = stockId;
     Side             = side;
     OriginalQuantity = originalQuantity;
     Price            = price;
     TimeIssued       = timeIssued;
     Fills            = fills;
 }
 public static double CalculatePL(TradeSide tradeSide, double size, double level, double buyPrice, double sellPrice)
 {
     if (tradeSide == TradeSide.BUY)
     {
         return(Math.Round((buyPrice - level) * size, 2));
     }
     else
     {
         return(Math.Round((level - sellPrice) * size, 2));
     }
 }
Пример #26
0
 private static decimal MergePrice2(decimal price, decimal factor, TradeSide side)
 {
     if (side == TradeSide.Buy)
     {
         return(Math.Truncate(price / factor) * factor);
     }
     else
     {
         return(Math.Truncate((price + (factor - 0.000000001m)) / factor) * factor);
     }
 }
Пример #27
0
 private static decimal MergePrice(decimal price, decimal factor, TradeSide side)
 {
     if (side == TradeSide.Buy)
     {
         return(Math.Truncate(price * factor) / factor);
     }
     else
     {
         return(Math.Ceiling(price * factor) / factor);
     }
 }
Пример #28
0
 public TradeCoinResponse New(string fromCoin, string toCoin, TradeType tradeType, TradeSide tradeSide, decimal tradePrice, decimal units, TradeLevel tradeLevel)
 {
     return
         this.CallMethod<TradeCoinResponse>(
             new RequestBuilder(RequestType.POST, "order/new")
             .AddUrlSegment(new CoinsPairSegment(fromCoin, toCoin))
             .AddUrlSegment(tradeType)
             .AddUrlSegment(tradeSide)
             .AddUrlSegment(tradePrice)
             .AddUrlSegment(units)
             .AddUrlSegment(tradeLevel));
 }
Пример #29
0
        /// <summary>
        /// Updates Direction i.e. Negative or Positive
        /// </summary>
        /// <param name="executionSide">Execution Size</param>
        /// <param name="position">Position to manage direction</param>
        /// <param name="tradeSide">Trade Side</param>
        private void UpdateTradeDirection(string executionSide, ref int position, ref TradeSide tradeSide)
        {
            // Set 'Negative' sign if the execution is 'SELL'/'SHORT'
            if (executionSide.Equals(OrderSide.SELL) || executionSide.Equals(OrderSide.SHORT))
            {
                // Set Position to 'Negative'
                position *= -1;

                // Update Trade Side
                tradeSide = TradeSide.Sell;
            }
        }
        private async void OrderCheckTimer_TickAsync(object sender, EventArgs e)
        {
            if (isOrderWaiting)
            {
                FileLogger.Instance.WriteLog($"Hit&RunTrading: Order Check | Order ID: {waitingOrderId}");

                // if order was waiting check it for filling status
                var order = await Api.GetOrderAsync(User, Symbol, waitingOrderId);

                if (order.Status == OrderStatus.Filled)
                {
                    LogManager.Instance.AddLog(new TradeLog()
                    {
                        Amount = order.OriginalQuantity,
                        Price  = order.Price,
                        Side   = order.Side == OrderSide.Buy ? TradeSide.Buy : TradeSide.Sell,
                        Symbol = order.Symbol
                    });

                    FileLogger.Instance.WriteLog($"Hit&RunTrading: Order Check | Order ID: {waitingOrderId} has been filled!");

                    if (order.Side == OrderSide.Buy)
                    {
                        tradeSide = TradeSide.Sell;
                    }
                    else if (order.Side == OrderSide.Sell)
                    {
                        tradeSide    = TradeSide.Buy;
                        dateLastSold = DateTime.Now;
                    }

                    ResetValuesAfterTrade();
                    orderCheckTimer.Stop();

                    await Task.Delay(2000);

                    if (tradeSide == TradeSide.Sell)
                    {
                        MakeTrade();
                    }

                    stablenessCheckTimer.Start();
                }
                else if (order.Status == OrderStatus.Canceled || order.Status == OrderStatus.Expired || order.Status == OrderStatus.Rejected)
                {
                    isOrderWaiting = false;
                }
            }

#if TRADE_TEST
            orderCheckTimer.Stop();
#endif
        }
Пример #31
0
        private void UpdateTrends(ExchangeIdSymbol eventEis, TradeSide side, ILocalSnapshotService localSnapshotService)
        {
            if (!_relatedTrends.TryGetValue(eventEis.ToTradePlace(), out var trendInfoList))
            {
                return;
            }

            foreach (var trendInfo in trendInfoList)
            {
                UpdateTrendState(trendInfo, side, localSnapshotService);
            }
        }
Пример #32
0
        public Trade GetLastTradeForPair(string currency, string exchange, TradeSide side)
        {
            var enumerable = _db.Query <Trade>()
                             .Where(x => x.Terms == currency && x.Exchange == exchange)
                             .ToEnumerable()
                             .OrderByDescending(x => x.TimeStamp);

            var onlyBuys  = enumerable.Where(x => x.Side == TradeSide.Buy);
            var lastTrade = onlyBuys.FirstOrDefault();

            return(lastTrade);
        }
Пример #33
0
        public void LogLevel2Change(bool recordTrade, TradeSide side, double price, int size)
        {
            CreateTick();

            if (TryAddLevel2())
            {
                if (recordTrade && Symbol.TimeAndSales == TimeAndSales.Extrapolated)
                {
                    tick.SetTrade(side, price, size);
                }
                SendTick();
            }
        }