Some of the content of the API documentation (python version) is outdated and needs to be adjusted to avoid misinterpretation.

Author: The Little Dream, Created: 2016-10-21 09:38:12, Updated: 2017-12-04 16:51:55

API documentation (python version)

Some of the new users may be familiar with the language is Python, not familiar with the JavaScript language.

  • 0 python basic grammar tutorial links

runoob.comPython language Details of the syntax can be found here.

  • 1 Data structures: Some commonly used data structures returned by transaction functions.

    • Record: A standard OHLC dictionary (Dict), used for drawing K-strings and analyzing indicators, returns a list of lists in this dictionary by the GetRecords function
{
    'Volume': 153.8109090909091, # 交易量。
    'High'  : 4237.59,       # 最高价。
    'Low'   : 4237.59,       # 最低价。
    'Time'  : 1476892800000, # 这个字典数据的键值,时间间隔是以【毫秒】为单位的。
                             # 引入time模块,time.time()函数返回的时间,间隔是以秒为单位的浮点小数。所以在python语言中时间运算、对比时需要处理。
    'Close' : 4237.59,       # 收盘价。
    'Open'  : 4237.59        # 开盘价。
}
  • MarketOrder: Market Depth list, the function GetDepth () returns the values of the keystrokes Asks and Bids in the dictionary, which is the list that the MarketOrder dictionary consists of.
{
    'Price'  : 4237.58,  # 市场深度单 的价格 (订单薄 的某一档的 价格)。
    'Amount' : 15        # 市场深度单 的量  (订单薄 的某一档的量)。
}
  • Ticker: Market sector, This dictionary data is returned by the GetTicker function.
{
    'Sell'   : 4237.6,   # 卖一价。
    'Volume' : 100,      # 最近成交量。
    'Buy'    : 4237.58,  # 买一价。
    'Last'   : 4237.59,  # 最后成交价。
    'High'   : 4237.6,   # 最高价。
    'Low'    : 4237.58   # 最低价。
}
  • Order: order dictionary data, returned by the GetOrder function
{
    'Status': 1,         # 订单状态, 参考常量里的订单状态,以下是此键值的常量。
                         # ORDER_STATE_PENDING  :未完成
                         # ORDER_STATE_CLOSED   :已关闭
                         # ORDER_STATE_CANCELED :已取消
                         
    'Amount': 20.0,      # 下单数量。
    'DealAmount': 20.0,  # 成交数量。
    'Price': -1,         # 下单价格,-1 为市价单。
    
    'Type': 0,           # 订单类型, 参考常量里的订单类型,以下是此键值的常量。
                         # ORDER_TYPE_BUY   :买单
                         # ORDER_TYPE_SELL  :卖单

    'Id': 1,             # 交易单唯一标识。
    'AvgPrice': 4237.6   # JS的API文档没有写此项,此键已经更新可用,此键是交易成交均价。
}
  • Depth: Market depth, returned by the GetDepth function, the data returned is a dictionary, the key value is a list of dictionaries (MarketOrder)
{
    'Bids': [                                  # 买单列表, 包含MarketOrder字典的列表, 按价格从低向高排序
             {'Price': 4237.58, 'Amount': 15}, 
             {'Price': 4237.57, 'Amount': 15}, 
             {'Price': 4237.56, 'Amount': 15},
             ...
            ], 
    'Asks': [                                  # 卖单列表, 包含MarketOrder字典的列表, 按价格从高向低排序
             {'Price': 4237.6, 'Amount': 15}, 
             {'Price': 4237.61, 'Amount': 15}, 
             {'Price': 4237.62, 'Amount': 15}, 
             ...
            ]
}
  • Trade: Retrieves all transaction history (other than its own) returned by the GetTrades function.
[
    map[
         Price:4283.16           # 价格
         Time:1.477020122e+12    # 时间(Unix timestamp 毫秒) 
         Type:0                  # 订单类型
         Amount:0.048            # 数量
         Id:5.213554531e+09      # 订单ID (JS API文档没写)
       ] 
    ...
]

