Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            int    login    = 0;            // Enter your login
            string password = "******";   // Enter your password

            var client = new APIClient(new APIConnection(ServerType.Demo));

            client.Connect().Wait();
            Console.WriteLine("Connected");

            client.Login(login, password).ContinueWith(r =>
            {
                var resp = r.Result;
                Console.WriteLine("Login response: {0} - {1}", resp.Login, resp.LoginStatus);

                TradeCommand command = TradeCommand.Buy;
                string instrument    = "EURUSD";
                double volume        = 0.1;

                client.Trade.OpenOrder(instrument, command, 0, 0, 0, volume).ContinueWith(p =>
                {
                    Console.WriteLine("Trade response {0} for order {1}", p.Result.Order, p.Result.ErrorCode);
                }
                                                                                          );
            });

            Console.ReadKey();
        }
Ejemplo n.º 2
0
        public void OpenOrder_Has_Send_The_Right_Packet(string symbol, TradeCommand tradeCommand,
                                                        double price, double stopLoss, double takeProfit, double volume, string comment)
        {
            Action <APIClient> request_with_comment    = c => c.Trade.OpenOrder(symbol, tradeCommand, price, stopLoss, takeProfit, volume, comment);
            Action <APIClient> request_without_comment = c => c.Trade.OpenOrder(symbol, tradeCommand, price, stopLoss, takeProfit, volume);

            Expression <Func <TradeTransRequestPacket, bool> > match = p => p.TradeCommand == tradeCommand &&
                                                                       p.TransactionType == TransactionType.OpenOrder &&
                                                                       p.Price == price &&
                                                                       p.StopLoss == stopLoss &&
                                                                       p.TakeProfit == takeProfit &&
                                                                       p.Symbol == symbol &&
                                                                       p.Volume == volume &&
                                                                       p.Comment == comment &&
                                                                       p.Expiration == new DateTime(1970, 1, 1);

            if (comment == String.Empty)
            {
                VerifyRequest <TradeTransRequestPacket>(request_without_comment, match);
            }
            else
            {
                VerifyRequest <TradeTransRequestPacket>(request_with_comment, match);
            }
        }
Ejemplo n.º 3
0
        Task <TradeTransResponsePacket> ITradeProvider.OpenOrder(string symbol, TradeCommand tradeCommand,
                                                                 double price, double stopLoss, double takeProfit, double volume, string comment)
        {
            Func <int, APINetworkPacket> lambda = (reqId =>
                                                   new TradeTransRequestPacket(reqId, tradeCommand, TransactionType.OpenOrder, price, stopLoss, takeProfit, symbol, volume, 0, comment, new DateTime(1970, 1, 1)));

            return(HandleRequestPacket <TradeTransResponsePacket>(lambda));
        }
Ejemplo n.º 4
0
        public FxOrder OpenNewOrder(string operationId, string symbol, TradeCommand command, TradeRecordSide side, double priceThreshold, double volume, double? stopLoss, double? takeProfit, DateTime? expiration, string comment, int timeoutInMilliseconds)
        {
            if (operationId == null)
                operationId = string.Empty;

            this.VerifyInitialized();

            var order = new FxOrder(symbol, (int)command, side, priceThreshold, volume, stopLoss, takeProfit, expiration, comment);

            return Native.TradeServer.OpenNewOrder(this.handle, operationId, order, (uint)timeoutInMilliseconds); 
        }
