Exemplo n.º 1
0
 static void TestActiveOrders()
 {
     var api = new TradeApi(key, secret);
     var res = api.ActiveOrders().Result;
     //            Console.WriteLine(res.Return.ActiveOrders["184"].CurrencyPair);
     //            Console.WriteLine(res.Return.TokenActiveOrders["184"].CurrencyPair);
 }
Exemplo n.º 2
0
        public void Initialize()
        {
            _api             = new TradeApi(_brokerID, _frontAddr);
            _api.OnRspError += new TradeApi.RspError((ref CThostFtdcRspInfoField pRspInfo, int nRequestID, byte bIsLast) =>
            {
                Console.WriteLine("ErrorID: {0}, ErrorMsg: {1}", pRspInfo.ErrorID, pRspInfo.ErrorMsg);
            });
            _api.OnFrontConnect += new TradeApi.FrontConnect(() =>
            {
                _isConnected = true;
                _api.UserLogin(-3, _investorID, _password);
            });
            _api.OnRspUserLogin += new TradeApi.RspUserLogin((ref CThostFtdcRspUserLoginField pRspUserLogin,
                                                              ref CThostFtdcRspInfoField pRspInfo, int nRequestID, byte bIsLast) =>
            {
                _isLogin = true;
                _api.SettlementInfoConfirm(-4);
            });
            _api.OnDisconnected += new TradeApi.Disconnected((int nReasion) =>
            {
                _isConnected = false;
            });
            _api.OnRspUserLogout += new TradeApi.RspUserLogout((ref CThostFtdcUserLogoutField pUserLogout,
                                                                ref CThostFtdcRspInfoField pRspInfo, int nRequestID, byte bIsLast) =>
            {
                _isLogin = false;
                _api.Disconnect();
            });

            _api.Connect();
            Thread.Sleep(200);
        }
Exemplo n.º 3
0
        static void TestTradeApi()
        {
            var api = new TradeApi(key, secret);
            var res = api.Getinfo().Result;

            Console.WriteLine(res.Return.Funds[CurrenciesEnum.jpy]);
        }
Exemplo n.º 4
0
        public bool Init()
        {
            _tradeApi = new TradeApi();
            InitReport tradeReport;

            return(_tradeApi.Init(out tradeReport));
        }
Exemplo n.º 5
0
        static void GetPersonalInfo()
        {
            var api = new TradeApi(key, secret);
            var res = api.GetPersonalInfo().Result;

            Console.WriteLine(res.Return.IconPath);
        }
Exemplo n.º 6
0
        public TraderApiWrapper()
        {
            m_Api = new TradeApi();

            m_Api.OnConnect    = OnConnect_callback;
            m_Api.OnDisconnect = OnDisconnect_callback;
            m_Api.OnRspError   = OnRspError_callback;

            m_Api.OnErrRtnOrderAction              = OnErrRtnOrderAction_callback;
            m_Api.OnErrRtnOrderInsert              = OnErrRtnOrderInsert_callback;
            m_Api.OnRspOrderAction                 = OnRspOrderAction_callback;
            m_Api.OnRspOrderInsert                 = OnRspOrderInsert_callback;
            m_Api.OnRspQryDepthMarketData          = OnRspQryDepthMarketData_callback;
            m_Api.OnRspQryInstrument               = OnRspQryInstrument_callback;
            m_Api.OnRspQryInstrumentCommissionRate = OnRspQryInstrumentCommissionRate_callback;
            m_Api.OnRspQryInstrumentMarginRate     = OnRspQryInstrumentMarginRate_callback;
            m_Api.OnRspQryInvestorPosition         = OnRspQryInvestorPosition_callback;
            m_Api.OnRspQryInvestorPositionDetail   = OnRspQryInvestorPositionDetail_callback;
            m_Api.OnRspQryOrder          = OnRspQryOrder_callback;
            m_Api.OnRspQryTrade          = OnRspQryTrade_callback;
            m_Api.OnRspQryTradingAccount = OnRspQryTradingAccount_callback;
            m_Api.OnRtnInstrumentStatus  = OnRtnInstrumentStatus_callback;
            m_Api.OnRtnOrder             = OnRtnOrder_callback;
            m_Api.OnRtnTrade             = OnRtnTrade_callback;

            m_Api.CTP_RegTD();
        }
        public HaasonlineClient(string ip, int port, string privateKey)
        {
            MarketDataApi  = new MarketDataApi($"http://{ip}:{port}", privateKey);
            AccountDataApi = new AccountDataApi($"http://{ip}:{port}", privateKey);
            TradeApi       = new TradeApi($"http://{ip}:{port}", privateKey);

            TradeBotApi  = new TradeBotApi($"http://{ip}:{port}", privateKey);
            CustomBotApi = new CustomBotApi($"http://{ip}:{port}", privateKey);
        }
