API функции для OANDA - Python
Формулировка задачи:
Может будет нужно тем кто занимается разработкой торговых роботов.
Если кто увидит серьезные огрехи, буду рад если поправите.
Python изучаю только пол года. Специально для этой темы.
Решение задачи: «API функции для OANDA»
textual
Листинг программы
def make_order(account_id, instrument, units, side, exp, price, takeprofit, stoploss, trailingstop, upperbound, lowerbound): try: time.sleep(1) #now = datetime.now() now = datetime.utcnow() expire = now + timedelta(hours=exp) expire = expire.isoformat('T') + "Z" params = urllib.urlencode({"instrument": instrument, "units": units, "side": side, "type": "marketIfTouched", "expiry": expire, "price": price, "takeProfit": takeprofit, "stopLoss": stoploss, "trailingStop": trailingstop, "upperBound": upperbound, "lowerBound": lowerbound}) conn = httplib.HTTPSConnection(url) conn.request("POST", "/v1/accounts/" + account_id + "/orders", params, headers) response = conn.getresponse() resptext = response.read() return resptext except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e) def make_limit_order(account_id, instrument, units, side, exp, price, takeprofit, stoploss, trailingstop): try: time.sleep(1) #now = datetime.now() now = datetime.utcnow() expire = now + timedelta(days=exp) expire = expire.isoformat('T') + "Z" params = urllib.urlencode({"instrument": instrument, "units": units, "side": side, "type": "limit", "expiry": expire, "price": price, "takeProfit": takeprofit, "stopLoss": stoploss, "trailingStop": trailingstop}) conn = httplib.HTTPSConnection(url) conn.request("POST", "/v1/accounts/" + account_id + "/orders", params, headers) response = conn.getresponse() resptext = response.read() return resptext except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e) def del_orders(account_id, id): try: time.sleep(0.5) params = urllib.urlencode({'accountId': account_id}) conn = httplib.HTTPSConnection(url) conn.request("DELETE", "/v1/accounts/" + account_id + "/orders/" + str(id), params, headers) response = conn.getresponse() resptext = response.read() if response.status == 403: print str(id) + ' not closed' elif response.status == 200: print str(id) + ' closed' return response.status except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e) def del_trades(account_id, id): try: time.sleep(0.5) params = urllib.urlencode({'accountId': account_id}) conn = httplib.HTTPSConnection(url) conn.request("DELETE", "/v1/accounts/" + account_id + "/trades/" + str(id), params, headers) response = conn.getresponse() resptext = response.read() if response.status == 403: print str(id) + ' not closed' elif response.status == 200: print str(id) + ' closed' return response.status except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e) def close_all_orders(account_id): try: time.sleep(1) for p in range(1): data = get_orders(account_id) data = json.loads(data) time.sleep(1) if 'orders' in data.keys(): if data['orders']: print 'Close all orders for account N ' + str(account_id) for key in data['orders']: # print key[u'instrument'] order_id = key['id'] stat = del_orders(account_id, order_id) except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e) def close_all_trades(account_id): try: time.sleep(1) for p in range(1): data = get_trades(account_id) data = json.loads(data) time.sleep(1) if 'trades' in data.keys(): if data['trades']: print 'Close all trades for account N ' + str(account_id) + ' trying ' + str(p + 1) for key in data['trades']: order_id = key['id'] stat = del_trades(account_id, order_id) except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e) def get_orders(account_id): try: time.sleep(1) params = urllib.urlencode({'accountId': account_id}) conn = httplib.HTTPSConnection(url) conn.request("GET", "/v1/accounts/" + account_id + "/orders", params, headers) response = conn.getresponse() resptext = response.read() return resptext except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e) def get_orders_instrument(account_id, instrument, count): # count максимальное количество, ордеров дефаулт 50 try: time.sleep(1) params = urllib.urlencode({'accountId': account_id}) conn = httplib.HTTPSConnection(url) # GET "https://api-fxtrade.oanda.com/v1/accounts/12345/orders?instrument=EUR_USD&count=2" conn.request("GET", "/v1/accounts/" + account_id + "/orders?instrument=" + instrument + '&count=' + str(count), params, headers) response = conn.getresponse() resptext = response.read() return resptext except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e) def get_trades(account_id): try: time.sleep(1) params = urllib.urlencode({'accountId': account_id}) conn = httplib.HTTPSConnection(url) conn.request("GET", "/v1/accounts/" + account_id + "/trades", params, headers) response = conn.getresponse() resptext = response.read() return resptext except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e) def get_trades_instrument(account_id, instrument): try: time.sleep(1) params = urllib.urlencode({'accountId': account_id}) conn = httplib.HTTPSConnection(url) conn.request("GET", "/v1/accounts/" + account_id + "/trades?instrument=" + instrument, params, headers) response = conn.getresponse() resptext = response.read() return resptext except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e) def rename_file(newnamefile): try: dir = os.getcwd() # Текущий каталог files = os.listdir(dir) # Список файлов в текущем каталоге filterfiles = filter(lambda x: x.startswith('balans'), files) # Фильтруем список по началу файла if not filterfiles: my_file = open('balans', 'w') namefile = my_file.name my_file.close() os.rename(namefile, newnamefile) else: namefile = filterfiles[0] os.rename(namefile, newnamefile) except IOError: print 'file busy' def get_balans(account_id): # запрос баланса по счету try: time.sleep(1) params = urllib.urlencode({'accountId': account_id}) conn = httplib.HTTPSConnection(url) conn.request("GET", "/v1/accounts/" + account_id, params, headers) response = conn.getresponse() resptext = response.read() if response.status == 200: data = json.loads(resptext) sredstva = float("%.2f" % data['balance']) + float("%.2f" % data['unrealizedPl']) marginused = float("%.2f" % data['marginUsed']) marginavail = float("%.2f" % data['marginAvail']) currency = data['accountCurrency'] return sredstva, marginused, marginavail, currency except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e) def get_spred(instrument, period): # 3600 - 1 hour # 43200 - 12 hour # 86400 - 1 day try: time.sleep(1) params = urllib.urlencode({}) conn = httplib.HTTPSConnection(url) conn.request("GET", "/labs/v1/spreads?instrument=" + instrument + "&period=" + period, params, headers) # (таблица периодов на сайте Oanda Forex Labs) response = conn.getresponse() resptext = response.read() # print resptext if response.status == 200: spred = 0 data = json.loads(resptext) sumspred = 0 nspred = 0 max_spred = 0 # максимальный min_spred = 999999 # минимальный avg_spred = 999999 # минимальный for key in data[u'max']: if max_spred < round(key[1], 2): max_spred = round(key[1], 2) for key in data[u'min']: if min_spred > round(key[1], 2): min_spred = round(key[1], 2) for key in data[u'avg']: if avg_spred > round(key[1], 2): avg_spred = round(key[1], 2) # print instrument, max_spred, min_spred, avg_spred return max_spred, min_spred, avg_spred else: return 0 except Exception as e: print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e)
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д