Skip to content

Commit 120a789

Browse files
authored
Add files via upload
0 parents  commit 120a789

File tree

85 files changed

+10697
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

85 files changed

+10697
-0
lines changed

Defi-BotAdditional/API.cs

+273
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
using TradingBot.Models;
2+
using Newtonsoft.Json;
3+
using System;
4+
using System.Linq;
5+
using System.Timers;
6+
using System.ComponentModel;
7+
8+
namespace TradingBot
9+
{
10+
public class API
11+
{
12+
/// <summary>
13+
/// The Bot takes a currency pair, checks previous trades for the pair
14+
/// Only the opposite of the last trade can be executed (maximising stock quantity technique)
15+
/// If the price has changed according to the desired percentage, a trade is executed.
16+
/// </summary>
17+
18+
// Do not change from here
19+
public static string baseUrl { get; set; } = "https://www.binance.com/api/";
20+
21+
/// <summary>
22+
/// Test Connectivity to Binance Rest API
23+
/// </summary>
24+
/// <returns>Boolean value (True/False) based on success</returns>
25+
public static bool Ping()
26+
{
27+
string apiRequestUrl = $"{baseUrl}v1/ping";
28+
29+
string response = Helper.webRequest(apiRequestUrl, "GET", null);
30+
if (response == "{}")
31+
return true;
32+
else
33+
return false;
34+
}
35+
36+
/// <summary>
37+
/// Test Connectivity to Binance Rest API and get current server time
38+
/// </summary>
39+
/// <returns>String of current time in milliseconds</returns>
40+
public static string Time()
41+
{
42+
string apiRequestUrl = $"{baseUrl}v1/time";
43+
44+
var response = Helper.webRequest(apiRequestUrl, "GET", null);
45+
return response;
46+
}
47+
48+
49+
/// <summary>
50+
/// Get prices for all symbols
51+
/// </summary>
52+
/// <returns>Current price for all symbols</returns>
53+
public static SymbolPrice[] GetAllPrices()
54+
{
55+
string apiRequestUrl = $"{baseUrl}v1/ticker/allPrices";
56+
57+
var response = Helper.webRequest(apiRequestUrl, "GET", null);
58+
var parsedResponse = JsonConvert.DeserializeObject<SymbolPrice[]>(response);
59+
60+
return parsedResponse;
61+
}
62+
63+
64+
/// <summary>
65+
/// Get the current price for the given symbol
66+
/// </summary>
67+
/// <param name="symbol">Asset symbol e.g.ETHBTC</param>
68+
/// <returns>The price. Double.</returns>
69+
public static double GetOnePrice(string symbol)
70+
{
71+
var symbolPrices = GetAllPrices();
72+
73+
SymbolPrice symbolPrice = (from sym in symbolPrices where sym.Symbol == symbol select sym).FirstOrDefault();
74+
if (symbolPrice == null)
75+
{
76+
throw new ApplicationException($"No symbol, {symbol}, exists");
77+
}
78+
79+
return symbolPrice.Price;
80+
}
81+
82+
83+
/// <summary>
84+
/// Get AccountInformation including all Asset Balances
85+
/// </summary>
86+
/// <param name="recvWindow">Interval (in milliseconds) in which the request must be processed within a certain number of milliseconds or be rejected by the server. Defaults to 5000 milliseconds</param>
87+
/// <returns>AccountInformation object including current asset balances</returns>
88+
public static AccountInformation GetAccountInformation()
89+
{
90+
string apiRequestUrl = $"{baseUrl}v3/account";
91+
92+
string query = $"";
93+
query = $"{query}&timestamp={Helper.getTimeStamp()}";
94+
95+
var signature = Helper.getSignature(Globals.SecretKey, query);
96+
query += "&signature=" + signature;
97+
98+
apiRequestUrl += "?" + query;
99+
100+
var response = Helper.webRequest(apiRequestUrl, "GET", Globals.ApiKey);
101+
102+
var parsedResponse = JsonConvert.DeserializeObject<AccountInformation>(response);
103+
return parsedResponse;
104+
}
105+
106+
/// <summary>
107+
/// Get your Open Orders for the given symbol
108+
/// </summary>
109+
/// <param name="symbol">Asset symbol e.g.ETHBTC</param>
110+
/// <returns>A list of Order objects with the order data</returns>
111+
public static Order[] GetOpenOrders(string symbol)
112+
{
113+
string apiRequestUrl = $"{baseUrl}v3/openOrders";
114+
115+
string query = $"symbol={symbol}";
116+
117+
query = $"{query}&timestamp={Helper.getTimeStamp()}";
118+
119+
var signature = Helper.getSignature(Globals.SecretKey, query);
120+
121+
query += "&signature=" + signature;
122+
123+
apiRequestUrl += "?" + query;
124+
125+
var response = Helper.webRequest(apiRequestUrl, "GET", Globals.ApiKey);
126+
var parsedResponse = JsonConvert.DeserializeObject<Order[]>(response);
127+
return parsedResponse;
128+
}
129+
130+
/// <summary>
131+
/// Get trades for a specific account and symbol
132+
/// </summary>
133+
/// <param name="symbol">Asset symbol e.g.ETHBTC</param>
134+
/// <returns>A list of Trades</returns>
135+
public static Trades[] GetMyTrades(string symbol)
136+
{
137+
string apiRequestUrl = $"{baseUrl}v3/myTrades";
138+
139+
string query = $"symbol={symbol}";
140+
141+
query = $"{query}&timestamp={Helper.getTimeStamp()}";
142+
143+
var signature = Helper.getSignature(Globals.SecretKey, query);
144+
query += "&signature=" + signature;
145+
146+
apiRequestUrl += "?" + query;
147+
148+
var response = Helper.webRequest(apiRequestUrl, "GET", Globals.ApiKey);
149+
var parsedResponse = JsonConvert.DeserializeObject<Trades[]>(response);
150+
return parsedResponse;
151+
}
152+
153+
/// <summary>
154+
/// Gets the last trade.
155+
/// </summary>
156+
/// <returns>The last trade. Trades object</returns>
157+
/// <param name="symbol">Symbol.</param>
158+
public static Trades GetLastTrade(string symbol)
159+
{
160+
var parsedResponse = GetMyTrades(symbol);
161+
162+
if (parsedResponse.Length != 0)
163+
return parsedResponse[parsedResponse.Length - 1];
164+
else
165+
return null;
166+
}
167+
168+
/// <summary>
169+
/// Places an order
170+
/// </summary>
171+
/// <returns>The order object</returns>
172+
/// <param name="symbol">Symbol of currencies to be traded, eg BCCETH</param>
173+
/// <param name="side">Order Side, BUY or SELL</param>
174+
/// <param name="type">Order Type, see Set.OrderTypes </param>
175+
/// <param name="timeInForce">Time order will be active for.</param>
176+
/// <param name="quantity">Amount to be traded</param>
177+
/// <param name="price">Price to be bought at.</param>
178+
179+
public static Order PlaceOrder(string symbol, OrderSides side, OrderTypes type, TimesInForce timeInForce, double quantity, double price)
180+
{
181+
string apiRequestUrl = "";
182+
183+
if (Globals.testCase == true)
184+
apiRequestUrl = $"{baseUrl}v3/order/test";
185+
else
186+
apiRequestUrl = $"{baseUrl}v3/order";
187+
188+
189+
string query = $"symbol={symbol}&side={side}&type={type}&timeInForce={timeInForce}&quantity={quantity}&price={price}";
190+
191+
query = $"{query}&timestamp={Helper.getTimeStamp()}";
192+
193+
var signature = Helper.getSignature(Globals.SecretKey, query);
194+
query += "&signature=" + signature;
195+
196+
apiRequestUrl += "?" + query;
197+
var response = Helper.webRequest(apiRequestUrl, "POST", Globals.ApiKey);
198+
199+
var parsedResponse = JsonConvert.DeserializeObject<Order>(response);
200+
return parsedResponse;
201+
}
202+
203+
/// <summary>
204+
/// Places a market order. (Order at the current market price, needs no price or timeInForce params).
205+
/// </summary>
206+
/// <returns>The order object</returns>
207+
/// <param name="symbol">Symbol of currencies to be traded, eg BCCETH.</param>
208+
/// <param name="side">Order Side, BUY or SELL.</param>
209+
/// <param name="quantity">Amount to be traded.</param>
210+
211+
public static Order PlaceMarketOrder(string symbol, OrderSides side, double quantity)
212+
{
213+
string apiRequestUrl = "";
214+
215+
if (Globals.testCase == true)
216+
apiRequestUrl = $"{baseUrl}v3/order/test";
217+
else
218+
apiRequestUrl = $"{baseUrl}v3/order";
219+
220+
string query = $"symbol={symbol}&side={side}&type={OrderTypes.MARKET}&quantity={quantity}";
221+
query = $"{query}&timestamp={Helper.getTimeStamp()}";
222+
223+
var signature = Helper.getSignature(Globals.SecretKey, query);
224+
query += "&signature=" + signature;
225+
226+
apiRequestUrl += "?" + query;
227+
var response = Helper.webRequest(apiRequestUrl, "POST", Globals.ApiKey);
228+
229+
var parsedResponse = JsonConvert.DeserializeObject<Order>(response);
230+
return parsedResponse;
231+
}
232+
233+
234+
/***********
235+
236+
//Ping
237+
var pingTest = Ping();
238+
239+
//Time
240+
var timeTest = Time();
241+
242+
///Get your account Info
243+
//Returned as object, see Set.cs to parse through it
244+
var accountInfo = GetAccountInformation();
245+
246+
///Get prices of all available currency pairs
247+
//Returned as list of objects, see Set.cs or GetOnePrice() function to parse through it
248+
var allPrices = GetAllPrices();
249+
250+
///Get prices of a specific currency pair/symbol
251+
var onePrice = GetOnePrice("BCCETH");
252+
253+
///Get all open orders on your account
254+
var openOrders = GetOpenOrders("BCCETH");
255+
256+
///Get your trade history related to a specific currency pair/symbol
257+
//Returned as list of objects, see Set.cs or GetLastTrade() function to parse through it
258+
var trades = GetMyTrades("XRPETH");
259+
260+
///Get your last trade of a specific currency pair/symbol
261+
//Returned as object, see Set.cs to parse through it
262+
var lastTrade = GetLastTrade("XRPETH");
263+
264+
///Place any kind of acccepted order, set to "test" phase as not in use.
265+
//var order = PlaceOrder("BCCETH", OrderSides.SELL, OrderTypes.MARKET, TimesInForce.GTC, 0.01, 2.09);
266+
267+
///Place a Market order
268+
var marketOrder = PlaceMarketOrder("BCCETH", OrderSides.SELL, 0.01);
269+
270+
**********/
271+
272+
}
273+
}