Exemplo n.º 8
0
        public void WithdrawAsync_should_throw_ArgumentException_if_parameters_include_opt_fee_when_currency_is_not_btc_or_mona_1()
        {
            //arrange
            var obj = new TradeApi(TestHelper.CreateApiClientWithMockHttpAccessor());

            //act
            var actual = Record.ExceptionAsync(async() => await obj.WithdrawAsync("xem", "test", 0, null, optFee: 1));

            //assert
            Assert.IsType <ArgumentException>(actual.Result);
        }
Exemplo n.º 9
0
        public void Construtcor_should_return_instance_1(string apiKey, string apiSecret)
        {
            //arrange

            //act
            var obj = new TradeApi(apiKey, apiSecret);

            //assert
            Assert.NotNull(obj);
            Assert.IsType <TradeApi>(obj);
        }
Exemplo n.º 10
0
        public void Construtcor_should_return_instance_2(ApiClientOption option)
        {
            //arrange

            //act
            var obj = new TradeApi(option);

            //assert
            Assert.NotNull(obj);
            Assert.IsType <TradeApi>(obj);
        }
Exemplo n.º 11
0
        public async void CancelOrderAsync_should_success(string jsonString, int orderId, string currencyPair, bool?isToken)
        {
            //arrange
            var response = TestHelper.CreateJsonResponse(jsonString);

            var obj = new TradeApi(TestHelper.CreateApiClientWithMockHttpAccessor(response));

            //act
            var actual = await obj.CancelOrderAsync(orderId, currencyPair, isToken);

            //assert
            Assert.NotNull(actual);
            Assert.IsAssignableFrom <CancelOrderResponse>(actual);
        }
Exemplo n.º 12
0
        static void TestDepositHistory()
        {
            var api = new TradeApi(key, secret);
            var res = api.DepositHistory(new Dictionary <string, string>()
            {
                { "currency", "jpy" }
            }).Result;

            foreach (var item in res.Return)
            {
                Console.WriteLine(item.Key);
                Console.WriteLine(item.Value.Amount);
            }
        }
Exemplo n.º 13
0
        public async void ActiveOrdersAsync_should_success(string jsonString, string currencyPair, bool?isToken)
        {
            //arrange
            var response = TestHelper.CreateJsonResponse(jsonString);

            var obj = new TradeApi(TestHelper.CreateApiClientWithMockHttpAccessor(response));

            //act
            var actual = await obj.ActiveOrdersAsync(currencyPair, isToken);

            //assert
            Assert.NotNull(actual);
            Assert.IsAssignableFrom <IDictionary <int, ActiveOrdersResponse> >(actual);
        }
Exemplo n.º 14
0
        public async void GetIdInfoAsync_should_success(string jsonString)
        {
            //arrange
            var response = TestHelper.CreateJsonResponse(jsonString);

            var obj = new TradeApi(TestHelper.CreateApiClientWithMockHttpAccessor(response));

            //act
            var actual = await obj.GetIdInfoAsync();

            //assert
            Assert.NotNull(actual);
            Assert.IsAssignableFrom <GetIdInfoResponse>(actual);
        }