Ejemplo n.º 5
0
        /// <summary>
        /// The method opens a new order.
        /// </summary>
        /// <param name="operationId">
        /// Can be null, in this case FDK generates a new unique operation ID automatically.
        /// Otherwise, please use GenerateOperationId method of DataClient object.
        /// </param>
        /// <param name="symbol">Trading currency pair symbol; can not be null.</param>
        /// <param name="command">Market, limit or stop.</param>
        /// <param name="side">Trade record side: buy or sell.</param>
        /// <param name="volume">Requsted volume.</param>
        /// <param name="maxVisibleVolume">Max visible volume.</param>
        /// <param name="price">Activating price for pending orders; price threshold for market orders.</param>
        /// <param name="stopPrice">Stop price.</param>
        /// <param name="stopLoss">Stop loss price.</param>
        /// <param name="takeProfit">Take profit price.</param>
        /// <param name="expiration">Expiration time, should be specified for pending orders.</param>
        /// <param name="comment">User defined comment for a new opening order. Null is interpreded as empty string.</param>
        /// <param name="tag">User defined tag for a new opening order. Null is interpreded as empty string.</param>
        /// <param name="magic">User defined magic number for a new opening order. Null is not defined.</param>
        /// <param name="timeoutInMilliseconds">Timeout of the synchronous operation.</param>
        /// <returns>A new trade record; can not be null.</returns>
        TradeRecord SendOrderEx(string operationId, string symbol, TradeCommand command, TradeRecordSide side, double volume, double? maxVisibleVolume, double? price, double? stopPrice, double? stopLoss, double? takeProfit, DateTime? expiration, string comment, string tag, int? magic, int timeoutInMilliseconds)
        {
#if LOG_PERFORMANCE
            ulong timestamp = Client.loggerIn_.GetTimestamp();
#endif
            var order = this.Client.DataTradeHandle.OpenNewOrder(operationId, symbol, command, side, volume, maxVisibleVolume, price, stopPrice, stopLoss, takeProfit, expiration, comment ?? string.Empty, tag ?? string.Empty, magic, timeoutInMilliseconds);
            TradeRecord tradeRecord = new TradeRecord(this.Client, order);

#if LOG_PERFORMANCE
            Client.loggerIn_.LogTimestamp(tradeRecord.ClientOrderId, timestamp, "NewOrder");
#endif
            return tradeRecord;
        }
Ejemplo n.º 6
0
        private static bool ParseCommand(string[] tokens)
        {
            try
            {
                if (tokens[0] == "market")
                {
                    TradeCommand command    = (TradeCommand)Enum.Parse(typeof(TradeCommand), tokens[1]);
                    string       instrument = tokens[2];
                    double       volume     = double.Parse(tokens[3]);

                    client.Trade.OpenOrder(instrument, command, 0, 0, 0, volume).ContinueWith(tradeResponseHandler);
                }
                else if (tokens[0] == "pending")
                {
                    TradeCommand command    = (TradeCommand)Enum.Parse(typeof(TradeCommand), tokens[1]);
                    string       instrument = tokens[2];
                    double       price      = double.Parse(tokens[3]);
                    double       volume     = double.Parse(tokens[4]);

                    client.Trade.OpenOrder(instrument, command, price, 0, 0, volume).ContinueWith(tradeResponseHandler);
                }
                else if (tokens[0] == "modify")
                {
                    int    orderId = int.Parse(tokens[1]);
                    double price   = double.Parse(tokens[2]);
                    double sl      = double.Parse(tokens[3]);

                    client.Trade.ModifyOrder(orderId, price, sl, 0, 0, new DateTime(1970, 1, 1)).ContinueWith(tradeResponseHandler);
                }
                else if (tokens[0] == "delete")
                {
                    int orderId = int.Parse(tokens[1]);

                    client.Trade.DeleteOrder(orderId).ContinueWith(tradeResponseHandler);
                }
                else if (tokens[0] == "close")
                {
                    int    orderId = int.Parse(tokens[1]);
                    double volume  = 100;
                    double.TryParse(tokens[2], out volume);

                    client.Trade.CloseOrder(orderId, volume).ContinueWith(tradeResponseHandler);
                }
                return(true);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                return(true);
            }
        }
Ejemplo n.º 7
0
        public long SELL(TradeCommand Command)
        {
            var formVariables = new List <string> {
                $"symbol={Command.Symbol}",
                "side=SELL",         // SELL, BUY
                "type=MARKET",       // LIMIT, MARKET, STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT, LIMIT_MAKER
                $"quantity={Math.Round(Command.Quantity, 4)}",
                ///$"price={Math.Round(Command.Price, 4)}",
                ///"timeInForce=GTC",
                "recvWindow=60000",
                $"timestamp={ToUnixTimeStamp(DateTime.UtcNow)}"
            };

            if (Command.OrderId > 0)
            {
                formVariables.Add($"newClientOrderId={Command.OrderId}");
            }

            // sign the request
            var signature = this.SignThis(SECRET_KEY, string.Join("&", formVariables)).signature;

            formVariables.Add($"signature={signature}");

            var response = this.HttpService.POST_DATA($"{SERVER}order", formVariables, headers: new Dictionary <string, string>
            {
                { "X-MBX-APIKEY", API_KEY },
                { "Content-Type", "application/x-www-form-urlencoded" }
            });

            var schema = new
            {
                orderId       = 0L,
                clientOrderId = "",
                transactTime  = 0L,
                status        = "",
                type          = "",
                side          = ""
            };

            if (!response.Success)
            {
                throw new Exception(response.Content);
            }

            var model = JsonConvert.DeserializeAnonymousType(response.Content, schema);

            return(model.orderId);
        }
