├── TDAmeritrade.Client
├── Resources
│ ├── Logo.png
│ ├── Errors.Designer.cs
│ └── Errors.resx
├── Models
│ ├── Interval.cs
│ ├── UserExchangeStatus.cs
│ ├── Markets.cs
│ ├── PositionType.cs
│ ├── OptionTradingType.cs
│ ├── ErrorQuote.cs
│ ├── Quote.cs
│ ├── WatchlistItem.cs
│ ├── UserAuthorizations.cs
│ ├── AssetType.cs
│ ├── FundQuote.cs
│ ├── Watchlist.cs
│ ├── IndexQuote.cs
│ ├── AvailableQuotes.cs
│ ├── RealtimeMarkets.cs
│ ├── StockQuote.cs
│ ├── AccountAuthorizations.cs
│ ├── WatchedSymbol.cs
│ ├── UserAccount.cs
│ ├── OptionQuote.cs
│ ├── StreamerInfo.cs
│ └── AccountPreferences.cs
├── Extensions
│ ├── DateTimeExtensions.cs
│ ├── HttpClientExtensions.cs
│ └── BinaryReaderExtensions.cs
├── Properties
│ └── AssemblyInfo.cs
├── Controls
│ ├── LoginScreen.xaml.cs
│ └── LoginScreen.xaml
├── Utility
│ └── Settings.cs
├── TDAmeritrade.Client.csproj
└── AmeritradeClient.cs
├── TDAmeritrade.Client.Tests
├── AmeritradeClientTest.cs
├── Properties
│ └── AssemblyInfo.cs
└── TDAmeritrade.Client.Tests.csproj
├── TDAmeritrade.Client.nuspec
├── Settings.StyleCop
├── README.md
├── TDAmeritrade.Client.sln
├── .gitignore
└── LICENSE.txt
/TDAmeritrade.Client/Resources/Logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kriasoft/TDAmeritrade/HEAD/TDAmeritrade.Client/Resources/Logo.png
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/Interval.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | public enum Interval
10 | {
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/UserExchangeStatus.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | public enum UserExchangeStatus
10 | {
11 | Unknown,
12 | Professional,
13 | NonProfessional
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/Markets.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | public enum Markets
10 | {
11 | NYSE,
12 | NASDAQ,
13 | OPRA,
14 | AMEX,
15 | CME,
16 | ICE,
17 | FOREX
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/PositionType.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Xml.Serialization;
10 |
11 | public enum PositionType
12 | {
13 | [XmlEnum("LONG")]
14 | Long,
15 |
16 | [XmlEnum("SHORT")]
17 | Short
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/OptionTradingType.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Runtime.Serialization;
10 |
11 | ///
12 | /// Option trading type enumeration.
13 | ///
14 | public enum OptionTradingType
15 | {
16 | None,
17 | Long,
18 | Covered,
19 | Spread,
20 | Full
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/ErrorQuote.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Xml.Serialization;
10 |
11 | [XmlRoot("quote", Namespace = "")]
12 | public class ErrorQuote
13 | {
14 | [XmlElement("symbol")]
15 | public string Symbol { get; set; }
16 |
17 | [XmlElement("error")]
18 | public string ErrorMessage { get; set; }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/Quote.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System;
10 |
11 | public class Quote
12 | {
13 | public DateTime Date { get; set; }
14 |
15 | public float Open { get; set; }
16 |
17 | public float High { get; set; }
18 |
19 | public float Low { get; set; }
20 |
21 | public float Close { get; set; }
22 |
23 | public float Volume { get; set; }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/WatchlistItem.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System;
10 |
11 | public class WatchlistItem
12 | {
13 | public string Symbol { get; set; }
14 |
15 | public int? Quantity { get; set; }
16 |
17 | public double? AveragePrice { get; set; }
18 |
19 | public double? Commission { get; set; }
20 |
21 | public DateTime? OpenDate { get; set; }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/UserAuthorizations.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | ///
10 | /// Contains a list of services to which the user has a valid authorization.
11 | ///
12 | public class UserAuthorizations
13 | {
14 | ///
15 | /// Gets a value indicating whether the user has authorization to the Options360 service.
16 | ///
17 | public bool Options360 { get; internal set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Extensions/DateTimeExtensions.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Extensions
8 | {
9 | using System;
10 |
11 | public static class DateTimeExtensions
12 | {
13 | private static readonly TimeZoneInfo ServerTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
14 |
15 | public static DateTime ToServerTime(this DateTime dateTime)
16 | {
17 | return TimeZoneInfo.ConvertTime(dateTime, ServerTimeZone);
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/AssetType.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.ComponentModel;
10 | using System.Xml.Serialization;
11 |
12 | public enum AssetType
13 | {
14 | [XmlEnum("")]
15 | Unknown,
16 |
17 | [XmlEnum("E")]
18 | EquityOrETF,
19 |
20 | [XmlEnum("F")]
21 | MutualFund,
22 |
23 | [XmlEnum("O")]
24 | Option,
25 |
26 | [XmlEnum("B")]
27 | Bond,
28 |
29 | [XmlEnum("I")]
30 | Index
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Extensions/HttpClientExtensions.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Extensions
8 | {
9 | using System.Net.Http;
10 | using System.Threading.Tasks;
11 | using System.Xml.Linq;
12 |
13 | public static class HttpClientExtensions
14 | {
15 | public static async Task GetXmlAsync(this HttpClient http, string requestUri)
16 | {
17 | using (var stream = await http.GetStreamAsync(requestUri))
18 | {
19 | return XDocument.Load(stream);
20 | }
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/FundQuote.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Xml.Serialization;
10 |
11 | [XmlRoot("quote", Namespace = "")]
12 | public class FundQuote
13 | {
14 | [XmlElement("symbol")]
15 | public string Symbol { get; set; }
16 |
17 | [XmlElement("description")]
18 | public string Description { get; set; }
19 |
20 | [XmlElement("nav")]
21 | public float Nav { get; set; }
22 |
23 | [XmlElement("change")]
24 | public float Change { get; set; }
25 |
26 | [XmlElement("real-time")]
27 | public bool IsRealTime { get; set; }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client.Tests/AmeritradeClientTest.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Tests
8 | {
9 | using System;
10 | using System.Threading.Tasks;
11 | using Microsoft.VisualStudio.TestTools.UnitTesting;
12 |
13 | [TestClass]
14 | public class AmeritradeClientTest
15 | {
16 | [TestMethod, TestCategory("Integration")]
17 | public async Task GetWatchlists_Returns_a_List_of_Watchlists()
18 | {
19 | using (var client = new AmeritradeClient())
20 | {
21 | var watchlist = await client.GetWatchlists();
22 | Assert.IsNotNull(watchlist);
23 | Assert.IsTrue(watchlist.Count > 0);
24 | }
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | TDAmeritrade.Client
5 | 2.0.0-alpha3
6 | TD Ameritrade Client Library for .NET
7 | Konstantin Tarkus
8 | Konstantin Tarkus
9 | https://raw.github.com/kriasoft/tdameritrade/master/LICENSE.txt
10 | https://github.com/kriasoft/tdameritrade
11 | http://i.imgur.com/4wxcrN8.png
12 | false
13 | .NET Client for the TD Ameritrade Trading Platform. Helps developers integrate TD Ameritrade API into custom trading solutions.
14 | © 2013 Konstantin Tarkus, KriaSoft LLC
15 | en-US
16 | Finance Markets Trading Quotes
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/Watchlist.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Collections.Generic;
10 | using System.Xml.Serialization;
11 |
12 | [XmlRoot("watchlist", Namespace = "")]
13 | public class Watchlist
14 | {
15 | ///
16 | /// Gets or sets the name assigned to the given watchlist.
17 | ///
18 | [XmlElement("name")]
19 | public string Name { get; set; }
20 |
21 | ///
22 | /// Gets or sets numeric ID that identifies the watchlist.
23 | ///
24 | [XmlElement("id")]
25 | public string ID { get; set; }
26 |
27 | ///
28 | /// Gets or sets a list of symbols in the watchlist.
29 | ///
30 | [XmlArray("symbol-list"), XmlArrayItem("watched-symbol", typeof(WatchedSymbol))]
31 | public List Symbols { get; set; }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/IndexQuote.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Xml.Serialization;
10 |
11 | [XmlRoot("quote", Namespace = "")]
12 | public class IndexQuote
13 | {
14 | [XmlElement("symbol")]
15 | public string Symbol { get; set; }
16 |
17 | [XmlElement("description")]
18 | public string Description { get; set; }
19 |
20 | [XmlElement("open")]
21 | public float Open { get; set; }
22 |
23 | [XmlElement("high")]
24 | public float High { get; set; }
25 |
26 | [XmlElement("low")]
27 | public float Low { get; set; }
28 |
29 | [XmlElement("last")]
30 | public float Last { get; set; }
31 |
32 | [XmlElement("close")]
33 | public float Close { get; set; }
34 |
35 | [XmlElement("year-high")]
36 | public float YearHigh { get; set; }
37 |
38 | [XmlElement("year-low")]
39 | public float YearLow { get; set; }
40 |
41 | [XmlElement("real-time")]
42 | public bool IsRealTime { get; set; }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/AvailableQuotes.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Collections.Generic;
10 | using System.Linq;
11 |
12 | public class AvailableQuotes
13 | {
14 | private readonly SortedSet realtime = new SortedSet();
15 | private readonly SortedSet delayed = new SortedSet();
16 |
17 | public List All
18 | {
19 | get { return this.realtime.Union(this.delayed).ToList(); }
20 | }
21 |
22 | public List RealTime
23 | {
24 | get { return this.realtime.ToList(); }
25 | }
26 |
27 | public List Delayed
28 | {
29 | get { return this.delayed.ToList(); }
30 | }
31 |
32 | internal void Add(Markets market, bool isRealTime)
33 | {
34 | if (isRealTime)
35 | {
36 | this.realtime.Add(market);
37 | }
38 | else
39 | {
40 | this.delayed.Add(market);
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/RealtimeMarkets.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | ///
10 | /// Contains a list of markets and values indicating whether a real-time data is available for each of them.
11 | ///
12 | public class RealtimeMarkets
13 | {
14 | ///
15 | /// Gets a value indicating whether real-time streaming data is available for NYSE market.
16 | ///
17 | public bool NYSE { get; internal set; }
18 |
19 | ///
20 | /// Gets a value indicating whether real-time streaming data is available for NASDAQ market.
21 | ///
22 | public bool NASDAQ { get; internal set; }
23 |
24 | ///
25 | /// Gets a value indicating whether real-time streaming data is available for OPRA market.
26 | ///
27 | public bool OPRA { get; internal set; }
28 |
29 | ///
30 | /// Gets a value indicating whether real-time streaming data is available for AMEX market.
31 | ///
32 | public bool AMEX { get; internal set; }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Extensions/BinaryReaderExtensions.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Extensions
8 | {
9 | using System;
10 | using System.IO;
11 |
12 | internal static class BinaryReaderExtensions
13 | {
14 | public static short ReadInt16BE(this BinaryReader reader)
15 | {
16 | return BitConverter.ToInt16(reader.ReadBytes(sizeof(short)).Reverse(), 0);
17 | }
18 |
19 | public static int ReadInt32BE(this BinaryReader reader)
20 | {
21 | return BitConverter.ToInt32(reader.ReadBytes(sizeof(int)).Reverse(), 0);
22 | }
23 |
24 | public static long ReadInt64BE(this BinaryReader reader)
25 | {
26 | return BitConverter.ToInt64(reader.ReadBytes(sizeof(long)).Reverse(), 0);
27 | }
28 |
29 | public static float ToSingleBE(this BinaryReader reader)
30 | {
31 | return BitConverter.ToSingle(reader.ReadBytes(sizeof(float)).Reverse(), 0);
32 | }
33 |
34 | private static byte[] Reverse(this byte[] array)
35 | {
36 | Array.Reverse(array);
37 | return array;
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Settings.StyleCop:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | False
8 |
9 |
10 |
11 |
12 | False
13 |
14 |
15 |
16 |
17 | False
18 |
19 |
20 |
21 |
22 | False
23 |
24 |
25 |
26 |
27 | False
28 |
29 |
30 |
31 |
32 | False
33 |
34 |
35 |
36 |
37 | KriaSoft LLC
38 | Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## TD Ameritrade Client Library for .NET
2 |
3 | Free, open-source .NET Client for the [TD Ameritrade Trading Platform](https://www.tdameritrade.com/api.page).
4 | Helps developers integrate TD Ameritrade API into custom trading solutions.
5 |
6 | ### Download
7 |
8 | Get the latest version via [NuGet](https://www.nuget.org/packages/TDAmeritrade.Client/)
9 |
10 | ### Sample
11 |
12 | ```csharp
13 | using (var client = new AmeritradeClient())
14 | {
15 | client.LogIn();
16 | var quotes = await client.GetQuotes("GOOG", "AAPL", "MSFT");
17 | var symbols = await client.FindSymbols("bank");
18 | var prices = await client.GetHistoricalPrices("GOOG", startDate: DateTime.Now.AddYears(-1));
19 | var watchlists = await client.GetWatchlists();
20 | }
21 | ```
22 |
23 | If you have not specified username/password in code, you will be prompted to enter your
24 | TD Ameritrade client's credentials at runtime:
25 |
26 | 
27 |
28 | ### Credits
29 |
30 | Copyright (c) 2013 [Konstantin Tarkus](http://www.linkedin.com/in/koistya), [KriaSoft LLC](http://www.kriasoft.com)
31 |
32 | This software is released under the Apache License 2.0 (the "License"); you may not use the software
33 | except in compliance with the License. You can find a copy of the License in the file
34 | [LICENSE.txt](https://raw.github.com/kriasoft/tdameritrade/master/LICENSE.txt) accompanying this file.
35 |
36 | Logo image is a trademark of TD Ameritrade, Inc.
37 |
38 | ### Contacts
39 |
40 | Do you have any questions or need help? Email me at [hello@tarkus.me](mailto:hello@tarkus.me)
41 | or visit our [discussion board](https://groups.google.com/forum/#!forum/tdasdk).
42 |
43 | **P.S.**: Your contributions of any kind are welcome!
--------------------------------------------------------------------------------
/TDAmeritrade.Client.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.20623.1 VSUPREVIEW
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{6239A328-65C5-4171-9A22-BB8DF1D4CA8B}"
7 | ProjectSection(SolutionItems) = preProject
8 | LICENSE.txt = LICENSE.txt
9 | README.md = README.md
10 | Settings.StyleCop = Settings.StyleCop
11 | TDAmeritrade.Client.nuspec = TDAmeritrade.Client.nuspec
12 | EndProjectSection
13 | EndProject
14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TDAmeritrade.Client", "TDAmeritrade.Client\TDAmeritrade.Client.csproj", "{6E6A6434-F106-4EE0-990B-84716D7147AE}"
15 | EndProject
16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TDAmeritrade.Client.Tests", "TDAmeritrade.Client.Tests\TDAmeritrade.Client.Tests.csproj", "{1CA08FBC-F206-496B-8408-FB82BB660E67}"
17 | EndProject
18 | Global
19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
20 | Debug|Any CPU = Debug|Any CPU
21 | Release|Any CPU = Release|Any CPU
22 | EndGlobalSection
23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
24 | {6E6A6434-F106-4EE0-990B-84716D7147AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
25 | {6E6A6434-F106-4EE0-990B-84716D7147AE}.Debug|Any CPU.Build.0 = Debug|Any CPU
26 | {6E6A6434-F106-4EE0-990B-84716D7147AE}.Release|Any CPU.ActiveCfg = Release|Any CPU
27 | {6E6A6434-F106-4EE0-990B-84716D7147AE}.Release|Any CPU.Build.0 = Release|Any CPU
28 | {1CA08FBC-F206-496B-8408-FB82BB660E67}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
29 | {1CA08FBC-F206-496B-8408-FB82BB660E67}.Debug|Any CPU.Build.0 = Debug|Any CPU
30 | {1CA08FBC-F206-496B-8408-FB82BB660E67}.Release|Any CPU.ActiveCfg = Release|Any CPU
31 | {1CA08FBC-F206-496B-8408-FB82BB660E67}.Release|Any CPU.Build.0 = Release|Any CPU
32 | EndGlobalSection
33 | GlobalSection(SolutionProperties) = preSolution
34 | HideSolutionNode = FALSE
35 | EndGlobalSection
36 | EndGlobal
37 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client.Tests/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | using System.Reflection;
8 | using System.Runtime.CompilerServices;
9 | using System.Runtime.InteropServices;
10 |
11 | // General Information about an assembly is controlled through the following
12 | // set of attributes. Change these attribute values to modify the information
13 | // associated with an assembly.
14 | [assembly: AssemblyTitle("TDAmeritrade.Client.Tests")]
15 | [assembly: AssemblyDescription("")]
16 | [assembly: AssemblyConfiguration("")]
17 | [assembly: AssemblyCompany("")]
18 | [assembly: AssemblyProduct("TDAmeritrade.Client.Tests")]
19 | [assembly: AssemblyCopyright("Copyright © 2013")]
20 | [assembly: AssemblyTrademark("")]
21 | [assembly: AssemblyCulture("")]
22 |
23 | // Setting ComVisible to false makes the types in this assembly not visible
24 | // to COM components. If you need to access a type in this assembly from
25 | // COM, set the ComVisible attribute to true on that type.
26 | [assembly: ComVisible(false)]
27 |
28 | // The following GUID is for the ID of the typelib if this project is exposed to COM
29 | [assembly: Guid("88c4da3c-1125-4151-b53e-b14a5c9f9ba7")]
30 |
31 | // Version information for an assembly consists of the following four values:
32 | //
33 | // Major Version
34 | // Minor Version
35 | // Build Number
36 | // Revision
37 | //
38 | // You can specify all the values or you can default the Build and Revision Numbers
39 | // by using the '*' as shown below:
40 | // [assembly: AssemblyVersion("1.0.*")]
41 | [assembly: AssemblyVersion("1.0.0.0")]
42 | [assembly: AssemblyFileVersion("1.0.0.0")]
43 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | using System.Reflection;
8 | using System.Runtime.CompilerServices;
9 | using System.Runtime.InteropServices;
10 |
11 | // General Information about an assembly is controlled through the following
12 | // set of attributes. Change these attribute values to modify the information
13 | // associated with an assembly.
14 | [assembly: AssemblyTitle("TD Ameritrade Client Library")]
15 | [assembly: AssemblyDescription(".NET Client for the TD Ameritrade Trading Platform")]
16 | [assembly: AssemblyConfiguration("")]
17 | [assembly: AssemblyCompany("KriaSoft")]
18 | [assembly: AssemblyProduct("TD Ameritrade Client Library")]
19 | [assembly: AssemblyCopyright("Copyright © 2013 Konstantin Tarkus, KriaSoft LLC")]
20 | [assembly: AssemblyTrademark("")]
21 | [assembly: AssemblyCulture("")]
22 |
23 | // Setting ComVisible to false makes the types in this assembly not visible
24 | // to COM components. If you need to access a type in this assembly from
25 | // COM, set the ComVisible attribute to true on that type.
26 | [assembly: ComVisible(false)]
27 |
28 | // The following GUID is for the ID of the typelib if this project is exposed to COM
29 | [assembly: Guid("0de574e0-42c4-4873-9207-f4d00470f3c6")]
30 |
31 | // Version information for an assembly consists of the following four values:
32 | //
33 | // Major Version
34 | // Minor Version
35 | // Build Number
36 | // Revision
37 | //
38 | // You can specify all the values or you can default the Build and Revision Numbers
39 | // by using the '*' as shown below:
40 | // [assembly: AssemblyVersion("1.0.*")]
41 | [assembly: AssemblyVersion("2.0.0.0")]
42 | [assembly: AssemblyFileVersion("2.0.0.0")]
43 | [assembly: AssemblyInformationalVersion("2.0.0-alpha3")]
44 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/StockQuote.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Xml.Serialization;
10 |
11 | [XmlRoot("quote", Namespace = "")]
12 | public class StockQuote
13 | {
14 | [XmlElement("symbol")]
15 | public string Symbol { get; set; }
16 |
17 | [XmlElement("description")]
18 | public string Description { get; set; }
19 |
20 | [XmlElement("bid")]
21 | public float Bid { get; set; }
22 |
23 | [XmlElement("ask")]
24 | public float Ask { get; set; }
25 |
26 | [XmlElement("bid-ask-size")]
27 | public string BidAskSize { get; set; }
28 |
29 | [XmlElement("last")]
30 | public float Last { get; set; }
31 |
32 | [XmlElement("last-trade-size")]
33 | public int LastTradeSize { get; set; }
34 |
35 | [XmlElement("last-trade-date")]
36 | public string LastTradeDate { get; set; }
37 |
38 | [XmlElement("open")]
39 | public float Open { get; set; }
40 |
41 | [XmlElement("high")]
42 | public float High { get; set; }
43 |
44 | [XmlElement("low")]
45 | public float Low { get; set; }
46 |
47 | [XmlElement("close")]
48 | public float Close { get; set; }
49 |
50 | [XmlElement("volume")]
51 | public long Volume { get; set; }
52 |
53 | [XmlElement("year-high")]
54 | public float YearHigh { get; set; }
55 |
56 | [XmlElement("year-low")]
57 | public float YearLow { get; set; }
58 |
59 | [XmlElement("real-time")]
60 | public bool IsRealTime { get; set; }
61 |
62 | [XmlElement("exchange")]
63 | public string Exchange { get; set; }
64 |
65 | [XmlElement("change")]
66 | public float Change { get; set; }
67 |
68 | [XmlElement("change-percent")]
69 | public string ChangePercent { get; set; }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/AccountAuthorizations.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Runtime.Serialization;
10 |
11 | ///
12 | /// Container for the Authorizations for the given account.
13 | ///
14 | public class AccountAuthorizations
15 | {
16 | ///
17 | /// Gets a value indicating whether or not the account has APEX status.
18 | ///
19 | public bool Apex { get; internal set; }
20 |
21 | ///
22 | /// Gets a value indicating whether the account is authorized for Level 2 quotes (NASDAQ Level II).
23 | ///
24 | public bool Level2 { get; internal set; }
25 |
26 | ///
27 | /// Gets a value indicating whether the account is enabled for stock trading.
28 | ///
29 | public bool StockTrading { get; internal set; }
30 |
31 | ///
32 | /// Gets a value indicating whether the account is enabled for MARGIN trading. If false, then its a CASH account.
33 | ///
34 | public bool MarginTrading { get; internal set; }
35 |
36 | ///
37 | /// Gets a value indicating whether the account is enabled for streaming news.
38 | ///
39 | public bool StreamingNews { get; internal set; }
40 |
41 | ///
42 | /// Gets a value indicating whether the account is enabled for options trading. If so, then the type of permissions.
43 | ///
44 | public OptionTradingType OptionTrading { get; internal set; }
45 |
46 | ///
47 | /// Gets a value indicating whether the account is enabled for streaming data access.
48 | ///
49 | public bool Streamer { get; internal set; }
50 |
51 | ///
52 | /// Gets a value indicating whether the account will use a new middleware (AMX-TIBCO) for margin computation.
53 | ///
54 | public bool AdvancedMargin { get; internal set; }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/WatchedSymbol.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System;
10 | using System.Xml;
11 | using System.Xml.Schema;
12 | using System.Xml.Serialization;
13 |
14 | public class WatchedSymbol
15 | {
16 | ///
17 | /// Gets or sets the number of units in the position. Field may have up to 3 digits to the right of the decimal point.
18 | ///
19 | [XmlElement("quantity")]
20 | public double Quantity { get; set; }
21 |
22 | [XmlElement("security")]
23 | public SecurityNode Security { get; set; }
24 |
25 | ///
26 | /// Gets or sets position type: LONG or SHORT
27 | ///
28 | [XmlElement("position-type")]
29 | public PositionType PositionType { get; set; }
30 |
31 | ///
32 | /// Gets or sets the value calculated by dividing the total cost to acquire the position by the number of units
33 | /// in the position. The field may contain up to six digits to the right of the decimal point.
34 | ///
35 | [XmlElement("average-price")]
36 | public double AveragePrice { get; set; }
37 |
38 | [XmlElement("commission")]
39 | public double Commission { get; set; }
40 |
41 | ///
42 | /// Gets or sets the value indicating when the "position" was opened.
43 | ///
44 | [XmlElement("open-date")]
45 | public string OpenDate { get; set; }
46 |
47 | public class SecurityNode
48 | {
49 | [XmlElement("symbol")]
50 | public string Symbol { get; set; }
51 |
52 | [XmlElement("symbol-with-type-prefix")]
53 | public string SymbolWithTypePrefix { get; set; }
54 |
55 | [XmlElement("description")]
56 | public string Description { get; set; }
57 |
58 | [XmlElement("asset-type")]
59 | public AssetType AssetType { get; set; }
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.sln.docstates
8 |
9 | # Build results
10 |
11 | [Dd]ebug/
12 | [Rr]elease/
13 | x64/
14 | build/
15 | [Bb]in/
16 | [Oo]bj/
17 |
18 | # Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets
19 | !packages/*/build/
20 |
21 | # MSTest test Results
22 | [Tt]est[Rr]esult*/
23 | [Bb]uild[Ll]og.*
24 |
25 | *_i.c
26 | *_p.c
27 | *.ilk
28 | *.meta
29 | *.obj
30 | *.pch
31 | *.pdb
32 | *.pgc
33 | *.pgd
34 | *.rsp
35 | *.sbr
36 | *.tlb
37 | *.tli
38 | *.tlh
39 | *.tmp
40 | *.tmp_proj
41 | *.log
42 | *.vspscc
43 | *.vssscc
44 | .builds
45 | *.pidb
46 | *.log
47 | *.scc
48 |
49 | # Visual C++ cache files
50 | ipch/
51 | *.aps
52 | *.ncb
53 | *.opensdf
54 | *.sdf
55 | *.cachefile
56 |
57 | # Visual Studio profiler
58 | *.psess
59 | *.vsp
60 | *.vspx
61 |
62 | # Guidance Automation Toolkit
63 | *.gpState
64 |
65 | # ReSharper is a .NET coding add-in
66 | _ReSharper*/
67 | *.[Rr]e[Ss]harper
68 |
69 | # TeamCity is a build add-in
70 | _TeamCity*
71 |
72 | # DotCover is a Code Coverage Tool
73 | *.dotCover
74 |
75 | # NCrunch
76 | *.ncrunch*
77 | .*crunch*.local.xml
78 |
79 | # Installshield output folder
80 | [Ee]xpress/
81 |
82 | # DocProject is a documentation generator add-in
83 | DocProject/buildhelp/
84 | DocProject/Help/*.HxT
85 | DocProject/Help/*.HxC
86 | DocProject/Help/*.hhc
87 | DocProject/Help/*.hhk
88 | DocProject/Help/*.hhp
89 | DocProject/Help/Html2
90 | DocProject/Help/html
91 |
92 | # Click-Once directory
93 | publish/
94 |
95 | # Publish Web Output
96 | *.Publish.xml
97 | *.pubxml
98 |
99 | # NuGet Packages Directory
100 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line
101 | #packages/
102 |
103 | # Windows Azure Build Output
104 | csx
105 | *.build.csdef
106 |
107 | # Windows Store app package directory
108 | AppPackages/
109 |
110 | # Others
111 | sql/
112 | *.Cache
113 | ClientBin/
114 | [Ss]tyle[Cc]op.*
115 | ~$*
116 | *~
117 | *.dbmdl
118 | *.[Pp]ublish.xml
119 | *.pfx
120 | *.publishsettings
121 |
122 | # RIA/Silverlight projects
123 | Generated_Code/
124 |
125 | # Backup & report files from converting an old project file to a newer
126 | # Visual Studio version. Backup files are not needed, because we have git ;-)
127 | _UpgradeReport_Files/
128 | Backup*/
129 | UpgradeLog*.XML
130 | UpgradeLog*.htm
131 |
132 | # SQL Server files
133 | App_Data/*.mdf
134 | App_Data/*.ldf
135 |
136 | # =========================
137 | # Windows detritus
138 | # =========================
139 |
140 | # Windows image file caches
141 | Thumbs.db
142 | ehthumbs.db
143 |
144 | # Folder config file
145 | Desktop.ini
146 |
147 | # Recycle Bin used on file shares
148 | $RECYCLE.BIN/
149 |
150 | # Mac crap
151 | .DS_Store
152 |
153 | # Custom
154 | Docs/
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/UserAccount.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Runtime.Serialization;
10 |
11 | ///
12 | /// Represents an individual account.
13 | ///
14 | public class UserAccount
15 | {
16 | ///
17 | /// Initializes a new instance of the class.
18 | ///
19 | public UserAccount()
20 | {
21 | this.Preferences = new AccountPreferences();
22 | this.Authorizations = new AccountAuthorizations { OptionTrading = OptionTradingType.None };
23 | }
24 |
25 | ///
26 | /// Gets the ID of the user's account.
27 | ///
28 | public string AccountID { get; internal set; }
29 |
30 | ///
31 | /// Gets the display name for the account; same as shown on the TD Ameritrade web site.
32 | ///
33 | public string DisplayName { get; internal set; }
34 |
35 | ///
36 | /// Gets the user friendly description or the name associated with the account.
37 | ///
38 | public string Description { get; internal set; }
39 |
40 | ///
41 | /// Gets a value indicating whether or not this account is the main account associated with the User ID/LogIn session.
42 | ///
43 | public bool IsAssociatedAccount { get; internal set; }
44 |
45 | ///
46 | /// Gets a TDA internal code for the company the account is associated with. Will be needed for Streaming Quote requests.
47 | ///
48 | public string Company { get; internal set; }
49 |
50 | ///
51 | /// Gets a TDA internal code for the segment the account is associated with. Will be needed for Streaming Quote requests.
52 | ///
53 | public string Segment { get; internal set; }
54 |
55 | ///
56 | /// Gets a value indicating whether the account is enabled for Unified Site. If not, then you will not be able to launch any URL commands with /u/ in them.
57 | ///
58 | public bool IsUnified { get; internal set; }
59 |
60 | ///
61 | /// Gets a list of preference settings for the given account.
62 | ///
63 | public AccountPreferences Preferences { get; private set; }
64 |
65 | ///
66 | /// Gets a list of authorizations for the given account.
67 | ///
68 | public AccountAuthorizations Authorizations { get; private set; }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Controls/LoginScreen.xaml.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Controls
8 | {
9 | using System.Windows;
10 | using System.Windows.Input;
11 |
12 | using TDAmeritrade.Client.Utility;
13 |
14 | ///
15 | /// Interaction logic for LoginScreen.xaml
16 | ///
17 | public partial class LoginScreen : Window
18 | {
19 | private const string UserNameKey = "UserName";
20 | private const string RememberUserNameKey = "RememberUserName";
21 |
22 | private readonly AmeritradeClient client;
23 |
24 | public LoginScreen()
25 | {
26 | this.InitializeComponent();
27 |
28 | this.UserName.Text = Settings.GetProtected(UserNameKey);
29 | this.RememberUserName.IsChecked = Settings.Get(RememberUserNameKey, defaultValue: true);
30 | this.ErrorMessage.Visibility = Visibility.Collapsed;
31 |
32 | if (!string.IsNullOrWhiteSpace(this.UserName.Text))
33 | {
34 | this.Password.Focus();
35 | }
36 | }
37 |
38 | public LoginScreen(AmeritradeClient client)
39 | : this()
40 | {
41 | this.client = client;
42 | }
43 |
44 | private async void LoginButton_Click(object sender, RoutedEventArgs e)
45 | {
46 | if (string.IsNullOrWhiteSpace(this.UserName.Text) || string.IsNullOrWhiteSpace(this.Password.Password))
47 | {
48 | this.ErrorMessage.Visibility = Visibility.Visible;
49 | return;
50 | }
51 |
52 | Settings.SetProtected(UserNameKey, this.RememberUserName.IsChecked.Value ? this.UserName.Text : string.Empty);
53 | Settings.Set(RememberUserNameKey, this.RememberUserName.IsChecked.Value);
54 |
55 | this.UserName.IsEnabled = false;
56 | this.Password.IsEnabled = false;
57 | this.LoginButton.IsEnabled = false;
58 |
59 | var result = await this.client.LogIn(this.UserName.Text, this.Password.Password);
60 |
61 | if (!result)
62 | {
63 | this.UserName.IsEnabled = true;
64 | this.Password.IsEnabled = true;
65 | this.LoginButton.IsEnabled = true;
66 | this.ErrorMessage.Visibility = Visibility.Visible;
67 | return;
68 | }
69 |
70 | this.DialogResult = result;
71 | }
72 |
73 | private void CancelButton_Click(object sender, RoutedEventArgs e)
74 | {
75 | this.DialogResult = false;
76 | }
77 |
78 | private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
79 | {
80 | this.DragMove();
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/OptionQuote.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Xml.Serialization;
10 |
11 | [XmlRoot("quote", Namespace = "")]
12 | public class OptionQuote
13 | {
14 | [XmlElement("symbol")]
15 | public string Symbol { get; set; }
16 |
17 | [XmlElement("description")]
18 | public string Description { get; set; }
19 |
20 | [XmlElement("bid")]
21 | public float Bid { get; set; }
22 |
23 | [XmlElement("ask")]
24 | public float Ask { get; set; }
25 |
26 | [XmlElement("bid-ask-size")]
27 | public string BidAskSize { get; set; }
28 |
29 | [XmlElement("last")]
30 | public float Last { get; set; }
31 |
32 | [XmlElement("last-trade-size")]
33 | public int LastTradeSize { get; set; }
34 |
35 | [XmlElement("last-trade-date")]
36 | public string LastTradeDate { get; set; }
37 |
38 | [XmlElement("open")]
39 | public float Open { get; set; }
40 |
41 | [XmlElement("high")]
42 | public float High { get; set; }
43 |
44 | [XmlElement("low")]
45 | public float Low { get; set; }
46 |
47 | [XmlElement("close")]
48 | public float Close { get; set; }
49 |
50 | [XmlElement("volume")]
51 | public long Volume { get; set; }
52 |
53 | [XmlElement("strike-price")]
54 | public float StrikePrice { get; set; }
55 |
56 | [XmlElement("open-interest")]
57 | public int OpenInterest { get; set; }
58 |
59 | [XmlElement("expiration-month")]
60 | public int ExpirationMonth { get; set; }
61 |
62 | [XmlElement("expiration-day")]
63 | public int ExpirationDay { get; set; }
64 |
65 | [XmlElement("expiration-year")]
66 | public int ExpirationYear { get; set; }
67 |
68 | [XmlElement("real-time")]
69 | public bool IsRealTime { get; set; }
70 |
71 | [XmlElement("exchange")]
72 | public string Exchange { get; set; }
73 |
74 | [XmlElement("underlying-symbol")]
75 | public string UnderlyingSymbol { get; set; }
76 |
77 | [XmlElement("delta")]
78 | public float Delta { get; set; }
79 |
80 | [XmlElement("gamma")]
81 | public float Gamma { get; set; }
82 |
83 | [XmlElement("theta")]
84 | public float Theta { get; set; }
85 |
86 | [XmlElement("vega")]
87 | public float Vega { get; set; }
88 |
89 | [XmlElement("rho")]
90 | public float Rho { get; set; }
91 |
92 | [XmlElement("implied-volatility")]
93 | public float ImpliedVolatitily { get; set; }
94 |
95 | [XmlElement("days-to-expiration")]
96 | public int DaysToExpiration { get; set; }
97 |
98 | [XmlElement("time-value-index")]
99 | public float TimeValueIndex { get; set; }
100 |
101 | [XmlElement("multiplier")]
102 | public float Multiplier { get; set; }
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Utility/Settings.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Utility
8 | {
9 | using System;
10 | using System.Security.Cryptography;
11 | using System.Text;
12 |
13 | using Microsoft.Win32;
14 |
15 | internal static class Settings
16 | {
17 | internal static bool Get(string name, bool defaultValue)
18 | {
19 | var key = Registry.CurrentUser.CreateSubKey("Software\\KriaSoft\\TD Ameritrade Client Library for .NET");
20 | var value = (int?)key.GetValue(name);
21 |
22 | if (value.HasValue)
23 | {
24 | return value.Value == 1;
25 | }
26 |
27 | key.SetValue(name, defaultValue, RegistryValueKind.DWord);
28 | return defaultValue;
29 | }
30 |
31 | internal static T Get(string name, Func defaultValue = null) where T : class
32 | {
33 | var key = Registry.CurrentUser.CreateSubKey("Software\\KriaSoft\\TD Ameritrade Client Library for .NET");
34 | var value = key.GetValue(name) as T;
35 |
36 | if (defaultValue != null && value == null)
37 | {
38 | value = defaultValue();
39 | key.SetValue(name, value);
40 | }
41 |
42 | return value;
43 | }
44 |
45 | internal static void Set(string name, bool value)
46 | {
47 | Registry.CurrentUser.CreateSubKey("Software\\KriaSoft\\TD Ameritrade Client Library for .NET").SetValue(name, value, RegistryValueKind.DWord);
48 | }
49 |
50 | internal static void Set(string name, T value)
51 | {
52 | Registry.CurrentUser.CreateSubKey("Software\\KriaSoft\\TD Ameritrade Client Library for .NET").SetValue(name, value);
53 | }
54 |
55 | internal static string GetProtected(string name)
56 | {
57 | var encryptedData = Get(name);
58 |
59 | if (encryptedData == null)
60 | {
61 | return null;
62 | }
63 |
64 | var entropy = GetEntropy();
65 | var data = ProtectedData.Unprotect(encryptedData, entropy, DataProtectionScope.CurrentUser);
66 | return Encoding.Unicode.GetString(data);
67 | }
68 |
69 | internal static void SetProtected(string name, string value)
70 | {
71 | var entropy = GetEntropy();
72 | var encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(value), entropy, DataProtectionScope.CurrentUser);
73 | Set(name, encryptedData);
74 | }
75 |
76 | private static byte[] GetEntropy()
77 | {
78 | return Get(
79 | "Entropy",
80 | defaultValue: () =>
81 | {
82 | var val = new byte[20];
83 |
84 | using (var rng = new RNGCryptoServiceProvider())
85 | {
86 | rng.GetBytes(val);
87 | }
88 |
89 | return val;
90 | });
91 | }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/StreamerInfo.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Runtime.Serialization;
10 | using System.Xml.Serialization;
11 |
12 | ///
13 | /// Container for StreamerInfo information object.
14 | ///
15 | [XmlRoot("streamer-info", Namespace = "")]
16 | public class StreamerInfo
17 | {
18 | ///
19 | /// Gets or sets the domain of the server that should be used for streaming data.
20 | ///
21 | [XmlElement("streamer-url", Order = 0)]
22 | public string StreamerUrl { get; set; }
23 |
24 | ///
25 | /// Gets or sets the variable to be passed in the "token" parameter in all streamer requests.
26 | ///
27 | [XmlElement("token", Order = 1)]
28 | public string Token { get; set; }
29 |
30 | ///
31 | /// Gets or sets the variable to be passed in the "timestamp" parameter in all streamer requests.
32 | ///
33 | [XmlElement("timestamp", Order = 2)]
34 | public long Timestamp { get; set; }
35 |
36 | ///
37 | /// Gets or sets the variable to be passed in the "cddomain" parameter in all streamer requests.
38 | ///
39 | [XmlElement("cd-domain-id", Order = 3)]
40 | public string CDDomainID { get; set; }
41 |
42 | ///
43 | /// Gets or sets the variable to be passed in the "usergroup" parameter in all streamer requests.
44 | ///
45 | [XmlElement("usergroup", Order = 4)]
46 | public string UserGroup { get; set; }
47 |
48 | ///
49 | /// Gets or sets the variable to be passed in the "accesslevel" parameter in all streamer requests.
50 | ///
51 | [XmlElement("access-level", Order = 5)]
52 | public string AccessLevel { get; set; }
53 |
54 | ///
55 | /// Gets or sets the variable to be passed in the "acl" parameter in all streamer requests.
56 | ///
57 | [XmlElement("acl", Order = 6)]
58 | public string Acl { get; set; }
59 |
60 | ///
61 | /// Gets or sets the variable to be passed in the "appid" parameter in all streamer requests.
62 | ///
63 | /// NOTE: This is NOT the same as the Source ID assigned to the developer application.
64 | ///
65 | ///
66 | [XmlElement("app-id", Order = 7)]
67 | public string AppID { get; set; }
68 |
69 | ///
70 | /// Gets or sets the variable to be passed in the "authorized" parameter in all streamer requests.
71 | ///
72 | [XmlElement("authorized", Order = 8)]
73 | public string Authorized { get; set; }
74 |
75 | ///
76 | /// Gets or sets a plain text message of the error, in case one occurred.
77 | ///
78 | [XmlElement("error-msg", Order = 9)]
79 | internal string ErrorMessage { get; set; }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Models/AccountPreferences.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client.Models
8 | {
9 | using System.Runtime.Serialization;
10 |
11 | ///
12 | /// Represents the preference options for the given account.
13 | ///
14 | public class AccountPreferences
15 | {
16 | ///
17 | /// Gets a value indicating whether the user has selected Express Trading option on the web site (does not affect API).
18 | ///
19 | public bool ExpressTrading { get; internal set; }
20 |
21 | ///
22 | /// Gets a value indicating whether the account is enabled for direct routing options orders.
23 | ///
24 | public bool OptionDirectRouting { get; internal set; }
25 |
26 | ///
27 | /// Gets a value indicating whether the account is enabled for direct routing stock orders.
28 | ///
29 | public bool StockDirectRouting { get; internal set; }
30 |
31 | ///
32 | /// Gets the action used to pre-populate the stock order ticket
33 | ///
34 | public string DefaultStockAction { get; internal set; }
35 |
36 | ///
37 | /// Gets the type of order to pre-populate the stock order ticket
38 | ///
39 | public string DefaultStockOrderType { get; internal set; }
40 |
41 | ///
42 | /// Gets the number of shares to pre-populate into the stock order ticket
43 | ///
44 | public string DefaultStockQuantity { get; internal set; }
45 |
46 | ///
47 | /// Gets the expiration used to pre-populate the stock order ticket
48 | ///
49 | public string DefaultStockExpiration { get; internal set; }
50 |
51 | ///
52 | /// Gets the list of instructions used to pre-populate the stock order ticket
53 | ///
54 | public string DefaultStockSpecialInstructions { get; internal set; }
55 |
56 | ///
57 | /// Gets the routing destination used to pre-populate the stock order ticket
58 | ///
59 | public string DefaultStockRouting { get; internal set; }
60 |
61 | ///
62 | /// Gets the display size used with INET direct routing
63 | ///
64 | public string DefaultStockDisplaySize { get; internal set; }
65 |
66 | ///
67 | /// Gets the tax lot methodology used when selling shares
68 | ///
69 | public string StockTaxLotMethod { get; internal set; }
70 |
71 | ///
72 | /// Gets the tax lot methodology used when selling options
73 | ///
74 | public string OptionTaxLotMethod { get; internal set; }
75 |
76 | ///
77 | /// Gets the tax lot methodology used when selling mutual funds
78 | ///
79 | public string MutualFundTaxLotMethod { get; internal set; }
80 |
81 | ///
82 | /// Gets the advanced tool launched when logging into the Ameritrade website.
83 | ///
84 | public string DefaultAdvancedToolLaunch { get; internal set; }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Resources/Errors.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.18213
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace TDAmeritrade.Client.Resources {
12 | using System;
13 |
14 |
15 | ///
16 | /// A strongly-typed resource class, for looking up localized strings, etc.
17 | ///
18 | // This class was auto-generated by the StronglyTypedResourceBuilder
19 | // class via a tool like ResGen or Visual Studio.
20 | // To add or remove a member, edit your .ResX file then rerun ResGen
21 | // with the /str option, or rebuild your VS project.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Errors {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Errors() {
33 | }
34 |
35 | ///
36 | /// Returns the cached ResourceManager instance used by this class.
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TDAmeritrade.Client.Resources.Errors", typeof(Errors).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// Overrides the current thread's CurrentUICulture property for all
51 | /// resource lookups using this strongly typed resource class.
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 |
63 | ///
64 | /// Looks up a localized string similar to The '{0}' argument cannot be empty..
65 | ///
66 | internal static string CannotBeEmpty {
67 | get {
68 | return ResourceManager.GetString("CannotBeEmpty", resourceCulture);
69 | }
70 | }
71 |
72 | ///
73 | /// Looks up a localized string similar to The '{0}' argument cannot be null or whitespace..
74 | ///
75 | internal static string CannotBeNullOrWhitespace {
76 | get {
77 | return ResourceManager.GetString("CannotBeNullOrWhitespace", resourceCulture);
78 | }
79 | }
80 |
81 | ///
82 | /// Looks up a localized string similar to Unexpected end of the price data stream..
83 | ///
84 | internal static string UnexpectedEnfOfPriceData {
85 | get {
86 | return ResourceManager.GetString("UnexpectedEnfOfPriceData", resourceCulture);
87 | }
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client.Tests/TDAmeritrade.Client.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | {1CA08FBC-F206-496B-8408-FB82BB660E67}
7 | Library
8 | Properties
9 | TDAmeritrade.Client.Tests
10 | TDAmeritrade.Client.Tests
11 | v4.5.1
12 | 512
13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
14 | 10.0
15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages
17 | False
18 | UnitTest
19 |
20 |
21 | true
22 | full
23 | false
24 | bin\Debug\
25 | DEBUG;TRACE
26 | prompt
27 | 4
28 |
29 |
30 | pdbonly
31 | true
32 | bin\Release\
33 | TRACE
34 | prompt
35 | 4
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | {6e6a6434-f106-4ee0-990b-84716d7147ae}
59 | TDAmeritrade.Client
60 |
61 |
62 |
63 |
64 |
65 |
66 | False
67 |
68 |
69 | False
70 |
71 |
72 | False
73 |
74 |
75 | False
76 |
77 |
78 |
79 |
80 |
81 |
82 |
89 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Controls/LoginScreen.xaml:
--------------------------------------------------------------------------------
1 |
14 |
15 |
20 |
29 |
38 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 | Remember username
76 | Invalid username or password
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/TDAmeritrade.Client.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {6E6A6434-F106-4EE0-990B-84716D7147AE}
8 | Library
9 | Properties
10 | TDAmeritrade.Client
11 | TDAmeritrade.Client
12 | v4.5
13 | 512
14 |
15 |
16 |
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | pdbonly
27 | true
28 | bin\Release\
29 | TRACE
30 | prompt
31 | 4
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | LoginScreen.xaml
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 | True
83 | True
84 | Errors.resx
85 |
86 |
87 |
88 |
89 |
90 | Designer
91 | MSBuild:Compile
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 | ResXFileCodeGenerator
100 | Errors.Designer.cs
101 |
102 |
103 |
104 |
111 |
--------------------------------------------------------------------------------
/TDAmeritrade.Client/Resources/Errors.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | The '{0}' argument cannot be empty.
122 |
123 |
124 | The '{0}' argument cannot be null or whitespace.
125 |
126 |
127 | Unexpected end of the price data stream.
128 |
129 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/TDAmeritrade.Client/AmeritradeClient.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
4 | //
5 | // --------------------------------------------------------------------------------------------------------------------
6 |
7 | namespace TDAmeritrade.Client
8 | {
9 | using System;
10 | using System.Collections.Generic;
11 | using System.Collections.ObjectModel;
12 | using System.IO;
13 | using System.Linq;
14 | using System.Net.Http;
15 | using System.Runtime.InteropServices;
16 | using System.Security;
17 | using System.Text;
18 | using System.Threading.Tasks;
19 | using System.Xml.Linq;
20 | using System.Xml.Serialization;
21 |
22 | using TDAmeritrade.Client.Controls;
23 | using TDAmeritrade.Client.Extensions;
24 | using TDAmeritrade.Client.Models;
25 | using TDAmeritrade.Client.Resources;
26 |
27 | ///
28 | /// Represents a REST client for interacting with the TD Ameritrade Trading Platform.
29 | ///
30 | public class AmeritradeClient : IDisposable
31 | {
32 | private readonly HttpClient http;
33 |
34 | private readonly string key;
35 | private readonly string name;
36 | private readonly string version;
37 |
38 | private string sessionID;
39 | private SecureString userID;
40 | private TimeSpan timeout;
41 | private StreamerInfo streamerInfo;
42 |
43 | ///
44 | /// Initializes a new instance of the class.
45 | ///
46 | /// Organization's unique identifier to be passed as part of every request to the TD Ameritrade Trading Platform.
47 | /// Organization's name to be passed to the TD Ameritrade Trading Platform during authentication.
48 | /// The package's version to be passed to the TD Ameritrade Trading Platform during authentication.
49 | public AmeritradeClient(string key = "DEMO", string name = "TD Ameritrade Client Library for .NET", string version = "2.0.0")
50 | {
51 | if (string.IsNullOrWhiteSpace(key))
52 | {
53 | throw new ArgumentException(string.Format(Errors.CannotBeNullOrWhitespace, "key"));
54 | }
55 |
56 | if (string.IsNullOrWhiteSpace(name))
57 | {
58 | throw new ArgumentException(string.Format(Errors.CannotBeNullOrWhitespace, "name"));
59 | }
60 |
61 | if (string.IsNullOrWhiteSpace(version))
62 | {
63 | throw new ArgumentException(string.Format(Errors.CannotBeNullOrWhitespace, "version"));
64 | }
65 |
66 | this.key = key;
67 | this.name = name;
68 | this.version = version;
69 |
70 | this.http = new HttpClient
71 | {
72 | BaseAddress = new Uri("https://apis.tdameritrade.com")
73 | };
74 |
75 | this.Reset();
76 | }
77 |
78 | ~AmeritradeClient()
79 | {
80 | this.Dispose(false);
81 | }
82 |
83 | public string UserID
84 | {
85 | get
86 | {
87 | if (this.userID == null)
88 | {
89 | return null;
90 | }
91 |
92 | var valuePtr = IntPtr.Zero;
93 | try
94 | {
95 | valuePtr = Marshal.SecureStringToGlobalAllocUnicode(this.userID);
96 | return Marshal.PtrToStringUni(valuePtr);
97 | }
98 | finally
99 | {
100 | Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
101 | }
102 | }
103 |
104 | private set
105 | {
106 | if (value == null)
107 | {
108 | this.userID = null;
109 | }
110 | else
111 | {
112 | this.userID = new SecureString();
113 | foreach (char c in value)
114 | {
115 | this.userID.AppendChar(c);
116 | }
117 | }
118 | }
119 | }
120 |
121 | public UserExchangeStatus UserExchangeStatus { get; private set; }
122 |
123 | public UserAccount UserAccount { get; private set; }
124 |
125 | public Dictionary UserAuthorizations { get; private set; }
126 |
127 | public ReadOnlyCollection UserAccounts { get; private set; }
128 |
129 | public bool IsAuthenticated { get; private set; }
130 |
131 | public AvailableQuotes AvailableQuotes { get; private set; }
132 |
133 | public bool LogIn()
134 | {
135 | var login = new LoginScreen(this);
136 | return login.ShowDialog().Value;
137 | }
138 |
139 | public async Task LogIn(string userName, string password)
140 | {
141 | if (string.IsNullOrWhiteSpace(userName))
142 | {
143 | throw new ArgumentException(string.Format(Errors.CannotBeNullOrWhitespace, "userName"), "userName");
144 | }
145 |
146 | if (string.IsNullOrWhiteSpace(password))
147 | {
148 | throw new ArgumentException(string.Format(Errors.CannotBeNullOrWhitespace, "password"), "password");
149 | }
150 |
151 | var response = await this.http.PostAsync(
152 | "/apps/300/LogIn?source=" + Uri.EscapeDataString(this.key) + "&version=" + Uri.EscapeDataString(this.version),
153 | new FormUrlEncodedContent(new[]
154 | {
155 | new KeyValuePair("userid", userName),
156 | new KeyValuePair("password", password),
157 | new KeyValuePair("source", this.key),
158 | new KeyValuePair("version", this.version)
159 | }));
160 |
161 | userName = password = null;
162 | var text = await response.Content.ReadAsStringAsync();
163 | var xml = XDocument.Parse(text);
164 |
165 | if (this.IsAuthenticated = xml.Root.Element("result").Value == "OK")
166 | {
167 | var node = xml.Root.Element("xml-log-in");
168 | this.UserID = node.Element("user-id").Value;
169 | this.sessionID = node.Element("session-id").Value;
170 | this.timeout = TimeSpan.FromMinutes(int.Parse(node.Element("timeout").Value));
171 | var associatedAccountID = node.Element("associated-account-id").Value;
172 | this.AvailableQuotes = new AvailableQuotes();
173 | this.AvailableQuotes.Add(Markets.NYSE, node.Element("nyse-quotes").Value == "realtime");
174 | this.AvailableQuotes.Add(Markets.NASDAQ, node.Element("nasdaq-quotes").Value == "realtime");
175 | this.AvailableQuotes.Add(Markets.OPRA, node.Element("opra-quotes").Value == "realtime");
176 | this.AvailableQuotes.Add(Markets.AMEX, node.Element("amex-quotes").Value == "realtime");
177 | this.AvailableQuotes.Add(Markets.CME, node.Element("cme-quotes").Value == "realtime");
178 | this.AvailableQuotes.Add(Markets.ICE, node.Element("ice-quotes").Value == "realtime");
179 | this.AvailableQuotes.Add(Markets.FOREX, node.Element("forex-quotes").Value == "realtime");
180 | this.UserAuthorizations = node.Element("authorizations").Elements().ToDictionary(x => x.Name.LocalName, x => x.Value == "true");
181 |
182 | switch (node.Element("exchange-status").Value)
183 | {
184 | case "non-professional":
185 | this.UserExchangeStatus = UserExchangeStatus.NonProfessional;
186 | break;
187 | case "professional":
188 | this.UserExchangeStatus = UserExchangeStatus.Professional;
189 | break;
190 | default:
191 | this.UserExchangeStatus = UserExchangeStatus.Unknown;
192 | break;
193 | }
194 |
195 | this.UserAccounts = node.Element("accounts").Elements().Select(n =>
196 | {
197 | var account = new UserAccount();
198 | account.AccountID = n.Element("account-id").Value;
199 | account.DisplayName = n.Element("display-name").Value;
200 | account.Description = n.Element("description").Value;
201 | account.IsAssociatedAccount = n.Element("associated-account").Value == "true";
202 | account.Company = n.Element("company").Value;
203 | account.Segment = n.Element("segment").Value;
204 | account.IsUnified = n.Element("unified").Value == "true";
205 | var prefNode = n.Element("preferences");
206 | account.Preferences.ExpressTrading = prefNode.Element("express-trading").Value == "true";
207 | account.Preferences.OptionDirectRouting = prefNode.Element("option-direct-routing").Value == "true";
208 | account.Preferences.StockDirectRouting = prefNode.Element("stock-direct-routing").Value == "true";
209 | account.Preferences.DefaultStockAction = prefNode.Element("default-stock-action").Value;
210 | account.Preferences.DefaultStockOrderType = prefNode.Element("default-stock-order-type").Value;
211 | account.Preferences.DefaultStockQuantity = prefNode.Element("default-stock-quantity").Value;
212 | account.Preferences.DefaultStockExpiration = prefNode.Element("default-stock-expiration").Value;
213 | account.Preferences.DefaultStockSpecialInstructions = prefNode.Element("default-stock-special-instructions").Value;
214 | account.Preferences.DefaultStockRouting = prefNode.Element("default-stock-routing").Value;
215 | account.Preferences.DefaultStockDisplaySize = prefNode.Element("default-stock-display-size").Value;
216 | account.Preferences.StockTaxLotMethod = prefNode.Element("stock-tax-lot-method").Value;
217 | account.Preferences.OptionTaxLotMethod = prefNode.Element("option-tax-lot-method").Value;
218 | account.Preferences.MutualFundTaxLotMethod = prefNode.Element("mutual-fund-tax-lot-method").Value;
219 | account.Preferences.DefaultAdvancedToolLaunch = prefNode.Element("default-advanced-tool-launch").Value;
220 | var authNode = n.Element("authorizations");
221 | account.Authorizations.Apex = authNode.Element("apex").Value == "true";
222 | account.Authorizations.Level2 = authNode.Element("level2").Value == "true";
223 | account.Authorizations.StockTrading = authNode.Element("stock-trading").Value == "true";
224 | account.Authorizations.MarginTrading = authNode.Element("margin-trading").Value == "true";
225 | account.Authorizations.StreamingNews = authNode.Element("streaming-news").Value == "true";
226 | switch (authNode.Element("option-trading").Value)
227 | {
228 | case "long": account.Authorizations.OptionTrading = OptionTradingType.Long; break;
229 | case "covered": account.Authorizations.OptionTrading = OptionTradingType.Covered; break;
230 | case "spread": account.Authorizations.OptionTrading = OptionTradingType.Spread; break;
231 | case "full": account.Authorizations.OptionTrading = OptionTradingType.Full; break;
232 | default: account.Authorizations.OptionTrading = OptionTradingType.None; break;
233 | }
234 |
235 | account.Authorizations.Streamer = authNode.Element("streamer").Value == "true";
236 | account.Authorizations.AdvancedMargin = authNode.Element("advanced-margin").Value == "true";
237 |
238 | if (account.AccountID == associatedAccountID)
239 | {
240 | this.UserAccount = account;
241 | }
242 |
243 | return account;
244 | }).ToList().AsReadOnly();
245 |
246 | return true;
247 | }
248 |
249 | this.Reset();
250 | return false;
251 | }
252 |
253 | public async Task LogOut()
254 | {
255 | var text = await this.http.GetStringAsync("/apps/100/LogOut?source=" + Uri.EscapeDataString(this.key));
256 | var xml = XDocument.Parse(text);
257 |
258 | if (xml.Root.Element("result").Value == "LoggedOut")
259 | {
260 | this.Reset();
261 | }
262 | }
263 |
264 | public async Task KeepAlive()
265 | {
266 | this.EnsureIsAuthenticated();
267 |
268 | var text = await this.http.GetStringAsync("/apps/KeepAlive?source=" + Uri.EscapeDataString(this.key));
269 |
270 | if (text != "LoggedOn")
271 | {
272 | this.Reset();
273 | }
274 | }
275 |
276 | public async Task GetStreamerInfo(string accountID = null)
277 | {
278 | this.EnsureIsAuthenticated();
279 |
280 | var url = "/apps/100/StreamerInfo?source=" + Uri.EscapeDataString(this.key) +
281 | (accountID == null ? string.Empty : "&accountid=" + Uri.EscapeDataString(accountID));
282 | var text = await this.http.GetStringAsync(url);
283 | var xml = XDocument.Parse(text);
284 |
285 | if (xml.Root.Element("result").Value == "OK")
286 | {
287 | using (var reader = xml.Root.Element("streamer-info").CreateReader())
288 | {
289 | this.streamerInfo = (StreamerInfo)new XmlSerializer(typeof(StreamerInfo)).Deserialize(reader);
290 | }
291 | }
292 | }
293 |
294 | public async Task> GetQuotes(params string[] symbols)
295 | {
296 | if (symbols == null)
297 | {
298 | throw new ArgumentNullException("symbols");
299 | }
300 |
301 | var quotes = new List