Defi-BotAdditional/Algorithm.cs

+101
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+

2+
using TradingBot.Models;
3+
using System;
4+
using System.Linq;
5+
6+
7+
8+
namespace TradingBot
9+
{
10+
public class Algorithm
11+
{
12+
13+
14+
public static void Bot()
15+
{
16+
string symbol = Globals.C1 + Globals.C2;
17+
18+
//GetAccountInformation
19+
var accInfo = API.GetAccountInformation();
20+
21+
//Check account funds for both currencies
22+
AssetBalance Currency1 = (from coin in accInfo.Balances where coin.Asset == Globals.C1 select coin).FirstOrDefault();
23+
var freeCurrency1 = Currency1.Free;
24+
25+
AssetBalance Currency2 = (from coin in accInfo.Balances where coin.Asset == Globals.C2 select coin).FirstOrDefault();
26+
var freeCurrency2 = Currency2.Free;
27+
28+
//Get Price of last BCCBTC trade
29+
var lastTrade = API.GetLastTrade(symbol);
30+
var lastTradePrice = 0.0;
31+
var lastTradeSide = OrderSides.SELL; //if lastTrade == null, this means buy Currency1
32+
33+
34+
//get price and OrderSide of last trade (if any)
35+
if (lastTrade != null)
36+
{
37+
lastTradePrice = lastTrade.Price;
38+
39+
if (lastTrade.isBuyer == true)
40+
lastTradeSide = OrderSides.BUY;
41+
else
42+
lastTradeSide = OrderSides.SELL;
43+
}
44+
45+
//Check current price
46+
var currentPrice = API.GetOnePrice(symbol);
47+
48+
//Calculate actual price change percentage
49+
var priceChange = 100 * (currentPrice - lastTradePrice) / currentPrice;
50+
51+
Console.WriteLine("Current Price is " + currentPrice);
52+
Console.WriteLine("Price Change is " + priceChange);
53+
54+
//Create Order
55+
Order marketOrder = null;
56+
57+
if (lastTradeSide == OrderSides.BUY && priceChange > Globals.percentageChange)
58+
{
59+
//if last order was buy, and price has increased
60+
//sell C1
61+
marketOrder = API.PlaceMarketOrder(symbol, OrderSides.SELL, Globals.quatityPerTrade);
62+
63+
}
64+
else if (lastTradeSide == OrderSides.SELL && priceChange < -Globals.percentageChange)
65+
{
66+
//if last order was sell, and price has decreased
67+
//buy C1
68+
marketOrder = API.PlaceMarketOrder(symbol, OrderSides.BUY, Globals.quatityPerTrade);
69+
}
70+
71+
72+
//Statements
73+
if (marketOrder == null)
74+
{
75+
Console.WriteLine("No trade was made.");
76+
var actualLastTrade = API.GetLastTrade(symbol);
77+
if (actualLastTrade.isBuyer == true)
78+
{
79+
Console.WriteLine(actualLastTrade.Qty + " of " + Globals.C1 + " was previously bought for " + actualLastTrade.Price);
80+
}
81+
else if (actualLastTrade.isBuyer == false)
82+
{
83+
Console.WriteLine(actualLastTrade.Qty + " of " + Globals.C1 + " was previously sold for " + actualLastTrade.Price);
84+
}
85+
}
86+
else
87+
{
88+
var newLastTrade = API.GetLastTrade(symbol);
89+
if (marketOrder.Side == OrderSides.BUY)
90+
{
91+
Console.WriteLine(newLastTrade.Qty + " of " + Globals.C1 + " was bought for " + newLastTrade.Price);
92+
}
93+
else if (marketOrder.Side == OrderSides.SELL)
94+
{
95+
Console.WriteLine(newLastTrade.Qty + " of " + Globals.C1 + " was sold for " + newLastTrade.Price);
96+
}
97+
}
98+
99+
}
100+
}
101+
}

0 commit comments

Comments
 (0)