API функции для OANDA - Python

Формулировка задачи:

Может будет нужно тем кто занимается разработкой торговых роботов. Если кто увидит серьезные огрехи, буду рад если поправите. Python изучаю только пол года. Специально для этой темы.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import openpyxl
import httplib
import urllib
import urllib2
import json
import datetime
from datetime import datetime, timedelta, date, time
import os
import msvcrt
import time
import shutil  # копирование
import ssl
import requests
import sys
ssl._create_default_https_context = ssl._create_unverified_context  # убирает ошибку [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)
#в”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв–’в–“в–‘в–€в•ђв–Њв–* в–ђв‰Ўв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђ
url = "api-fxtrade.oanda.com"
access_token = "Bearer 099935ef71b8203fxxxxxxxxxxxxxxxxdbd7b30dbdb3019d673671020752f"
headers = {'Authorization': access_token, "Content-Type": "application/x-www-form-urlencoded"}
accounts = []
account_id = ""
instrument = ""
sentSMS = True
 
#в”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђ
 
print u'в–€' * 11 + '  Oanda API script started  ' + u'в–€' * 11
 
#в”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђ
mypairs = ['AUD_HKD', 'AUD_JPY', 'AUD_USD', 'CAD_HKD', 'CAD_JPY', 'CHF_JPY', 'EUR_AUD', 'EUR_GBP', 'EUR_HKD', 'EUR_JPY',
           'EUR_USD', 'GBP_AUD', 'GBP_CAD', 'GBP_CHF', 'GBP_HKD', 'GBP_JPY', 'GBP_NZD', 'GBP_USD', 'NZD_HKD', 'NZD_JPY',
           'NZD_USD', 'USD_CAD', 'USD_JPY']
#в”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђ
data_pair = dict((x, [0] * 2) for x in mypairs)  # генерация словаря
#в”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђ
p_prices = {'USD': {'USD': 1.00000,
                    'CAD': 0.76620,
                    'CHF': 1.01360,
                    'JPY': 0.93000,
                    'AUD': 0.74820,
                    'GBP': 1.31650,
                    'NZD': 0.70230,
                    'EUR': 1.10190,
                    'HKD': 0.12900},
            'CHF': {'CHF': 1.00000,
                    'CAD': 0.76090,
                    'USD': 0.98230,
                    'JPY': 0.93000,
                    'AUD': 0.74980,
                    'GBP': 1.31030,
                    'NZD': 0.70240,
                    'EUR': 1.10190,
                    'HKD': 0.12710}}
 
#в”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђв”Ђ
 
 
def get_currency_rates(currency):
    params = urllib.urlencode({'number': '1'})
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0)'}
    dictfull = False
    while True:
        try:
            print 'в•ђ' * 30
            print 'GETTING CURRENCY RATES for ' + currency
            print 'в•ђ' * 30
            for key in sorted(p_prices[currency]):
                pairforprice = key + '-' + currency
                time.sleep(0.5)
                url = 'https://www.mataf.net/ru/currency/converter-' + pairforprice
                request = urllib2.Request(url, params, headers)
                resptext = urllib2.urlopen(request).read()
                line = resptext
                line = line.strip()
                linekurs = line.find('<title>')
                startkurs = line.find('=', linekurs)
                endkurs = line.find(')</title>', linekurs)
                kurs = float(line[startkurs + 1:endkurs])
                if 'JPY' in key:
                    kurs *= 100
                kurs = "%.4f" % kurs
                print pairforprice, kurs
                p_prices[currency][key] = float(kurs)
            dictfull = True
        except Exception as e:
            print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e)
        if dictfull:
            return datetime.utcnow()
        else:
            print 'CURRENCY RATES DATA PROBLEM!'
            time.sleep(60)
 
 