Ejemplo n.º 8
0
        public FxOrder OpenNewOrder(string operationId, string symbol, TradeCommand command, TradeRecordSide side, double volume, double?maxVisibleVolume, double?price, double?stopPrice, double?stopLoss, double?takeProfit, DateTime?expiration, string comment, string tag, int?magic, int timeoutInMilliseconds)
        {
            if (operationId == null)
            {
                operationId = string.Empty;
            }

            this.VerifyInitialized();

            this.Validate(nameof(volume), volume);
            this.Validate(nameof(maxVisibleVolume), maxVisibleVolume);
            this.Validate(nameof(price), price);
            this.Validate(nameof(stopPrice), stopPrice);
            this.Validate(nameof(stopLoss), stopLoss);
            this.Validate(nameof(takeProfit), takeProfit);

            var order = new FxOrder(symbol, (int)command, side, volume, maxVisibleVolume, price, stopPrice, stopLoss, takeProfit, expiration, comment, tag, magic);

            return(Native.TradeServer.OpenNewOrder(this.handle, operationId, order, (uint)timeoutInMilliseconds));
        }
Ejemplo n.º 9
0
 public TradeTransRequestPacket(int requestId,
                                TradeCommand tradeCommand,
                                TransactionType transactionType, double price,
                                double stopLoss, double takeProfit,
                                string symbol, double volume, int order,
                                string comment, DateTime expiration)
     : base(APINetworkPacketType.TradeTransRequest)
 {
     RequestId       = requestId;
     TradeCommand    = tradeCommand;
     TransactionType = transactionType;
     Price           = price;
     StopLoss        = stopLoss;
     TakeProfit      = takeProfit;
     Symbol          = symbol;
     Volume          = volume;
     Order           = order;
     Comment         = comment;
     Expiration      = expiration;
 }
Ejemplo n.º 10
0
 public TradeTransRequestPacket(int requestId,
                 TradeCommand tradeCommand,
                 TransactionType transactionType, double price,
                 double stopLoss, double takeProfit,
                 string symbol, double volume, int order,
                 string comment, DateTime expiration)
     : base(APINetworkPacketType.TradeTransRequest)
 {
     RequestId = requestId;
     TradeCommand = tradeCommand;
     TransactionType = transactionType;
     Price = price;
     StopLoss = stopLoss;
     TakeProfit = takeProfit;
     Symbol = symbol;
     Volume = volume;
     Order = order;
     Comment = comment;
     Expiration = expiration;
 }
Ejemplo n.º 11
0
 public OTradePacket(TradeCommand Command, object Message)
 {
     this.Command = Command;
     this.Message = Message;
 }
Ejemplo n.º 12
0
 Task <TradeTransResponsePacket> ITradeProvider.OpenOrder(string symbol, TradeCommand tradeCommand,
                                                          double price, double stopLoss, double takeProfit, double volume)
 {
     return(((ITradeProvider)this).OpenOrder(symbol, tradeCommand, price, stopLoss, takeProfit, volume, string.Empty));
 }