Exemplo n.º 15
0
        public async void TradeHistoryAsync_should_success(string jsonString, int?from, int?count,
                                                           int?fromId, int?endId, string order, long?since, long?end, string currencyPair, bool?isToken)
        {
            //arrange
            var response = TestHelper.CreateJsonResponse(jsonString);

            var obj = new TradeApi(TestHelper.CreateApiClientWithMockHttpAccessor(response));

            //act
            var actual = await obj.TradeHistoryAsync(from, count, fromId, endId, order, since, end, currencyPair, isToken);

            //assert
            Assert.NotNull(actual);
            Assert.IsAssignableFrom <IDictionary <int, TradeHistoryResponse> >(actual);
        }
Exemplo n.º 16
0
        public async void TradeAsync_should_success(string jsonString, string currencyPair, string action,
                                                    decimal price, decimal amount, decimal?limit, string comment)
        {
            //arrange
            var response = TestHelper.CreateJsonResponse(jsonString);

            var obj = new TradeApi(TestHelper.CreateApiClientWithMockHttpAccessor(response));

            //act
            var actual = await obj.TradeAsync(currencyPair, action, price, amount, limit, comment);

            //assert
            Assert.NotNull(actual);
            Assert.IsAssignableFrom <TradeResponse>(actual);
        }
Exemplo n.º 17
0
        public async void WithdrawAsync_should_success(string jsonString, string currency, string address,
                                                       decimal amount, string message, decimal?optFee)
        {
            //arrange
            var response = TestHelper.CreateJsonResponse(jsonString);

            var obj = new TradeApi(TestHelper.CreateApiClientWithMockHttpAccessor(response));

            //act
            var actual = await obj.WithdrawAsync(currency, address, amount, message, optFee);

            //assert
            Assert.NotNull(actual);
            Assert.IsAssignableFrom <WithdrawResponse>(actual);
        }
Exemplo n.º 18
0
        public void ActiveOrdersAsync_should_throw_NotSupportedException_if_parameters_include_is_token_both()
        {
            //arrange
            var obj        = new TradeApi(TestHelper.CreateApiClientWithMockHttpAccessor());
            var parameters = new Dictionary <string, string>
            {
                { "is_token_both", "true" }
            };

            //act
            var actual = Record.ExceptionAsync(async() => await obj.ActiveOrdersAsync(parameters));

            //assert
            Assert.IsType <NotSupportedException>(actual.Result);
        }
Exemplo n.º 19
0
        public void WithdrawAsync_should_throw_ArgumentException_if_parameters_include_opt_fee_when_currency_is_not_btc_or_mona_2()
        {
            //arrange
            var obj        = new TradeApi(TestHelper.CreateApiClientWithMockHttpAccessor());
            var parameters = new Dictionary <string, string>
            {
                { "currency", "xem" },
                { "address", "test" },
                { "amount", "0" },
                { "opt_fee", "1" }
            };

            //act
            var actual = Record.ExceptionAsync(async() => await obj.WithdrawAsync(parameters));

            //assert
            Assert.IsType <ArgumentException>(actual.Result);
        }
