예제 #1
0
        public PostOrderResponse PostOrder(PostOrderRequest apor_por)
        {
            PostOrderResponse lpor_response;

            lpor_response        = new PostOrderResponse();
            lpor_response.status = new Status();

            try
            {
                IOrderServiceBusiness liosb_iosb;

                liosb_iosb    = new OrderServiceBusiness();
                lpor_response = liosb_iosb.PostOrder(apor_por);
            }
            catch (Exception ae_e)
            {
                Exception le_e;

                le_e = ae_e.InnerException != null ? ae_e.InnerException : ae_e;
                lpor_response.status.CodeResp    = "01";
                lpor_response.status.MessageResp = ae_e.InnerException != null ? "Error en la ejecucion del servicio" : ae_e.Message;
                lpor_response.result             = null;
                Common.CreateTrace.WriteLog(Common.CreateTrace.LogLevel.Error, "ERROR EN LA CAPA DE SERVICIO OrderService:PostOrder");
                Common.CreateTrace.WriteLog(Common.CreateTrace.LogLevel.Error, " :: " + le_e.Message);
            }

            return(lpor_response);
        }
예제 #2
0
        protected virtual async Task <PostOrderResponse> PlaceLimitOrder(Dictionary <string, string> order)
        {
            // do limit stuff

            // place order
            PostOrderResponse response = await PlaceOrder("limit", order);

            return(response);
        }
예제 #3
0
        static async Task <long?> PlaceMarketOrder(string side = "buy")
        {
            WriteNewLine("Creating a EUR_USD market BUY order ...");

            var parameters = new AccountInstrumentsParameters()
            {
                instruments = new List <string>()
                {
                    INSTRUMENT
                }
            };
            var     oandaInstrument = (await Rest20.GetAccountInstrumentsAsync(AccountID, parameters)).First();
            decimal orderUnits      = side == "buy" ? 10 : -10;

            var request = new MarketOrderRequest(oandaInstrument)
            {
                units = orderUnits
            };

            PostOrderResponse response = null;

            try
            {
                response = await Rest20.PostOrderAsync(AccountID, request);

                WriteNewLine("Congrats! You've put on a trade! Let it run! :)");
            }
            catch (Exception ex)
            {
                var errorResponse = ErrorResponseFactory.Create(ex.Message);

                WriteNewLine("Oops. Order creation failed.");
                WriteNewLine($"The failure message is: {errorResponse.errorMessage}.");
                WriteNewLine("Try again later.");
            }

            return(response?.orderFillTransaction?.tradeOpened?.tradeID);
        }
예제 #4
0
        protected virtual async Task <PostOrderResponse> PlaceOrder(string type, Dictionary <string, string> order)
        {
            // make sure type is correct
            if (!order.ContainsKey("type"))
            {
                order.Add("type", type);
            }
            else
            {
                order["type"] = type;
            }

            ValidateOrder(order);

            PostOrderResponse response = null;

            if (!await Helpers.IsMarketHalted())
            {
                response = await Rest.PostOrderAsync(_accountId, order);
            }

            return(response);
        }
