// Портфели /// <summary> /// взять портфели /// </summary> public async void GetPortfolios() { // string tags = "AccountType,NetLiquidation"; // reqAccountSummary(50000001, "All", tags); if (_isConnected == false) { return; } try { List <AccountProperties> result = await Rest20.GetAccountListAsync(); // в result что-то лежит foreach (var accountName in result) { Account account = await Rest20.GetAccountDetailsAsync(accountName.id); Portfolio newPortfolio = new Portfolio(); newPortfolio.Number = account.id; newPortfolio.ValueBegin = Convert.ToDecimal(account.balance); newPortfolio.ValueCurrent = Convert.ToDecimal(account.balance); if (PortfolioChangeEvent != null) { PortfolioChangeEvent(newPortfolio); } } } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); } }
static private async Task PutOnATrade() { WriteNewLine("Checking to see if EUR_USD is open for trading ..."); // first, check the market status for EUR_USD // if it is tradeable, we'll try to make some money :) if (!(await Utilities.IsMarketHalted(INSTRUMENT))) { WriteNewLine("EUR_USD is open and rockin', so let's start trading!"); long?tradeID = await PlaceMarketOrder(); if (tradeID.HasValue) { // we have an open trade. // give it some time to make money :) await Task.Delay(10000); WriteNewLine("Okay, we've waited 10 seconds. Closing trade now ..."); // now, let' close the trade and collect our profits! .. hopefully TradeCloseResponse closeResponse = null; try { closeResponse = await Rest20.CloseTradeAsync(AccountID, tradeID.Value, "ALL"); } catch { WriteNewLine("Oops. The trade can't be closed. Something went wrong. :("); } if (closeResponse != null) { WriteNewLine("Nice! The trade is closed."); var profit = closeResponse.orderFillTransaction.pl; WriteNewLine($"Our profit was USD {profit}"); if (profit > 0) { WriteNewLine($"Nice work! You are an awesome trader."); } else { WriteNewLine($"Looks like you need to learn some money-making strategies. :("); WriteNewLine($"Keep studying, learning, but most of all .. keep trading!!"); } } } else { WriteNewLine($"Looks like something went awry with the trade. you need to learn some money-making strategies. :("); } } else { WriteNewLine("Sorry, Oanda markets are closed or Euro market is not tradeable."); WriteNewLine("Try again another time."); } }
/// <summary> /// execute orders in the exchange /// исполнить ордер на бирже /// </summary> public async void ExecuteOrder(Order order) { if (_isConnected == false) { return; } _orders.Add(order); try { string expiry = ConvertDateTimeToAcceptDateFormat(DateTime.Now.AddMonths(1)); decimal volume = order.Volume; if (order.Side == Side.Sell) { volume = -order.Volume; } string price = order.Price.ToString(new CultureInfo("en-US")); Instrument myInstrument = _allInstruments.Find(inst => inst.name == order.SecurityNameCode); // create new pending order var request = new LimitOrderRequest(myInstrument) { instrument = order.SecurityNameCode, units = Convert.ToInt64(volume), timeInForce = TimeInForce.GoodUntilDate, gtdTime = expiry, price = price.ToDecimal(), clientExtensions = new ClientExtensions() { id = order.NumberUser.ToString(), comment = "", tag = "" }, tradeClientExtensions = new ClientExtensions() { id = order.NumberUser.ToString(), comment = "", tag = "" } }; var response = await Rest20.PostOrderAsync(Credentials.GetDefaultCredentials().DefaultAccountId, request); var orderTransaction = response.orderCreateTransaction; if (orderTransaction.id > 0) { order.NumberMarket = orderTransaction.id.ToString(); } } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); } }
private async Task <List <Price> > GetLastPrice(string accountId, string instrument) { SetCredentials(accountId); List <Price> prices = await Rest20.GetPriceListAsync(accountId, new List <string>() { instrument }, new Dictionary <string, string>()); return(prices); }
/// <summary> /// отозвать ордер /// </summary> public void CanselOrder(Order order) { if (string.IsNullOrWhiteSpace(order.NumberMarket)) { return; } if (string.IsNullOrEmpty(order.NumberMarket)) { return; } try { var openOrders = Rest20.GetPendingOrderListAsync(Credentials.GetDefaultCredentials().DefaultAccountId); while (!openOrders.IsCanceled && !openOrders.IsCompleted && !openOrders.IsFaulted) { Thread.Sleep(20); } for (int i = 0; i < openOrders.Result.Count; i++) { if (openOrders.Result[i].id == Convert.ToInt64(order.NumberMarket)) { Rest20.CancelOrderAsync(Credentials.GetDefaultCredentials().DefaultAccountId, openOrders.Result[i].id); } } } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); } }
static async Task <long?> PlaceMarketOrder(string side = "buy") { WriteNewLine("Creating a EUR_USD market BUY order ..."); var oandaInstrument = (await Rest20.GetAccountInstrumentsAsync(AccountID, INSTRUMENT)).First(); long orderUnits = side == "buy" ? 10 : -10; var request = new MarketOrderRequest(oandaInstrument) { units = orderUnits }; OrderPostResponse response = null; try { response = await Rest20.PostOrderAsync(AccountID, request); WriteNewLine("Congrats! You've put on a trade! Let it run! :)"); } catch { WriteNewLine("Oops. Order creation failed."); } return(response?.orderFillTransaction?.tradeOpened?.tradeID); }
public async Task <List <ITransaction> > GetTransactions(string accountId, DateTime from) { Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("from", GetOandaDateTime(from)); List <ITransaction> transactions = await Rest20.GetTransactionsByDateRangeAsync(accountId, parameters); return(transactions); }
public async Task <long> CreateMarketOrder(string accountId, string instrument, long units) { MarketOrderRequest request = new MarketOrderRequest() { instrument = instrument, units = units, }; OrderPostResponse response = await Rest20.PostOrderAsync(accountId, request); return(response.orderFillTransaction.id); }
// instruments // инструменты public async void GetSecurities(List <Portfolio> portfolios) { if (portfolios == null || portfolios.Count == 0) { return; } _allInstruments = new List <Instrument>(); // Get an instrument list (basic) for (int i = 0; i < portfolios.Count; i++) { List <Instrument> result = await Rest20.GetAccountInstrumentsAsync(portfolios[i].Number); _allInstruments.AddRange(result); } List <Security> _securities = new List <Security>(); for (int i = 0; i < _allInstruments.Count; i++) { Security newSecurity = new Security(); newSecurity.Name = _allInstruments[i].name; newSecurity.NameFull = _allInstruments[i].displayName; newSecurity.NameClass = _allInstruments[i].type; newSecurity.SecurityType = SecurityType.CurrencyPair; newSecurity.NameId = "none"; newSecurity.Lot = 1; decimal step = 1; for (int i2 = 0; i2 < _allInstruments[i].displayPrecision; i2++) { step *= 0.1m; } newSecurity.PriceStep = step; newSecurity.PriceStepCost = step; _securities.Add(newSecurity); } if (NewSecurityEvent != null) { NewSecurityEvent(_securities); } }
// инструменты public async void GetSecurities(List <Portfolio> portfolios) { if (portfolios == null || portfolios.Count == 0) { SendLogMessage("Прервана попытка получить инструменты раньше авторизации аккаунта", LogMessageType.System); return; } _allInstruments = new List <Instrument>(); // Get an instrument list (basic) for (int i = 0; i < portfolios.Count; i++) { List <Instrument> result = await Rest20.GetAccountInstrumentsAsync(portfolios[i].Number); _allInstruments.AddRange(result); } List <Security> _securities = new List <Security>(); for (int i = 0; i < _allInstruments.Count; i++) { Security newSecurity = new Security(); newSecurity.Name = _allInstruments[i].name; newSecurity.NameFull = _allInstruments[i].displayName; newSecurity.NameClass = _allInstruments[i].type; newSecurity.Lot = 1; decimal step = 1; for (int i2 = 0; i2 < _allInstruments[i].displayPrecision; i2++) { step *= 0.1m; } newSecurity.PriceStep = step; newSecurity.PriceStepCost = step; _securities.Add(newSecurity); } if (NewSecurityEvent != null) { NewSecurityEvent(_securities); } }
/// <summary> /// Determines if trading is halted for the provided instrument. /// </summary> /// <param name="instrument">Instrument to check if halted. Default is EUR_USD.</param> /// <returns>True if trading is halted, false if trading is not halted.</returns> public static async Task <bool> IsMarketHalted(string instrument = InstrumentName.Currency.EURUSD) { var accountId = Credentials.GetDefaultCredentials().DefaultAccountId; var prices = await Rest20.GetPriceListAsync(accountId, new List <string>() { instrument }); bool isTradeable = false, hasBids = false, hasAsks = false; if (prices[0] != null) { isTradeable = prices[0].tradeable; hasBids = prices[0].bids.Count > 0; hasAsks = prices[0].asks.Count > 0; } return(!(isTradeable && hasBids && hasAsks)); }
public async Task <TradeCloseResponse> CloseOrder(String accountId, long orderId) { SetCredentials(accountId); try { TradeCloseResponse tradeCloseResponse = await Rest20.CloseTradeAsync(accountId, orderId); return(tradeCloseResponse); } catch (Exception e) { if (e.Message.IndexOf("MARKET_ORDER_REJECT") > 0 && e.Message.IndexOf("TRADE_DOESNT_EXIST") > 0) { return(null); } throw e; } }
public OAOrders GetMarketOrders(string accountId, string instrument) { Task <List <Trade> > callTask = Task.Run(() => Rest20.GetOpenTradeListAsync(accountId)); callTask.Wait(); OAOrders oaOrders = new OAOrders(); foreach (Trade trade in callTask.Result.FindAll(x => x.instrument == instrument)) { OAOrder oaOrder = new OAOrder(); oaOrder.Id = trade.id; oaOrder.Units = trade.currentUnits; oaOrder.Instrument = trade.instrument; oaOrder.Price = trade.price; oaOrders.Add(oaOrder); } return(oaOrders); }
public async Task ModifyMarketOrder(string accountId, OAOrder order) { SetCredentials(accountId); PriceInformation priceInformation = new PriceInformation(); priceInformation.instrument = await GetInstrument(accountId, order.Instrument); priceInformation.priceProperties = new List <string>(); PatchExitOrdersRequest request = new PatchExitOrdersRequest(); request.stopLoss = new StopLossDetails(instruments[0]); request.stopLoss.price = Math.Round(order.SL, priceInformation.instrument.displayPrecision); request.stopLoss.timeInForce = TimeInForce.GoodUntilCancelled; if (order.PT > 1) // != 0, kvuli zaokrouhlovani { request.takeProfit = new TakeProfitDetails(instruments[0]); request.takeProfit.price = Math.Round(order.PT, priceInformation.instrument.displayPrecision); request.takeProfit.timeInForce = TimeInForce.GoodUntilCancelled; } else { request.takeProfit = null; } try { TradePatchExitOrdersResponse tradePatchExitOrdersResponse = await Rest20.PatchTradeExitOrders(accountId, order.Id, request); } catch (Exception e) { if (e.Message.IndexOf("NO_SUCH_TRADE") > 0) { return; } throw e; } }
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); }
protected override async Task <WebResponse> GetSession() { return(await Rest20.StartTransactionsSession(_accountId)); }
public async Task <List <Instrument> > GetInstrumentEx(string accountId) { List <Instrument> result = await Rest20.GetAccountInstrumentsAsync(accountId); return(result); }
public async Task <Trade> GetMarketOrder(string accountId, long orderId) { Trade trade = await Rest20.GetTradeDetailsAsync(accountId, orderId); return(trade); }
/// <summary> /// Начать выгрузку данных по инструменту. /// </summary> /// <param name="namePaper">имя бумаги которую будем запускать</param> /// <param name="timeFrameBuilder">объект несущий </param> /// <returns>В случае удачи возвращает CandleSeries /// в случае неудачи null</returns> public CandleSeries StartThisSecurity(string namePaper, TimeFrameBuilder timeFrameBuilder) { try { if (_lastStartServerTime.AddSeconds(15) > DateTime.Now) { return(null); } lock (_lockerStarter) { if (namePaper == "") { return(null); } // надо запустить сервер если он ещё отключен if (ServerStatus != ServerConnectStatus.Connect) { //MessageBox.Show("Сервер не запущен. Скачивание данных прервано. Инструмент: " + namePaper); return(null); } if (_securities == null || _portfolios == null) { Thread.Sleep(5000); return(null); } if (_lastStartServerTime != DateTime.MinValue && _lastStartServerTime.AddSeconds(15) > DateTime.Now) { return(null); } Security security = null; for (int i = 0; _securities != null && i < _securities.Count; i++) { if (_securities[i].Name == namePaper) { security = _securities[i]; break; } } if (security == null) { return(null); } if (_connectedContracts == null) { _connectedContracts = new List <string>(); } if (_connectedContracts.Find(s => s == security.Name) == null) { _connectedContracts.Add(security.Name); } _tickStorage.SetSecurityToSave(security); // 2 создаём серию свечек CandleSeries series = new CandleSeries(timeFrameBuilder, security); if (NeadToGetCandles(timeFrameBuilder.TimeFrame)) { // подгружаем в серию свечки, если коннектор это позволяет short count = 500; string price = "MBA"; string instrument = security.Name; string granularity = GetTimeFrameInOandaFormat(timeFrameBuilder.TimeFrame).ToString(); var parameters = new Dictionary <string, string>(); parameters.Add("price", price); parameters.Add("granularity", granularity); parameters.Add("count", count.ToString()); Task <List <CandlestickPlus> > result = Rest20.GetCandlesAsync(instrument, parameters); while (!result.IsCanceled && !result.IsCompleted && !result.IsFaulted) { Thread.Sleep(10); } List <CandlestickPlus> candleOanda = result.Result; List <Candle> candlesOsEngine = new List <Candle>(); for (int i = 0; i < candleOanda.Count; i++) { Candle newCandle = new Candle(); newCandle.Open = Convert.ToDecimal(candleOanda[i].bid.o); newCandle.High = Convert.ToDecimal(candleOanda[i].bid.h); newCandle.Low = Convert.ToDecimal(candleOanda[i].bid.l); newCandle.Close = Convert.ToDecimal(candleOanda[i].bid.c); newCandle.TimeStart = DateTime.Parse(candleOanda[i].time); newCandle.State = CandleStates.Finished; newCandle.Volume = candleOanda[i].volume; candlesOsEngine.Add(newCandle); } series.CandlesAll = candlesOsEngine; } _candleManager.StartSeries(series); SendLogMessage("Инструмент " + series.Security.Name + "ТаймФрейм " + series.TimeFrame + " успешно подключен на получение данных и прослушивание свечек", LogMessageType.System); return(series); } } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); return(null); } }
protected override async Task <WebResponse> GetSession() { return(await Rest20.StartPricingSession(_accountId, _instruments, _snapshot)); }
private void CandleGeterThread() { while (true) { Thread.Sleep(1000); if (_depthsDontGo == false) { return; } try { for (int i = 0; i < _namesSecuritiesToGetTicks.Count; i++) { short count = 1; string price = "MBA"; string instrument = _namesSecuritiesToGetTicks[i].Name; string granularity = GetTimeFrameInOandaFormat(TimeFrame.Min1).ToString(); var parameters = new Dictionary <string, string>(); parameters.Add("price", price); parameters.Add("granularity", granularity); parameters.Add("count", count.ToString()); Task <List <CandlestickPlus> > result = Rest20.GetCandlesAsync(instrument, parameters); while (!result.IsCanceled && !result.IsCompleted && !result.IsFaulted) { Thread.Sleep(10); } List <CandlestickPlus> candleOanda = result.Result; Trade newCandle = new Trade(); newCandle.Price = Convert.ToDecimal(candleOanda[0].bid.c); newCandle.Time = DateTime.Parse(candleOanda[0].time); newCandle.SecurityNameCode = _namesSecuritiesToGetTicks[i].Name; newCandle.Volume = candleOanda[0].volume; newCandle.Side = Side.Buy; if (NewTradesEvent != null) { NewTradesEvent(newCandle); } MarketDepth depth = new MarketDepth(); depth.SecurityNameCode = newCandle.SecurityNameCode; depth.Time = newCandle.Time; depth.Asks = new List <MarketDepthLevel>() { new MarketDepthLevel() { Ask = 1, Price = newCandle.Price + _namesSecuritiesToGetTicks[i].PriceStep } }; depth.Bids = new List <MarketDepthLevel>() { new MarketDepthLevel() { Bid = 1, Price = newCandle.Price - _namesSecuritiesToGetTicks[i].PriceStep } }; if (MarketDepthEvent != null) { MarketDepthEvent(depth); } } } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); Thread.Sleep(1000); } } }