diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000..e7d981cc Binary files /dev/null and b/.DS_Store differ diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 1b31956e..00000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Mateusz Magda - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index 6661a2ed..00000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# MSiD -System Analysis and Decision Support Methods diff --git a/l1 b/l1 deleted file mode 100644 index 76140c26..00000000 --- a/l1 +++ /dev/null @@ -1,6 +0,0 @@ -1) Sforkować repozytorium na Wasze konto -2) Przejść na Waszego forka -3) Ściągnąć wasze repo na dysk i powiązać z repozytorium zdalnym (remote) -4) Napisać sortowanie liczb w dwoma znanymi Wam metodami(język jak ustalaliśmy na laboratorium). Starajcie się napisać funkcje w sposób zwarty, bez żadnych komentarzy czy śmieci w kodzie, w sposób optymalny, z użyciem najlepszych, znanych Wam struktur danych i metod przeglądania ich. Tworząc rozwiązania pracujcie z gitem- dodawajcie na stage, twórzcie commity. Pracujcie na branchu, stwórzcie na potrzeby zadania brancha i nazwijcie go np SortingMethods -5) wypchnijcie zmiany lokalne na repo zdalne -6) utwórzcie merge requesta z brancha SortingMethods do brancha master mojego repo (oryginalnego repo, z którego powstał fork) i nazwijcie go L1. diff --git a/l2 b/l2 deleted file mode 100644 index 89f8155e..00000000 --- a/l2 +++ /dev/null @@ -1,2 +0,0 @@ -Rozwinięcie zadania z listy 1. Do wybranych algorytmów sortowania z listy 1 dobrać 2 inne i zaimplementować je. Napisać funkcję służącą do porównywania algorytmów sortowania, która przyjmuje funkcję i mierzy czas / czasy sortowania. Za jej pomocą porównać algorytmy sortowania. -Pracujcie z gitem, proponuję zrobić osobnego brancha, nazwać go SortingComparison i w nim pracować. Na koniec - jak poprzednio - wysłać na repozytorium remote i wystawić pull request do mojego repozytorium, z którego pierwotnie forkowaliście. Nie akceptuję plików dodanych do gita przez „upload”. Wysyłanie plików na wasze remote repo odbywa się poprzez git push. diff --git a/l3 b/l3 deleted file mode 100644 index ef45d519..00000000 --- a/l3 +++ /dev/null @@ -1,10 +0,0 @@ -1. Znaleźć w internecie API ze źródłem danych o rynkach finansowych, przykłady: -https://bittrex.github.io/api/v1-1 -https://bitbay.net/en/public-api -https://www.tradingview.com/rest-api-spec/#section/Authentication - -Stworzyć prostą funkcję, która łączy się z danym API, pobiera listę ofert kupna oraz listę ofert sprzedaży i printuje do konsoli. (5pkt) - -2. Odświeża (pobiera) ją co 5 sekund, następnie kalkuluje różnicę pomiędzy kupnem a sprzedażą i podaje ją w procentach (np. 1 - (cena sprzedaży - cena kupna) / cena kupna) -(5pkt) - diff --git a/l4 b/l4 deleted file mode 100644 index 81d6f4e0..00000000 --- a/l4 +++ /dev/null @@ -1,21 +0,0 @@ -1. Rozszerzyć źródła danych do 4 API, porównywać 4 pary zasobów (np BTC-USD i BTC-LTC, ...) i ich ceny kupna-sprzedaży na przestrzeni czasu. -Tym razem na podstawie cen kupna / sprzedaży z pośród poszerzonej bazy macie za zadanie na bieżąco wyliczać czy występuje możliwość arbitrażu. -Pod pojęciem arbitrażu kryje się przeprowadzanie dwóch transakcji przeciwstawnych na dwóch różnych giełdach. -Pisząc bardziej zrozumiale - sprawdzacie czy da się kupić taniej w miejscu 1 i sprzedać drożej w miejscu 2. -Pamiętajcie, że chcąc kupić w miejscu X musicie patrzeć na oferty sprzedaży w miejscu X, a chcąc sprzedać w miejscu Y musicie patrzeć na oferty kupna w miejscu Y. -Program, jak poprzedni, ma się automatycznie odświeżać. Wynikiem jego działania ma być print informacji(przykładowo): -Na giełdzie X można kupić 0.1 BTC za USD po kursie 6800 i sprzedać na giełdzie Y po kursie 6900, zyskując 10USD. -(2.5pkt) - -2. Przy kalkulacjach wziąć pod uwagę prowizję kupna sprzedaży na giełdach. Pamiętajcie, żeby brać tu pod uwagę prowizję podawaną typu Taker (tę wyższą), bo bierzecie ofertę cudzą, nie składacie własnej i nie czekacie aż ktoś się na nią zdecyduje. -(1pkt) - -3. Założyć wirtualny budżet rozpatrywanych zasobów i w czasie rzeczywistym liczyć ile potencjalnie zarobilibyście na Waszych operacjach. Nie musicie brać pod uwagę opóźnienia w przesyłaniu środków pomiędzy giełdami. -Dla uproszczenia identyfikacji rozpatrywanego systemu zakładamy że dysponujemy środkami w każdej z rozpatrywanych walut na każdej z rozpatrywanych giełd. -(2.5pkt) - -4. Stworzyć własny algorytm spekulacyjny (agenta decyzyjnego) polegający na zmienności rynku. Znajdźcie pary, które charakteryzują się stosunkowo dużymi wahaniami oscylacyjnymi (po polsku- "wykres przez długi czas idzie w bok, bez wyraźnego trendu spadku lub wzrostu, ale z dużymi wahaniami"). -Po znalezieniu takich par stwórzcie algorytm który na podstawie historii stara się nauczyć gdzie warto kupować(gdzie znajduje się minimum lokalne) i gdzie warto sprzedawać (maksimum lokalne). -Przeprowadźcie symulację Waszego algorytmu, uwzględniając wolumen (ilość), odejmując koszty prowizji. Dla uproszczenia rzeczywistości Wasz algorytm ma działać w ramach jednej giełdy- bez transakcji arbitrażu pomiędzy giełdami. -Kupuje- sam decyduje co ile i za ile, sprzedaje- sam decyduje kiedy. Oczekiwanym rezultatem jest printowanie podejmowanych działań i ich wyników(czy udało się zarobić, czy algorytm sprzedał ze stratą). -(4pkt) diff --git a/l4.py b/l4.py new file mode 100644 index 00000000..98b7808a --- /dev/null +++ b/l4.py @@ -0,0 +1,219 @@ +import json +import time +import requests +import string +from operator import itemgetter + +market_names = ['bitstamp.net','cex.io','bitbay.net','bittrex.com'] + +trade_pairs = ["BTCPLN","BTCUSD","ETHEUR","ETHBTC"] + +fees = {'bitstamp.net': 0.005,'cex.io': 0.0025, 'bitbay.net': 0.0043,'bittrex.com':0.002} + + #bid to kupno, ask to sprzedaz pierwszej z walut w parze +def accept_bid(wallet, trade_pair, rate, ammount, fee): + wallet[trade_pair[3:]] = wallet[trade_pair[3:]] - (ammount * 1 / rate) + wallet[trade_pair[:3]] = wallet[trade_pair[:3]] + (ammount - ammount * fee) + +def accept_ask(wallet, trade_pair, rate, ammount, fee): + wallet[trade_pair[3:]] = wallet[trade_pair[3:]] + (ammount * rate - ammount * rate * fee) + wallet[trade_pair[:3]] = wallet[trade_pair[:3]] - ammount + + + #operation_name np. "ticker" albo "orderbook" - zwraca odpowiedni slownik otrzymany od API +def get_resources(operation_name, market_name, trade_pair): + + url = "" + + if market_name == 'bitbay.net': + url = 'https://bitbay.net/API/Public/' + trade_pair + '/' + operation_name + '.json' + + if market_name == 'bittrex.com': + url = 'https://api.bittrex.com/api/v1.1/public/get' + operation_name + '?market=' + trade_pair[:3]+ '-' + trade_pair[3:] + if operation_name == "orderbook": + url = url + "&type=both" + + if market_name == 'bitstamp.net': + url = 'https://www.bitstamp.net/api/v2/' + if operation_name == "orderbook": + url = url + "order_book" + else: + url = url + operation_name + url = url + '/' + trade_pair[:3].lower() + trade_pair[3:].lower() + '/' + + if market_name == 'cex.io': + url = 'https://cex.io/api/' + if operation_name == "orderbook": + url = url + "order_book" + else: + url = url + operation_name + url = url +'/' + trade_pair[:3]+ "/" + trade_pair[3:] + if url == "": + print("URL failed") + return {} + + try: + recieved_dict = json.loads(str(requests.get(url).json()).replace('\'', '\"')) + except ValueError as e: + return {} + #print(str(recieved_dict)) + return recieved_dict + + +def best_offers(market, trade_pair): + resource_dict = get_resources("ticker",market,trade_pair) + if 'bid' not in resource_dict.keys(): + return {} + amounts_pair = ammounts(market, trade_pair) + return{"ask":resource_dict['ask'],"ask_amount":amounts_pair[0],"bid":resource_dict['bid'],"bid_amount":amounts_pair[1]} + +def sort_offers(list_to_sort,reverseOrder=False): + sorted_list = sorted(list_to_sort,key=itemgetter(0),reverse=reverseOrder) + return sorted_list + + +def ammounts(market, trade_pair): #Zwraca pare - (ilosc w najlepszym asku,ilosc w najlepszym bidzie) + + resource_dict = get_resources("orderbook",market, trade_pair) + if 'asks' not in resource_dict.keys(): + return (-1,-1) + sorted_asks = sort_offers(resource_dict['asks']) + sorted_bids = sort_offers(resource_dict['bids'],reverseOrder=True) + return (sorted_asks[0][1],sorted_bids[0][1]) + + +def arbitrage(market1, market2, trade_pair): #zwraca trojke(x,y,z, ilosc) x -> -1 jesli + #niemozliwy arbitraz oraz 1 lub 2 mowiace + market1_values = best_offers(market1, trade_pair) # w ktora strone zadziala arbitraz (gdzie kupic) + market2_values = best_offers(market2, trade_pair) #y i z to odpowiednio ceny kupna i sprzedazy + if market1_values == {} or market2_values == {}: # ilosc to ilosc waluty jaka mozna zamienic + return (-1,0,0,0) + fee1 = fees[market1] + fee2 = fees[market2] +# print(str(market1_values['bid'])) + sell1 = float(market1_values['bid'])-float(market1_values['bid'])*fee1 + sell2 = float(market2_values['bid'])-float(market2_values['bid'])*fee2 + buy1 = float(market1_values['ask'])+float(market1_values['ask'])*fee1 + buy2 = float(market2_values['ask'])+float(market2_values['ask'])*fee2 + if buy1 < sell2: + return (1,buy1,sell2,min(float(market1_values['bid_amount']),float(market2_values['ask_amount']))) + if buy2 < sell1: + return (2,buy2,sell1,min(float(market1_values['ask_amount']),float(market2_values['bid_amount']))) + return (-1,0,0,0) + + +def print_arbitrage(arbitrage_tuple, market1, market2, pair): + if arbitrage_tuple[0] == 1: + source_market = market1 + destination_market = market2 + else: + source_market = market2 + destination_market = market1 + print("Arbitrage possible with fees included! Buy on market " + source_market + " " + str(arbitrage_tuple[3]) + " of " + str(pair[:3]) + " with ") + print(pair[3:] + " with price " + str(arbitrage_tuple[1]) + " and sell on market " + destination_market + " with price " + str(arbitrage_tuple[2])) + +def run_arbitrage_checker(): + while True: + for x in range(len(market_names)): + for y in range(x+1,len(market_names)): + for pair in trade_pairs: + arb = arbitrage(market_names[x],market_names[y],pair) + if arb[0] != -1: + print_arbitrage(arb,market_names[x],market_names[y],pair) + time.sleep(0.5) + + + +# Z4 + +#Najpierw znalezc pare z duzymi odchyleniami +#Dzialac to bedzie na tej zasadzie ze liczy srednia i liczy laczne odchylenia od tej sredniej +# +#Po znalezieniu takiej pary +#Pozniej, jezeli od 10 iteracji lub wiecej cena best aska spada to czekamy az zacznie rosnac (minimum lokalne) i kupujemy +#Jednoczesnie, jezeli od 10 iteracji lub wiecej cena best bida rosnie to czekamy az zacznie spadac (maximum lokalne) i sprzedajemy +#Jednoczesnie drugim wymogiem jest ze wartosci musza byc odpowiednoi minimum i maximum na przedziale ostatnich 1000 ofert + +def find_pair_with_biggest_deviation(market,iterations): + #Algorytm dziala w obrebie 100 iteracji + asks = {} + bids = {} + for pair in trade_pairs: + asks[pair] = [] + bids[pair] = [] + for i in range(iterations): + for pair in trade_pairs: + resources_dict = best_offers(market,pair) + asks[pair].append(resources_dict['ask']) + bids[pair].append(resources_dict['bid']) + time.sleep(0.1) + best_pair = trade_pairs[0] + biggest_deviation_sum = 0.0 + for pair in trade_pairs: + average_ask = sum(asks[pair]) / len(asks[pair]) + average_bid= sum(bids[pair]) / len(bids[pair]) + sum_of_deviations_asks = 0.0 + sum_of_deviations_bids = 0.0 + for ask in asks[pair]: + sum_of_deviations_asks += abs(ask - average_ask) + for bid in bids[pair]: + sum_of_deviations_bids += abs(bid - average_bid) + if sum_of_deviations_asks + sum_of_deviations_bids > biggest_deviation_sum: + biggest_deviation_sum = sum_of_deviations_asks + sum_of_deviations_bids + best_pair = pair + return pair + + #Step - czas w sekundach miedzy iteracjami +def run_speculation_agent(wallet, market,iterations_to_specify_deviated_pair,iterations_to_start,step): + pair = find_pair_with_biggest_deviation(market,iterations_to_specify_deviated_pair) + print("Chosen pair with biggest deviation! The chosen pair is " + pair) + asks = [] + bids = [] + for step in range(iterations_to_start): + resources_dict = best_offers(market,pair) + asks.append(resources_dict['ask']) + bids.append(resources_dict['bid']) + last_iteration_ask = asks[len(asks)-1] + last_iteration_bid = bids[len(bids)-1] + times_ask_is_lowering = 0 + times_bid_is_increasing = 0 + while True: + resources_dict = best_offers(market,pair) + ask = resources_dict['ask'] + bid = resources_dict['bid'] + asks.append(ask) + bids.append(bid) + + if times_ask_is_lowering > 10: + if ask < last_iteration_ask and ask == min(asks[-1000:]): + accept_ask(wallet, pair, ask, min(wallet[pair[:3]],resources_dict['ask_amount']) , fees[market]) + print("Minimum of asks found! Decision made - accepting ask for price: " + ask + " ammount possible to buy: " + min(wallet[pair[:3]],resources_dict['ask_ammount'])) + print("Wallet state after transaction: " + str(wallet)) + + if times_bid_is_increasing > 10: + if bid > last_iteration_bid and bid == max(bids[-1000:]): + accept_bid(wallet, pair, bid, min(wallet[pair[3:]],resources_dict['bid_amount']) , fees[market]) + + print("Maximum of bids found! Decision made - accepting bid for price: " + bid + " ammount possible to buy: " + min(wallet[pair[3:]],resources_dict['bid_ammount'])) + print("Wallet state after transaction: " + str(wallet)) + if ask < last_iteration_ask: + times_ask_is_lowering += 1 + else: + times_ask_is_lowering = 0 + + if bid > last_iteration_bid: + times_bid_is_increasing += 1 + else: + times_bid_is_increasing = 0 + + last_iteration_ask = ask + last_iteration_bid = bid + + time.sleep(step) + +def main(): + wallet = {"ETH": 100.0, "USD": 100.0, "LTC": 100.0, "BTC": 100.0, "EUR": 100.0,"PLN" : 100.0} +# run_arbitrage_checker() + run_speculation_agent(wallet,"bitbay.net",10,10,0.1) + +main() \ No newline at end of file diff --git a/searching_methods/src/algorithms/bubble.java b/searching_methods/src/algorithms/bubble.java deleted file mode 100644 index bd80ecee..00000000 --- a/searching_methods/src/algorithms/bubble.java +++ /dev/null @@ -1,28 +0,0 @@ -package algorithms; - -import java.util.ArrayList; - -public class bubble extends sorting_algorithm -{ - public bubble() - { - super(); - } - - public bubble(ArrayList source) - { - super(source); - } - - @Override - public ArrayList sort_out() - { - int size = to_be_sorted.size(); - for(int i = 0; i < size; i++) - for(int j = 0; j < size - 1; j++) - if(to_be_sorted.get(j) > to_be_sorted.get(j + 1)) - swap(j, j + 1); - - return to_be_sorted; - } -} diff --git a/searching_methods/src/algorithms/insert.java b/searching_methods/src/algorithms/insert.java deleted file mode 100644 index 4e81792c..00000000 --- a/searching_methods/src/algorithms/insert.java +++ /dev/null @@ -1,37 +0,0 @@ -package algorithms; - -import java.util.ArrayList; - -public class insert extends sorting_algorithm -{ - public insert() - { - super(); - } - - public insert(ArrayList to_be_sorted) - { - super(to_be_sorted); - } - - @Override - public ArrayList sort_out() - { - int size = to_be_sorted.size(); - for (int i = 1; i < size; i++) - { - int key = to_be_sorted.get(i); - int j = i - 1; - - while (j >= 0 && to_be_sorted.get(j) > key) - { - to_be_sorted.set(j + 1, to_be_sorted.get(j)); - j = j - 1; - } - - to_be_sorted.set(j + 1, key); - } - - return to_be_sorted; - } -} diff --git a/searching_methods/src/algorithms/quick.java b/searching_methods/src/algorithms/quick.java deleted file mode 100644 index b1b7ea75..00000000 --- a/searching_methods/src/algorithms/quick.java +++ /dev/null @@ -1,44 +0,0 @@ -package algorithms; - -import java.util.ArrayList; - -public class quick extends sorting_algorithm -{ - public quick() - { - super(); - } - - public quick(ArrayList source) - { - super(source); - } - - @Override - public ArrayList sort_out() - { - sorting_procedure(0, to_be_sorted.size() - 1); - - return to_be_sorted; - } - - void sorting_procedure(int low, int high) - { - int pivot = to_be_sorted.get((low + high) / 2); - int i = low, j = high; - - do{ - while (to_be_sorted.get(i) < pivot) i++; - while (to_be_sorted.get(j) > pivot) j--; - if (i <= j) - { - swap(i, j); - i++; - j--; - } - } while (i <= j); - - if (j > low) sorting_procedure(low, j); - if (i < high) sorting_procedure(i, high); - } -} diff --git a/searching_methods/src/algorithms/select.java b/searching_methods/src/algorithms/select.java deleted file mode 100644 index 2b5ac8f9..00000000 --- a/searching_methods/src/algorithms/select.java +++ /dev/null @@ -1,38 +0,0 @@ -package algorithms; - -import java.util.ArrayList; - -public class select extends sorting_algorithm -{ - public select() - { - super(); - } - - public select(ArrayList source) - { - super(source); - } - - @Override - public ArrayList sort_out() - { - for (int i = to_be_sorted.size(); i >= 2; i--) - { - int max = max_element_index(i); - if (max != i - 1) - swap(i - 1, max); - } - - return to_be_sorted; - } - - int max_element_index(int limit) - { - int max = 0; - for (int i = 1; i < limit; i++) - if (to_be_sorted.get(i) > to_be_sorted.get(max)) - max = i; - return max; - } -} diff --git a/searching_methods/src/algorithms/sorting_algorithm.java b/searching_methods/src/algorithms/sorting_algorithm.java deleted file mode 100644 index 34f95675..00000000 --- a/searching_methods/src/algorithms/sorting_algorithm.java +++ /dev/null @@ -1,38 +0,0 @@ -package algorithms; - -import java.util.ArrayList; - -public abstract class sorting_algorithm -{ - ArrayList to_be_sorted; - - sorting_algorithm() - { - this.to_be_sorted = new ArrayList<>(); - } - - sorting_algorithm(ArrayList to_be_sorted) - { - this.to_be_sorted = new ArrayList<>(to_be_sorted.size()); - this.to_be_sorted.addAll(to_be_sorted); - } - public void change_source(ArrayList to_be_sorted) - { - this.to_be_sorted = new ArrayList<>(to_be_sorted.size()); - this.to_be_sorted.addAll(to_be_sorted); - } - - void swap(int index_1, int index_2) - { - int temp = to_be_sorted.get(index_1); - to_be_sorted.set(index_1, to_be_sorted.get(index_2)); - to_be_sorted.set(index_2, temp); - } - public ArrayList sort_out(ArrayList to_be_sorted) - { - change_source(to_be_sorted); - return sort_out(); - } - - abstract public ArrayList sort_out(); -} diff --git a/searching_methods/src/testing/main.java b/searching_methods/src/testing/main.java deleted file mode 100644 index 14206c2f..00000000 --- a/searching_methods/src/testing/main.java +++ /dev/null @@ -1,56 +0,0 @@ -package testing; - -import algorithms.*; - -import java.util.ArrayList; -import java.util.Random; - -public class main -{ - static Random seed = new Random(); - static ArrayList randomize_new_array(int size) - { - ArrayList new_array = new ArrayList(size); - for (int i = 0; i < size; i++) new_array.add(seed.nextInt()); - return new_array; - } - - static void print_array_out(ArrayList array) - { - for (Integer integer : array) - System.out.println(integer); - - System.out.println("🧶-----------------------🐈"); - } - - static float estimate_sorting_duration(sorting_algorithm algorithm, ArrayList> arrays) - { - if(arrays.isEmpty()) return -1; - - long start_time = System.currentTimeMillis(); - - for (ArrayList array : arrays) - algorithm.sort_out(array); - - return (float)(System.currentTimeMillis() - start_time) / arrays.size(); - } - - public static void main(String args[]) - { - int number_of_tests = 10, test_size = 10000; - ArrayList> set_of_tests = new ArrayList>(number_of_tests); - - for (int i = 0; i < number_of_tests; i++) - set_of_tests.add(randomize_new_array(test_size)); - - bubble bubble_sort = new bubble(); - insert insert_sort = new insert(); - select select_sort = new select(); - quick quick_sort = new quick(); - - System.out.println(estimate_sorting_duration(bubble_sort, set_of_tests) + " [ms]"); - System.out.println(estimate_sorting_duration(insert_sort, set_of_tests) + " [ms]"); - System.out.println(estimate_sorting_duration(select_sort, set_of_tests) + " [ms]"); - System.out.println(estimate_sorting_duration(quick_sort, set_of_tests) + " [ms]"); - } -}