无法使用货币的 api 获取市场数据

如何解决无法使用货币的 api 获取市场数据

我的 Algo 交易系统使用 python 3.9,我有 API,但我无法获取货币市场的市场数据。交换是 IIFL,我使用的是 XTS API。 下面是 conenct.py 文件

from six.moves.urllib.parse import urljoin
import json
import logging
import requests
import Exception as ex
from requests.adapters import HTTPAdapter
import configparser

log = logging.getLogger(__name__)


class XTSCommon:
    """
    Base variables class
    """

    def __init__(self,token=None,userID=None,isInvestorClient=None):
        """Initialize the common variables."""
        self.token = token
        self.userID = userID
        self.isInvestorClient = isInvestorClient


class XTSConnect(XTSCommon):
    """
    The XTS Connect API wrapper class.
    In production,you may initialise a single instance of this class per `api_key`.
    """
    """Get the configurations from config.ini"""
    cfg = configparser.ConfigParser()
    cfg.read('config.ini')

    # Default root API endpoint. It's possible to
    # override this by passing the `root` parameter during initialisation.
    _default_root_uri = cfg.get('root_url','root')
    _default_login_uri = _default_root_uri + "/user/session"
    _default_timeout = 7  # In seconds

    # SSL Flag
    _ssl_flag = cfg.get('SSL','disable_ssl')

    # Constants
    # Products
    PRODUCT_MIS = "MIS"
    PRODUCT_NRML = "NRML"

    # Order types
    ORDER_TYPE_MARKET = "MARKET"
    ORDER_TYPE_LIMIT = "LIMIT"

    # Transaction type
    TRANSACTION_TYPE_BUY = "BUY"
    TRANSACTION_TYPE_SELL = "SELL"

    # Squareoff mode
    SQUAREOFF_DAYWISE = "DayWise"
    SQUAREOFF_NETWISE = "Netwise"

    # Squareoff position quantity types
    SQUAREOFFQUANTITY_EXACTQUANTITY = "ExactQty"
    SQUAREOFFQUANTITY_PERCENTAGE = "Percentage"

    # Validity
    VALIDITY_DAY = "DAY"

    # Exchange Segments

    EXCHANGE_NSECD = "NSECD"

    # URIs to various calls
    _routes = {
        # Market API endpoints
        "marketdata.prefix": "marketdata","market.login": "/marketdata/auth/login","market.logout": "/marketdata/auth/logout","market.config": "/marketdata/config/clientConfig","market.instruments.master": "/marketdata/instruments/master","market.instruments.subscription": "/marketdata/instruments/subscription","market.instruments.unsubscription": "/marketdata/instruments/subscription","market.instruments.ohlc": "/marketdata/instruments/ohlc","market.instruments.indexlist": "/marketdata/instruments/indexlist","market.instruments.quotes": "/marketdata/instruments/quotes","market.search.instrumentsbyid": '/marketdata/search/instrumentsbyid',"market.search.instrumentsbystring": '/marketdata/search/instruments',"market.instruments.instrument.series": "/marketdata/instruments/instrument/series","market.instruments.instrument.equitysymbol": "/marketdata/instruments/instrument/symbol","market.instruments.instrument.futuresymbol": "/marketdata/instruments/instrument/futureSymbol","market.instruments.instrument.optionsymbol": "/marketdata/instruments/instrument/optionsymbol","market.instruments.instrument.optiontype": "/marketdata/instruments/instrument/optionType","market.instruments.instrument.expirydate": "/marketdata/instruments/instrument/expiryDate"
    }

    def __init__(self,apiKey,secretKey,source,root=None,debug=False,timeout=None,pool=None,disable_ssl=_ssl_flag):
        """
        Initialise a new XTS Connect client instance.

        - `api_key` is the key issued to you
        - `token` is the token obtained after the login flow. Pre-login,this will default to None,but once you have obtained it,you should persist it in a database or session to pass
        to the XTS Connect class initialisation for subsequent requests.
        - `root` is the API end point root. Unless you explicitly
        want to send API requests to a non-default endpoint,this
        can be ignored.
        - `debug`,if set to True,will serialise and print requests
        and responses to stdout.
        - `timeout` is the time (seconds) for which the API client will wait for
        a request to complete before it fails. Defaults to 7 seconds
        - `pool` is manages request pools. It takes a dict of params accepted by HTTPAdapter
        - `disable_ssl` disables the SSL verification while making a request.
        If set requests won't throw SSLError if its set to custom `root` url without SSL.
        """
        self.debug = debug
        self.apiKey = apiKey
        self.secretKey = secretKey
        self.source = source
        self.disable_ssl = disable_ssl
        self.root = root or self._default_root_uri
        self.timeout = timeout or self._default_timeout

        super().__init__()

        # Create requests session only if pool exists. Reuse session
        # for every request. Otherwise create session for each request
        if pool:
            self.reqsession = requests.Session()
            reqadapter = requests.adapters.HTTPAdapter(**pool)
            self.reqsession.mount("https://",reqadapter)
        else:
            self.reqsession = requests

        # disable requests SSL warning
        requests.packages.urllib3.disable_warnings()

    def _set_common_variables(self,access_token,userID,isInvestorClient=None):
        """Set the `access_token` received after a successful authentication."""
        super().__init__(access_token,isInvestorClient)

    def _login_url(self):
        """Get the remote login url to which a user should be redirected to initiate the login flow."""
        return self._default_login_uri

    def marketdata_login(self):
        try:
            params = {
                "appKey": self.apiKey,"secretKey": self.secretKey,"source": self.source
            }
            response = self._post("market.login",params)
            #print(response)
            if "token" in response['result']:
                self._set_common_variables(response['result']['token'],response['result']['userID'])
            return response
        except Exception as e:
            return response['description']
    def get_config(self):
        try:
            params = {}
            response = self._get('market.config',params)
            return response
        except Exception as e:
            return response['description']

    def get_future_symbol(self,exchangeSegment,series,symbol,expiryDate):
        try:
            params = {'exchangeSegment': exchangeSegment,'series': series,'symbol': symbol,'expiryDate': expiryDate}
            response = self._get(
                'market.instruments.instrument.futuresymbol',params)
            return response
        except Exception as e:
            return response['description']

    def marketdata_logout(self):
        try:
            params = {}
            response = self._delete('market.logout',params)
            return response
        except Exception as e:
            return response['description']

    ########################################################################################################
    # Common Methods
    ########################################################################################################

    def _get(self,route,params=None):
        """Alias for sending a GET request."""
        return self._request(route,"GET",params)

    def _post(self,params=None):
        """Alias for sending a POST request."""
        return self._request(route,"POST",params)

    def _put(self,params=None):
        """Alias for sending a PUT request."""
        return self._request(route,"PUT",params)

    def _delete(self,params=None):
        """Alias for sending a DELETE request."""
        return self._request(route,"DELETE",params)

    def _request(self,method,parameters=None):
        """Make an HTTP request."""
        params = parameters if parameters else {}

        # Form a restful URL
        uri = self._routes[route].format(params)
        url = urljoin(self.root,uri)
        headers = {}

        if self.token:
            # set authorization header
            headers.update({'Content-Type': 'application/json','Authorization': self.token})

        try:
            r = self.reqsession.request(method,url,data=params if method in [
                                            "POST","PUT"] else None,params=params if method in [
                                            "GET","DELETE"] else None,headers=headers,verify=not self.disable_ssl)

        except Exception as e:
            raise e

        if self.debug:
            log.debug("Response: {code} {content}".format(
                code=r.status_code,content=r.content))

        # Validate the content type.
        if "json" in r.headers["content-type"]:
            try:
                data = json.loads(r.content.decode("utf8"))
            except ValueError:
                raise ex.XTSDataException("Couldn't parse the JSON response received from the server: {content}".format(
                    content=r.content))

            # api error
            if data.get("type"):

                if r.status_code == 400 and data["type"] == "error" and data["description"] == "Invalid Token":
                    raise ex.XTSTokenException(data["description"])

                if r.status_code == 400 and data["type"] == "error" and data["description"] == "Bad Request":
                    message = "Description: " + \
                        data["description"] + " errors: " + \
                        data['result']["errors"]
                    raise ex.XTSInputException(str(message))

            return data
        else:
            raise ex.XTSDataException("Unknown Content-Type ({content_type}) with response: ({content})".format(
                content_type=r.headers["content-type"],content=r.content))