Here, the print output above is a real-disc Log output, and before the Trade is a reverse-test Log. There are some maps in the real-disc Log information that represent the dictionary behind [] and the list without the map.img

  • Fee: Fee structure, returned by the GetFee function (e.g. foreign platform bitfinex purchases and sells transaction fees related to account volume)
{
    'Sell': 0.03,  # 卖出手续费, 为一个浮点数, 如0.2表示0.2%的手续费
    'Buy': 0.03    # 买入手续费, 格式同上
}
  • Account: Account information returned by the GetAccount function
{
    'Balance': 10000.0,    # 余额(人民币或者美元, 在Poloniex交易所里BTC_ETC这样的品种, Balance就指的是BTC的数量, 
                           # Stocks指的是ETC数量, BTC38的ETC_BTC相当于Poloniex的BTC_ETC, 指的是以BTC计价)
    
    'Stocks': 3.0,         # BTC/LTC数量, 现货为当前可操作币的余额(去掉冻结的币), 
                           # 期货的话为合约当前可用保证金(传统期货为此属性)
                           
    'FrozenBalance': 0.0,  # 冻结的余额
    'FrozenStocks': 0.0    # 冻结的BTC/LTC数量(传统期货无此属性)
}
  • Exchange function: a function that is stored on an exchange or exchange like the one you have (the document below is being tested in retesting)

    • GetName: Returns the name of the exchange (string)
exchange.GetName()  # 测试的交易所是OKCoin,用Log 函数输出 Log(exchange.GetName()),  显示为 : OKCoin
  • GetLabel: Returns the customized label of the exchange (string)
exchange.GetLabel() # 在添加交易所的时候,可以设置标签,用来区别同一个交易所的不同账户,比如标签设置为OKCoin1、OKCoin2
  • GetUSDCNY: Returns the exchange rate of the dollar used by the exchange, OKCoin futures returns the official exchange rate (float), which is not affected by the SetRate
Log(exchange.GetUSDCNY(),type(exchange.GetUSDCNY())) # 交易所为OKCoin ,输出显示 6.7294 <type 'float'>
  • GetRate: Returns the exchange rate of the currency used in the exchange against the yuan, the foreign exchange is USD/EUR against CNY
# 汇率接口调用雅虎提供的接口, 5分钟更新一次
# 所有函数自动经过汇率转换,在脚本层,自动都转换为人民币,下单也是用人民币价格,不管内盘外盘
Log(exchange.GetRate()) # 交易所为OKCoin期货  输出显示6.7294
  • SetRate: Set the exchange rate of the currency in circulation against the yuan, the foreign exchange is USD/EUR against CNY, returning the exchange rate before setting
比如OKCoin期货设置SetRate(6.13), 就是设定USD/EUR对CNY的汇率为6.13, 程序所有价格会自动用这个汇率计算
SetRate(), 如果不加参数,则恢复系统内置汇率
exchange.SetRate(6.13)    #  交易所为OKCoin期货 
Log(exchange.GetRate())   #  6.13
exchange.SetRate()
Log(exchange.GetRate())   #  6.7294
  • GetCurrency: return the name of the currency operated by the exchange (string), the traditional futures CTP return fixed as STOCK
Log(exchange.GetCurrency())   # 交易所为OKCoin期货,标的物 BTC, 函数返回字符串,输出 BTC
  • GetTicker: Returns a Ticker dictionary with details of the document-data structure
Log(exchange.GetTicker())  #  返回 行情数据
                             #  {'Sell': 4259.98, 'Volume': 100, 'Buy': 4259.96, 'Last': 4259.97, 'High': 4259.98, 'Low': 4259.96}
  • GetDepth: Returns a depth dictionary
Log(exchange.GetDepth())  # 返回 市场深度数据(订单薄)如下
{
    'Bids': [{'Price': 4259.96, 'Amount': 15}, {'Price': 4259.95, 'Amount': 15}], ...  #买单列表:买一、买二
    'Asks': [{'Price': 4259.98, 'Amount': 15}, {'Price': 4259.99, 'Amount': 15}], ...  #卖单列表:卖一、卖二
}
  • GetTrades: Returns a list containing the Trade dictionary, in chronological order from low to high, only supporting digital currencies (BTC/LTC)