예제 #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="signal"></param>
        /// <param name="instrument"></param>
        /// <param name="retracement"></param>
        /// <returns></returns>
        protected virtual async Task <int> CreateEntryOrder(MCE.Signal signal, Chart chart, Thrust thrust)
        {
            StrategyTransaction transaction = null;

            Tuple <double, double, double> orderPrices = GetOrderPrices(chart.HistoricBidAskSpread, signal.Side, thrust);
            double entryPrice      = orderPrices.Item1;
            double stopLossPrice   = orderPrices.Item2;
            double takeProfitPrice = orderPrices.Item3;

            int tradeUnits = await TradeUnitsCapacity(chart.Instrument, entryPrice, stopLossPrice);

            if (tradeUnits > 0)
            {
                // 12 hours for now .. how should this change? .. read from metaSetting?
                string expiry = MAOE.Utilities.GetTimeAsXmlSerializedUtc(DateTime.UtcNow.AddHours(12));

                string type   = "limit";
                string side   = signal.Side == MACC.Constants.SignalSide.Buy ? "buy" : "sell";
                int    places = ((FibonacciRetracement)thrust.Study).LevelPlaces();

                // create order
                var orderData = new Dictionary <string, string>
                {
                    { "instrument", chart.Instrument },
                    { "units", tradeUnits.ToString() },
                    { "side", side },
                    { "type", type },
                    { "expiry", expiry },
                    { "price", Math.Round(entryPrice, places).ToString() },
                    { "stopLoss", Math.Round(stopLossPrice, places).ToString() },
                    { "takeProfit", Math.Round(takeProfitPrice, places).ToString() }
                };

                PostOrderResponse response = await PlaceLimitOrder(orderData);

                if (response.orderOpened != null && response.orderOpened.id > 0)
                {
                    MarketMinerOrder orderOpened = new MarketMinerOrder(response.orderOpened);
                    orderOpened.SignalID = signal.SignalID;

                    transaction = CreateEntryTransaction(chart.Instrument, orderOpened.side, response.time, type, response.price.GetValueOrDefault(), orderOpened.takeProfit, orderOpened.stopLoss, orderOpened.id.ToString());
                    transaction = await StrategyCaller.Instance().SaveStrategyTransactionAsync(transaction, MarketMiner.Common.Constants.Brokers.OANDA);

                    orderOpened.StrategyTransactionID = transaction.StrategyTransactionID;

                    // add entry trans id to the signal
                    signal.StrategyTransactionID = transaction.StrategyTransactionID;
                    await SubscriptionCaller.Instance().UpdateSignalAsync(signal);

                    AddOrUpdateAlgorithmOrder(orderOpened);

                    DateTime transactionTime = Convert.ToDateTime(response.time).ToUniversalTime();
                    thrust.SetOrUpdatePrices(entryPrice, takeProfitPrice, stopLossPrice, places, transactionTime);
                }
            }
            else
            {
                string missedTradeReason = Utilities.GetMissedTradeReason(tradeUnits);
                AddAlgorithmMessage(string.Format("Missed trade: {0} for signalId: {1}", missedTradeReason, signal.SignalID), true, TraceEventType.Information);
            }

            return(transaction == null ? 0 : transaction.StrategyTransactionID);
        }
예제 #6
0
    static void Main(string[] args)
    {
        List <Instrument> instruments = null;
        var task = Task.Run(async() => instruments = await Rest.GetInstrumentsAsync(AccountId, null, new List <string>(_majors)));

        task.Wait();

        var          selectedMajors = instruments.Where(s => Array.Exists <string>(_majors, y => y == s.instrument));
        RatesSession session        = new RatesSession(AccountId, new List <Instrument>(selectedMajors));

        _tickReceived         = new Semaphore(0, 100);
        session.DataReceived += SessionOnDataReceived;
        session.StartSession();
        Console.WriteLine("Starting rate stream test");
        bool success = _tickReceived.WaitOne(10000);

        session.StopSession();


        EventsSession eventSession = new EventsSession(AccountId);

        _eventReceived             = new Semaphore(0, 100);
        eventSession.DataReceived += OnEventReceived;
        eventSession.StartSession();
        Console.WriteLine("Starting event stream test");
        Task.Run(() =>
        {
            success = _eventReceived.WaitOne(10000);
            eventSession.StopSession();
        }
                 );

        List <Price> prices;

        var task2 = Task.Run(async() => prices = await Rest.GetRatesAsync(instruments));

        task2.Wait();


        List <Position> positions = null;

        var task3 = Task.Run(async() => positions = await Rest.GetPositionsAsync(AccountId));

        task3.Wait();

        var request = new Dictionary <string, string>
        {
            { "instrument", TestInstrument },
            { "units", "10000" },
            { "side", "sell" },
            { "type", "market" },
            { "price", "1.0" }
        };

        if (positions.Count == 0)
        {
            //Open a position
            PostOrderResponse response = null;
            var task4 = Task.Run(async() => response = await Rest.PostOrderAsync(AccountId, request));
            task4.Wait();

            if (response.tradeOpened != null && response.tradeOpened.id > 0)
            {
                Console.WriteLine("Post order success");
            }
        }
        else
        {
            //Close all positions
            foreach (var position in positions)
            {
                DeletePositionResponse closePositionResponse = null;
                var task5 = Task.Run(async() => closePositionResponse = await Rest.DeletePositionAsync(AccountId, TestInstrument));
                task5.Wait();

                if (closePositionResponse.ids.Count > 0 && closePositionResponse.instrument == TestInstrument)
                {
                    Console.WriteLine("Position closed");
                }

                if (closePositionResponse.totalUnits > 0 && closePositionResponse.price > 0)
                {
                    Console.WriteLine("Position close response seems valid");
                }

                foreach (var id in closePositionResponse.ids)
                {
                    Transaction transaction = null;
                    var         task6       = Task.Run(async() => transaction = await Rest.GetTransactionDetailsAsync(AccountId, id));
                    task6.Wait();
                }
            }
        }

        Console.ReadLine();
    }