下面是Example.py文件

from Connect import XTSConnect
API_KEY = ""
API_SECRET = ""
XTS_API_BASE_URL = "https://developers.symphonyfintech.in"
source = "WEBAPI"

"""Make the XTSConnect Object with Marketdata API appKey,secretKey and source"""
xt = XTSConnect(API_KEY,API_SECRET,source)

"""Using the object we call the login function Request"""
response = xt.marketdata_login()
print("MarketData Login: ",response)

"""Get Config Request"""
response = xt.get_config()
print('Config :',response)

"""Get Future Symbol Request"""
response = xt.get_future_symbol(
    exchangeSegment=3,series='FUTCUR',symbol='USDINR',expiryDate='28MAY')
print('Future Symbol:',str(response))

"""Marketdata Logout Request"""
response = xt.marketdata_logout()
print('Marketdata Logout :',str(response))

下面是config.ini文件

[user]
source = WEBAPI

[SSL]
disable_ssl=True

[root_url]
root = https://developers.symphonyfintech.in
;root=http://103.69.170.14:10332
broadcastMode=Full

我还收到了这两个错误,即“无法从源代码解析导入“six.moves.urllib.parse”“响应”未定义

如果有人对如何获取 USDINR 的市场数据作为未来交易品种有任何其他想法,请告诉我。

提前致谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res