Log("GetTrades()函数 返回:", exchange.GetTrades())  # 回测不支持此函数,以下实盘测试
                                                  # GetTrades()函数 返回: 
[map[Price:4295.43 Time:1.47710627e+12 Type:1 Amount:0.02 Id:5.222046713e+09] 
 map[Price:4295.42 Time:1.47710627e+12 Type:1 Amount:0.23 Id:5.222046715e+09] 
 map[Price:4295.49 Time:1.477106271e+12 Type:0 Amount:0.01 Id:5.222046763e+09]
 ...
 ]
  • GetRecords ((Period): Returns a K-line history, the K-line cycle specified when the bot was created, containing a list of Record dictionaries
# 不加参数, 默认返回添加机器人时时指量的K线周期, 但也可以自定义K线周期
# 支持: PERIOD_M1 指1分钟, PERIOD_M5 指5分钟, PERIOD_M15 指15分钟, PERIOD_M30 指30分钟, PERIOD_H1 指1小时, PERIOD_D1 指一天
Log(exchange.GetRecords()) # 获取K线数据,并输出显示。
[{'Volume': 8637.650000000,'High': 4259.0,'Low': 4257.56,'Time': 1476964200000,'Close': 4258.85,'Open': 4257.6},# 第一根K线bar
 {'Volume': 14325.999999999,'High': 4258.95,'Low': 4256.0,'Time': 1476964500000,'Close': 4256.25,'Open': 4258.87},# 第二根K线bar
 ...
 {'Volume': 1339.070000000, 'High': 4258.38, 'Low': 4257.0, 'Time': 1476967200000, 'Close': 4258.12, 'Open': 4257.0} 
 # 最后一根(最新)K线bar。(这一根的数据除了Time 键值,其它的都是时刻变化的,只有这个周期完成数据才确定。)
 ]
  • GetAccount: Returns an Account dictionary, such as exchange.GetAccount ((), which returns the main exchange account information
Log(exchanges[0].GetName(), exchanges[0].GetAccount())
Log(exchanges[1].GetName(), exchanges[1].GetAccount())
# exchange 和 exchanges[0] 都代表策略第一个添加的交易所(主交易所)
# 输出显示: 
# OKCoin {'Balance': 10000.0, 'Stocks': 3.0, 'FrozenBalance': 0.0, 'FrozenStocks': 0.0} 
# Huobi {'Balance': 10000.0, 'Stocks': 3.0, 'FrozenBalance': 0.0, 'FrozenStocks': 0.0}
  • Buy ((Price, Amount): Next purchase, Price is the purchase price, Amount is the quantity, returns an order ID
可以跟多余的参数做为附加消息显示到日志, 如exchange.Buy(1000,0.1, "OK", 123)
支持现货(火币/BitVC/OKCoin/OKCoin国际/OKCoin期货)市价单, 市价单价格指定为-1
id1 = exchange.Buy(4300,1)     # 日期                  平台    类型  价格     数量   信息
                                   # 2016-10-21 00:00:00  OKCoin  买入  4300     1
id2 = exchange.Buy(-1, 8000)   # 市价单 的第二个参数的意义是  购买8000金额的 币数。
  • Sell (Price, Amount): Calls and scenarios similar to Buy
id1 = exchange.Sell(4300,1) #     日期                     平台        类型      价格      数量     信息
                                #     2016-10-21 00:00:00     OKCoin      卖出      市价单     1	
id2 = exchange.Sell(-1, 1)  #     日期                     平台        类型      价格      数量     信息
                                #     2016-10-21 00:00:00     OKCoin      卖出      4300      1
                            # 一般错误提示: 小于允许的最小交易单位,大部分是这个原因(参数1是1块钱而不是1个币)。
  • GetOrders: Returns a list of orders that have not been completed
# 区别于 GetOrder 函数,该函数不加参数,返回一个列表。
id1 = exchange.Sell(4500,1)
id2 = exchange.Buy(2300, 1)
Log(exchange.GetOrders())
# Log输出以下信息(状态是未成交)
[{'Status': 0, 'Amount': 1.0, 'DealAmount': 0.0, 'Price': 4500.0, 'Type': 1, 'Id': 1, 'AvgPrice': 0.0}, 
{'Status': 0, 'Amount': 1.0, 'DealAmount': 0.0, 'Price': 2300.0, 'Type': 0, 'Id': 2, 'AvgPrice': 0.0}]
  • GetOrder ((orderId): Returns an Order dictionary to get order details based on order number
id1 = exchange.Sell(4500,1)
Log(exchange.GetOrder(id1))
# {'Status': 0, 'Amount': 1.0, 'DealAmount': 0.0, 'Price': 4500.0, 'Type': 1, 'Id': 1, 'AvgPrice': 0.0}
  • CancelOrder ((orderId): Cancel an order based on the order number, returning true or false
根据Buy 、Sell 函数返回的 订单id , 或者 Order字典 中的id 键值, 取消指定id 的订单。 可以扩展代码循环调用,用来取消所有未完成的挂单。
  • GetMinStock: Minimum number of transactions returned by coin
回测和实盘精度有区别,可以自行测试一下。
  • GetMinPrice: Returns the minimum amount required for an order (price* quantity)
Bitstamp要求5美元(程序会根据汇率自动转换为人民币), 其它没有限制
  • GetFee: Returns a Fee dictionary
Log(exchange.GetFee())  # OKCoin 实盘测试 map[Sell:0 Buy:0]
  • GetRawJSON: Returns the original content (string) returned by the last REST API request, which the user can use to parse the extension information themselves
# 注: 模拟测试的话,会一直返回一个空字符串, 只在真实环境下有效
ticker = exchange.GetTicker()
Log("GetRawJSON:", exchange.GetRawJSON())
Log("type(json1)", type(json1))
# OKCoin 实盘 输出 GetRawJSON: 
# {"date":"1477130308","ticker":{"buy":"4337.33","high":"4345.97","last":"4337.32","low":"4280.0",
# "sell":"4337.38","vol":"1164227.77"}}
# type(json1) <type 'str'>
  • Go ((Method, Args...): Multi-threaded asynchronous support function, which can make all supported function operations asynchronous.
Support: GetTicker, GetDepth, GetTrades, GetRecords, GetAccount, GetOrders, GetOrder, CancelOrder, Buy, Sell, GetPosition
# Python与Javascript的区别, Python的wait返回两个参数, 第一个是异步的api返回的结果, 第二个表示是异步调用是否完成
ret, ok = d.wait() # ok是一定返回True的, 除非策略被停止
ret, ok = d.wait(100) # ok返回False, 如果等待超时, 或者wait了一个已经结束的实例
  • IO (api, ApiName, Args): Calls other functional interfaces of the exchange
exchange.IO("api", "cancel_borrow", "symbol=cny&borrow_id=123"); # no need api & sign
ret = exchange.IO("websocket")
Log("is Open websocket mode:", ret)
# OKCoin 实盘 输出: is Open websocket mode: websocket
  • Global functions: some of the extensions provided by the system, (built-in _C, _N, _G)

    • Version: Returns the current version number of the system, a string value, such as 3.0
Log("当前的托管者版本为:" ,Version())
# 回测使用 云端服务器 ,输出:  当前的托管者版本为: 3.1
  • Log: Save a message to the log list
i = 1
Bool = False
string = "hello world!"
Dict = {"name": "jack", "age": 18}
List = [Dict, "I love python!"] 
Log("输出信息,可以加多个参数。参数可以是各种类型。", "--Dict:", Dict,"--List:", 
        List, "--Number:", i, "--String:", string, "--Bool:", Bool)   
# 输出:可以加多个参数。参数可以是各种类型。 
# --Dict: {'age': 18, 'name': 'jack'} --List: [{'age': 18, 'name': 'jack'}, 'I love python!'] 
#       --Number: 1 --String: hello world! --Bool: False
  • Sleep (millisecond): Sleep function is a function of the number of milliseconds.
参数为毫秒数,如Sleep(1000)为休眠一秒, 该函数在回测时根据参数大小会影响回测速度, 大小一般为500 或者 1000 。
  • LogProfit ((Profit): Record the profit value, which is the value of the total profit, the parameter type is floating point number
def main():
    i = 0 # 定义一个int 型变量,控制循环次数
    while i < 10: # 循环体, i 小于 10 为 True 时执行循环,为False 了跳出循环。
        i += 1    # 每次i 值自己加1 , i += 1 即: i = i + 1 
        LogProfit(i) # 在日志中输出 盈利数值,  并且在收益图表上显示出来。
        Sleep(1000)
        # 显示如下图

img

  • LogProfitReset: Clear all earnings logs, with a numeric parameter to specify the number of records to be reserved
def main():
    i = 0
    LogProfitReset(5) # 在开始调用,用于清除上次执行后的收益图表,参数为5 表示保留上次最后5个收益数据。
    while i < 10:
        i += 1
        LogProfit(i)
        Sleep(1000)
# 使用OKCoin 实盘测试, 第一次启动策略显示 输出了10个收益日志信息,图表也显示了10个点的收益曲线。
# 第二次启动策略同样显示了10个收益日志信息(日志信息并没有清除。),图表上的数据保留了之前的最后5条(需要刷新下)。
  • LogReset: Clear all logs, with a numeric parameter to specify reserved records
# 该函数只清除日志信息,(需要刷新下才能看出来),在加参数时如果希望保留之前的N条日志的话,参数需要写N+1,
# 因为策略开始运行第一条语句前会输出一条启动日志,所以需要多保留一条(参数加1,即N+1)。图表没有变化。
  • LogStatus ((Msg): This information is not saved to the log list, only updates the current bot's status information, displayed at the top of the log, can be called multiple times, updates the status
    LogStatus('这是一个普通的状态提示')
    LogStatus('这是一个红色字体的状态提示 #ff0000')
    LogStatus('这是一个多行的状态信息\n我是第二行')
    
    LogStatus("`data:image/png;base64,AAAA`")
    # LogStatus支持打印base64编码后的图片, 以"`"开头, 以"`"结尾, 如LogStatus("`data:image/png;base64,AAAA`")
    # 网上有转换工具,比如这个网站: http://tool.css-js.com/base64.html  。
    # 选择图片转换后的代码直接替换掉 LogStatus("`data:image/png;base64,AAAA`")中的 `data:image/png;base64,AAAA` 就可以了。
    
    table = {"type":'table',"title":'持仓信息',"cols": ['列1', '列2'],"rows":[ ['abc', 'def'],['ABC', 'support color #ff0000']]};
    LogStatus('`' + json.dumps(table)+'`'); # 需要 import json 模块
    
    table = {"type":'table',"title":'持仓信息',"cols": ['列1', '列2'],"rows":[ ['abc', 'def'],['ABC', 'support color #ff0000']]};
    LogStatus('第一行消息\n`' + json.dumps(table)+'`\n第三行消息'); # 表格信息也可以在多行中出现
    
    table = {"type":'table',"title":'持仓信息',"cols": ['列1', '列2'],"rows":[ ['abc', 'def'],['ABC', 'support color #ff0000']]};
    LogStatus('`' + json.dumps([table, table])+'`'); # 支持多个表格同时显示, 将以TAB显示到一组里
    # json.dumps方法对简单数据类型encoding(转为JSON),json.loads方法处理简单数据类型的decoding(转为python对象)
  • EnableLog ((IsEnable): opens or closes log records for the fixed tab and the error message tab
# 参数是布尔值: False  、 True  (区别于 JavaScript 的 false 、 true)。
  • Chart (({...}): Chart drawing function
import json
chart = {
    '__isStock': True,
    'title': {
        'text': '测试API :Chart({...}) '
    },
    'yAxis': {
        'plotLines': [{
            'value': 4520,
            'color': 'red',
            'width': 2,
            'label': {
                'text': 'line1',
                'align': 'center'
            },
        }, {
            'value': 4500,
            'color': 'green',
            'width': 2,
            'label': {
                'text': 'line2',
                'align': 'center'
            },
        }]
    },
    'series': [{
        'type': 'candlestick',
        'name': '当前周期',
        'id': 'primary',
        'data': []
    }]
}
def main():
    global chart  # 记得 引用全局
    records = _C(exchange.GetRecords) # 获取 K线数据
    obj_chart = Chart(chart) # 创建 图表对象
    obj_chart.reset() # 清空
    for i in range(len(records)): #  遍历 Dict records 
        b = records[i] #  间接一下,少些点代码
        obj_chart.add(0,[b['Time'], b['Open'], b['High'], b['Low'], b['Close']]) # 向图表中写入 K线数据
    obj_chart.update(chart)   # 更新图表,  记得调用 API :  update 的时候传入 JSON 图表结构(这里是chart)
    
    # 1、参数为可以JSON序列化的HighStocks的Highcharts.StockChart参数, 比原生的参数增加一个__isStock属性, 
    #    如果指定__isStock: false, 则显示为普通图表
    # 2、返回对像可以调用add([series索引(如0), 数据])向指定索引的series添加数据, 调用reset()清空图表数据, 
    #    reset可以带一个数字参数, 指定保留的条数
    # 3、可以调用add([series索引(如0), 数据, 此数据在series中的索引])来更改数据
    #    可以为负数, -1指最后一个, -2是倒数第二个, 如:chart.add([0, 13.5, -1]), 更改series[0].data的倒数第一个点的数据
    # 4、记得调用 chart.update({...})  参数即 全局变量 字典chart
    #    HighStocks: http://api.highcharts.com/highstock ,  实际运行效果下图。

img

  • Mail ((...): the function to send mail
Mail(smtpServer, smtpUsername, smtpPassword, mailTo, title, body); ret true or false
Mail("smtp.163.com", "asdf@163.com", "password", "111@163.com", "title", "body")
# 平台API Mail()函数的使用详解 链接:https://www.fmz.com/bbs-topic/310
  • SetErrorFilter ((RegEx) filtered for error messages
# 被此正则表达式匹配的错误将不上传到日志系统, 可多次调用设置多个
SetErrorFilter("502:|503:|tcp|character|unexpected|network|timeout|WSARecv|Connect|GetAddr|
no such|reset|http|received|EOF|reused")
  • GetPid: Returns the process ID of the bot
Log(GetPid())   
  • GetCommand: get interactive commands (utf-8)
# 获取策略交互界面发来的命令并清空, 没有命令则返回null, 返回的命令格式为 "按钮名称:参数", 如果没有参数, 则命令就是按钮名称
while 1:
    cmd = GetCommand()
    if cmd:
        Log(cmd)
    Sleep(1000)

img img

  • _G(K, V): a global dictionary list that can be saved
def main(): 
    # KV表, 永久保存在本地文件, 每个机器人单独一个数据库, 重启或者托管者退出后一直存在
    # K必须为数字或者字符串, 不区分大小写, V可以为任何可以JSON序列化的内容
    _G("num", 1)  # 设置一个全局变量num, 值为1
    Log("_G 取得num 值:", _G("num"))
    _G("num", "ok")  # 更改一个全局变量num, 值为字符串ok
    Log("_G 取得num 值:", _G("num"))
    _G("num", null)  # 删除全局变量 num
    _G("num2", "false")
    Log("_G 取得num 值:", _G("num"), "_G 取得num2 值:", _G("num2"))
    _G()  # 返回当前机器人的ID
    _G(null)  # 删除所有全局变量
    Log("_G 取得num 值:", _G("num"), "_G 取得num2 值:", _G("num2"))

img

  • _C(): This function is mainly used for API error tolerance, such as the exchange.GetAccount() function, which is called as follows: _C(exchange.GetAccount); note that the function name does not include parentheses, if the error tolerant function requires the addition of parameters, it is written in the second parameter of the _C() function, in turn backwards.
def main(): 
    amount = 1
    price = 2000
    Log("使用_C 函数:", _C(exchange.GetAccount))
    _C(exchange.Buy, price, amount)
  • _N(): This function is used to handle too many decimal places and retain a few decimal places.
def main(): 
    pi = 3.1415926535897
    Log("使用_N函数前pi:", pi)
    
    piOfDeal = _N(pi, 2)
    Log("使用_N函数后pi:", piOfDeal)
  • others1, only supports Websocket mode (huobi),okcoin.cn, BTCC supported) and Commodity Futures CTPexchange.IO("websocket")Switching the market communications protocol to websocket (default rest), Ticker, Depth switches to websocket protocol to update, Commodity Futures CTP does not need switching Switch between GetTicker and GetDepth data update mode

    2、exchange.IO("mode", 0)Instant return mode, returns the old market data immediately if the exchange has not received the latest market data push yet, returns the new data if there is new data

    3、exchange.IO("mode", 1)Cache mode (default mode) if the exchange has not yet received the latest market data (comparison with the data obtained by the last API) It waits to receive and then returns, and immediately returns the most recent data if it received the latest market data before calling the function.

    4、exchange.IO("mode", 2)Mandatory update mode, enter wait until you receive the latest push data to the exchange next time you return

    5 If you want to get the latest market data for the first time, you can switch to the websocket and then use the instantaneous detection data of Sleepless, GetTicker, GetDepth to work in caching mode.

    exchange.IO("websocket")
    while 1:
        Log(exchange.GetTicker())
    

    6, each message string can end with an RGB value such as "#ff0000" to represent the foreground color to be displayed, and if the format is #ff0000112233 then the next six will represent the background color

  • Futures trading: Futures support the traditional commodity futures CTP protocol, BTC futures: 796, BitVC, OKCoin

    • Position Dictionary: Position information held in futures trading, returned by the GetPosition () function in this structured array
{
        "MarginLevel":    # 杆杠大小, 796期货有可能为5, 10, 20三个参数, OKCoin为10或者20, 
                          # BitVC期货和OK期货的全仓模式返回为固定的10, 因为原生API不支持
                      
        "Amount":         # 持仓量, 796期货表示持币的数量, BitVC指持仓的总金额(100的倍数), 
                          # OKCoin表示合约的份数(整数且大于1)
                      
        "CanCover":       # 可平量, 只有股票有此选项, 表示可以平仓的数量(股票为T+1)今日仓不能平
    
        "FrozenAmount":   # 冻结量, 支持传统期货与股票, 数字货币只支持796交易所
    
        "Price":          # 持仓均价
    
        "Profit":         # 持仓浮动盈亏(数据货币单位:BTC/LTC, 传统期货单位:RMB, 股票不支持此字段, 
                          # 注: OKCoin期货全仓情况下指实现盈余, 并非持仓盈亏, 逐仓下指持仓盈亏)
                      
        "Type":           # PD_LONG为多头仓位(CTP中用closebuy_today平仓), 
                          # PD_SHORT为空头仓位(CTP用closesell_today)平仓, 
                          # (CTP期货中)PD_LONG_YD为咋日多头仓位(用closebuy平),
                          # PD_SHORT_YD为咋日空头仓位(用closesell平)
                      
        "ContractType":   # 商品期货为合约代码, 股票为'交易所代码_股票代码', 具体参数SetContractType的传入类型
}
  • GetPosition: Get the current holdings
# 返回一个Position数组, (BitVC和OKCoin)可以传入一个参数, 指定要获取的合约类型
    def main(): 
        exchange.SetContractType("MA701")
        ticker1 = exchange.GetTicker()
        exchange.SetDirection("buy")
        exchange.Buy(ticker1['Sell'] + 1, 1, "MA701")
        exchange.SetDirection("sell")
        exchange.Sell(ticker1['Buy'] - 1, 2, "MA701")
        exchange.SetContractType("CF701")
        exchange.SetDirection("buy")
        ticker2 = exchange.GetTicker()
        exchange.Buy(ticker2['Sell'] + 1, 4, "CF701")
        positions = exchange.GetPosition()     # GetPosition() 函数返回的是 一个列表。
        Log("positions:", positions)    #  输出这个列表
        for i in range(len(positions)):  #  遍历
            Log(positions[i])

img

  • Set Margin Level: Set the size of the bar
# 设置Buy(多单)或者Sell(空单)的杆杠大小, MarginLevel有5, 10, 20 三个可选参数
# 796支持5,10,20,50三个选项, BitVC的LTC不支持20倍杠杆, OKCoin支持10倍和20倍
# 如: exchange.SetMarginLevel(5)
  • SetDirection (Direction): Set the Buy or Sell order type
# Direction可以取buy, closebuy, sell, closesell四个参数, 传统期货多出closebuy_today,与closesell_today, 
# 指平今仓, 默认为closebuy/closesell为平咋仓
# 对于CTP传统期货, 可以设置第二个参数"1"或者"2"或者"3", 分别指"投机", "套利", "套保", 不设置默认为投机
# 股票只支持buy与closebuy, 因为股票只能买跟平仓
exchange.SetMarginLevel(5)
exchange.SetDirection("buy")
exchange.Buy(1000, 2)
exchange.SetMarginLevel(5)
exchange.SetDirection("closebuy")
exchange.Sell(1000, 2)
  • SetContractType: Set the type of the contract
# 传统的CTP期货的ContractType就是指的合约ID,  如SetContractType("au1506") 返回合约的详细信息, 
# 如最少一次买多少, 手续费, 交割时间等
# 股票合约格式为 股票代码.(SH/SZ), SH指上交所, SZ指深交所, 如000001.SZ就是指深交所的平安银行
# 商品期货与股票取消订阅合约, 在合约名前加上"-"前缀重新调用即可, 如SetContractType("-au1506"); 成功返回true
# 数字货币796支持: "week", "weekcny", 默认为子账户A, 要指定子账户是A还是B, 在合约后加"@A"或"@B", 
# 如: "day@A" 为日合约A子账户
# BitVC有week和quarter和next_week三个可选参数, OKCoin期货有this_week, next_week, quarter三个参数
exchange.SetContractType("week");

Commodity futures include:https://www.fmz.com/api img

  • Indicator functions: TA - optimized rewrite of commonly used index library, talib -http://ta-lib.org/

    • TA - Optimized partial rewrite of common indicator libraries
MACD                  # 指数平滑异同平均线
KDJ                   # 随机指标
RSI                   # 强弱指标
ATR                   # 平均真实波幅
OBV                   # 能量潮
MA                    # 移动平均线
EMA                   # 指数平均数指标
BOLL                  # 布林带
Alligator             # Alligator Indicator
CMF                   # 蔡金货币流量指标
Highest               # 周期最高价
Lowest                # 周期最低价
help       #查询指标调用格式
ACOS       #Vector Trigonometric ACos
AD         #Chaikin A/D Line
ADOSC      #Chaikin A/D Oscillator
ADX        #Average Directional Movement Index
ADXR       #Average Directional Movement Index Rating
APO        #Absolute Price Oscillator
AROON      #Aroon
AROONOSC   #Aroon Oscillator
...

https://www.fmz.com/api


More

simple-chun.NewPositionManager ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))

FangBeiWhy isn't the indicator function written?

mosidaThe explanation for Depth, the commentary on ask and bid seem to be backwards.

The Little DreamThere was an error, welcome to the QQ group, post and reply to comments.

The Little DreamYes, this is a CTP commodity futures.

simple-chunThis version is only for CTP commodity futures, right? Is there a digital futures version?

simple-chunThank you teachers!

The Little DreamThe template for the corresponding version of Python should be here: https://www.botvs.com/strategy/24288 This is a list of all the different ways Dn-filebox.qbox.me/4a9057b2a17e4893ae7699faf30e35c51d4ae0f3.png is credited in the database.

simple-chunThis template for PY (NEWPOSITIONMANAGER) is not available on our BOTVS platform, please ask if teachers can run JS directly in a PY environment or call this template for JS through a third-party library for PY (e.g. python-spidermonkey).

The Little DreamThis is the JS version of the template export function, which can be understood as the interface function of the JS version of the code module. The python version is not available, the python version of the template export function starts with ext.

The Little DreamYes~ Thanks for asking, I'll fix it right away ^^