Ejemplo n.º 13
0
 /// <summary>
 /// The method opens a new order.
 /// </summary>
 /// <param name="symbol">Trading currency pair symbol; can not be null.</param>
 /// <param name="command">Market, limit or stop.</param>
 /// <param name="side">Trade record side: buy or sell.</param>
 /// <param name="volume">Requsted volume.</param>
 /// <param name="maxVisibleVolume">Max visible volume.</param>
 /// <param name="price">Activating price for pending orders; price threshold for market orders.</param>
 /// <param name="stopPrice">Stop price.</param>
 /// <param name="stopLoss">Stop loss price.</param>
 /// <param name="takeProfit">Take profit price.</param>
 /// <param name="expiration">Expiration time, should be specified for pending orders.</param>
 /// <param name="comment">User defined comment for a new opening order. Null is interpreded as empty string.</param>
 /// <param name="tag">User defined tag for a new opening order. Null is interpreded as empty string.</param>
 /// <param name="magic">User defined magic number for a new opening order. Null is not defined.</param>
 /// <param name="timeoutInMilliseconds">Timeout of the synchronous operation.</param>
 /// <returns>A new trade record; can not be null.</returns>
 public TradeRecord SendOrderEx(string symbol, TradeCommand command, TradeRecordSide side, double volume, double? maxVisibleVolume, double? price, double? stopPrice, double? stopLoss, double? takeProfit, DateTime? expiration, string comment, string tag, int? magic, int timeoutInMilliseconds)
 {
     return this.SendOrderEx(null, symbol, command, side, volume, maxVisibleVolume, price, stopPrice, stopLoss, takeProfit, expiration, comment, tag, magic, timeoutInMilliseconds);
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Creates a new Outgoing Trade Packet with the SET_POKEMON Trade Command
 /// </summary>
 /// <param name="pokemonToTrade">The SeriPokemon that needs to be set (visible to the other player)</param>
 public OutgoingPacket(TradeCommand command, SeriPokemon pokemonToTrade)
 {
     Type            = OutgoingPacketType.TRADE;
     PacketContainer = new OTradePacket(command, pokemonToTrade);
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Creates a new empty Outgoing Trade Packet with the set TradeCommand
 /// </summary>
 /// <param name="tradeCommand"></param>
 public OutgoingPacket(TradeCommand tradeCommand)
 {
     Type            = OutgoingPacketType.TRADE;
     PacketContainer = new OTradePacket(tradeCommand, "");
 }
Ejemplo n.º 16
0
 public ArchiveTradeCommand(TradeCommand tradeCommand)
     : base(tradeCommand)
 {
 }
        private int UpdateItem(CommandManagementItem cmdMngItem, List <ModifySecurityItem> modifiedSecuItems, DateTime startDate, DateTime endDate, string notes)
        {
            //var oldInstance = _tradeInstanceBLL.GetInstance(cmdMngItem.InstanceId);
            //if (oldInstance == null || oldInstance.InstanceId != cmdMngItem.InstanceId)
            //{
            //    return -1;
            //}

            //TODO: add the StartDate, EndDate
            TradeCommand cmdItem = new TradeCommand
            {
                CommandId      = cmdMngItem.CommandId,
                ECommandStatus = Model.EnumType.CommandStatus.Modified,
                DStartDate     = startDate,
                DEndDate       = endDate,
                ModifiedDate   = DateTime.Now,
                Notes          = !string.IsNullOrEmpty(notes)?notes: cmdMngItem.Notes,
            };

            List <TradeCommandSecurity> tradeModifiedSecuItems = new List <TradeCommandSecurity>();
            List <TradeCommandSecurity> tradeCancelSecuItems   = new List <TradeCommandSecurity>();
            var selectedModifiedSecuItems = modifiedSecuItems.Where(p => p.Selection).ToList();

            foreach (var secuItem in selectedModifiedSecuItems)
            {
                TradeCommandSecurity tradeSecuItem = new TradeCommandSecurity
                {
                    CommandId     = cmdItem.CommandId,
                    SecuCode      = secuItem.SecuCode,
                    SecuType      = secuItem.SecuType,
                    EDirection    = secuItem.EDirection,
                    CommandAmount = secuItem.NewCommandAmount,
                    CommandPrice  = secuItem.NewCommandPrice,
                    CurrentPrice  = secuItem.LastPrice,
                };

                if (secuItem.Selection)
                {
                    tradeModifiedSecuItems.Add(tradeSecuItem);
                }
                else
                {
                    tradeCancelSecuItems.Add(tradeSecuItem);
                }
            }

            int result = _tradeCommandBLL.Update(cmdItem, tradeModifiedSecuItems, tradeCancelSecuItems);

            if (result > 0)
            {
                //TODO: add more parameters
                TradeInstance tradeInstance = new TradeInstance
                {
                    InstanceId      = cmdMngItem.InstanceId,
                    InstanceCode    = cmdMngItem.InstanceCode,
                    FuturesContract = cmdMngItem.BearContract,
                    //MonitorUnitId = oldInstance.MonitorUnitId,
                    //StockDirection = oldInstance.StockDirection,
                    //FuturesDirection = oldInstance.FuturesDirection,
                    //FuturesPriceType = oldInstance.FuturesPriceType,
                };

                List <TradeInstanceSecurity> modifiedInstSecuItems = new List <TradeInstanceSecurity>();
                List <TradeInstanceSecurity> cancelInstSecuItems   = new List <TradeInstanceSecurity>();
                foreach (var secuItem in selectedModifiedSecuItems)
                {
                    int modifiedAmount = secuItem.NewCommandAmount - secuItem.OriginCommandAmount;

                    TradeInstanceSecurity tradeInstSecuItem = new TradeInstanceSecurity
                    {
                        SecuCode           = secuItem.SecuCode,
                        SecuType           = secuItem.SecuType,
                        InstructionPreBuy  = 0,
                        InstructionPreSell = 0,
                    };

                    //TODO::::::how to handle the case???
                    switch (secuItem.EDirection)
                    {
                    case Model.EnumType.EntrustDirection.BuySpot:
                    {
                        tradeInstSecuItem.InstructionPreBuy = modifiedAmount;
                    }
                    break;

                    case Model.EnumType.EntrustDirection.SellSpot:
                    {
                        tradeInstSecuItem.InstructionPreSell = modifiedAmount;
                    }
                    break;

                    case Model.EnumType.EntrustDirection.SellOpen:
                    {
                        tradeInstSecuItem.InstructionPreSell = modifiedAmount;
                    }
                    break;

                    case Model.EnumType.EntrustDirection.BuyClose:
                    {
                        tradeInstSecuItem.InstructionPreBuy = modifiedAmount;
                    }
                    break;
                    }

                    if (secuItem.Selection)
                    {
                        modifiedInstSecuItems.Add(tradeInstSecuItem);
                    }
                    else
                    {
                        cancelInstSecuItems.Add(tradeInstSecuItem);
                    }
                }

                result = _tradeInstanceBLL.Update(tradeInstance, modifiedInstSecuItems, cancelInstSecuItems);
            }

            return(result);
        }
Ejemplo n.º 18
0
 /// <summary>
 /// The method opens a new order.
 /// </summary>
 /// <param name="operationId">
 /// Can be null, in this case FDK generates a new unique operation ID automatically.
 /// Otherwise, please use GenerateOperationId method of DataClient object.
 /// </param>
 /// <param name="symbol">Trading currency pair symbol; can not be null.</param>
 /// <param name="command">Market, limit or stop.</param>
 /// <param name="side">Trade record side: buy or sell.</param>
 /// <param name="volume">Requsted volume.</param>
 /// <param name="maxVisibleVolume">Max visible volume.</param>
 /// <param name="price">Activating price for pending orders; price threshold for market orders.</param>
 /// <param name="stopPrice">Stop price.</param>
 /// <param name="stopLoss">Stop loss price.</param>
 /// <param name="takeProfit">Take profit price.</param>
 /// <param name="expiration">Expiration time, should be specified for pending orders.</param>
 /// <param name="comment">User defined comment for a new opening order. Null is interpreded as empty string.</param>
 /// <param name="tag">User defined tag for a new opening order. Null is interpreded as empty string.</param>
 /// <param name="magic">User defined magic number for a new opening order. Null is not defined.</param>
 /// <returns>A new trade record; can not be null.</returns>
 public TradeRecord SendOrderEx(string operationId, string symbol, TradeCommand command, TradeRecordSide side, double volume, double? maxVisibleVolume, double? price, double? stopPrice, double? stopLoss, double? takeProfit, DateTime? expiration, string comment, string tag, int? magic)
 {
     return this.SendOrderEx(operationId, symbol, command, side, volume, maxVisibleVolume, price, stopPrice, stopLoss, takeProfit, expiration, comment, tag, magic, this.Client.SynchOperationTimeout);
 }
Ejemplo n.º 19
0
 static void ConvertCmdToCommandAndSide(int cmd, out TradeCommand command, out TradeRecordSide side)
 {
     if (cmd == OP_BUY)
     {
         command = TradeCommand.Market;
         side = TradeRecordSide.Buy;
     }
     else if (cmd == OP_SELL)
     {
         command = TradeCommand.Market;
         side = TradeRecordSide.Sell;
     }
     else if (cmd == OP_BUYLIMIT)
     {
         command = TradeCommand.Limit;
         side = TradeRecordSide.Buy;
     }
     else if (cmd == OP_SELLLIMIT)
     {
         command = TradeCommand.Limit;
         side = TradeRecordSide.Sell;
     }
     else if (cmd == OP_BUYSTOP)
     {
         command = TradeCommand.Stop;
         side = TradeRecordSide.Buy;
     }
     else if (cmd == OP_SELLSTOP)
     {
         command = TradeCommand.Stop;
         side = TradeRecordSide.Sell;
     }
     else
         throw new ArgumentOutOfRangeException("cmd", cmd, "Expected: OP_BUY, OP_SELL, OP_BUYLIMIT, OP_SELLLIMIT, OP_BUYSTOP or OP_SELLSTOP");
 }