Exemplo n.º 20
0
        /// <summary>
        /// OandaApiConnection constuctor
        /// Sets up the configuration and the datetime format
        /// </summary>
        /// <param name="connectionType">Type of the connection</param>
        /// <param name="accessToken">Access token for the connection</param>
        /// <param name="dateTimeFormat">Date time format to use for the connection</param>
        public OandaApiConnection(OandaConnectionType connectionType, string accessToken, DateTimeFormat dateTimeFormat = DateTimeFormat.RFC3339)
        {
            // Init configuration
            Configuration = new Configuration()
            {
                UserAgent   = $"OandaDotnetSdk/{Assembly.GetExecutingAssembly().GetName().Version}",
                BasePath    = connectionType.ToBasePath(),
                AccessToken = accessToken
            };

            // Init date time format
            DateTimeFormat = dateTimeFormat;

            // Init actual Oanda API connections from the GeriRemenyi.Oanda.V20.Client
            AccountApi     = new AccountApi(Configuration);
            InstrumentApi  = new InstrumentApi(Configuration);
            OrderApi       = new OrderApi(Configuration);
            TradeApi       = new TradeApi(Configuration);
            PositionApi    = new PositionApi(Configuration);
            TransactionApi = new TransactionApi(Configuration);
            PricingApi     = new PricingApi(Configuration);

            // Init object caches
            _accountsCache   = new Dictionary <string, IAccount>();
            _instrumentCache = new Dictionary <InstrumentName, IInstrument>();

            // Fire a really small request synchronously to check that the inited connection is OK
            // Also fill the available accounts based on this
            try
            {
                Accounts = AccountApi.GetAccounts().Accounts;
            }
            catch
            {
                throw new ConnectionInitializationException($"Unable to connect to {Configuration.BasePath} with the given token");
            }
        }
Exemplo n.º 21
0
 public CtpTrade()
 {
     //释放接口的C++相关文件
     _t = new TradeApi("libCtpTrade");
     SetCallBack();
 }
Exemplo n.º 22
0
 public static void Init()
 {
     dapi = TQuantApi.CreateDataApi("ipc://tqc_10001");
     tapi = TQuantApi.CreateTradeApi("ipc://tqc_10001");
 }
Exemplo n.º 23
0
 public void Init()
 {
     instance = new TradeApi();
 }
 public TradeApiTests()
 {
     instance = new TradeApi();
 }
Exemplo n.º 25
0
        static void TestTradeApi(TradeApi tapi)
        {
            tapi.OnAccountStatus += OnAccountStatus;
            tapi.OnOrderStatus   += OnOrderStatus;
            tapi.OnOrderTrade    += OnOrderTrade;

            {
                var r = tapi.QueryAccountStatus();
                if (r.Value != null)
                {
                    foreach (var act in r.Value)
                    {
                        Console.WriteLine("account: " + act.AccountId + ","
                                          + act.Broker + "," + act.AccountId + "," + act.AccountType);
                    }
                }
                else
                {
                    Console.WriteLine("QueryAccountStatus error: " + r.Msg);
                }
            }

            {
                var r = tapi.QueryBalance("glsc");
                if (r.Value != null)
                {
                    var bal = r.Value;
                    Console.WriteLine("balance: "
                                      + bal.InitBalance + ","
                                      + bal.EnableBalance + ","
                                      + bal.Margin + ","
                                      + bal.FloatPnl + ","
                                      + bal.ClosePnl
                                      );
                }
                else
                {
                    Console.WriteLine("QueryBalance error: " + r.Msg);
                }
            }
            {
                var r = tapi.QueryPositions("glsc");
                if (r.Value != null)
                {
                    foreach (var pos in r.Value)
                    {
                        Console.WriteLine("position: "
                                          + pos.Code + ","
                                          + pos.Name + ","
                                          + pos.Side + ","
                                          + pos.InitSize + ","
                                          + pos.EnableSize + ","
                                          + pos.CurrentSize + ","
                                          + pos.TodaySize
                                          );
                    }
                }
                else
                {
                    Console.WriteLine("QueryPositions error: " + r.Msg);
                }
            }
            {
                var r = tapi.QueryOrders("glsc");
                if (r.Value != null)
                {
                    foreach (var ord in r.Value)
                    {
                        Console.WriteLine("order: "
                                          + ord.AccountId + ","
                                          + ord.Code + ","
                                          + ord.EntrustAction + ","
                                          + ord.EntrustPrice + ","
                                          + ord.EntrustSize + ","
                                          + ord.EntrustDate + ","
                                          + ord.EntrustTime + ","
                                          + ord.EntrustNo + ","
                                          + ord.FillPrice + ","
                                          + ord.FillSize + ","
                                          + ord.Status + ","
                                          + ord.StatusMsg
                                          );
                    }
                }
                else
                {
                    Console.WriteLine("QueryOrders error: " + r.Msg);
                }
            }
            {
                var r = tapi.QueryTrades("glsc");
                if (r.Value != null)
                {
                    foreach (var trade in r.Value)
                    {
                        Console.WriteLine("order: "
                                          + trade.AccountId + ","
                                          + trade.FillDate + ","
                                          + trade.FillTime + ","
                                          + trade.Code + ","
                                          + trade.EntrustAction + ","
                                          + trade.EntrustNo + ","
                                          + trade.FillPrice + ","
                                          + trade.FillSize + ","
                                          + trade.FillNo
                                          );
                    }
                }
                else
                {
                    Console.WriteLine("QueryTrades error: " + r.Msg);
                }
            }

            {
                var r = tapi.PlaceOrder("glsc", "000001.SH", 10.0, 100, "Buy");
                if (r.Value != null)
                {
                    var oid = r.Value;
                    Console.WriteLine("PlaceOrder result: " + oid.EntrustNo + "," + oid.OrderId);
                }
                else
                {
                    Console.WriteLine("PlaceOrder error: " + r.Msg);
                }

                if (r.Value != null)
                {
                    var r2 = tapi.CancelOrder("glsc", "000001.SH", r.Value.EntrustNo);
                    if (r2.Value)
                    {
                        Console.WriteLine("CancelOrder result: " + r2.Value);
                    }
                    else
                    {
                        Console.WriteLine("CancelOrder error: " + r2.Msg);
                    }
                }
            }

            while (true)
            {
                Thread.Sleep(1000);
            }
        }