def close_position(account_id, instrument):
    try:
        time.sleep(0.5)
        params = urllib.urlencode({'accountId': account_id})
        conn = httplib.HTTPSConnection(url)
        conn.request("DELETE", "/v1/accounts/" + account_id + "/positions/" + instrument, params, headers)
        response = conn.getresponse()
        resptext = response.read()
        if response.status == 403:
            print instrument + ' position not closed'
        elif response.status == 200:
            print instrument + ' position 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 get_position(account_id, instrument):
    try:
        time.sleep(1)
        params = urllib.urlencode({})
        conn = httplib.HTTPSConnection(url)
        # GET /v1/accounts/:account_id/positions/:instrument
        conn.request("GET", "/v1/accounts/" + account_id +
                     "/positions/" + 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 get_instrument(account_id, instrument):
    try:
        time.sleep(1)
        params = urllib.urlencode({})
        conn = httplib.HTTPSConnection(url)
        conn.request("GET", "/v1/instruments?accountId=" + account_id +
                     "&instruments=" + instrument +
                     "&fields=instrument%2CdisplayName%2Cpip%2CmarginRate%2Chalted", 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_all_instrument(account_id):
    try:
        time.sleep(1)
        params = urllib.urlencode({})
        conn = httplib.HTTPSConnection(url)
        conn.request("GET", "/v1/instruments?accountId=" + account_id, 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_price(instrument):
    try:
        time.sleep(1)
        params = urllib.urlencode({})
        conn = httplib.HTTPSConnection(url)
        conn.request("GET", "/v1/prices?instruments=" + 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 get_FXdata1(instrument, granularity, start, end):  # пара, таймфрейм
    try:
        time.sleep(1)
        # start = str(date.today()) + 'T00%3A00%3A00Z'
        # end = str(date.today()) + 'T03%3A00%3A00Z'
        conn = httplib.HTTPSConnection(url)
        conn.request("GET", "/v1/candles?instrument=" + instrument +
                     "&granularity=" + granularity +
                     "&candleFormat=" + 'midpoint' +
                     "&dailyAlignment=" + str(0) +
                     "&alignmentTimezone=" + 'UTC' +
                     "&start=" + start +
                     "&end=" + end)
        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_FXdata2(instrument, granularity, count):  # пара, таймфрейм
    try:
        time.sleep(1)
        conn = httplib.HTTPSConnection(url)
        conn.request("GET", "/v1/candles?instrument=" + instrument +
                     "&count=" + str(count) +
                     "&granularity=" + granularity +
                     "&candleFormat=" + 'midpoint' +
                     "&dailyAlignment=" + str(0) +
                     "&alignmentTimezone=" + 'UTC')
        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 send_sms(text):
    if sentSMS:
        url = "http://sms.ru/sms/send?api_id=4760338A-D9xxxxxxxxxxxxxxxx2D5C&to=79205616220&from=Forex Robot&text=" + text
        try:
            answer = requests.get(url)
            print "SMS sended"
        except Exception as e:
            print "SMS not sended"
            print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e)
 
 
def get_range(instrument, granularity, count):
    try:
        time.sleep(1)
        count += 1  # для незакрытой свечи
        data = get_FXdata2(instrument, granularity, count)
        data = json.loads(data)
        max_highMid = 0
        min_lowMid = 999999
        for key in data['candles']:
            if max_highMid < key[u'highMid']:
                max_highMid = key[u'highMid']
            if min_lowMid > key[u'lowMid']:
                min_lowMid = key[u'lowMid']
        return max_highMid, min_lowMid
    except Exception as e:
        print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e)
 
 
def get_avg_volatil(instrument, granularity, count):
    try:
        time.sleep(1)
        count += 1  # для незакрытой свечи
        data = get_FXdata2(instrument, granularity, count)
        data = json.loads(data)
        maxcandle = 0
        mincandle = 99999
        sumcandle = 0
        for key in data['candles']:
            if key[u'complete']:
                volatilcandle = (key[u'highMid'] - key[u'lowMid']) * 10000
                if 'JPY' in instrument:
                    volatilcandle = volatilcandle / 100
                if maxcandle < volatilcandle:
                    maxcandle = volatilcandle
                if mincandle > volatilcandle:
                    mincandle = volatilcandle
                sumcandle += volatilcandle
        if count >= 4:
            avgvolatil = int(round((sumcandle - maxcandle - mincandle) / (count - 3)))
        else:
            avgvolatil = int(round(sumcandle / (count - 1)))
        return avgvolatil
    except Exception as e:
        print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e)
 
 
def get_today_volatil(instrument, granularity, count):
    try:
        time.sleep(1)
        count += 1  # для незакрытой свечи
        data = get_FXdata2(instrument, granularity, count)
        data = json.loads(data)
        max_highMid = 0
        min_lowMid = 999999
        max_body = 0
        min_body = 999999
        if 'candles' in data.keys():
            for key in data['candles']:
                if max_highMid < key[u'highMid']:
                    max_highMid = key[u'highMid']
                if min_lowMid > key[u'lowMid']:
                    min_lowMid = key[u'lowMid']
                #===============================
                if key[u'openMid'] >= key[u'closeMid']:
                    high_body = key[u'openMid']
                    low_body = key[u'closeMid']
                else:
                    high_body = key[u'closeMid']
                    low_body = key[u'openMid']
                #=================================
                if max_body < high_body:
                    max_body = high_body
                if min_body > low_body:
                    min_body = low_body
 
            volatil_candle = (max_highMid - min_lowMid) * 10000
            volatil_body = (max_body - min_body) * 10000
            if 'JPY' in instrument:
                volatil_body = float(volatil_body) / 100
                volatil_candle = float(volatil_candle) / 100
            hightoday = round(float(max_body + ((max_highMid - max_body)) / 2), 5)
            lowtoday = round(float(min_body - ((min_body - min_lowMid)) / 2), 5)
            todayvolatil = round(float((volatil_body + volatil_candle)) / 2, 1)
 
            return hightoday, lowtoday, todayvolatil
    except Exception as e:
        print sys._getframe().f_code.co_name + " @ Caught exception when connecting to stream\n" + str(e)
 
 
def get_history_instrument(account_id, instrument, count):
    try:
        time.sleep(1)
        params = urllib.urlencode({})
        conn = httplib.HTTPSConnection(url)
        conn.request("GET", "/v1/accounts/" + account_id + "/transactions?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_history(account_id, count):
    try:
        time.sleep(1)
        params = urllib.urlencode({})
        conn = httplib.HTTPSConnection(url)
        conn.request("GET", "/v1/accounts/" + account_id + "/transactions?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)

Код к задаче: «API функции для OANDA - Python»

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)

12   голосов, оценка 4.500 из 5


СОХРАНИТЬ ССЫЛКУ