Exemplo n.º 26
0
        void RefreshData()
        {
            TradeApi tapi = GlobalData.GetTradeApi();

            var accounts = tapi.QueryAccountStatus().Value;

            if (accounts == null)
            {
                return;
            }

            List <Position> positions = new List <Position>();

            foreach (var act in accounts)
            {
                var r = tapi.QueryPositions(act.AccountId);
                if (r.Value == null)
                {
                    MessageBox.Show(r.Msg, "Error");
                    continue;
                }
                foreach (var p in r.Value)
                {
                    positions.Add(p);
                }
            }

            listView1.BeginUpdate();
            listView1.Items.Clear();
            foreach (var pos in positions)
            {
                ListViewItem item = new ListViewItem();
                item.Text = ""; // i.ToString();
                item.SubItems.Add(pos.AccountId);
                item.SubItems.Add(pos.Code);
                item.SubItems.Add(pos.Name);
                item.SubItems.Add(pos.CurrentSize.ToString());
                item.SubItems.Add(pos.EnableSize.ToString());
                item.SubItems.Add(pos.InitSize.ToString());
                item.SubItems.Add(pos.TodaySize.ToString());
                item.SubItems.Add(pos.FrozenSize.ToString());
                item.SubItems.Add(pos.Side);
                item.SubItems.Add(pos.Cost.ToString());
                item.SubItems.Add(pos.CostPrice.ToString());
                item.SubItems.Add(pos.LastPrice.ToString());
                item.SubItems.Add(pos.FloatPnl.ToString()).ForeColor = pos.LastPrice > pos.CostPrice ? Color.Red : Color.Green;
                item.SubItems.Add(pos.ClosePnl.ToString());
                item.SubItems.Add(pos.Margin.ToString());
                item.SubItems.Add(pos.Commission.ToString());

                listView1.Items.Add(item);
            }

            foreach (ColumnHeader col in listView1.Columns)
            {
                col.Width     = -2;
                col.TextAlign = HorizontalAlignment.Right;
            }

            listView1.EndUpdate();
        }
Exemplo n.º 27
0
 public TraderApiWrapper()
 {
     m_pMsgQueue = new MsgQueue();
     m_Api       = new TradeApi(m_pMsgQueue);
 }