This commit is contained in:
Zero
2018-12-08 12:40:55 +08:00
parent 7cef148712
commit 5ac7b446ef
246 changed files with 20309 additions and 4262 deletions
@@ -1,234 +0,0 @@
/*
策略出处: https://www.fmz.com/strategy/63221
策略名称: 03基于商品期货的套利策略模型 (Share 1513096985)
策略作者: ellajella-0378
策略描述:
商品期货对冲 + 网格
传统的跨期对冲一般指统计套利, 用线性回归或者其它办法生成一个套利区间, 这样套利机会比较少, 而且有预测性, 未来价差很可能不是预计的那样回归
为了解决这种办法, 进而更频繁的进行套利操作, 我们把两个关联品种或者跨期品种的套利价差定义成一个网格, 每满足一定的价差就开一次仓, 做一次对冲
这样价差来回在我们设置的网格里进行波动,我们就能不断的开仓平仓实现盈利.
不善文案, 不做文字表达了, 具体看策略代码
参数 默认值 描述
----------- -------------------------------------------------------------------------------------- -----------
HedgeTable (MA705&MA709)30:15:1;40:25:1;50:35:1;60:45:1(FG705&FG709)10:0:1;15:5:1;20:10:1;25:15:1 开仓表
CoverAll false 启动时平掉所有仓位
CalcPeriod 60 账户权益统计周期(分)
AutoRestore false 自动恢复
*/
function Hedge(q, e, positions, symbolA, symbolB, hedgeSpread) {
var self = {}
self.q = q
self.symbolA = symbolA
self.symbolB = symbolB
self.name = symbolA + " & " + symbolB
self.e = e
self.isBusy = false
self.diffA = 0
self.diffB = 0
self.update = _D()
var arr = hedgeSpread.split(';')
self.dic = []
var n = 0
var coefficient = 1
for (var i = 0; i < positions.length; i++) {
if (positions[i].ContractType == symbolA) {
n += positions[i].Amount
if (positions[i].Type == PD_LONG || positions[i].Type == PD_LONG_YD) {
coefficient = -1
}
}
}
_.each(arr, function(pair) {
var tmp = pair.split(':');
if (tmp.length != 3) {
throw "开仓表不正确";
}
var st = {
open: Number(tmp[0]),
cover: Number(tmp[1]),
amount: Number(tmp[2]),
hold: 0
}
if (n > 0) {
var m = Math.min(n, st.amount)
n -= m
st.hold = m * coefficient
Log("恢复", self.name, st)
}
self.dic.push(st)
});
if (n > 0) {
throw "恢复失败, 有多余仓位 " + n;
}
self.poll = function() {
if (self.isBusy || (!$.IsTrading(self.symbolA))) {
return
}
var insDetailA = exchange.SetContractType(self.symbolA)
if (!insDetailA) {
return
}
var tickerA = exchange.GetTicker()
if (!tickerA) {
return
}
var insDetailB = exchange.SetContractType(self.symbolB)
if (!insDetailB) {
return
}
var tickerB = exchange.GetTicker()
if (!tickerB) {
return
}
self.update = _D(tickerA.Time)
var action = null
var diffA = _N(tickerA.Buy - tickerB.Sell)
var diffB = _N(tickerA.Sell - tickerB.Buy)
self.diffA = diffA
self.diffB = diffB
for (var i = 0; i < self.dic.length && !action; i++) {
if (self.dic[i].hold == 0) {
if (self.dic[i].open <= diffA) {
action = [i, "sell", "buy", self.dic[i].amount]
} else if (self.dic[i].open <= -diffB) {
action = [i, "buy", "sell", -self.dic[i].amount]
}
} else {
if (self.dic[i].hold > 0 && self.dic[i].cover >= diffB) {
action = [i, "closesell", "closebuy", self.dic[i].hold]
} else if (self.dic[i].hold < 0 && self.dic[i].cover >= -diffA) {
action = [i, "closebuy", "closesell", self.dic[i].hold]
}
}
}
if (!action) {
return
}
Log("A卖B买: " + _N(diffA) + ", A买B卖: " + _N(diffB), ", Action: " + JSON.stringify(action))
self.isBusy = true
self.q.pushTask(self.e, self.symbolA, action[1], self.dic[action[0]].amount, function(task, ret) {
if (!ret) {
self.isBusy = false
return
}
self.q.pushTask(self.e, self.symbolB, action[2], self.dic[action[0]].amount, function(task, ret) {
if (!ret) {
throw "开仓失败..."
}
self.isBusy = false
if (task.action != "buy" && task.action != "sell") {
self.dic[action[0]].hold = 0;
} else {
self.dic[action[0]].hold = action[3];
}
})
})
}
return self
}
function main() {
SetErrorFilter("ready|login|timeout")
Log("正在与交易服务器连接...")
while (!exchange.IO("status")) Sleep(1000);
Log("与交易服务器连接成功")
var mode = exchange.IO("mode", 0);
if (typeof(mode) !== 'number') {
throw "切换模式失败, 请更新到最新托管者!";
} else {
Log("已切换到适合多品种价格查询的立即模式");
}
if (CoverAll) {
Log("开始平掉所有残余仓位...");
$.NewPositionManager().CoverAll();
Log("操作完成");
}
LogStatus("尝试获取持仓状态")
var positions = _C(exchange.GetPosition)
LogStatus("Ready")
if (positions.length > 0 && !AutoRestore) {
throw "发现持仓, 请勾选自动恢复"
}
var pairs = []
var q = $.NewTaskQueue(function(task, ret) {
Log(task.desc, ret ? "成功" : "失败")
})
var arr = HedgeTable.split('(');
var tbl = {
type: 'table',
title: 'Runtime',
cols: ['Pair', 'Open', 'Cover', 'Hold', 'DiffA', 'DiffB', 'Time'],
rows: []
};
_.each(arr, function(item) {
if (item != '') {
var tmp = item.split(')');
var pair = tmp[0].replace('(', '').split('&');
var symbolDetail = _C(exchange.SetContractType, pair[0])
Log("合约", symbolDetail.InstrumentName, "一手", symbolDetail.VolumeMultiple, "份, 最大下单量", symbolDetail.MaxLimitOrderVolume, "保证金率:", _N(symbolDetail.LongMarginRatio), _N(symbolDetail.ShortMarginRatio), "交割日期", symbolDetail.StartDelivDate);
symbolDetail = _C(exchange.SetContractType, pair[1])
Log("合约", symbolDetail.InstrumentName, "一手", symbolDetail.VolumeMultiple, "份, 最大下单量", symbolDetail.MaxLimitOrderVolume, "保证金率:", _N(symbolDetail.LongMarginRatio), _N(symbolDetail.ShortMarginRatio), "交割日期", symbolDetail.StartDelivDate);
pairs.push(Hedge(q, exchanges[0], positions, pair[0], pair[1], tmp[1]))
}
});
var ts = 0
var lastUpdate = 0
while (true) {
if (!exchange.IO("status")) {
Sleep(1000)
continue
}
var now = new Date().getTime()
if (now - ts > (CalcPeriod * 60000)) {
var account = exchange.GetAccount()
if (account) {
var obj = JSON.parse(exchange.GetRawJSON())
$.PlotLine('账户权益', obj['Balance'] + obj['PositionProfit']);
ts = now
}
}
// IO("wait") 会一直等待收到任何一个品种的行情推送信息, 返回收到行情的真实时间
var n = exchange.IO("wait")
// 计算行情信息传到策略层花费的时间
var idle = UnixNano() - n
if (now - lastUpdate > 5000) {
tbl.rows = []
_.each(pairs, function(t) {
for (var i = 0; i < t.dic.length; i++) {
tbl.rows.push([t.name, t.dic[i].open, t.dic[i].cover, t.dic[i].hold, t.diffA, t.diffB, t.update])
}
});
LogStatus('`' + JSON.stringify(tbl) + '`\nUpdate: ' + _D() + ', Idle: ' + (idle/1000000) + ' ms')
lastUpdate = now
}
_.each(pairs, function(t) {
t.poll()
});
q.poll()
}
}
-25
View File
@@ -1,25 +0,0 @@
/*
策略出处: https://www.fmz.com/strategy/14436
策略名称: 10行人品策略
策略作者: 春哥
策略描述:
赚不赚钱看人品
参数 默认值 描述
-------- ----- -------
Interval 300 轮询周期(秒)
*/
function main() {
while (true) {
Sleep(Interval * 1000);
if (Math.random() > 0.5) $.Buy(1000000); else {
$.Sell(1000000);
var a = $.GetAccount();
if (a) LogProfit( a.Balance , 'CNY:', a.Balance, 'BTC:', a.Stocks);
}
}
}
@@ -1,8 +1,13 @@
/*
策略出处: https://www.fmz.com/strategy/1088
策略名称: 2014年的简易短线机器人
策略作者: botvsing
策略描述:
> 策略名称
2014年的简易短线机器人
> 策略作者
botvsing
> 策略描述
**策略的介绍**
@@ -100,15 +105,21 @@ function onTick() {
整个程序也就40多行,看上去十分简单,但当时也花了我一个多星期,这还是在botvs平台上情况下。最大的优势还是起步早,在2014年,市场上以搬砖为主,网格和抢盘口的高频也不多,使得策略如鱼得水,后来竞争不可避免越来越激烈,我的钱也越来越多,面临的挑战很多,每隔一段时间都要进行较大的改动来应对,但总体还算顺利。在交易平台不收取手续费的情况下,是程序化交易的天堂,散户因为不收手续费跟倾向于操作,为高频和套利提供了空间,这一切也基本随着动辄0.1-0.2%的双向手续费终结了,不仅是自己被收费的问题,而是整个市场活跃度下降。
但不需要高频的量化策略任然有很大的空间。
> 策略参数
参数 默认值 描述
--------------- ------ ----
sleeptime 3500 休眠时间
floatamountbuy 8 买单深度
floatamountsell 8 卖单高度
diffprice 1.5 套利差价
*/
|参数|默认值|描述|
|----|----|----|
|sleeptime|3500|休眠时间|
|floatamountbuy|8|买单深度|
|floatamountsell|8|卖单高度|
|diffprice|1.5|套利差价|
> 源码 (javascript)
``` javascript
/*
就是我刚开始编写机器人的源代码,几乎没有改动,参数也是原来的参数。这个版本的程序有许多
需要改进的地方,但即使如此,它也当时表现除了惊人的盈利能力,在我本金不多时,不加杠杆平
@@ -180,3 +191,12 @@ function main() {
onTick();
}
}
```
> 策略出处
https://www.fmz.com/strategy/1088
> 更新时间
2018-06-20 17:29:14
+65
View File
@@ -0,0 +1,65 @@
> 策略名称
30行赌徒策略 (做空)
> 策略作者
小小梦
> 策略参数
|参数|默认值|描述|
|----|----|----|
|_StopWin|500|止盈|
|_StopLoss|500|止损|
|_FirstAmount|0.01|单次下单量|
|_MaxGear|8|加倍赌的次数|
> 源码 (javascript)
``` javascript
var hold = {price : 0, amount : 0}
var _Gear = 0
function main(){
var initAccount = _C(exchange.GetAccount)
Log(initAccount, "#FF0000")
while(1){
var ticker = _C(exchange.GetTicker)
if(hold.amount == 0){
var firstInfo = $.Sell(_FirstAmount)
hold.amount = firstInfo.amount
hold.price = firstInfo.price
} else {
if(ticker.Buy < hold.price - _StopWin){
var coverStopWinInfo = $.Buy(hold.amount)
hold.price = 0
hold.amount = 0
_Gear = 0
} else if(ticker.Buy > hold.price + _StopLoss && _Gear < _MaxGear){
$.Buy(hold.amount)
var amount = hold.amount * 2
var addInfo = $.Sell(amount)
hold.price = addInfo.price
hold.amount = addInfo.amount
_Gear++
}
}
LogStatus(_D(), "加倍下注次数:", _Gear, "\n", "当前持仓:", hold)
Sleep(500)
}
}
```
> 策略出处
https://www.fmz.com/strategy/113986
> 更新时间
2018-08-29 14:16:21
+65
View File
@@ -0,0 +1,65 @@
> 策略名称
30行赌徒策略
> 策略作者
小小梦
> 策略参数
|参数|默认值|描述|
|----|----|----|
|_StopWin|500|止盈|
|_StopLoss|500|止损|
|_FirstAmount|0.01|单次下单量|
|_MaxGear|8|加倍赌的次数|
> 源码 (javascript)
``` javascript
var hold = {price : 0, amount : 0}
var _Gear = 0
function main(){
var initAccount = _C(exchange.GetAccount)
Log(initAccount, "#FF0000")
while(1){
var ticker = _C(exchange.GetTicker)
if(hold.amount == 0){
var firstInfo = $.Buy(_FirstAmount)
hold.amount = firstInfo.amount
hold.price = firstInfo.price
} else {
if(ticker.Sell > hold.price + _StopWin){
var coverStopWinInfo = $.Sell(hold.amount)
hold.price = 0
hold.amount = 0
_Gear = 0
} else if(ticker.Sell < hold.price - _StopLoss && _Gear < _MaxGear){
$.Sell(hold.amount)
var amount = hold.amount * 2
var addInfo = $.Buy(amount)
hold.price = addInfo.price
hold.amount = addInfo.amount
_Gear++
}
}
LogStatus(_D(), "加倍下注次数:", _Gear, "\n", "当前持仓:", hold)
Sleep(500)
}
}
```
> 策略出处
https://www.fmz.com/strategy/113796
> 更新时间
2018-08-31 10:43:45
+87
View File
@@ -0,0 +1,87 @@
> 策略名称
50行多平台对冲策略(教学)
> 策略作者
小小梦
> 策略描述
教学策略
> 策略参数
|参数|默认值|描述|
|----|----|----|
|_HedgePrice|10|对冲差价|
|_HedgeAmount|0.02|对冲量|
|_CurrencyPrecision|2|下单量精度|
|_BaseCurrencyPrecision|2|下单价格精度|
> 源码 (javascript)
``` javascript
var preSumBalance = 0
var initSumBalance = 0
function UpdateAccount(isFirst){
var msg = ""
var sumStocks = 0
var sumBalance = 0
for(var i = 0; i < exchanges.length; i++){
if(exchanges[i].needUpdate == true || isFirst == true){
exchanges[i].account = _C(exchanges[i].GetAccount)
exchanges[i].needUpdate = false
if(isFirst == true){
initSumBalance += (exchanges[i].account.Balance + exchanges[i].account.FrozenBalance)
exchanges[i].SetPrecision(_CurrencyPrecision, _BaseCurrencyPrecision)
}
}
sumStocks += (exchanges[i].account.Stocks + exchanges[i].account.FrozenStocks)
sumBalance += (exchanges[i].account.Balance + exchanges[i].account.FrozenBalance)
msg += exchanges[i].GetName() + "币:" + exchanges[i].account.Stocks + "冻币:" + exchanges[i].account.FrozenStocks + "钱:" + exchanges[i].account.Balance + "冻钱:" + exchanges[i].account.FrozenBalance + "\n"
}
LogStatus(_D(), "总币:" + sumStocks, "总钱:" + sumBalance, "\n", msg)
if(preSumBalance != sumBalance){
LogProfit(sumBalance - initSumBalance, preSumBalance = sumBalance)
}
}
function main(){
UpdateAccount(true)
while(1){
for(var i = 0; i < exchanges.length; i++){
for(var j = 0; j < exchanges.length; j++){
if(i == 0 && j == 0){
for(var m = 0; m < exchanges.length; m++){
exchanges[m].thread = exchanges[m].Go("GetTicker")
}
for(var n = 0; n < exchanges.length; n++){
exchanges[n].ticker = exchanges[n].thread.wait()
}
}
if(exchanges[i].GetName() != exchanges[j].GetName() && exchanges[i].ticker && exchanges[j].ticker && exchanges[i].ticker.Buy - exchanges[j].ticker.Sell > _HedgePrice){
if(exchanges[i].account.Stocks > _HedgeAmount && exchanges[j].account.Balance / ((exchanges[i].ticker.Buy + exchanges[j].ticker.Sell) / 2) > _HedgeAmount){
var sellId_I = exchanges[i].Sell((exchanges[i].ticker.Buy + exchanges[j].ticker.Sell) / 2, _HedgeAmount, exchanges[i].GetName())
var buyId_J = exchanges[j].Buy((exchanges[i].ticker.Buy + exchanges[j].ticker.Sell) / 2, _HedgeAmount, exchanges[i].GetName())
exchanges[i].needUpdate = exchanges[j].needUpdate = true
}
}
}
}
UpdateAccount(false)
Sleep(300) // 测试
}
}
```
> 策略出处
https://www.fmz.com/strategy/113278
> 更新时间
2018-08-25 16:44:16
+86
View File
@@ -0,0 +1,86 @@
> 策略名称
50行网格策略(教学)
> 策略作者
小小梦
> 策略参数
|参数|默认值|描述|
|----|----|----|
|direction|true|网格方向|
|_GridNum|10|网格节点数量|
|_GridPointAmount|0.1|网格节点下单量|
|_GridPointDis|20|网格节点间距|
|_GridCovDis|50|网格节点平仓差价|
> 源码 (javascript)
``` javascript
var _StopLoss = 0
var _StopWin = 0
var _Grid = []
function UpdateGrid(nowBidsPrice, nowAsksPrice, direction){ // up 1, down -1
if(_Grid.length == 0 || (direction == 1 && nowBidsPrice - _Grid[_Grid.length - 1].price > _GridPointDis) ||
(direction == -1 && _Grid[_Grid.length - 1].price - nowAsksPrice > _GridPointDis)){
var nowPrice = direction == 1 ? nowBidsPrice : nowAsksPrice
_Grid.push({
price: _Grid.length == 0 ? nowPrice : _Grid[_Grid.length - 1].price + _GridPointDis * direction,
hold : {price: 0, amount: 0},
coverPrice : _Grid.length == 0 ? nowPrice - direction * _GridCovDis : _Grid[_Grid.length - 1].price + _GridPointDis * direction - direction * _GridCovDis
})
var tradeInfo = direction == 1 ? $.Sell(_GridPointAmount) : $.Buy(_GridPointAmount)
_Grid[_Grid.length - 1].hold.price = tradeInfo.price
_Grid[_Grid.length - 1].hold.amount = tradeInfo.amount
$.PlotFlag(new Date().getTime(), JSON.stringify(tradeInfo), "O")
}
if(_Grid.length > 0 &&
((direction == 1 && nowAsksPrice < _Grid[_Grid.length - 1].coverPrice) || (direction == -1 && nowBidsPrice > _Grid[_Grid.length - 1].coverPrice))){
var coverInfo = direction == 1 ? $.Buy(_Grid[_Grid.length - 1].hold.amount) : $.Sell(_Grid[_Grid.length - 1].hold.amount)
_Grid.pop()
$.PlotFlag(new Date().getTime(), JSON.stringify(coverInfo), "C")
_StopWin++
} else if(_Grid.length > _GridNum){
var coverfirstInfo = direction == 1 ? $.Buy(_Grid[0].hold.amount) : $.Sell(_Grid[0].hold.amount)
_Grid.shift()
$.PlotFlag(new Date().getTime(), JSON.stringify(coverfirstInfo), "C")
_StopLoss++
}
}
function main(){
while(1){
var ticker = _C(exchange.GetTicker)
var records = _C(exchange.GetRecords)
$.PlotRecords(records, "kline")
UpdateGrid(ticker.Buy, ticker.Sell, direction)
var msg = ""
for(var i = 0; i < _Grid.length; i++){
msg += JSON.stringify(_Grid[i]) + "\n"
}
LogStatus(_D(), "_StopWin:", _StopWin, "_StopLoss:", _StopLoss, _C(exchange.GetAccount), "\n", "_Grid.length:", _Grid.length, "_GridNum:", _GridNum, "\n", msg)
Sleep(500)
}
}
```
> 策略出处
https://www.fmz.com/strategy/113144
> 更新时间
2018-08-25 18:19:22
@@ -1,30 +1,41 @@
/*
策略出处: https://www.fmz.com/strategy/3648
策略名称: 796期货反手加倍算法
策略作者: Zero
策略描述:
> 策略名称
796期货反手加倍算法
> 策略作者
Zero
> 策略描述
796期货反手加倍算法, 先开空或多, 也可以指定失败了继续上次方向, 如果失败了就按指定倍数加仓, 策略有风险, 仅限学习使用.
> 策略参数
参数 默认值 描述
----------- ----- -----------
MarginIdx 0 杠杆大小: 10|20
OpType 0 开仓方向: 做多|做空
OpAmount 0.1 开仓数量
OpMode 0 开仓方式: 吃单|挂单
MaxSpace 0.5 挂单失效距离
SlidePrice 0.1 下单滑动价(元)
StopProfit 0.2 止赢(百分比)
StopLoss 0.1 止损(百分比)
ReverseRate 2 反手加仓倍数
MaxLoss 10 最多反手次数
ReverseMode 0 反手模式: 反仓|顺仓
SaveLocal false 保存本地日志
Interval true 轮询间隔(秒)
*/
|参数|默认值|描述|
|----|----|----|
|MarginIdx|0|杠杆大小: 10|20|
|OpType|0|开仓方向: 做多|做空|
|OpAmount|0.1|开仓数量|
|OpMode|0|开仓方式: 吃单|挂单|
|MaxSpace|0.5|挂单失效距离|
|SlidePrice|0.1|下单滑动价(元)|
|StopProfit|0.2|止赢(百分比)|
|StopLoss|0.1|止损(百分比)|
|ReverseRate|2|反手加仓倍数|
|MaxLoss|10|最多反手次数|
|ReverseMode|0|反手模式: 反仓|顺仓|
|SaveLocal|false|保存本地日志|
|Interval|true|轮询间隔(秒)|
> 源码 (javascript)
``` javascript
var MarginLevel = [10,20][MarginIdx];
var FirstTradeType = [ORDER_TYPE_BUY, ORDER_TYPE_SELL][OpType];
var OrgAccount = null;
@@ -367,3 +378,12 @@ function main() {
Sleep(Interval);
}
}
```
> 策略出处
https://www.fmz.com/strategy/3648
> 更新时间
2015-02-04 13:49:31
-27
View File
@@ -1,27 +0,0 @@
/*
策略出处: https://www.fmz.com/strategy/4
策略名称: API 测试新手入门
策略作者: Zero
策略描述:
新手入门学习模板
参数 默认值 描述
--------- ----- -------------
message Hello 回显的信息
running true 布尔值
maxNumber 111 回显数字
ListIdx 0 下拉框: 第一|第二|第三
cond 123 条件显示1
*/
function main() {
Log(exchange.GetAccount());
Log(message, running, maxNumber);
Log('ListIdx :', ListIdx);
LogProfit(100.3);
Log("这是红色字体颜色", "#ff0000");
Log("我是带背景色的", "#ffffff223344");
LogProfit(90, "我也带背景色", "#ffffff0000ff");
}
+47
View File
@@ -0,0 +1,47 @@
> 策略名称
API 测试新手入门
> 策略作者
Zero
> 策略描述
新手入门学习模板
> 策略参数
|参数|默认值|描述|
|----|----|----|
|message|Hello|回显的信息|
|running|true|布尔值|
|maxNumber|111|回显数字|
|ListIdx|0|下拉框: 第一|第二|第三|
|cond|123|条件显示1|
> 源码 (javascript)
``` javascript
function main() {
Log(exchange.GetAccount());
Log(message, running, maxNumber);
Log('ListIdx :', ListIdx);
LogProfit(100.3);
Log("这是红色字体颜色", "#ff0000");
Log("我是带背景色的", "#ffffff223344");
LogProfit(90, "我也带背景色", "#ffffff0000ff");
}
```
> 策略出处
https://www.fmz.com/strategy/4
> 更新时间
2017-02-28 10:14:17
@@ -1,23 +1,34 @@
/*
策略出处: https://www.fmz.com/strategy/1295
策略名称: BTC-LTC 地址监视, 短信通知
策略作者: Zero
策略描述:
> 策略名称
BTC-LTC 地址监视, 短信通知
> 策略作者
Zero
> 策略描述
有新的交易, 立即提醒
> 策略参数
参数 默认值 描述
--------- ---------------------------------- -----------
Type 0 类型: BTC|LTC
Addr 1LuckyY9fRzcJre7aou7ZhWVXktxjjBb9S 地址
Interval 3 轮询间隔
EnableSMS false 启动短信通知
SMSUser *** 短信宝用户名
SMSPass *** 短信宝MD5密码
PhoneNum 1111 接收短信手机号
*/
|参数|默认值|描述|
|----|----|----|
|Type|0|类型: BTC|LTC|
|Addr|1LuckyY9fRzcJre7aou7ZhWVXktxjjBb9S|地址|
|Interval|3|轮询间隔|
|EnableSMS|false|启动短信通知|
|SMSUser|***|短信宝用户名|
|SMSPass|***|短信宝MD5密码|
|PhoneNum|1111|接收短信手机号|
> 源码 (javascript)
``` javascript
var LastMsg = "";
function SMSSend(msg) {
if (msg == LastMsg) {
@@ -71,3 +82,12 @@ function main() {
Sleep(Interval*1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/1295
> 更新时间
2014-11-07 19:41:42
+179
View File
@@ -0,0 +1,179 @@
> 策略名称
BTC-V反策略
> 策略作者
ztjeff
> 策略参数
|参数|默认值|描述|
|----|----|----|
|password|'test888'|口令|
|按钮|默认值|描述|
|----|----|----|
|recv|true|结束程序|
> 源码 (python)
``` python
# encoding: utf-8
import os
from time import time, sleep
from threading import Thread
from socket import socket, AF_INET, SOCK_DGRAM, gethostname, timeout, error
prct = 0.1
password = 'test888'
req = {}
pos = {}
recv = True
data = ''
n=60 #减数触发器,减到零触发
def trade(req):
"""测试交易"""
for symbol, mpos in req.items():
if symbol not in pos.keys():
pos[symbol] = 0.0
targetPos=round(mpos*prct, 4)
Log('targetPos =', targetPos)
if targetPos == pos[symbol]:
#Log("No Trade Operation! client Pos %s is %.3f" % (symbol, pos[symbol]))
continue
tick = exchange.GetTicker();
if targetPos > pos[symbol]:
vol = round(targetPos-pos[symbol], 4)
type = 'buy-market'
#Log(' Buy btcusdt', vol)
id = exchange.Buy(tick.Sell+10, vol)
#Log(' Buy btcusdt at %s = %s' %(tick.Sell, vol))
Log("Order id:", id);
elif targetPos < pos[symbol]:
vol = round(pos[symbol]-targetPos, 4)
type = 'sell-market'
#Log(' Sell btcusdt', vol)
id = exchange.Sell(-1, vol)
#Log(' Sell btcusdt at %s = %s' %(tick.Buy, vol))
Log("Order id:", id);
account = exchange.GetAccount()
Log("账户信息,Balance:", account.Balance, "FrozenBalance:", account.FrozenBalance, "Stocks:",
account.Stocks, "FrozenStocks:", account.FrozenStocks)
pos[symbol] = round(account.Stocks, 4)
Log('Now Client %s POS = %s' % (symbol, pos[symbol]))
class recServer(object):
"""recServer is receving Signal from SigServer"""
def __init__(self, c):
self.rcv = True
self.t = Thread(target = self.recSig, args = (c,))
self.t.start()
def recSig(self, c):
while self.rcv:
try:
data, addr = c.recvfrom(1024)
#Log('n=',n)
except timeout:
continue
except error:
msg = traceback.format_exc()
Log(msg)
continue
if data == 'ok':
#Log('SigServer is alive! Receving "ok" from', addr)
pass
elif 'send password' in data:
Log('The client not login, press any key to exit and restart!')
self.rcv = False
elif not data:
Log("SigServer is stopped, press any Key to exit SigClient!")
self.rcv = False
else:
try:
c.sendto('ack', addr)
Log('send ack to ', addr)
except error:
Log('Send ack error!')
req = eval(data)
Log(req, 'from', addr)
trade(req)
else:
Log('RecSig Thread is Exiting...')
return None
def heart(self, c, ADDR):
try:
c.sendto('live', ADDR)
except error:
Log('Send keepAlive error!')
return None
def close(self):
self.rcv = False
self.t.join()
def main():
account = exchange.GetAccount()
Log("账户信息,Balance:", account.Balance, "FrozenBalance:", account.FrozenBalance, "Stocks:",
account.Stocks, "FrozenStocks:", account.FrozenStocks)
pos['btcusdt'] = round(account.Stocks, 4)
Log(pos)
# 启动UDP客户端
c = socket(AF_INET, SOCK_DGRAM)
host = '47.98.130.139'
port = 1234
ADDR = (host, port)
c.settimeout(5)
try:
c.sendto(password, ADDR)
data, addr = c.recvfrom(256)
Log(data+' from ', addr)
except timeout, error:
Log('SigServer is not active, client is aborting!')
c.close()
return None
if 'invalid' in data:
Log('\nYou failed to Login! SigClient is Exiting...')
c.close()
return None
# 如果密码正确,开启接收信号模式
rc = recServer(c)
sleep(1)
global n
while recv:
n -= 1
if not n:
rc.heart(c, ADDR)
account = exchange.GetAccount()
pos['btcusdt'] = round(account.Stocks, 4)
#Log(pos)
n = 60
sleep(1)
else:
rc.close()
Log('Program is End!')
```
> 策略出处
https://www.fmz.com/strategy/117202
> 更新时间
2018-09-27 21:45:01
@@ -0,0 +1,70 @@
> 策略名称
Binance buy and sell statistics|币安买卖统计
> 策略作者
botvsing
> 策略描述
记录主动成交数据
> 策略参数
|参数|默认值|描述|
|----|----|----|
|Interval|600|Log interval(second)|
|Pair|btcusdt|trading pair|
> 源码 (javascript)
``` javascript
var tradeHistory = {buyData:{amount:0, money:0}, sellData:{amount:0, money:0}}
if(_G('tradeHistory')){
tradeHistory = _G('tradeHistory')
}
function onexit(){
Log('exit,saving data...')
_G('tradeHistory', tradeHistory)
}
function main(){
var client = Dial("wss://stream.binance.com:9443/ws/" + Pair.toLowerCase() + "@trade", 60)
var updateTime = new Date().getTime()
while(true){
var trade = JSON.parse(client.read())
if(trade.m){
tradeHistory.sellData.amount += parseFloat(trade.q)
tradeHistory.sellData.money += parseFloat(trade.q) * parseFloat(trade.p)
}else{
tradeHistory.buyData.amount += parseFloat(trade.q)
tradeHistory.buyData.money += parseFloat(trade.q) * parseFloat(trade.p)
}
var buyNet = _N(tradeHistory.buyData.money - tradeHistory.sellData.money, 3)
logSting = 'active buy amount:' + _N(tradeHistory.buyData.amount, 3) + ' total money: ' + _N(tradeHistory.buyData.money, 3) + '\n'
logSting += 'active sell amount:' + _N(tradeHistory.sellData.amount, 3) + ' total money: ' + _N(tradeHistory.sellData.money, 3) + '\n'
logSting += 'Net inflow of funds: ' + _N(tradeHistory.buyData.money - tradeHistory.sellData.money, 3)
LogStatus(logSting)
if(new Date().getTime() - updateTime > Interval*1000){
updateTime = new Date().getTime()
LogProfit(buyNet)
$.PlotLine('buyNet', buyNet)
$.PlotLine('buy', _N(tradeHistory.buyData.money,3))
$.PlotLine('sell', _N(tradeHistory.sellData.money,3))
Log(logSting)
}
}
}
```
> 策略出处
https://www.fmz.com/strategy/121917
> 更新时间
2018-10-27 16:01:47
@@ -1,13 +1,21 @@
/*
策略出处: https://www.fmz.com/strategy/40289
策略名称: BitMEX 简单测试
策略作者: Tony123
策略描述:
> 策略名称
BitMEX 简单测试
> 策略作者
发明者量化
> 策略描述
现已接入BitMEX, 支持全平台API, 支持IO扩展.
*/
> 源码 (javascript)
``` javascript
// 只支持实盘
function main() {
exchange.SetContractType("XBTUSD")
@@ -27,3 +35,12 @@ function main() {
}
Log(_C(exchange.GetPosition))
}
```
> 策略出处
https://www.fmz.com/strategy/40289
> 更新时间
2017-05-08 17:20:34
@@ -0,0 +1,75 @@
> 策略名称
BitMEX 高级API功能 (期货:批量下单,一键撤单) JavaScript
> 策略作者
FawkesPan
> 源码 (javascript)
``` javascript
/*
BitMEX Advanced API Interface for FMZ.com.
Copyright 2018 FawkesPan
Contact : i@fawkex.me / Telegram@FawkesPan
GNU General Public License v3.0
*/
function main() {
Log(exchange.GetAccount());
}
var bulk = []
// 添加批量买单
function BulkBuy(symbol,qty,price,type,exec) {
Log("新的Bulk订单 开多 "+ symbol + " " + price + " " + qty)
var order = {};
order.symbol = symbol;
order.side = "Buy";
order.orderQty = qty;
order.price = price;
order.ordType = type;
order.execInst = exec;
bulk[Object.keys(bulk).length] = order;
}
// 添加批量卖单
function BulkSell(symbol,qty,price,type,exec) {
Log("新的Bulk订单 开空 "+ symbol + " " + price + " " + qty)
var order = {};
order.symbol = symbol;
order.side = "Sell";
order.orderQty = qty;
order.price = price;
order.ordType = type;
order.execInst = exec;
bulk[Object.keys(bulk).length] = order;
}
//执行批量订单
function BulkPost() {
Log("正在执行Bulk订单 共计 " + Object.keys(bulk).length + " 个订单");
var param = "orders=" + JSON.stringify(bulk);
bulk = [];
exchange.IO("api", "POST", "/api/v1/order/bulk", param);
}
//取消所有订单
function CancelPendingOrders() {
exchange.IO("api","DELETE","/api/v1/order/all","symbol="+exchange.GetCurrency());
}
```
> 策略出处
https://www.fmz.com/strategy/105056
> 更新时间
2018-08-30 03:01:43
@@ -0,0 +1,443 @@
> 策略名称
BitMEX 高级API功能 V.1.1.0 (期货:批量下单,编辑订单,冰山订单,一键撤单,定时撤单) Python2-3
> 策略作者
FawkesPan
> 策略描述
# BitMEX 高级API功能 (FMZ.com)
### 初始化
这个库整合了一些高级的 BitMEX API 功能,使用前需要进行初始化。
```
# 单个交易所
BitMEX = ext.BitMEXPlus(exchange) # 创建一个新的接口对象
# 多个交易所
BitMEX = ext.BitMEXPlus(exchanges[0]) # exchanges[这里取决于你的交易所添加在第几个]
```
### 订单操作
#### 批量订单
##### BulkAdd() 添加新订单到本地订单列表
```
side price amount 为必填参数
symbol 不填则使用默认交易对设置
displayQty 用于冰山订单功能 设置订单显示部分大小 设置为0则完全隐藏
orderType execInst 可选参数请看源码内备注
BitMEX.BulkAdd(side=string, price=float, amount=integer, symbol=string, displayQty=integer, ordType='Limit', clOrdID='', execInst='')
```
##### BulkClear() 清除本地未提交订单
```
symbol 指定后可清除指定交易对订单 如不指定则清除所有订单
notify 是否显示日志 默认为显示
BitMEX.BulkClear(symbol=string, notify=True)
```
##### BulkPost() 提交本地未提交订单
```
symbol 指定后只提交指定交易对订单 不指定则提交所有订单
BitMEX.BulkPost(symbol=string)
```
##### BulkOrders() 查看本地所有未提交订单
```
BitMEX.BulkOrders()
```
#### 取消订单
##### CancelAllOrders() 取消当前的未完成订单
```
symbol 指定后只取消指定交易对订单 不指定则取消所有订单
filter 自定义订单过滤 只取消符合条件的订单 如 filter={'side': 'Buy'} 取消所有买单
BitMEX.CancelAllOrders(symbol=string, filter=dict)
```
##### CancelAllAfter() 在一定时间后取消所有未完成订单
再次请求可以重置计数器
```
timeout 指定在多少毫秒后取消订单 填0可以删除计数器
BitMEX.CancelAllAfter(timeout=integer)
```
#### 编辑订单
##### Amend() 修改一个订单
```
symbol 指定交易对 不指定交易对则使用默认交易对
orderID clOrdID 订单ID和用户自定义订单ID 至少指定其中一项 两项都填则只使用orderID
price amount 订单的新价格和订单的新数量 至少修改其中一项 可以同时修改两项
BitMEX.Amend(symbol=string, orderID=string, clOrdID=string, price=float, amount=integer)
```
#### 批量编辑订单
##### AmendAdd() 添加一个需要修改的订单到本地待修改订单列表
```
symbol 指定交易对 不指定交易对则使用默认交易对
orderID clOrdID 订单ID和用户自定义订单ID 至少指定其中一项 两项都填则只使用orderID
price amount 订单的新价格和订单的新数量 至少修改其中一项 可以同时修改两项
BitMEX.AmendAdd(symbol=string, orderID=string, clOrdID=string, price=float, amount=integer)
```
##### AmendClear() 清除本地未提交的待修改订单
```
symbol 指定后可清除指定交易对订单 如不指定则清除所有订单
notify 是否显示日志 默认为显示
BitMEX.AmendClear(symbol=string, notify=True)
```
##### AmendPost() 提交本地未提交的待修改订单
```
symbol 指定后提交指定交易对订单修改请求 不指定则提交默认交易对订单的修改请求
BitMEX.AmendPost(symbol=string)
```
##### AmendOrders() 查看本地所有未提交订单
```
BitMEX.AmendOrders()
```
### 与我联系
邮箱 i@fawkex.me
电报 [FawkesPan](https://telegram.me/FawkesPan)
接受策略定制
### 关于这个库
[BitMEX API文档](https://www.bitmex.com/app/apiOverview)
[使用 GNU General Public License v3](https://www.gnu.org/licenses/gpl-3.0.en.html)
> 策略参数
|参数|默认值|描述|
|----|----|----|
|LANG|ZH|语言 / Language|
> 源码 (python)
``` python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# encoding: utf-8
#
# BitMEX Advanced API Interface for FMZ.com.
#
# Copyright 2018 FawkesPan
# Contact : i@fawkex.me / Telegram@FawkesPan
#
# GNU General Public License v3.0
#
import json
import math
import decimal
def toNearest(num, tickSize):
tickDec = decimal.Decimal(str(tickSize))
return float((decimal.Decimal(round(num / tickSize, 0)) * tickDec))
QUOTES = {}
QUOTES['ZH'] = {
'GREET' : '[BitMEX 接口已初始化] 合约: %s. %s',
'INITF' : '使用的交易所不正确,当前交易所: %s',
'PARAMERR' : '***传的参数不对 检查你的代码*** %s',
'NEWORDER' : '[添加订单] 合约: %s 方向: %s 价格: %.8f 数量: %d 张. %s',
'MODORDER' : '[修改订单] orderID/clOrdID: %s 新价格: %.8f 新数量: %d. %s',
'MODORDERP' : '[修改订单] orderID/clOrdID: %s 新价格: %.8f. %s',
'MODORDERA' : '[修改订单] orderID/clOrdID: %s 新数量: %d. %s',
'ORDCOUNT' : '[本次批量发送订单] 总计: %d 条. %s',
'THISBATCH' : '[信息] 正在处理 合约: %s 条数: %d. %s',
'CLEARALL' : '[信息] 已清除所有本地订单. %s',
'CLEAR' : '[信息] 已清除所有 %s 本地订单. %s',
'CA' : '[订单计划取消] 所有订单都将在 %d 毫秒 后取消. %s'
}
COLORS = {
'DEEPBLUE' : '#1F618D',
'BLUE' : '#0000FF',
'LIGHTBLUE' : '#5DADE2',
'DEEPGREEN' : '#27AE60',
'GREEN' : '#00FF00',
'LIGHTGREEN' : '#58D68D',
'LAPIS' : '#26619C',
'DEEPRED' : '#CB4335',
'RED' : '#FF0000',
'LIGHTRED' : '#EC7063'
}
class BitMEX:
def __init__(self, exchange):
self.QUOTES = {}
exchange.GetCurrency()
if isinstance(exchange.GetCurrency(), bytes):
self.symbol = str(exchange.GetCurrency(), "utf-8").lower()
name = str(exchange.GetName(), "utf-8")
else:
self.symbol = exchange.GetCurrency()
name = exchange.GetName()
self.IO = exchange.IO
self.bulks = []
self.amends = []
if 'BitMEX' in str(name):
Log(QUOTES[LANG]['GREET'] % (self.symbol.upper(),COLORS['LAPIS']))
else:
Log(QUOTES[LANG]['INITF'] % (name))
def BulkAdd(self, side=None, price=None, amount=None, symbol=None, ordType='Limit', displayQty=None, clOrdID=None, execInst=None):
if type is None or price is None or amount is None:
Log(QUOTES[LANG]['PARAMERR'] % (COLORS['RED']))
return False
side = side.lower()
if 'sell' in side:
side = 'Sell'
cl = COLORS['DEEPRED']
else:
side = 'Buy'
cl = COLORS['DEEPGREEN']
if symbol is None:
symbol = self.symbol
# Order structure
order = {}
order['symbol'] = symbol.upper() # Symbol
order['price'] = price # Price
order['side'] = side # Buy/Sell
order['orderQty'] = int(amount) # Amount
# Valid order types
# Market, Limit, Stop, StopLimit, MarketIfTouched, LimitIfTouched, MarketWithLeftOverAsLimit, Pegged
# Limit: The default order type. Specify an orderQty and price.
# Market: A traditional Market order. A Market order will execute until filled or your bankruptcy price is reached, at which point it will cancel.
# MarketWithLeftOverAsLimit: A market order that, after eating through the order book as far as permitted by available margin, will become a limit order. The difference between this type and Market only affects the behavior in thin books. Upon reaching the deepest possible price, if there is quantity left over, a Market order will cancel the remaining quantity. MarketWithLeftOverAsLimit will keep the remaining quantity in the books as a Limit.
# Stop: A Stop Market order. Specify an orderQty and stopPx. When the stopPx is reached, the order will be entered into the book.
## On sell orders, the order will trigger if the triggering price is lower than the stopPx. On buys, higher.
## Note: Stop orders do not consume margin until triggered. Be sure that the required margin is available in your account so that it may trigger fully.
## Close Stops don't require an orderQty. See Execution Instructions below.
# StopLimit: Like a Stop Market, but enters a Limit order instead of a Market order. Specify an orderQty, stopPx, and price.
# MarketIfTouched: Similar to a Stop, but triggers are done in the opposite direction. Useful for Take Profit orders.
# LimitIfTouched: As above; use for Take Profit Limit orders.
order['ordType'] = ordType
# If you want to keep track of order IDs yourself, set a unique clOrdID per order. This clOrdID will come back as a property on the order and any related executions (including on the WebSocket), and can be used to get or cancel the order. Max length is 36 characters.
if clOrdID is not None:
order['clOrdID'] = clOrdID
# The following execInsts are supported. If using multiple, separate with a comma (e.g. LastPrice,Close).
# ParticipateDoNotInitiate, MarkPrice, LastPrice, IndexPrice, ReduceOnly, Close
# ParticipateDoNotInitiate: Also known as a Post-Only order. If this order would have executed on placement, it will cancel instead.
# MarkPrice, LastPrice, IndexPrice: Used by stop and if-touched orders to determine the triggering price. Use only one. By default, 'MarkPrice' is used. Also used for Pegged orders to define the value of 'LastPeg'.
# ReduceOnly: A 'ReduceOnly' order can only reduce your position, not increase it. If you have a 'ReduceOnly' limit order that rests in the order book while the position is reduced by other orders, then its order quantity will be amended down or canceled. If there are multiple 'ReduceOnly' orders the least aggressive will be amended first.
# Close: 'Close' implies 'ReduceOnly'. A 'Close' order will cancel other active limit orders with the same side and symbol if the open quantity exceeds the current position. This is useful for stops: by canceling these orders, a 'Close' Stop is ensured to have the margin required to execute, and can only execute up to the full size of your position. If orderQty is not specified, a 'Close' order has an orderQty equal to your current position's size.
## Note that a Close order without an orderQty requires a side, so that BitMEX knows if it should trigger above or below the stopPx.
if execInst is not None:
order['execInst'] = execInst
if 'Close' in execInst:
del order['orderQty']
# Optional quantity to display in the book. Use 0 for a fully hidden order. (Iceberg Order)
if displayQty is not None:
order['displayQty'] = displayQty
self.bulks.append(order)
Log(QUOTES[LANG]['NEWORDER'] % (symbol.upper(),side.upper(),price,amount,cl))
return True
def BulkClear(self, symbol=None, notify=True):
ret = []
if symbol is None:
ret = self.bulks
self.bulks = []
if notify:
Log(QUOTES[LANG]['CLEARALL'] % (COLORS['RED']))
else:
new = []
for i in self.bulks:
if i['symbol'] != symbol:
new.append(i)
else:
ret.append(i)
self.bulks = new
Log(QUOTES[LANG]['CLEAR'] % (symbol.encode().upper(), COLORS['RED']))
return ret
def BulkPost(self, symbol=None):
orders = []
if symbol is None:
orders = self.BulkClear(notify=False)
else:
orders = self.BulkClear(symbol=symbol, notify=False)
ret = self.IO("api", "POST", "/api/v1/order/bulk", 'orders=%s' % json.dumps(orders))
Log(QUOTES[LANG]['ORDCOUNT'] % (len(orders),COLORS['LAPIS']))
return ret
def BulkOrders(self):
return self.bulks
def Amend(self, symbol=None, orderID=None, clOrdID=None, price=None, amount=None):
if symbol is None:
symbol = self.symbol
order = {}
order['symbol'] = symbol
if orderID is None:
if clOrdID is None:
Log(QUOTES[LANG]['PARAMERR'] % (COLORS['RED']))
return False
else:
order['clOrdID'] = clOrdID
else:
order['orderID'] = orderID
if price is not None:
order['price'] = price
if amount is not None:
order['orderQty'] = amount
if price is None and amount is None:
Log(QUOTES[LANG]['PARAMERR'] % (COLORS['RED']))
return False
ret = self.IO("api", "PUT", "/api/v1/order/bulk", 'orders=%s' % json.dumps([order]))
if ret == False:
return False
try:
id = order['orderID']
except:
id = order['clOrdID']
if price is None:
Log(QUOTES[LANG]['MODORDERA'] % (id, amount, COLORS['LAPIS']))
return ret
elif amount is None:
Log(QUOTES[LANG]['MODORDERP'] % (id, price, COLORS['LAPIS']))
return ret
else:
Log(QUOTES[LANG]['MODORDER'] % (id, price, amount, COLORS['LAPIS']))
return ret
def AmendAdd(self, symbol=None, orderID=None, clOrdID=None, price=None, amount=None):
if symbol is None:
symbol = self.symbol
order = {}
order['symbol'] = symbol
if orderID is None:
if clOrdID is None:
Log(QUOTES[LANG]['PARAMERR'] % (COLORS['RED']))
return False
else:
order['clOrdID'] = clOrdID
else:
order['orderID'] = orderID
if price is not None:
order['price'] = price
if amount is not None:
order['orderQty'] = amount
if price is None and amount is None:
Log(QUOTES[LANG]['PARAMERR'] % (COLORS['RED']))
return False
self.amends.append(order)
try:
id = order['orderID']
except:
id = order['clOrdID']
if price is None:
Log(QUOTES[LANG]['MODORDERA'] % (id, amount, COLORS['LAPIS']))
return True
elif amount is None:
Log(QUOTES[LANG]['MODORDERP'] % (id, price, COLORS['LAPIS']))
return True
else:
Log(QUOTES[LANG]['MODORDER'] % (id, price, amount, COLORS['LAPIS']))
return True
def AmendClear(self, symbol=None, notify=True):
ret = []
if symbol is None:
ret = self.amends
self.amends = []
if notify:
Log(QUOTES[LANG]['CLEARALL'] % (COLORS['RED']))
else:
new = []
for i in self.amends:
if i['symbol'] != symbol:
new.append(i)
else:
ret.append(i)
self.self.amends = new
Log(QUOTES[LANG]['CLEAR'] % (symbol.encode().upper(), COLORS['RED']))
return ret
def AmendPost(self, symbol=None):
if symbol is None:
symbol = self.symbol
orders = self.AmendClear(symbol=symbol, notify=False)
param = "orders=" + json.dumps(orders)
Log(QUOTES[LANG]['ORDCOUNT'] % (len(orders),COLORS['LAPIS']))
return self.IO("api", "PUT", "/api/v1/order/bulk", param)
def AmendOrders(self):
return self.amends
def CancelAllOrders(self, symbol=None, filters=None):
param = ''
if symbol is not None:
param = param + 'symbol=' + symbol
if filters is not None:
param = param + 'filters=' + json.dumps(filters)
return self.IO("api","DELETE","/api/v1/order/all", param)
def CancelAllAfter(self, timeout=0):
param = 'timeout=' + str(timeout)
Log(QUOTES[LANG]['CA'] % (timeout,COLORS['LAPIS']))
return self.IO("api","POST","/api/v1/order/cancelAllAfter", param)
def GetInstrument(self, symbol='XBTUSD'):
try:
import requests
except ModuleNotFoundError:
Log('pip安装requests以使用GetInstrument()函数.')
return {}
return requests.get('https://www.bitmex.com/api/v1/instrument?symbol=%s&count=1&reverse=false' % symbol).json()[0]
ext.BitMEXPlus = BitMEX # 导出BitMEX Class, 主策略可以通过BitMEXPlus = ext.BitMEXPlus(exchange)调用
ext.toNearest = toNearest
# 模块功能测试
def main():
LogReset()
Log(exchange.GetAccount())
BitMEXPlus = ext.BitMEXPlus(exchange)
exchange.SetContractType(exchange.GetCurrency())
base_price = exchange.GetTicker()['Last']
_toNearest = ext.toNearest
BitMEXPlus.BulkAdd('sell', _toNearest(base_price*1.4, 0.5), 30)
BitMEXPlus.BulkAdd('buy', _toNearest(base_price*0.7, 0.5), 30)
Log(BitMEXPlus.BulkOrders())
Log(BitMEXPlus.BulkPost())
Log(exchange.GetOrders())
Log(BitMEXPlus.CancelAllAfter(5000))
Sleep(8000)
Log(exchange.GetOrders())
Log(BitMEXPlus.BulkOrders())
```
> 策略出处
https://www.fmz.com/strategy/114148
> 更新时间
2018-11-13 18:07:03
@@ -0,0 +1,44 @@
> 策略名称
Bitmex仓位变化推送微信(wss协议,需要bitmex api ID)|Bitmex position-change push(websocket)
> 策略作者
botvsing
> 策略描述
使用websocket协议和平台最新的HMAC获取签名的方法,仓位有变化推送到微信
> 源码 (javascript)
``` javascript
function main() {
var APIKEY = "your Access Key(Bitmex API ID)"
var expires = parseInt(Date.now() / 1000) + 10
var signature = exchange.HMAC("sha256", "hex", "GET/realtime" + expires, "{{secretkey}}")
var client = Dial("wss://www.bitmex.com/realtime", 60)
var auth = JSON.stringify({args: [APIKEY, expires, signature], op: "authKeyExpires"})
var pos = 0
client.write(auth)
client.write('{"op": "subscribe", "args": "position"}')
while (true) {
bitmexData = client.read()
if(bitmexData.table == 'position' && pos != parseInt(bitmexData.data[0].currentQty)){
Log('position change', pos, parseInt(bitmexData.data[0].currentQty), '@')
pos = parseInt(bitmexData.data[0].currentQty)
}
}
}
```
> 策略出处
https://www.fmz.com/strategy/128624
> 更新时间
2018-12-04 18:04:36
@@ -1,32 +1,46 @@
/*
策略出处: https://www.fmz.com/strategy/59120
策略名称: BotVS 商品期货 量化 测试入门 策略
策略作者: 小小梦
策略描述:
> 策略名称
BotVS 商品期货 量化 测试入门 策略
> 策略作者
小小梦
> 策略描述
知乎专栏 文章:
via. https://zhuanlan.zhihu.com/p/30880706
> 策略参数
参数 默认值 描述
---------------- ------ ------
_Interval 500 轮询间隔
_StrContractType rb1801 测试合约代码
按钮 默认值 描述
---------------- ------------------- --------------
changeSymbol MA801 更改商品期货合约代码
OPEN_LONG true 开多
OPEN_SHORT true 开空
COVER true 按数量平仓
GET_PNEDING __button__ 获取当前合约未完成的订单
GET_ORDER 空 获取当前合约指定id 的订单
GET_POSITION 空 获取当前合约持仓信息
GET_ALL_POSITION __button__ 获取所有合约持仓信息
CANCEL_ORDER 空 取消订单
JS_CODE Log("call js code") 调用 JS 代码
*/
|参数|默认值|描述|
|----|----|----|
|_Interval|500|轮询间隔|
|_StrContractType|rb1801|测试合约代码|
|按钮|默认值|描述|
|----|----|----|
|changeSymbol|MA801|更改商品期货合约代码|
|OPEN_LONG|true|开多|
|OPEN_SHORT|true|开空|
|COVER|true|按数量平仓|
|GET_PNEDING|__button__|获取当前合约未完成的订单|
|GET_ORDER|空|获取当前合约指定id 的订单|
|GET_POSITION|空|获取当前合约持仓信息|
|GET_ALL_POSITION|__button__|获取所有合约持仓信息|
|CANCEL_ORDER|空|取消订单|
|JS_CODE|Log("call js code")|调用 JS 代码|
> 源码 (javascript)
``` javascript
// 商品期货 测试 程序
/*
1、 行情部分测试
@@ -351,3 +365,12 @@ function main(){
Sleep(_Interval)
}
}
```
> 策略出处
https://www.fmz.com/strategy/59120
> 更新时间
2017-11-09 13:41:44
@@ -1,13 +1,21 @@
/*
策略出处: https://www.fmz.com/strategy/61533
策略名称: C++ API调用例子
策略作者: Zero
策略描述:
> 策略名称
C++ API调用例子
> 策略作者
Zero
> 策略描述
支持C++ 11, 兼容各种平台(Windows/Linux/Mac). 云端编译.
*/
> 源码 (cpp)
``` cpp
void main() {
if (!Test("c++")) {
Panic("请下载最新版本托管者");
@@ -134,3 +142,12 @@ void main() {
}
}
}
```
> 策略出处
https://www.fmz.com/strategy/61533
> 更新时间
2018-02-14 11:35:11
@@ -1,8 +1,13 @@
/*
策略出处: https://www.fmz.com/strategy/17289
策略名称: CTP商品期货多品种海龟交易策略
策略作者: Zero
策略描述:
> 策略名称
CTP商品期货多品种海龟交易策略
> 策略作者
Zero
> 策略描述
- 只支持操作CTP商品期货
- 支持自动或手动恢复进度
@@ -18,32 +23,41 @@ BotVS docker 3.0 compiled at 2016-07-05T09:56:18+0800
https://dn-filebox.qbox.me/d33687abb648c489b6883296685e8717ea3f44ca.png
> 策略参数
参数 默认值 描述
-------------- --------------------------------------------------------------------------------------------------------------- -----------------------
Instruments MA701,CF701,zn1701,SR701,pp1701,l1701,hc1610,ni1701,i1701,v1701,rb1610,jm1701,ag1612,al1701,jd1701,cs1701,p1701 合约列表
LoopInterval 3 轮询周期(秒)
RiskRatio true % Risk Per N ( 0 - 100)
ATRLength 20 ATR计算周期
EnterPeriodA 20 系统一入市周期
LeavePeriodA 10 系统一离市周期
EnterPeriodB 55 系统二入市周期
LeavePeriodB 20 系统二离市周期
UseEnterFilter true 使用入市过滤
IncSpace 0.5 加仓间隔(N的倍数)
StopLossRatio 2 止损系数(N的倍数)
MaxLots 4 单品种加仓次数
RMode 0 进度恢复模式: 自动|手动
VMStatus {} 手动恢复字符串
WXPush true 推送交易信息
MaxTaskRetry 5 开仓最多重试次数
KeepRatio 10 预留保证金比例
按钮 默认值 描述
----- ---------- -----
暂停/继续 __button__ 暂停/继续
*/
|参数|默认值|描述|
|----|----|----|
|Instruments|MA701,CF701,zn1701,SR701,pp1701,l1701,hc1610,ni1701,i1701,v1701,rb1610,jm1701,ag1612,al1701,jd1701,cs1701,p1701|合约列表|
|LoopInterval|3|轮询周期(秒)|
|RiskRatio|true|% Risk Per N ( 0 - 100)|
|ATRLength|20|ATR计算周期|
|EnterPeriodA|20|系统一入市周期|
|LeavePeriodA|10|系统一离市周期|
|EnterPeriodB|55|系统二入市周期|
|LeavePeriodB|20|系统二离市周期|
|UseEnterFilter|true|使用入市过滤|
|IncSpace|0.5|加仓间隔(N的倍数)|
|StopLossRatio|2|止损系数(N的倍数)|
|MaxLots|4|单品种加仓次数|
|RMode|0|进度恢复模式: 自动|手动|
|VMStatus|{}|手动恢复字符串|
|WXPush|true|推送交易信息|
|MaxTaskRetry|5|开仓最多重试次数|
|KeepRatio|10|预留保证金比例|
|按钮|默认值|描述|
|----|----|----|
|暂停/继续|__button__|暂停/继续|
> 源码 (javascript)
``` javascript
/*backtest
start: 2016-03-01 00:00:00
end: 2016-12-30 00:00:00
@@ -624,3 +638,12 @@ function main() {
Sleep(LoopInterval * 1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/17289
> 更新时间
2018-03-23 22:33:42
@@ -1,30 +1,42 @@
'''
策略出处: https://www.fmz.com/strategy/101399
策略名称: CoinPark交易所通用协议 6.27 16:00 更新 关闭了SSL验证
策略作者: botvsing
策略描述:
> 策略名称
CoinPark交易所通用协议 6.27 16:00 更新 关闭了SSL验证
> 策略作者
botvsing
> 策略描述
## CoinPark通用协议Python2版本
用途:可以使BotVs支持coinpark.cc交易所
不知道什么是通用协议?https://www.botvs.com/bbs-topic/1052
可以把通用协议当成普通机器人,运行在BotVs模拟盘即可,不收取费用
也可以把代码保存起来,在服务器上用python运行
代码公开地址:https://www.botvs.com/strategy/101399
运行地址
http://127.0.0.1:6667
也可以在运行时指定端口
### 1.在托管者所在服务器运行插件
python coinpark.py 8866
在托管者所在服务器后台运行即可:
在保存成文件上传的托管者所在服务器,后台运行即可:
nohup python coinpark.py &
也可以在运行时指定端口:
python coinpark.py 8866
也可以当成一个普通机器人运行在模拟盘上,不收取费用。
### 2.在FMZ网站配置交易所
交易所配置如下:
![iamge](https://dn-filebox.qbox.me/c1456599386e597f2966f67b49c7102bab857fef.png)
已经经过部分人的测试,欢迎反馈
2018.6.26 18:46 更新,修改了Bug
由于账户没资产,未作详细测试,欢迎反馈Bug
2018.6.26 15:57 更新,修改了Bug
'''
> 源码 (python)
``` python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@@ -326,3 +338,12 @@ if __name__ == "__main__":
run(port=int(argv[1]))
else:
run()
```
> 策略出处
https://www.fmz.com/strategy/101399
> 更新时间
2018-09-01 14:55:09
@@ -1,19 +1,30 @@
/*
策略出处: https://www.fmz.com/strategy/37678
策略名称: Convert_Record_Cycle
策略作者: jxc6698
策略描述:
> 策略名称
Convert_Record_Cycle
> 策略作者
jxc6698
> 策略描述
# 得到指定周期的蜡烛图 线数据
如有BUG ,问题 欢迎留言
> 策略参数
参数 默认值 描述
---------------- ------------ -------
UI_NewCycleForMS 1000*60*60*2 合成周期毫秒数
*/
|参数|默认值|描述|
|----|----|----|
|UI_NewCycleForMS|1000*60*60*2|合成周期毫秒数|
> 源码 (javascript)
``` javascript
/**
* author: jcx
* date: 3/10/2017
@@ -190,3 +201,12 @@ function main() {
Sleep(1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/37678
> 更新时间
2017-03-13 16:41:10
@@ -1,27 +1,38 @@
/*
策略出处: https://www.fmz.com/strategy/103247
策略名称: Dual Thrust OKEX Feature
策略作者: botvsing
策略描述:
> 策略名称
Dual Thrust OKEX Feature
> 策略作者
botvsing
> 策略描述
Check the url below to learn abount Dual Thrust Strategy.
https://www.quantconnect.com/tutorials/strategy-library/dual-thrust-trading-algorithm
> 策略参数
参数 默认值 描述
--------------- ----- ------------------------------------------
ContractTypeIdx 0 Contract Name: this_week|next_week|quarter
MarginLevelIdx 0 Margin Level: 10|20
NPeriod 4 Period included
Ks 0.5 Up-track ratio
Kx 0.5 Down-track ratio
AmountOP true Open positon amount
Interval 2000 retry interval
LoopInterval 3 loop time(second)
PeriodShow 500 total K-line number to show for chart
*/
|参数|默认值|描述|
|----|----|----|
|ContractTypeIdx|0|Contract Name: this_week|next_week|quarter|
|MarginLevelIdx|0|Margin Level: 10|20|
|NPeriod|4|Period included|
|Ks|0.5|Up-track ratio|
|Kx|0.5|Down-track ratio|
|AmountOP|true|Open positon amount|
|Interval|2000|retry interval|
|LoopInterval|3|loop time(second)|
|PeriodShow|500|total K-line number to show for chart|
> 源码 (javascript)
``` javascript
var ChartCfg = {
__isStock: true,
title: {
@@ -237,3 +248,12 @@ function main() {
Sleep(LoopInterval * 1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/103247
> 更新时间
2018-07-04 14:41:06
+77
View File
@@ -0,0 +1,77 @@
> 策略名称
Dual Thrust (麦语言版)
> 策略作者
littleDreamXX
> 策略描述
> 基本原理
- 在当天收盘,计算两个值: 最高价-收盘价,和收盘价-最低价。然后取这两个值较大的那个,乘以k值,结果称为触发值。
- 在第二天开盘,记录开盘价,然后在价格超过(开盘+触发值)时马上买入,或者价格低于(开盘-触发值)时马上卖空。
- 这个系统是反转系统,没有单独止损。也就是说,反向信号也同时就是平仓信号。
> 图解
https://dn-filebox.qbox.me/ab06814528c0ae8c54c6bebaea4438325968fbe5.jpg
`Dual Thrust 策略包含完整的图表显示, 图表动态更新,模板引用等功能, 可做学习模板使用.`
策略的详细介绍 : http://xueqiu.com/5256769224/32429363
- 主图
上轨:公式:UPTRACK^^O+KS*RG;
下轨:公式:DOWNTRACK^^O-KX*RG;
- 副图:
无
> 策略参数
|参数|默认值|描述|
|----|----|----|
|N|4|计算周期|
|KS|0.5|上轨系数|
|KX|0.5|下轨系数|
> 源码 (麦语言)
``` pascal
(*backtest
start: 2018-01-01 00:00:00
end: 2018-02-28 00:00:00
period: 1d
exchanges: [{"eid":"Futures_OKCoin","currency":"BTC_USD"}]
args: [["ContractType","this_week",126961]]
*)
HH:=HV(H,N);
HC:=HV(C,N);
LL:=LV(L,N);
LC:=LV(C,N);
RG:=MAX(HH-LC,HC-LL);
UPTRACK^^O+KS*RG;
DOWNTRACK^^O-KX*RG;
// 交易信号
C>UPTRACK,BPK;
C<DOWNTRACK,SPK;
// 嵌入的JS 代码调整至 手册,有兴趣 可以研究。
```
> 策略出处
https://www.fmz.com/strategy/128884
> 更新时间
2018-12-06 12:09:22
@@ -1,8 +1,13 @@
/*
策略出处: https://www.fmz.com/strategy/12101
策略名称: Dual Thrust OKCoin 期货
策略作者: Zero
策略描述:
> 策略名称
Dual Thrust OKCoin 期货
> 策略作者
Zero
> 策略描述
> 基本原理
@@ -18,20 +23,26 @@
策略的详细介绍 : http://xueqiu.com/5256769224/32429363
> 策略参数
参数 默认值 描述
--------------- ----- --------------
ContractTypeIdx 0 合约品种: 当周|次周|季度
MarginLevelIdx 0 杠杆大小: 10|20
NPeriod 4 计算周期
Ks 0.5 上轨系数
Kx 0.5 下轨系数
AmountOP true 开仓合约张数
Interval 2000 重试间隔(毫秒)
LoopInterval 3 轮询间隔(秒)
PeriodShow 500 图表最大显示K线柱数
*/
|参数|默认值|描述|
|----|----|----|
|ContractTypeIdx|0|合约品种: 当周|次周|季度|
|MarginLevelIdx|0|杠杆大小: 10|20|
|NPeriod|4|计算周期|
|Ks|0.5|上轨系数|
|Kx|0.5|下轨系数|
|AmountOP|true|开仓合约张数|
|Interval|2000|重试间隔(毫秒)|
|LoopInterval|3|轮询间隔(秒)|
|PeriodShow|500|图表最大显示K线柱数|
> 源码 (javascript)
``` javascript
var ChartCfg = {
__isStock: true,
title: {
@@ -248,3 +259,12 @@ function main() {
Sleep(LoopInterval * 1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/12101
> 更新时间
2018-06-05 16:33:49
+166
View File
@@ -0,0 +1,166 @@
> 策略名称
Dual Thrust OKEX期货 (教学)
> 策略作者
小小梦
> 策略描述
> 基本原理
- 在当天收盘,计算两个值: 最高价-收盘价,和收盘价-最低价。然后取这两个值较大的那个,乘以k值,结果称为触发值。
- 在第二天开盘,记录开盘价,然后在价格超过(开盘+触发值)时马上买入,或者价格低于(开盘-触发值)时马上卖空。
- 这个系统是反转系统,没有单独止损。也就是说,反向信号也同时就是平仓信号。
> 图解
https://dn-filebox.qbox.me/ab06814528c0ae8c54c6bebaea4438325968fbe5.jpg
`Dual Thrust 策略包含完整的图表显示, 图表动态更新,模板引用等功能, 可做学习模板使用.`
策略的详细介绍 : http://xueqiu.com/5256769224/32429363
> 策略参数
|参数|默认值|描述|
|----|----|----|
|NPeriod|4|计算周期|
|Ks|0.5|上轨系数|
|Kx|0.5|下轨系数|
|AmountOP|true|开仓合约张数|
> 源码 (javascript)
``` javascript
var STATE_IDLE = 0
var STATE_LONG = 1
var STATE_SHORT = 2
var State = STATE_IDLE
var LastBarTime = 0
var UpTrack = 0
var DownTrack = 0
var InitAccount = null
function GetPosition(posType) {
var positions = exchange.GetPosition()
for (var i = 0; i < positions.length; i++) {
if (positions[i].Type === posType) {
return [positions[i].Price, positions[i].Amount];
}
}
return [0, 0]
}
function CancelPendingOrders() {
while (true) {
var orders = exchange.GetOrders()
for (var i = 0; i < orders.length; i++) {
exchange.CancelOrder(orders[i].Id)
Sleep(500)
}
if (orders.length === 0) {
break
}
}
}
function Trade(currentState, nextState) {
var pfn = nextState === STATE_LONG ? exchange.Buy : exchange.Sell
if (currentState !== STATE_IDLE) {
exchange.SetDirection(currentState === STATE_LONG ? "closebuy" : "closesell")
while (true) {
var amount = GetPosition(currentState === STATE_LONG ? PD_LONG : PD_SHORT)[1]
if (amount === 0) {
break
}
pfn(nextState === STATE_LONG ? _C(exchange.GetTicker).Sell * 1.001 : _C(exchange.GetTicker).Buy * 0.999, amount)
Sleep(500)
CancelPendingOrders()
}
var account = exchange.GetAccount()
LogProfit(_N(account.Stocks - InitAccount.Stocks, 3), "收益率:", _N((account.Stocks - InitAccount.Stocks) * 100 / InitAccount.Stocks, 3) + '%')
}
exchange.SetDirection(nextState === STATE_LONG ? "buy" : "sell")
while (true) {
var pos = GetPosition(nextState === STATE_LONG ? PD_LONG : PD_SHORT)
if (pos[1] >= AmountOP) {
Log("持仓均价", pos[0], "数量:", pos[1])
break
}
pfn(nextState === STATE_LONG ? _C(exchange.GetTicker).Sell * 1.001 : _C(exchange.GetTicker).Buy * 0.999, AmountOP-pos[1])
Sleep(500)
CancelPendingOrders()
}
}
function onTick() {
var records = exchange.GetRecords()
if (!records || records.length <= NPeriod) {
return
}
var Bar = records[records.length - 1]
$.PlotRecords(records, 'K线')
if (LastBarTime !== Bar.Time) {
var HH = TA.Highest(records, NPeriod, 'High')
var HC = TA.Highest(records, NPeriod, 'Close')
var LL = TA.Lowest(records, NPeriod, 'Low')
var LC = TA.Lowest(records, NPeriod, 'Close')
var Range = Math.max(HH - LC, HC - LL)
UpTrack = _N(Bar.Open + (Ks * Range), 3)
DownTrack = _N(Bar.Open - (Kx * Range), 3)
$.PlotHLine(UpTrack, 'UpTrack')
$.PlotHLine(DownTrack, 'DownTrack')
LastBarTime = Bar.Time
}
LogStatus("Price:", Bar.Close, "Up:", UpTrack, "Down:", DownTrack, "Date:", new Date())
var msg
if (State === STATE_IDLE || State === STATE_SHORT) {
if (Bar.Close >= UpTrack) {
msg = '做多 触发价: ' + Bar.Close + ' 上轨:' + UpTrack
Log(msg)
Trade(State, STATE_LONG)
State = STATE_LONG
$.PlotFlag(Bar.Time, msg, '多', 'flag', 'red')
}
}
if (State === STATE_IDLE || State === STATE_LONG) {
if (Bar.Close <= DownTrack) {
msg = '做空 触发价: ' + Bar.Close + ' 下轨:' + DownTrack
Log(msg)
Trade(State, STATE_SHORT)
$.PlotFlag(Bar.Time, msg, '空', 'circlepin', 'green')
State = STATE_SHORT
}
}
}
function main() {
exchange.SetContractType("quarter")
exchange.SetMarginLevel(10)
if (exchange.GetPosition().length > 0) {
throw "策略启动前不能有持仓."
}
CancelPendingOrders()
InitAccount = exchange.GetAccount()
while (true) {
onTick()
Sleep(500)
}
}
```
> 策略出处
https://www.fmz.com/strategy/112425
> 更新时间
2018-08-25 16:39:50
@@ -1,8 +1,13 @@
/*
策略出处: https://www.fmz.com/strategy/13011
策略名称: Dual Thrust 商品期货
策略作者: Zero
策略描述:
> 策略名称
Dual Thrust 商品期货
> 策略作者
Zero
> 策略描述
> 基本原理
@@ -18,21 +23,27 @@
策略的详细介绍 : http://xueqiu.com/5256769224/32429363
> 策略参数
参数 默认值 描述
---------------- ----- -----------
ContractTypeName MA701 合约品种
NPeriod 4 计算周期
Ks 0.5 上轨系数
Kx 0.5 下轨系数
AmountOP true 开仓合约张数
Interval 2000 重试间隔(毫秒)
LoopInterval 3 轮询间隔(秒)
PeriodShow 500 图表最大显示K线柱数
NotifyWX true 下单微信通知
CoverAll false 启动策略时清空合约仓位
*/
|参数|默认值|描述|
|----|----|----|
|ContractTypeName|MA701|合约品种|
|NPeriod|4|计算周期|
|Ks|0.5|上轨系数|
|Kx|0.5|下轨系数|
|AmountOP|true|开仓合约张数|
|Interval|2000|重试间隔(毫秒)|
|LoopInterval|3|轮询间隔(秒)|
|PeriodShow|500|图表最大显示K线柱数|
|NotifyWX|true|下单微信通知|
|CoverAll|false|启动策略时清空合约仓位|
> 源码 (javascript)
``` javascript
/*backtest
start: 2016-01-15 09:00:00
end: 2017-01-01 15:00:00
@@ -210,3 +221,12 @@ function main() {
Sleep(LoopInterval * 1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/13011
> 更新时间
2017-11-10 21:54:38
+106
View File
@@ -0,0 +1,106 @@
> 策略名称
Dynamic Balance Strategy
> 策略作者
ruby
> 策略参数
|参数|默认值|描述|
|----|----|----|
|threshold|0.05|threshold|
|ZPrecision|8|Price Precision|
|XPrecision|4|Amount Precision|
|MinStock|0.001|minimum buying amount|
|Interval|2000|error retry interval|
|LoopInterval|60|Polling Interval|
> 源码 (javascript)
``` javascript
var InitAccount = null;
function onTick(){
var acc = _C(exchange.GetAccount);
var ticker = _C(exchange.GetTicker);
var spread = ticker.Sell - ticker.Buy;
var diffAsset = (acc.Balance - (acc.Stocks * ticker.Sell))/2;
var ratio = diffAsset / acc.Balance;
LogStatus('ratio:', ratio, _D());
if(Math.abs(ratio) < threshold){
return false;
}
if(ratio > 0){
var buyPrice = _N(ticker.Sell + spread, ZPrecision);
var buyAmount = _N(diffAsset / buyPrice, XPrecision);
if(buyAmount < MinStock){
return false;
}
exchange.Buy(buyPrice, buyAmount);
} else {
var sellPrice = _N(ticker.Buy - spread, ZPrecision);
var sellAmount = _N(-diffAsset / sellPrice, XPrecision);
if (sellAmount < MinStock) {
return false;
}
exchange.Sell(sellPrice, sellAmount, diffAsset, ratio);
}
return true;
}
function CancelPendingOrders(){
var ret = false;
while(true){
var orders = null;
while(!(orders = exchange.GetOrders())){
Sleep(Interval);
}
if(orders.length == 0){
return ret;
}
for(var j = 0; j < orders.length; j++){
exchange.CancelOrder(orders[j],Id);
ret = true;
if(j < (orders.length - 1)){
Sleep(Interval);
}
}
}
}
function main() {
InitAccount = _C(exchange.GetAccount);
while(true){
if(onTick()){
Sleep(1000);
CancelPendingOrders();
Log(_C(exchange.GetAccount));
}
Sleep(LoopInterval * 1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/110900
> 更新时间
2018-08-13 12:35:18
@@ -1,146 +0,0 @@
/*
策略出处: https://www.fmz.com/strategy/98405
策略名称: FCoin交易手续费统计(感谢满总分享)
策略作者: 每日一嫩模
策略描述:
*/
//2018-6-13 22:19
var Trades = [];
var fees = {"usdt": 0, "btc": 0, "eth": 0, "etc": 0, "ft": 0};
var num = 0;
var table = {
type: "table",
title: "标题",
cols: ["ts", "时间", "买卖", "委托数", "委托价", "成交额", "成交数", "成交均价", "手续费", "来源", "状态", "交易对", "委托类型", "手续费币"],
rows: []
};
var FC_pairs = FC_pairs();
function main() {
/*
symbol 交易对
states 订单状态
submitted 已提交
partial_filled 部分成交
partial_canceled 部分成交已撤销
filled 完全成交
canceled 已撤销
pending_cancel 撤销已提交
before 查询某个页码之前的订单
after 查询某个页码之后的订单
limit 每页的订单数量,默认为 20 条
*/
var Pairs = Object.keys(FC_pairs);//["btcusdt","ltcusdt","ethusdt","ftusdt","ftbtc","etcusdt","bchusdt"];
var States = ["partial_canceled", "filled", "partial_filled"];
var after = new Date().setHours(0, 0, 0, 0);
var end = after + 24 * 3600 * 1000;
var ts0 = new Date().getTime();
Pairs.forEach(function (Symbol) {
var ts = after;
States.forEach(function (State) {
while (true) {
Sleep(1000);
//Log(56,new Date().getTime()-ts0);
ts0 = new Date().getTime();
var ordersHistory = FC_ordersHistory(Symbol, State, "after", ts);
calcFees(ordersHistory, end);
if (ordersHistory.length < 100) {
break;
}
ts = ordersHistory[0].created_at + 1;
}
});
});
Log(fees, after, new Date(after));//new Date().format("M-d h:m:s")
table.title = JSON.stringify(fees);
table.rows = Trades;
// LogStatus("`" + JSON.stringify([table]) + "`" + "\n");
}
function calcFees(ordersHistory, end) {
ordersHistory.forEach(function (v) {
if (v.created_at < end) {
var quote = FC_pairs[v.symbol][v.side === "buy" ? 0 : 1];
if (!fees.hasOwnProperty(quote)) {
fees[quote] = 0;
}
fees[quote] += Number(v.fill_fees);
Trades.push(FC_ordersformat(v).concat([quote]));
}
});
}
function FC_pairs() {
var info;
var sleep = 1000;
try {
info = exchange.IO("api", "GET", "/v2/public/symbols");//
} catch (e) {
Log("FC_pairs()出错重试");
Sleep(sleep);
sleep += sleep;
FC_pairs();
}
if (info.hasOwnProperty("status") && info.status === 429) {
Log("429错误");
Sleep(10000);
FC_pairs();
} else {
info = info.data;
}
var ret = {};
info.forEach(function (v) {
if (!ret.hasOwnProperty(v)) {
ret[v.name] = {};
}
ret[v.name] = [v.base_currency, v.quote_currency];
});
return ret;
}
function FC_ordersHistory(symbol, states, after_before, ts) {
Log(ts, new Date(ts));
var args = "symbol=" + symbol + "&limit=100&states=" + states + "&" + after_before + "=" + ts;
var info;
var sleep = 3000;
try {
info = exchange.IO("api", "GET", "/v2/orders", args);
Log(args);
Log(info.data.length);
} catch (e) {
Log("FC_ordersHistory 出错重试");
Sleep(sleep);
sleep += sleep;
return FC_ordersHistory(symbol, states, after_before, ts);
}
if (info.hasOwnProperty("status") && info.status === 429) {
Log("429错误");
Sleep(10000);
return FC_ordersHistory(symbol, states, after_before, ts);
}
return info.data;
}
function FC_ordersformat(v) {
var ret = [v.created_at, new Date(v.created_at), v.side, Number(v.amount), Number(v.price), Number(v.executed_value), Number(v.filled_amount), _N(Number(v.executed_value) / Number(v.filled_amount), 8), Number(v.fill_fees), v.source, v.state, v.symbol, v.type];
return ret;
}
@@ -0,0 +1,126 @@
> 策略名称
Fomo3D 智能合约监控 - Fomo3D Smart Contract Monitoring
> 策略作者
FawkesPan
> 策略参数
|参数|默认值|描述|
|----|----|----|
|TG|0|是否启用 Telegram 机器人: 0|1|
|TGKEY||Telegram 机器人KEY|
|TGID|false|Telegram 会话ID|
|THRESHOLD|300|触发通知阈值|
|REFRESH_DELAY|10|刷新数据间隔|
|INFURAKEY|需要到infura.io申请密钥并且添加合约地址白名单|数据接口密钥|
|CONTRACT|0xa62142888aba8370742be823c1782d17a0389da1|智能合约地址|
|WECHAT|0|启用微信通知: 0|1|
> 源码 (python)
``` python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# encoding: utf-8
#
# Fomo3D Smart Contract Monitoring
#
# Copyright 2018 FawkesPan
# Contact : i@fawkex.me / Telegram@FawkesPan
#
# Do What the Fuck You Want To Public License
#
import requests
import re
import json
import time
import datetime
LogReset()
if TG == 1:
TG_ENABLE = True
else:
TG_ENABLE = False
if WECHAT == 1:
WC_ENABLE = True
else:
WC_ENABLE = False
TG_BOT_KEY = TGKEY
TGURL = 'https://api.telegram.org/bot%s/sendMessage' % TG_BOT_KEY
TGPARAM = {}
TGPARAM['chat_id'] = TGID
def Send(message):
if TG_ENABLE == False:
return
try:
TGPARAM['text'] = message
res = requests.post(TGURL, data = TGPARAM)
return
except IOError as e:
print(e)
return
def Refresh():
URL = 'https://mainnet.infura.io/%s' % INFURAKEY
HEADER = {'Content-Type': 'application/json'}
PARAM = '{"jsonrpc": "2.0", "id": 1, "method": "eth_call", "params": [{"data":"0x747dff42","to":"%s"},"latest"]}' % CONTRACT
data = requests.post(URL,data=PARAM,headers=HEADER).json()
HEX = re.sub('(0{2,})','X',data['result']).split('X')[3]
print(HEX)
INT = int(HEX, 16)
NOW = int(time.time())
LEFT = INT - NOW
return LEFT
def main():
Log('Started!')
Log('ContractAddress: ' + CONTRACT)
Log('Telegram Enabled: ' + str(TG_ENABLE))
Log('WeChat Enabled: ' + str(WC_ENABLE))
while True:
try:
DATE = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
TIMELEFT = Refresh()
message = 'Time before FOMO ENDING : %d' % TIMELEFT
if TIMELEFT < 0:
TIMELEFT = THRESHOLD + 10
if TIMELEFT <= THRESHOLD:
Send(message)
if WC_ENABLE == True:
message = message + ' !@'
Log(message)
else:
Log(message)
except IOError as e:
print(e)
time.sleep(REFRESH_DELAY)
pass
time.sleep(REFRESH_DELAY)
```
> 策略出处
https://www.fmz.com/strategy/107916
> 更新时间
2018-09-12 02:35:10
@@ -0,0 +1,51 @@
> 策略名称
Get cryptocurrency current and max supply|获取币种供应量
> 策略作者
botvsing
> 源码 (javascript)
``` javascript
function GetSupply(symbol, max){
var ids = null
if(_G('ids')){
ids = _G('ids')
}else{
ids = JSON.parse(HttpQuery('https://api.coinmarketcap.com/v2/listings/')).data
_G('ids', ids)
}
var coinId = null
for (var i=0; i<ids.length; i++){
if(ids[i].symbol.toLowerCase() == symbol.toLowerCase() ){
coinId = ids[i].id
break
}
}
if(coinId){
var ticker = JSON.parse(HttpQuery('https://api.coinmarketcap.com/v2/ticker/'+ coinId + '/')).data
return parseFloat(max == undefined ? ticker.total_supply: ticker.max_supply)
}else{
throw 'symbol not found'
}
}
function main() {
Log(GetSupply('BTC')) // Get total current supply
Log(GetSupply('BTC', true)) // Get max supply
}
```
> 策略出处
https://www.fmz.com/strategy/122370
> 更新时间
2018-10-18 20:55:41
+85
View File
@@ -0,0 +1,85 @@
> 策略名称
GuoJian_First
> 策略作者
liuguojian
> 策略参数
|参数|默认值|描述|
|----|----|----|
|min|0.0085|买入最小值|
|max|0.008534|卖出最大值|
> 源码 (javascript)
``` javascript
/*backtest
start: 2018-08-27 00:00:00
end: 2018-08-28 20:00:00
period: 1m
exchanges: [{"eid":"Huobi","currency":"LTC_BTC"}]
*/
function main() {
Log(max);
Log(min);
var a = 1;
while(true){
Log(exchange.GetAccount());
var ticker = exchange.GetTicker();
Log(ticker);
if(ticker.High >= max){
//Log("当前最高价"+ticker.High);
//Log("将所有USDT换成BTC");
Log("卖出1");
exchange.Sell(-1, 1);
Log(exchange.GetAccount());
}
if(ticker.Low <= min){
Log("买入1");
exchange.Buy(-1, 1);
Log(exchange.GetAccount());
break;
}
a++;
Sleep(60000); // 一分钟
}
}
function onexit(){
Log("onexit");
}
function onerror(){
Log("onerror");
}
function init(){
Log("init");
}
```
> 策略出处
https://www.fmz.com/strategy/113871
> 更新时间
2018-08-28 21:43:15
@@ -1,8 +1,13 @@
/*
策略出处: https://www.fmz.com/strategy/48536
策略名称: Hedge_BTC-ETH Demo
策略作者: 小小梦
策略描述:
> 策略名称
Hedge_BTC-ETH Demo
> 策略作者
小小梦
> 策略描述
BTC 和 ETH 的 跨品种对冲 思路测试 DEMO
根据价格比 画出 图表,分析 价格比 变化,寻找套利空间。
@@ -10,12 +15,18 @@ BTC 和 ETH 的 跨品种对冲 思路测试 DEMO
by littleDream
> 策略参数
参数 默认值 描述
---- ----- ------------
Mode 0 模式: BOLL|SMA
*/
|参数|默认值|描述|
|----|----|----|
|Mode|0|模式: BOLL|SMA|
> 源码 (javascript)
``` javascript
/*exchanges
A : BTC
B : ETH
@@ -155,3 +166,12 @@ function main() {
}
}
```
> 策略出处
https://www.fmz.com/strategy/48536
> 更新时间
2017-07-25 13:19:52
+36 -16
View File
@@ -1,27 +1,38 @@
/*
策略出处: https://www.fmz.com/strategy/103319
策略名称: Iceberg Buy Order
策略作者: botvsing
策略描述:
> 策略名称
Iceberg Buy Order
> 策略作者
botvsing
> 策略描述
冰山委托指的是投资者在进行大额交易时,为避免对市场造成过大冲击,将大单委托自动拆为多笔委托,根据当前的最新买一/卖一价格和客户设定的价格策略自动进行小单委托,在上一笔委托被全部成交或最新价格明显偏离当前委托价时,自动重新进行委托。
例子:
如果单次均值浮动点数设置为10那么:
每一笔委托的数量为其单次委托平均值的90%~110%,委托价格为最新买1价*(1-委托深度),在上一笔委托全部成交后再进行新的一笔委托,在最新成交价格距离该笔委托超过委托深度*2时自动撤单并重新进行委托。在策略总成交量等于其总委托数量时停止委托。当市场的最新成交价格高于其最高买入价格时停止委托,在最新成交价格重新低于最高买入价后恢复委托。
> 策略参数
参数 默认值 描述
------------ ------ -----------------------
TotalBuyNet 10000 total buy value
AvgBuyOnce 100 avg buy value
FloatPoint 10 avg price float percent
EntrustDepth 0.1 buy depth percent
MaxBuyPrice 20000 Highest price to buy
Interval 1000 retry time(ms)
MinStock 0.0001 Min Stock
LoopInterval true loop time(second)
*/
|参数|默认值|描述|
|----|----|----|
|TotalBuyNet|10000|total buy value|
|AvgBuyOnce|100|avg buy value|
|FloatPoint|10|avg price float percent|
|EntrustDepth|0.1|buy depth percent|
|MaxBuyPrice|20000|Highest price to buy|
|Interval|1000|retry time(ms)|
|MinStock|0.0001|Min Stock|
|LoopInterval|true|loop time(second)|
> 源码 (javascript)
``` javascript
function CancelPendingOrders() {
while (true) {
var orders = _C(exchange.GetOrders);
@@ -99,3 +110,12 @@ function main() {
Log("All Done", _C(exchange.GetAccount));
}
```
> 策略出处
https://www.fmz.com/strategy/103319
> 更新时间
2018-07-05 11:10:09
@@ -1,13 +1,19 @@
/*
策略出处: https://www.fmz.com/strategy/44593
策略名称: JS版 商品期货 精简多品种 MACD 趋势策略框架
策略作者: 小小梦
策略描述:
> 策略名称
JS版 商品期货 精简多品种 MACD 趋势策略框架
> 策略作者
小小梦
*/
> 源码 (javascript)
``` javascript
/*backtest
start: 2016-01-30
end: 2016-12-30
@@ -87,3 +93,12 @@ function main(){
}
```
> 策略出处
https://www.fmz.com/strategy/44593
> 更新时间
2017-06-24 10:32:57
@@ -1,13 +1,21 @@
/*
策略出处: https://www.fmz.com/strategy/36100
策略名称: JS版本Dual Thrust
策略作者: BotVs@太极
策略描述:
> 策略名称
JS版本Dual Thrust
*/
> 策略作者
BotVs@太极
> 策略描述
JS版本Dual Thrust
> 源码 (javascript)
``` javascript
// botvs@505d17ec1da140d9467374ae4c1ad024
//==========================================
//API: Chart 函数使用的简单例子(画图功能)
@@ -118,3 +126,12 @@ function main() {
}
}
```
> 策略出处
https://www.fmz.com/strategy/36100
> 更新时间
2017-02-18 17:25:01
@@ -1,13 +1,19 @@
/*
策略出处: https://www.fmz.com/strategy/42283
策略名称: KingKeltner趋势策略_低频
策略作者: ipqhjjybj
策略描述:
> 策略名称
KingKeltner趋势策略_低频
> 策略作者
ipqhjjybj
*/
> 源码 (javascript)
``` javascript
/*
策略出处: vnpy
策略名称: KingKeltner趋势策略
@@ -137,3 +143,12 @@ function main() {
Sleep(LoopInterval*1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/42283
> 更新时间
2017-06-02 23:06:08
+81
View File
@@ -0,0 +1,81 @@
> 策略名称
MA5
> 策略作者
yy1987316
> 策略参数
|参数|默认值|描述|
|----|----|----|
|RETRY_INTERVAL|true|重试间隔(秒)|
> 源码 (python)
``` python
'''
MA5策略
站上买,跌破卖
'''
import datetime
def onTick():
'''轮训函数'''
account = _C(exchange.GetAccount)
Log(account)
kline_data = _C(exchange.GetRecords, PERIOD_D1)
# 前一个周期的MA5值,排除当前周期
ma5_list = TA.MA(kline_data, 5)
if len(ma5_list) >= 2:
ma5 = ma5_list[-2]
if ma5:
# 如果有值,回测时间段内开始的几个周期,没有ma5
# 取上个周期的开盘价、收盘价
open_price = kline_data[-2].Open
close_price = kline_data[-2].Close
Log('当前:open_price=', open_price, ',close_price=', close_price, ',ma5=', ma5)
if open_price < ma5 < close_price and account.Balance > 10:
Log('买')
exchange.Buy(-1, account.Balance)
elif close_price < ma5 < open_price and account.Stocks > 0.1:
Log('卖')
exchange.Sell(-1, account.Stocks)
else:
Log('无行情')
else:
Log('当前时间无MA5供参考')
def wait_to_tomorrow():
'''等待到第二天0点'''
s = _N(UnixNano() / 1000000000)
s = 86400 - (s - 16*60*60) % 86400 + 1
# Log(s)
Sleep(s * 1000)
def main():
# 设置重试延迟
_CDelay(RETRY_INTERVAL * 1000)
while True:
onTick()
wait_to_tomorrow()
# Sleep(LOOP_INTERVAL * 1000)
```
> 策略出处
https://www.fmz.com/strategy/125474
> 更新时间
2018-11-09 18:13:18
+99
View File
@@ -0,0 +1,99 @@
> 策略名称
MACD+MA指标组合策略
> 策略作者
littleDreamXX
> 策略描述
- 公式名称:MACD+MA指标组合策略
- 数据周期:日K
- 数据合约:指数合约
- 交易合约:主力合约
- 适合品种:商品期货
- 官方网站:WWW.QUANT.LA
- 副图
副图显示:MACDDIFF,公式 MACDDIFF:MACDVALUE-AVGMACD;
- 主图
主图显示:DMA1,公式 DMA1^^MA(C,L1);
DMA2,公式 DMA2^^MA(C,L2);
/upload/asset/6d7b1a3241d607bbc4f4f853687fcf54.png
> 策略参数
|参数|默认值|描述|
|----|----|----|
|FASTLENGTH|12|MACD指标参数1|
|SLOWLENGTH|26|MACD指标参数2|
|MACDLENGTH|9|MACD指标参数3|
|L1|50|均线1指标|
|L2|120|均线2指标|
|STOPLOSS|5|止损百分比|
> 源码 (麦语言)
``` pascal
(*backtest
start: 2016-06-01 00:00:00
end: 2016-07-19 00:00:00
period: 1h
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
*)
// MACD计算参数 已经添加到,策略参数
// FASTLENGTH:=12;
// SLOWLENGTH:=26;
// MACDLENGTH:=9;
// 均线长度 已经添加到,策略参数
// L1:=50;
// L2:=120;
// 止损5% 已经添加到,策略参数
// STOPLOSS:=5;
//MACD
MACDVALUE:=EMA(CLOSE,FASTLENGTH)-EMA(CLOSE,SLOWLENGTH);
AVGMACD:=EMA(MACDVALUE,MACDLENGTH);
MACDDIFF:MACDVALUE-AVGMACD;
//MA1、MA2
DMA1^^MA(C,L1);
DMA2^^MA(C,L2);
买入开仓价:=VALUEWHEN(BARSBK=1,O);
卖出开仓价:=VALUEWHEN(BARSSK=1,O);
BUYCONDITION:=MACDVALUE>0 && DMA1>DMA2 && MACDDIFF>0 && C>DMA1 && REF(C,1)>REF(DMA1,1);
SELLCONDITION:=MACDVALUE<0 && DMA1<DMA2 && MACDDIFF<0 && C<DMA1 && REF(C,1)<REF(DMA1,1);
//开仓条件
BKVOL=0 AND BUYCONDITION,BK;
SKVOL=0 AND SELLCONDITION,SK;
//离场条件
BKVOL>0 AND (REF(MACDVALUE,1)<0 OR REF(DMA1,1)<REF(DMA2,1)),SP;
SKVOL>0 AND (REF(MACDVALUE,1)>0 OR REF(DMA1,1)>REF(DMA2,1)),BP;
// 启动止损
SKVOL>0 AND HIGH>=卖出开仓价*(1+STOPLOSS*0.01),BP;
SETSIGPRICETYPE(BP,MAX(O,卖出开仓价*(1+STOPLOSS*0.01)));
BKVOL>0 AND LOW<=买入开仓价*(1-STOPLOSS*0.01),SP;
SETSIGPRICETYPE(SP,MIN(O,买入开仓价*(1-STOPLOSS*0.01)));
AUTOFILTER;
```
> 策略出处
https://www.fmz.com/strategy/128134
> 更新时间
2018-12-05 11:48:12
@@ -1,13 +1,19 @@
/*
策略出处: https://www.fmz.com/strategy/42451
策略名称: Ma单均线趋势交易
策略作者: ipqhjjybj
策略描述:
> 策略名称
Ma单均线趋势交易
> 策略作者
ipqhjjybj
*/
> 源码 (javascript)
``` javascript
/*
策略出处: internet
策略名称: MA 单均线趋势策略
@@ -139,3 +145,12 @@ function main() {
}
```
> 策略出处
https://www.fmz.com/strategy/42451
> 更新时间
2017-06-04 21:55:07
@@ -1,8 +1,13 @@
/*
策略出处: https://www.fmz.com/strategy/8602
策略名称: My-1-价值平均定投策略
策略作者: Lizza
策略描述:
> 策略名称
My-1-价值平均定投策略
> 策略作者
Lizza
> 策略描述
实盘:https://www.botvs.com/m/robot/26018
这个策略适合长期看好比特币的脑残粉,使用价值平均策略来进行定投,可以有效的抵抗市场波动。(关于价值平均定投请度娘。)
@@ -22,22 +27,31 @@
说明:程序会每次检查账户内的资金和比特币与启动时的差额,以此计算每次需要购买的数量,因此不要用其他机器人公用一个帐户,也不要手工进行买入卖出的操作。如果在交易所有充值和体现,应该在程序互动部分填入,否则程序计算会错误。
> 策略参数
参数 默认值 描述
--------------- ------- ------------
ErrorInterval 2000 出错重试(毫秒)
InvestInternal 15 投资间隔(按照分钟计算)
MoneyEveryMonth 5000 每月要投资的资金量
SlidePrice 0.05 购买时滑点
按钮 默认值 描述
----------- ---------- -----------
Pause __button__ 暂停交易
Continue __button__ 继续交易
MoneyChange false 纪录资金充值或提现
StockChange false 纪录数字货币充值或提现
*/
|参数|默认值|描述|
|----|----|----|
|ErrorInterval|2000|出错重试(毫秒)|
|InvestInternal|15|投资间隔(按照分钟计算)|
|MoneyEveryMonth|5000|每月要投资的资金量|
|SlidePrice|0.05|购买时滑点|
|按钮|默认值|描述|
|----|----|----|
|Pause|__button__|暂停交易|
|Continue|__button__|继续交易|
|MoneyChange|false|纪录资金充值或提现|
|StockChange|false|纪录数字货币充值或提现|
> 源码 (javascript)
``` javascript
var initAccount;
var startTime; //unix timestamp
var pause = false; //pause execution of strategy or continue
@@ -267,3 +281,12 @@ function onexit(){
Log('Robot Stopped!#ff0000@');
}
```
> 策略出处
https://www.fmz.com/strategy/8602
> 更新时间
2016-06-14 10:42:59
@@ -1,27 +1,38 @@
/*
策略出处: https://www.fmz.com/strategy/2169
策略名称: OKCoin期货条件触发委托带止损
策略作者: Zero
策略描述:
> 策略名称
OKCoin期货条件触发委托带止损
> 策略作者
Zero
> 策略描述
OKCoin期货条件触发下单, 成交后可条件触发自动止损
> 策略参数
参数 默认值 描述
--------------- ----- -----------------
CType 0 货币类型: 人民币|美元
ContractType 0 合约类型: 当周|下周|当月|季度
OpType 0 操作类型: 开多|开空
MLevel 0 杠杆大小: 10倍|20倍
TriggerType 0 触发方式: 涨超|跌落
TriggerPrice 2000 开仓触发价格(元)
OrderPrice 2005 开仓委托价(元)
OrderAmount true 开仓委托量
StopLossTrigger 1800 止损触发价(元)
StopOrderPrice 1790 止损委托价(元)
LoopInterval 300 轮询间隔(毫秒)
*/
|参数|默认值|描述|
|----|----|----|
|CType|0|货币类型: 人民币|美元|
|ContractType|0|合约类型: 当周|下周|当月|季度|
|OpType|0|操作类型: 开多|开空|
|MLevel|0|杠杆大小: 10倍|20倍|
|TriggerType|0|触发方式: 涨超|跌落|
|TriggerPrice|2000|开仓触发价格(元)|
|OrderPrice|2005|开仓委托价(元)|
|OrderAmount|true|开仓委托量|
|StopLossTrigger|1800|止损触发价(元)|
|StopOrderPrice|1790|止损委托价(元)|
|LoopInterval|300|轮询间隔(毫秒)|
> 源码 (javascript)
``` javascript
var _ContractType = ["this_week", "next_week", "month", "quarter"][ContractType];
var _TradeType = ["buy", "sell"][OpType];
var _MarginLevel = [10, 20][MLevel];
@@ -178,3 +189,12 @@ function main() {
}
Log("完成所有操作, 策略退出.");
}
```
> 策略出处
https://www.fmz.com/strategy/2169
> 更新时间
2014-12-10 15:33:25
@@ -0,0 +1,564 @@
> 策略名称
OKCoin期货跨期对冲策略(模板测试使用)
> 策略作者
小小梦
> 策略描述
OKCoin期货跨期对冲策略(模板)
> 策略参数
|参数|默认值|描述|
|----|----|----|
|OpMode|0|现货-下单方式: 吃单|挂单|
|MaxSpace|0.5|现货-挂单失效距离|
|SlidePrice|0.1|现货-下单滑动价(元)|
|MaxAmount|0.8|现货-开仓最大单次下单量|
|RetryDelay|500|现货-失败重试(毫秒)|
|MAType|0|现货-均线算法: EMA|MA|AMA(自适应均线)|
|Interval|300|期货—失败重试间隔(毫秒)|
|F_SlidePrice|2|期货—下单滑价(元)|
|lv|0.5|期货—滑价增长率|
|max_open_lv|true|期货—开仓滑价最大增长率|
|max_cover_lv|true|期货—平仓滑价最大增长率|
> 源码 (javascript)
``` javascript
// 现货部分
function CancelPendingOrders(e, orderType) {
while (true) {
var orders = e.GetOrders();
if (!orders) {
Sleep(RetryDelay);
continue;
}
var processed = 0;
for (var j = 0; j < orders.length; j++) {
if (typeof(orderType) === 'number' && orders[j].Type !== orderType) {
continue;
}
e.CancelOrder(orders[j].Id, orders[j]);
processed++;
if (j < (orders.length - 1)) {
Sleep(RetryDelay);
}
}
if (processed === 0) {
break;
}
}
}
function GetAccount(e, waitFrozen) {
if (typeof(waitFrozen) == 'undefined') {
waitFrozen = false;
}
var account = null;
var alreadyAlert = false;
while (true) {
account = _C(e.GetAccount);
if (!waitFrozen || (account.FrozenStocks < e.GetMinStock() && account.FrozenBalance < 0.01)) {
break;
}
if (!alreadyAlert) {
alreadyAlert = true;
Log("发现账户有冻结的钱或币", account);
}
Sleep(RetryDelay);
}
return account;
}
function StripOrders(e, orderId) {
var order = null;
if (typeof(orderId) == 'undefined') {
orderId = null;
}
while (true) {
var dropped = 0;
var orders = _C(e.GetOrders);
for (var i = 0; i < orders.length; i++) {
if (orders[i].Id == orderId) {
order = orders[i];
} else {
var extra = "";
if (orders[i].DealAmount > 0) {
extra = "成交: " + orders[i].DealAmount;
} else {
extra = "未成交";
}
e.CancelOrder(orders[i].Id, orders[i].Type == ORDER_TYPE_BUY ? "买单" : "卖单", extra);
dropped++;
}
}
if (dropped === 0) {
break;
}
Sleep(RetryDelay);
}
return order;
}
// mode = 0 : direct buy, 1 : buy as buy1
function Trade(e, tradeType, tradeAmount, mode, slidePrice, maxAmount, maxSpace, retryDelay) {
var initAccount = GetAccount(e, true);
var nowAccount = initAccount;
var orderId = null;
var prePrice = 0;
var dealAmount = 0;
var diffMoney = 0;
var isFirst = true;
var tradeFunc = tradeType == ORDER_TYPE_BUY ? e.Buy : e.Sell;
var isBuy = tradeType == ORDER_TYPE_BUY;
while (true) {
var ticker = _C(e.GetTicker);
var tradePrice = 0;
if (isBuy) {
tradePrice = _N((mode === 0 ? ticker.Sell : ticker.Buy) + slidePrice, 4);
} else {
tradePrice = _N((mode === 0 ? ticker.Buy : ticker.Sell) - slidePrice, 4);
}
if (!orderId) {
if (isFirst) {
isFirst = false;
} else {
nowAccount = GetAccount(e, true);
}
var doAmount = 0;
if (isBuy) {
diffMoney = _N(initAccount.Balance - nowAccount.Balance, 4);
dealAmount = _N(nowAccount.Stocks - initAccount.Stocks, 4);
doAmount = Math.min(maxAmount, tradeAmount - dealAmount, _N((nowAccount.Balance - 10) / tradePrice, 4));
} else {
diffMoney = _N(nowAccount.Balance - initAccount.Balance, 4);
dealAmount = _N(initAccount.Stocks - nowAccount.Stocks, 4);
doAmount = Math.min(maxAmount, tradeAmount - dealAmount, nowAccount.Stocks);
}
if (doAmount < e.GetMinStock()) {
break;
}
prePrice = tradePrice;
orderId = tradeFunc(tradePrice, doAmount, ticker);
if (!orderId) {
CancelPendingOrders(e, tradeType);
}
} else {
if (mode === 0 || (Math.abs(tradePrice - prePrice) > maxSpace)) {
orderId = null;
}
var order = StripOrders(e, orderId);
if (!order) {
orderId = null;
}
}
Sleep(retryDelay);
}
if (dealAmount <= 0) {
return null;
}
return {
price: _N(diffMoney / dealAmount, 4),
amount: dealAmount
};
}
$.Buy = function(e, amount) {
if (typeof(e) === 'number') {
amount = e;
e = exchange;
}
return Trade(e, ORDER_TYPE_BUY, amount, OpMode, SlidePrice, MaxAmount, MaxSpace, RetryDelay);
};
$.Sell = function(e, amount) {
if (typeof(e) === 'number') {
amount = e;
e = exchange;
}
return Trade(e, ORDER_TYPE_SELL, amount, OpMode, SlidePrice, MaxAmount, MaxSpace, RetryDelay);
};
$.CancelPendingOrders = function(e, orderType) {
if (typeof(orderType) === 'undefined') {
if (typeof(e) === 'number') {
orderType = e;
e = exchange;
} else if (typeof(e) === 'undefined') {
e = exchange;
}
}
return CancelPendingOrders(e, orderType);
};
$.GetAccount = function(e) {
if (typeof(e) === 'undefined') {
e = exchange;
}
return _C(e.GetAccount);
};
var _MACalcMethod = [TA.EMA, TA.MA, talib.KAMA][MAType];
// 返回上穿的周期数. 正数为上穿周数, 负数表示下穿的周数, 0指当前价格一样
$.Cross = function(a, b) {
var crossNum = 0;
var arr1 = [];
var arr2 = [];
if (Array.isArray(a)) {
arr1 = a;
arr2 = b;
} else {
var records = null;
while (true) {
records = exchange.GetRecords();
if (records && records.length > a && records.length > b) {
break;
}
Sleep(RetryDelay);
}
arr1 = _MACalcMethod(records, a);
arr2 = _MACalcMethod(records, b);
}
if (arr1.length !== arr2.length) {
throw "array length not equal";
}
for (var i = arr1.length-1; i >= 0; i--) {
if (typeof(arr1[i]) !== 'number' || typeof(arr2[i]) !== 'number') {
break;
}
if (arr1[i] < arr2[i]) {
if (crossNum > 0) {
break;
}
crossNum--;
} else if (arr1[i] > arr2[i]) {
if (crossNum < 0) {
break;
}
crossNum++;
} else {
break;
}
}
return crossNum;
};
// 期货部分
function GetPosition(e, contractType, direction) {
var allCost = 0;
var allAmount = 0;
var allProfit = 0;
var allFrozen = 0;
var posMargin = 0;
var positions = _C(e.GetPosition);
for (var i = 0; i < positions.length; i++) {
if (positions[i].ContractType == contractType &&
(((positions[i].Type == PD_LONG) && direction == PD_LONG) || ((positions[i].Type == PD_SHORT) && direction == PD_SHORT))
) {
posMargin = positions[i].MarginLevel;
allCost += (positions[i].Price * positions[i].Amount);
allAmount += positions[i].Amount;
allProfit += positions[i].Profit;
allFrozen += positions[i].FrozenAmount;
}
}
if (allAmount === 0) {
return null;
}
return {
MarginLevel: posMargin,
FrozenAmount: allFrozen,
Price: _N(allCost / allAmount),
Amount: allAmount,
Profit: allProfit,
Type: direction,
ContractType: contractType
};
}
function Open(e, contractType, direction, opAmount, price) {
var initPosition = GetPosition(e, contractType, direction);
var isFirst = true;
var initAmount = initPosition ? initPosition.Amount : 0;
var positionNow = initPosition;
var step = 0;
while (true) {
var needOpen = opAmount;
if (isFirst) {
isFirst = false;
} else {
positionNow = GetPosition(e, contractType, direction);
if (positionNow) {
needOpen = opAmount - (positionNow.Amount - initAmount);
}
}
if (needOpen < e.GetMinStock()) {
break;
}
if (step > max_open_lv) {
break;
}
var amount = needOpen;
e.SetDirection(direction == PD_LONG ? "buy" : "sell");
var orderId;
if (direction == PD_LONG) {
orderId = e.Buy(price + F_SlidePrice * (1 + step), amount, "开多仓", contractType, price);
} else {
orderId = e.Sell(price - F_SlidePrice * (1 + step), amount, "开空仓", contractType, price);
}
Sleep(Interval) // 增加延迟 避免 调用间隔过小导致 API 反应不过来,调换一下位置,写在合适的位置上, GetOrders 之前,避免刚下单就获取 未完成订单 导致问题。
while (true) {
var orders = _C(e.GetOrders);
if (orders.length === 0) {
break;
}
Sleep(Interval);
for (var j = 0; j < orders.length; j++) {
e.CancelOrder(orders[j].Id);
if (j < (orders.length - 1)) {
Sleep(Interval);
}
}
}
step += lv;
// Sleep(Interval) // 增加延迟 避免 调用间隔过小导致 API 反应不过来,调换一下位置,写在合适的位置上, GetOrders 之前,避免刚下单就获取 未完成订单 导致问题。
}
var ret = {
price: 0,
amount: 0,
position: positionNow
};
if (!positionNow) {
return ret;
}
if (!initPosition) {
ret.price = positionNow.Price;
ret.amount = positionNow.Amount;
} else {
ret.amount = positionNow.Amount - initPosition.Amount;
ret.price = _N(((positionNow.Price * positionNow.Amount) - (initPosition.Price * initPosition.Amount)) / ret.amount);
}
return ret;
}
function Cover(e, contractType, price, OP_amount, direction) {
var initP = null;
var positions = null;
var isFirst = true;
var ID = null;
var step = 0;
var index = 0;
var initP_contractTypeAmount = 0
while (true) {
var n = 0;
positions = _C(e.GetPosition);
if (isFirst === true) {
if (typeof(direction) === 'undefined' && positions.length > 1 || (direction !== PD_LONG && direction !== PD_SHORT && typeof(direction) !== 'undefined')) {
throw "有多,空双向持仓,并且参数direction未明确方向!或 direction 参数异常:" + direction;
}
initP = positions;
isFirst = false;
// 修改BUG
for(var m = 0 ; m < initP.length; m++){
if(initP[m].ContractType == contractType){
initP_contractTypeAmount = initP[m].Amount
}
}
}
for (var i = 0; i < positions.length; i++) {
if (positions[i].ContractType != contractType || (positions[i].Type !== direction && typeof(direction) !== 'undefined')) {
continue;
}
var amount = 0;
if (typeof(OP_amount) === 'undefined') {
amount = positions[i].Amount;
} else {
amount = OP_amount - (/*initP[i].Amount*/ initP_contractTypeAmount - positions[i].Amount);
}
if (amount <= 0) { // 修改为 小于 等于 0
continue;
}
if (positions[i].Type == PD_LONG) {
e.SetDirection("closebuy");
ID = e.Sell(price - F_SlidePrice * (1 + step), amount, "平多仓", contractType, price);
n++;
} else if (positions[i].Type == PD_SHORT) {
e.SetDirection("closesell");
ID = e.Buy(price + F_SlidePrice * (1 + step), amount, "平空仓", contractType, price);
n++;
}
index = i;
}
if (n === 0) {
break;
}
Sleep(Interval);
if (typeof(ID) !== 'number') {
CancelPendingOrders(e); // 测试
Log("ID:", ID);
continue;
}
//_C(e.CancelOrder, ID); // 测试修改 e.CancelOrder(ID);
CancelPendingOrders(e); // 测试
step += lv;
if (step > max_cover_lv) {
break;
}
}
var nowP = _C(e.GetPosition);
if (!nowP[index] || nowP[index].Type !== initP[index].Type) {
return initP.length === 0 ? 0 : initP[index].Amount;
} else {
var diff = initP[index].Amount - nowP[index].Amount;
return diff;
}
}
var PositionManager = (function() {
function PositionManager(e) {
if (typeof(e) === 'undefined') {
e = exchange;
}
if (e.GetName() !== 'Futures_OKCoin' && e.GetName() !== 'Futures_BitVC') {
throw 'Only support Futures_OKCoin & Futures_BitVC';
}
this.e = e;
this.account = null;
}
PositionManager.prototype.GetAccount = function() {
return _C(this.e.GetAccount);
};
PositionManager.prototype.OpenLong = function(contractType, shares, price) {
if (!this.account) {
this.account = _C(exchange.GetAccount);
}
return Open(this.e, contractType, PD_LONG, shares, price);
};
PositionManager.prototype.OpenShort = function(contractType, shares, price) {
if (!this.account) {
this.account = _C(exchange.GetAccount);
}
return Open(this.e, contractType, PD_SHORT, shares, price);
};
PositionManager.prototype.Cover = function(contractType, price, OP_amount, direction) {
if (!this.account) {
this.account = _C(exchange.GetAccount);
}
return Cover(this.e, contractType, price, OP_amount, direction);
};
PositionManager.prototype.Profit = function(contractType) {
var accountNow = _C(this.e.GetAccount);
Log("NOW:", accountNow, "--account:", this.account);
return _N(accountNow.Balance - this.account.Balance);
};
return PositionManager;
})();
$.NewPositionManager = function(e) {
return new PositionManager(e);
};
// 测试代码
function main() {
if (exchange.GetName() === 'Futures_OKCoin') {
var info = exchange.SetContractType("this_week");
Log("info 返回值:", info);
Log("当前持仓信息", exchange.GetPosition(), _C(exchange.GetTicker));
var depth = exchange.GetDepth();
var p = $.NewPositionManager();
p.OpenShort("this_week", 10, depth.Bids[0].Price - 2);
Log(exchange.GetPosition());
Sleep(500 * 1000);
depth = exchange.GetDepth();
var ret = p.Cover("this_week", depth.Bids[0].Price + 2, 5);
Log("cover ret:", ret);
//LogProfit(p.Profit());
Log(exchange.GetPosition());
Log("-----------------------------测试分割线----------------------------------------");
var depth = exchange.GetDepth();
p.OpenLong("this_week", 20, depth.Bids[0].Price + 2);
Log(exchange.GetPosition());
Sleep(500 * 1000);
depth = exchange.GetDepth();
var ret = p.Cover("this_week", depth.Bids[0].Price - 2, 10, PD_LONG);
Log("cover ret:", ret);
Log(exchange.GetPosition());
Log("-----------------------------测试分割线----------------------------------------");
var ret = p.Cover("this_week", depth.Bids[0].Price - 3, 10, PD_LONG);
Log("cover ret:", ret);
var ret = p.Cover("this_week", depth.Bids[0].Price + 3, 5, PD_SHORT);
Log("cover ret:", ret);
Log(exchange.GetPosition());
} else if (exchange.GetName() === 'Futures_BitVC') {
var info = exchange.SetContractType("week");
Log("info 返回值:", info);
Log("当前持仓信息", exchange.GetPosition(), _C(exchange.GetTicker));
var depth = exchange.GetDepth();
var p = $.NewPositionManager();
p.OpenLong("week", 500, depth.Bids[0].Price + 2);
Log(exchange.GetPosition());
Sleep(500 * 1000);
depth = exchange.GetDepth();
var ret = p.Cover("week", depth.Bids[0].Price - 2, 500);
Log("cover ret:", ret);
Log(exchange.GetPosition());
Log("-----------------------------测试分割线----------------------------------------");
var info = exchange.SetContractType("week");
Log("info 返回值:", info);
Log("当前持仓信息", exchange.GetPosition(), _C(exchange.GetTicker));
var depth = exchange.GetDepth();
p.OpenShort("week", 600, depth.Bids[0].Price - 2);
Log(exchange.GetPosition());
Sleep(500 * 1000);
depth = exchange.GetDepth();
var ret = p.Cover("week", depth.Bids[0].Price + 2, 500, PD_SHORT);
Log("cover ret:", ret);
Log(exchange.GetPosition());
Log("-----------------------------测试分割线----------------------------------------");
var ret = p.Cover("week", depth.Bids[0].Price + 3, 100, PD_SHORT);
Log("cover ret:", ret);
//p.Cover("week", depth.Asks[0].Price - 3, 300, PD_LONG);
Log(exchange.GetPosition());
} else if(exchange.GetName() === 'huobi' || exchange.GetName() === 'OKCoin'){
Log($.GetAccount());
Log($.Buy(0.5));
Log($.Sell(0.5));
exchange.Buy(1000, 3);
$.CancelPendingOrders(exchanges[0]);
Log($.Cross(30, 7));
Log($.Cross([1,2,3,2.8,3.5], [3,1.9,2,5,0.6]));
}
}
```
> 策略出处
https://www.fmz.com/strategy/36762
> 更新时间
2017-10-22 23:14:09
File diff suppressed because it is too large Load Diff
+621
View File
@@ -0,0 +1,621 @@
> 策略名称
OKEX期现对冲
> 策略作者
alinwo
> 策略描述
策略逻辑
此策略会自动检测OKEX上现货和期货的差价,当差价达到期望盈利阀值时,通过等量对冲来获取盈利。
策略特色
支持OKEX上的所有期货品种(BTC, EOS, BCH, ETH等等)
支持自定义杠杆倍数和合约类型(当周,次周等)
支持自定义盈利期望值(比如年化40%的利润)
详尽的报表(包括详尽的策略状态,交易历史,利润跟踪等)
全自动对冲,不需要人工操作
详细说明见我的博客:
http://www.pcclean.io/okex%E6%9C%9F%E7%8E%B0%E5%AF%B9%E5%86%B2js%E6%BA%90%E4%BB%A3%E7%A0%81%E5%88%86%E4%BA%AB%E5%9F%BA%E4%BA%8Efmz-botvs%E5%AE%9E%E7%8E%B0/
> 源码 (javascript)
``` javascript
//【OKEX期现对冲】说明
//==============================================================================================================================
/*
注意:
确定操作的ok期货为“全仓模式”
确定操作的合约类型为“当周”
严格按照2个一组的顺序添加交易所 BCH/USDC, BCH/USD A:现货 B:期货
策略会用USDT/USD汇率修正现货价格!
版本历史:
9:51 2018/1/9 first release
14:57 2018/1/13 正式开始运行
15:12 2018/11/15 自动处理强平,提高盈利目标,报表支持显示期货仓位,取消显示交易历史,图标只显示stocks
23:12 2018/11/15 支持按钮清空所有收益日志
16:09 2018/11/16 支持按钮更新收益图表, 用USDT/USD汇率修正现货价格
*/
var ExchangProcessor={
createNew: function(exA,exB){
//策略参数
//==============================================================================================================================
var contract_type ="this_week"; //合约类型
var margin_level =10; //杠杆倍数
var want_profit =0.01; //想要的额外收入(+汇率损失)
var ignore_range =0.001; //例如USDT对USD, 对冲期的安全波动范围,策略会忽略这个范围的波动
var max_wait_order =10000; //订单等待
var wait_ms =3000; //默认等待毫秒
var traders_recorder =false; //记录所有交易
var handfee= {OKEX:0.001, Futures_OKCoin:0.001}; //手续费
var trade_amount={ETH_USD:0.5, BCH_USD:0.5, BTC_USD:0.05}; //每次交易数量 例如0.5个bch
var contract_min={ETH_USD:10, BCH_USD:10, BTC_USD:100}; //一合约价值多少美金 USD,用这个计算买入张数
var price_n ={ETH_USDT:4, ETH_USD:3, BCH_USDT:4, BCH_USD:3, BTC_USDT:4, BTC_USD:2}; //价格精度
var num_n ={ETH_USDT:3, ETH_USD:0, BCH_USDT:3, BCH_USD:0, BTC_USDT:3, BTC_USD:0}; //数量精度
var minestbuy ={ETH_USDT:0.001, ETH_USD:1, BCH_USDT:0.001, BCH_USD:1, BTC_USDT:0.001, BTC_USD:1}; //最小买入量
var price_step ={ETH_USDT:0.03, ETH_USD:0.03, BCH_USDT:0.05, BCH_USD:0.05, BTC_USDT:0.65, BTC_USD:0.65}; //定价单调整价格的单位(每次调整万1, 大致等于25分钟调整%1)
//全局状态变量
//==============================================================================================================================
var pre_time=null; //记录轮询间隔时间
var limit_orders=[]; //限价单
var trades=[]; //所有交易
var pending_pos=[]; //未完成对冲仓位
var hedging_op=0; //对冲机会
var hedging_real=0; //真实对冲次数
var hedging_complete=0; //对冲完成次数
//构建处理器
var processor={};
//工具函数
//==============================================================================================================================
//重试购买,直到成功返回
processor.retryBuy=function(ex,price,num,mode)
{
var currency=ex.GetCurrency();
var r=ex.Buy(_N(price,price_n[currency]), _N(num,num_n[currency]));
var tempnum=num;
while (!r){
Log("Buy失败,正在重试。");
Sleep(wait_ms);
if (mode==="spot"){
var account=_C(ex.GetAccount);
var ticker=_C(ex.GetTicker);
var last=ticker.Last;
var fixedAmount=Math.min(account.Balance*0.95/last,num);
r=ex.Buy(_N(price,price_n[currency]), _N(fixedAmount,num_n[currency]));
}else if(mode==="futures"){
//tempnum=tempnum-1;
if (tempnum===0){
break;
}
r=ex.Buy(_N(price,price_n[currency]), _N(tempnum,num_n[currency]));
}
}
return r;
}
//重试卖出,直到成功返回
processor.retrySell=function(ex,price,num,mode){
var currency=ex.GetCurrency();
var r=ex.Sell(_N(price,price_n[currency]), _N(num,num_n[currency]));
var tempnum=num;
while (!r){
Log("Sell失败,正在重试。");
Sleep(wait_ms);
if (mode==="spot"){
var account=_C(ex.GetAccount);
var fixedAmount=Math.min(account.Stocks,num);
r=ex.Sell(_N(price,price_n[currency]), _N(fixedAmount,num_n[currency]));
}else if(mode==="futures"){
//tempnum=tempnum-1;
var position=_C(ex.GetPosition);
if (tempnum===0 || position.length===0){
break;
}
r=ex.Sell(_N(price,price_n[currency]), _N(tempnum,num_n[currency]));
}
}
return r;
}
//获得美元汇率
processor.getUSDTratio=function(){
var r = _C(HttpQuery,"https://api.coinmarketcap.com/v2/ticker/825/");
var o = JSON.parse(r);
return o.data.quotes.USD.price;
}
//获得中国时间
processor.get_ChinaTimeString=function(){
var date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
var cdate=new Date(now_utc);
cdate.setHours(cdate.getHours()+8);
var localstring=cdate.getFullYear()+'/'+(cdate.getMonth()+1)+'/'+cdate.getDate()+' '+cdate.getHours()+':'+cdate.getMinutes()+':'+cdate.getSeconds();
return localstring;
}
//处理定价单
processor.process_limiteorders=function(){
var cur_time=new Date();
var limit_orders_new=[];
for (var i=0; i<limit_orders.length; ++i){
var create_time=limit_orders[i].create_time;
var passedtime=cur_time-create_time;
if (passedtime>max_wait_order){
var exchange_c=limit_orders[i].exchange;
var order_ID=limit_orders[i].ID;
var ordermode=limit_orders[i].mode;
var exname=exchange_c.GetName();
var account=_C(exchange_c.GetAccount);
var ticker=_C(exchange_c.GetTicker);
var last=ticker.Last;
var orderdata=_C(exchange_c.GetOrder,order_ID);
var type=orderdata.Type;
var currency=exchange_c.GetCurrency();
if (orderdata.Status!=ORDER_STATE_CLOSED){
var notcompleted=orderdata.Amount-orderdata.DealAmount;
exchange_c.CancelOrder(order_ID);
if (type===ORDER_TYPE_BUY){
var allowbuy=notcompleted;
if (allowbuy>=minestbuy[currency]){
var limited_order_ID=processor.retryBuy(exchange_c,orderdata.Price+price_step[currency],allowbuy,ordermode);
Log("加价买入。"+orderdata.Price+"|"+(orderdata.Price+price_step[currency]));
var limited_order_data={
exchange:exchange_c,
ID:limited_order_ID,
create_time:new Date(),
utcdate:processor.get_ChinaTimeString(),
mode:ordermode
};
limit_orders_new.push(limited_order_data);
}
}else if (type===ORDER_TYPE_SELL){
var allowsell=notcompleted;
if (allowsell>=minestbuy[currency]){
var limited_order_ID=processor.retrySell(exchange_c,orderdata.Price-price_step[currency],allowsell,ordermode);
Log("降价卖出。"+orderdata.Price+"|"+(orderdata.Price-price_step[currency]));
var limited_order_data={
exchange:exchange_c,
ID:limited_order_ID,
create_time:new Date(),
utcdate:processor.get_ChinaTimeString(),
mode:ordermode
};
limit_orders_new.push(limited_order_data);
}
}
//保存交易信息
if (type===ORDER_TYPE_BUY){
var details={
type:"限价买",
time:limit_orders[i].utcdate,
RealAmount:orderdata.DealAmount,
WantAmount:orderdata.Amount,
RealPrice:orderdata.Price,
WantPrice:orderdata.Price,
Memo:"部分完成",
exname:exname
};
if (traders_recorder){
trades.push(details);
}
}else if (type===ORDER_TYPE_SELL){
var details={
type:"限价卖",
time:limit_orders[i].utcdate,
RealAmount:orderdata.DealAmount,
WantAmount:orderdata.Amount,
RealPrice:orderdata.Price,
WantPrice:orderdata.Price,
Memo:"部分完成",
exname:exname
};
if (traders_recorder){
trades.push(details);
}
}
}else{
//保存交易信息
if (type===ORDER_TYPE_BUY){
var details={
type:"限价买",
time:limit_orders[i].utcdate,
RealAmount:orderdata.DealAmount,
WantAmount:orderdata.Amount,
RealPrice:orderdata.Price,
WantPrice:orderdata.Price,
Memo:"已完成",
exname:exname
};
if (traders_recorder){
trades.push(details);
}
}else if (type===ORDER_TYPE_SELL){
var details={
type:"限价卖",
time:limit_orders[i].utcdate,
RealAmount:orderdata.DealAmount,
WantAmount:orderdata.Amount,
RealPrice:orderdata.Price,
WantPrice:orderdata.Price,
Memo:"已完成",
exname:exname
};
if (traders_recorder){
trades.push(details);
}
}
}
}else{
limit_orders_new.push(limit_orders[i]);
}
}
limit_orders=limit_orders_new;
}
//强制执行限价单
processor.force_limited_order=function(type,ex,price,num,mode){
if (type==="buy"){
var buyID=processor.retryBuy(ex,price,num,mode);
var order1={
exchange:ex,
ID:buyID,
create_time:new Date(),
utcdate:processor.get_ChinaTimeString(),
mode:mode
};
limit_orders.push(order1);
}
if (type==="sell"){
var sellID=processor.retrySell(ex,price,num,mode);
var order1={
exchange:ex,
ID:sellID,
create_time:new Date(),
utcdate:processor.get_ChinaTimeString(),
mode:mode
};
limit_orders.push(order1);
}
while(limit_orders.length!==0){
//process limited orders
processor.process_limiteorders();
Sleep(wait_ms);
}
}
//初始化
//==============================================================================================================================
processor.init_obj=function(){
_CDelay(wait_ms);
pre_time = new Date();
}
//处理交易
//==============================================================================================================================
processor.work=function(){
var cur_time = new Date();
var passedtime=cur_time-pre_time;
pre_time=cur_time;
var USDT_r=processor.getUSDTratio();
//get information
var A_account=_C(exA.GetAccount);
var A_exname=exA.GetName();
var A_currency=exA.GetCurrency();
var A_quotecurrency=exA.GetQuoteCurrency();
var A_ticker=_C(exA.GetTicker);
var A_last=A_ticker.Last;
var A_last_fixed=A_last*USDT_r; //Fixed price: ETH/USD
var A_depth=_C(exA.GetDepth);
var A_orders=_C(exA.GetOrders);
var A_buy1=A_depth.Bids[0].Price;
var A_sell1=A_depth.Asks[0].Price;
exB.SetContractType(contract_type);
exB.SetMarginLevel(margin_level);
var B_account=_C(exB.GetAccount);
var B_exname=exB.GetName();
var B_currency=exB.GetCurrency();
var B_quotecurrency=exB.GetQuoteCurrency();
var B_ticker=_C(exB.GetTicker);
var B_last=B_ticker.Last;
var B_depth=_C(exB.GetDepth);
var B_orders=_C(exB.GetOrders);
var B_buy1=B_depth.Bids[0].Price;
var B_sell1=B_depth.Asks[0].Price;
var cdiff=Math.abs(B_last-A_last_fixed)/A_last_fixed;
var cdiff2=(B_last-A_last_fixed)/A_last_fixed;
var target_bofu=want_profit+handfee[A_exname]*2+handfee[B_exname]*2+ignore_range;
//开始对冲
if (limit_orders.length===0 && A_last_fixed>B_last && cdiff>target_bofu){
hedging_op++;
var heyuefenshu_B=_N(trade_amount[B_currency]*B_last/contract_min[B_currency],0);
var exact_amount=heyuefenshu_B*contract_min[B_currency]/B_last;
if (A_account.Stocks*0.9>exact_amount && B_account.Stocks*0.9>exact_amount){
hedging_real++;
//sell 1 bch from A
processor.force_limited_order("sell",exA,A_buy1,exact_amount,"spot");
//buy 1 bch from B
exB.SetDirection("buy");
processor.force_limited_order("buy",exB,B_sell1,heyuefenshu_B,"futures");
var posA={
type:'spot-sell',
exchange:exA,
price:A_buy1,
amount:exact_amount,
starttime:processor.get_ChinaTimeString()
};
pending_pos.push(posA);
var posB={
type:'futures-buyup',
exchange:exB,
price:B_sell1,
amount:heyuefenshu_B,
starttime:processor.get_ChinaTimeString()
};
pending_pos.push(posB);
}
}
if (limit_orders.length===0 && A_last_fixed<B_last && cdiff>target_bofu){
hedging_op++;
var heyuefenshu_B=_N(trade_amount[B_currency]*B_last/contract_min[B_currency],0);
var exact_amount=heyuefenshu_B*contract_min[B_currency]/B_last;
if (A_account.Balance*0.9>exact_amount*A_last && B_account.Stocks*0.9>exact_amount){
hedging_real++;
//buy 1 bch from A
processor.force_limited_order("buy",exA,A_sell1,exact_amount,"spot");
//sell 1 bch from B
exB.SetDirection("sell");
processor.force_limited_order("buy",exB,B_sell1,heyuefenshu_B,"futures");
var posA={
type:'spot-buy',
exchange:exA,
price:A_sell1,
amount:exact_amount,
starttime:processor.get_ChinaTimeString()
};
pending_pos.push(posA);
var posB={
type:'futures-buydown',
exchange:exB,
price:B_sell1,
amount:heyuefenshu_B,
starttime:processor.get_ChinaTimeString()
};
pending_pos.push(posB);
}
}
//结束对冲
if (limit_orders.length===0 && cdiff<=ignore_range && A_orders.length===0 && B_orders.length===0 && pending_pos.length>0){
hedging_complete++;
for (var thidx=0; thidx<pending_pos.length; ++thidx){
var posinfo=pending_pos[thidx];
var ticker=_C(posinfo.exchange.GetTicker);
var last=ticker.Last;
var depth=_C(posinfo.exchange.GetDepth);
var buy1=depth.Bids[0].Price;
var sell1=depth.Asks[0].Price;
var account=_C(posinfo.exchange.GetAccount);
if (posinfo.type==='futures-buydown'){
posinfo.exchange.SetDirection("closesell");
processor.force_limited_order("sell",posinfo.exchange,buy1,posinfo.amount,"futures");
}
if (posinfo.type==='futures-buyup'){
posinfo.exchange.SetDirection("closebuy");
processor.force_limited_order("sell",posinfo.exchange,buy1,posinfo.amount,"futures");
}
if (posinfo.type==='spot-buy'){
processor.force_limited_order("sell",posinfo.exchange,buy1,Math.min(account.Stocks,posinfo.amount),"spot");
}
if (posinfo.type==='spot-sell'){
processor.force_limited_order("buy",posinfo.exchange,sell1,Math.min(account.Balance/last,posinfo.amount),"spot");
}
}
pending_pos=[];
}
//自动释放对冲仓位
var B_position=_C(exB.GetPosition);
if (B_position.length===0 && pending_pos.length>0 && limit_orders.length===0 && A_orders.length===0 && B_orders.length===0){
Log('检测到Okex的仓位已被强平,执行自动释放对冲仓位。');
hedging_complete++;
for (var thidx=0; thidx<pending_pos.length; ++thidx){
var posinfo=pending_pos[thidx];
var ticker=_C(posinfo.exchange.GetTicker);
var last=ticker.Last;
var depth=_C(posinfo.exchange.GetDepth);
var buy1=depth.Bids[0].Price;
var sell1=depth.Asks[0].Price;
var account=_C(posinfo.exchange.GetAccount);
if (posinfo.type==='spot-buy'){
processor.force_limited_order("sell",posinfo.exchange,buy1,Math.min(account.Stocks,posinfo.amount),"spot");
}
if (posinfo.type==='spot-sell'){
processor.force_limited_order("buy",posinfo.exchange,sell1,Math.min(account.Balance/last,posinfo.amount),"spot");
}
}
pending_pos=[];
}
//status
var table1 = {type: 'table', title: '交易所', cols: ['交易所','交易对','最新价格','钱','币','未完成订单','买一','卖一'], rows: []};
var table2 = {type: 'table', title: '统计', cols: ['轮询时间','当前价差','目标价差','对冲机会/实际对冲次数/对冲完成次数','USDT/USD','忽略波动范围'], rows: []};
var table3 = {type: 'table', title: '未完成对冲仓位', cols: ['交易所','类型','价格','数量','开仓时间'], rows: []};
var table4 = {type: 'table', title: '未完成定价单', cols: ['交易所','订单ID','发单日期'], rows: []};
var table5 = {type: 'table', title: '交易历史', cols: ['交易所','日期','类型', '成交数量','发单数量','成交价','发单价','备注'], rows: []};
var table6 = {type: 'table', title: '期货仓位', cols: ['交易所','持仓量','冻结量','持仓均价','实现盈余','类型','合约代码'], rows: []};
table1.rows.push([A_exname,A_currency,A_last+'(修正价:'+A_last_fixed+')',A_account.Balance,A_account.Stocks,A_orders.length,A_depth.Bids[0].Price,A_depth.Asks[0].Price]);
table1.rows.push([B_exname,B_currency,B_last,B_account.Balance,B_account.Stocks,B_orders.length,B_depth.Bids[0].Price,B_depth.Asks[0].Price]);
table2.rows.push([passedtime+'毫秒',cdiff2,target_bofu,hedging_op+'/'+hedging_real+'/'+hedging_complete,USDT_r,ignore_range]);
for (var thidx=0; thidx<pending_pos.length; ++thidx){
var posinfo=pending_pos[thidx];
table3.rows.push([posinfo.exchange.GetName(),posinfo.type,posinfo.price,posinfo.amount,posinfo.starttime]);
}
for (var idx2=0; idx2<limit_orders.length; ++idx2){
var info=limit_orders[idx2];
table4.rows.push([info.exchange.GetName(),info.ID,info.utcdate]);
}
for (var i=0; i < trades.length; i++){
table5.rows.push([trades[i].exname,trades[i].time,trades[i].type,trades[i].RealAmount,trades[i].WantAmount,trades[i].RealPrice,trades[i].WantPrice,trades[i].Memo]);
}
for (var i=0; i < B_position.length; i++){
table6.rows.push([B_exname,B_position[i].Amount,B_position[i].FrozenAmount,B_position[i].Price,B_position[i].Profit,B_position[i].Type,B_position[i].ContractType]);
}
processor.logstatus=('`' + JSON.stringify([table1,table2,table3,table4,table6,table5])+'`'+'\n');
processor.stocksbalance=A_account.Stocks+B_account.Stocks;
//sleep
Sleep(wait_ms);
}
return processor;
}
};
//主函数
//==============================================================================================================================
function main(){
var processors=[];
for (var i=0; i<exchanges.length; i+=2){
var p=ExchangProcessor.createNew(exchanges[i],exchanges[i+1]);
processors.push(p);
}
for (i=0; i<processors.length; ++i){
processors[i].init_obj();
}
var pre_profit=Number(_G("pre_profit"));
Log('之前收入累计:'+pre_profit);
var lastprofit=-1;
var total_loop=0;
var beginrunning=processors[0].get_ChinaTimeString();
while(true){
//running processors
total_loop++;
var allstatus='';
allstatus+=('♞策略启动时间: '+beginrunning+'#0000ff\n');
var mybalance=0;
for (i=0; i<processors.length; ++i){
processors[i].work();
allstatus+=processors[i].logstatus;
mybalance+=processors[i].stocksbalance;
}
allstatus+=('♜轮询次数: '+total_loop+'\n');
allstatus+=('♜更新时间: '+processors[0].get_ChinaTimeString()+'\n');
allstatus+=('♜策略仅作为学习交流之用!实盘风险自担!#0000ff'+'\n');
allstatus+=('`'+JSON.stringify({'type':'button', 'cmd': 'clearprofitchart', 'name': '清空收益图表'})+'`'+'\n');
allstatus+=('`'+JSON.stringify({'type':'button', 'cmd': 'logprofit', 'name': '更新收益图表'})+'`'+'\n');
LogStatus(allstatus);
if (lastprofit!==mybalance && total_loop%300===0){
LogProfit(mybalance);
_G("pre_profit", mybalance);
lastprofit=mybalance;
}
//process button commands
var cmd=GetCommand();
if (cmd!==null && cmd==='clearprofitchart') {
LogProfitReset();
Log("已清空所有收益日志!");
}
if (cmd!==null && cmd==='logprofit') {
LogProfit(mybalance);
_G("pre_profit", mybalance);
Log("已更新收益图表!");
}
}
}
```
> 策略出处
https://www.fmz.com/strategy/127939
> 更新时间
2018-11-29 11:23:51
+140
View File
@@ -0,0 +1,140 @@
> 策略名称
OkEX Websocket Realtime
> 策略作者
FawkesPan
> 策略描述
# OkEX WebSocket API Connecter (compress supported)
> 源码 (python)
``` python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# encoding: utf-8
#
# Market Real-time Subscription
#
# Copyright 2018 FawkesPan
#
# Do What the Fuck You Want To Public License
#
import time
import ssl
import sys
import code
import json
import hashlib
import hmac
import urllib
import threading
import websocket
import zlib
import string
try:
import readline
except ImportError:
pass
pong = time.time()
class WSSubscription:
def __init__(self,symbol='btc',contract_type='this_week',on_message=None):
self.__symbol = symbol.lower()
self.__contract_type = contract_type
self.__Depth = {}
self.__Position = {}
if on_message is not None:
self.__callbackEnabled = True
self.__callback = on_message
else:
self.__callbackEnabled = False
thread = threading.Thread(target=self.sub, args=())
thread.daemon = True
thread.start()
def GetDepth(self):
return self.__Depth
def subscribe(self,ws):
def run(*args):
ws.send("{'event':'addChannel','channel':'ok_sub_futureusd_%s_depth_%s_5'}" % (self.__symbol,self.__contract_type))
ws.send("{'event':'addChannel','channel':'ok_sub_futureusd_%s_trade_%s'}" % (self.__symbol,self.__contract_type))
while True:
ws.send("{'event':'ping'}")
time.sleep(30)
threading.Thread(target=run).start()
def sub(self):
websocket.enableTrace(False)
URL = "wss://real.okex.com:10441/websocket?compress=true"
ws = websocket.WebSocketApp(URL,
on_message=self.incoming,
on_error=self.error_handling,
on_close=self.closing)
ws.on_open = self.subscribe
while True:
try:
ws.run_forever()
except:
pass
pass
def incoming(self,ws,message):
message = zlib.decompress(message, -zlib.MAX_WBITS)
message = message.decode('utf-8')
global pong
if 'pong' in message:
pong = time.time()
if 'asks' in message and 'bids' in message:
d = json.loads(message)
self.__Depth = d[0]['data']
self.__Depth['asks'].reverse()
if self.__callbackEnabled:
self.__callback(message)
def error_handling(self,ws,error):
print(str(error))
def closing(self,ws):
print("WebSocket Closing...")
ext.OkEXWS = WSSubscription
# 模块测试
def main():
OkEX = ext.OkEXWS(symbol='btc',contract_type='this_week')
while (True):
Log(OkEX.GetDepth())
time.sleep(1)
```
> 策略出处
https://www.fmz.com/strategy/91176
> 更新时间
2018-11-06 00:13:58
@@ -0,0 +1,344 @@
> 策略名称
OkEX 高级API功能 V.1.1.0 (期货:批量下单,现货;TBD) Python2-3
> 策略作者
FawkesPan
> 策略描述
# OkEX 高级API功能 (FMZ.com)
### 初始化
这个库整合了一些 OkEX 高级API 功能,使用前需要进行初始化。
#### OkEX期货
```
# OkEX 期货
# future 可选参数 this_week next_week quarter , 不填默认 this_week
OkEXFuture = ext.OkEXFuturePlus(exchange, future=string) # 创建一个新的接口对象
# 多个交易所
OkEXFuture = ext.OkEXFuturePlus(exchanges[0], future=string) # exchanges[这里取决于你的交易所添加在第几个]
```
#### OkEX现货
#还在写
### 订单操作-期货
#### 批量订单
##### BulkAdd() 添加新订单到本地订单列表
```
side price amount 为必填参数
symbol future 不填则使用默认交易对设置
matchPrice 默认为False , 设置为True 使用对手价交易
OkEXFuture.BulkAdd(side=string, price=float, amount=integer, matchPrice=False, symbol=string, future=string)
```
##### BulkClear() 清除本地未提交订单
```
symbol 指定后可清除指定交易对订单 如不指定则清除所有订单
notify 是否显示日志 默认为显示
OkEXFuture.BulkClear(symbol=string, notify=True)
```
##### BulkPost() 提交本地未提交订单
```
symbol 指定后只提交指定交易对订单 不指定则提交所有订单
future 必须同时指定symbol才能使用 指定后只提交特定交易对的特定合约的订单
OkEXFuture.BulkPost(symbol=string, future=string)
```
##### BulkOrders() 查看本地未提交订单
```
symbol 指定后只查看指定交易对订单 不指定则查看所有订单
future 必须同时指定symbol才能使用 指定后只查看特定交易对的特定合约的订单
OkEXFuture.BulkOrders(symbol=string, future=string)
```
### 与我联系
邮箱 i@fawkex.me
电报 [FawkesPan](https://telegram.me/FawkesPan)
接受策略定制
### 关于这个库
[OkEX API文档](https://github.com/okcoin-okex/API-docs-OKEx.com/)
[使用 GNU General Public License v3](https://www.gnu.org/licenses/gpl-3.0.en.html)
> 策略参数
|参数|默认值|描述|
|----|----|----|
|LANG|ZH|语言 / Language|
> 源码 (python)
``` python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# encoding: utf-8
#
# OkEX Advanced API Interface for FMZ.com.
#
# Copyright 2018 FawkesPan
# Contact : i@fawkex.me / Telegram@FawkesPan
#
# GNU General Public License v3.0
#
import json
import time
QUOTES = {}
QUOTES['ZH'] = {
'GREET' : '[OkEX 接口已初始化] 币种: %s 合约: %s. %s',
'INITF' : '使用的交易所不正确,当前交易所: %s',
'PARAMERR' : '***传的参数不对 检查你的代码*** %s',
'NEWORDER' : '[添加订单] 币种: %s 合约: %s 方向: %s 价格: %.4f 数量: %d 张. %s',
'ORDCOUNT' : '[本次批量发送订单] 总计: %d 条. %s',
'THISBATCH' : '[信息] 正在处理 币种: %s 合约: %s 条数: %d. %s',
'ORDSENT' : '[已发送订单] 币种: %s 合约: %s 条数: %d. %s',
'NEEDSPLIT' : '[信息] 由于单合约单量大于5条 需要进行分片处理. %s',
'CLEARALL' : '[信息] 已清除所有本地订单. %s',
'CLEARS' : '[信息] 已清除所有 %s 本地订单. %s',
'CLEAR' : '[信息] 已清除所有 %s %s 本地订单. %s'
}
COLORS = {
'DEEPBLUE' : '#1F618D',
'BLUE' : '#0000FF',
'LIGHTBLUE' : '#5DADE2',
'DEEPGREEN' : '#27AE60',
'GREEN' : '#00FF00',
'LIGHTGREEN' : '#58D68D',
'LAPIS' : '#26619C',
'DEEPRED' : '#CB4335',
'RED' : '#FF0000',
'LIGHTRED' : '#EC7063'
}
class OkEXFuture:
def __init__(self, exchange, future='this_week'):
self.QUOTES = {}
exchange.GetCurrency()
if isinstance(exchange.GetCurrency(), bytes):
self.symbol = str(exchange.GetCurrency(), "utf-8").lower()
name = str(exchange.GetName(), "utf-8")
else:
self.symbol = exchange.GetCurrency()
name = exchange.GetName()
self.IO = exchange.IO
self.future = future
self.bulks = {}
self.bulks[self.symbol] = {}
self.bulks[self.symbol][self.future] = []
if 'OKCoin' in str(name):
Log(QUOTES[LANG]['GREET'] % (self.symbol.upper(),self.future.upper(),COLORS['LAPIS']))
else:
Log(QUOTES[LANG]['INITF'] % (name))
def BulkAdd(self, side=None, price=None, amount=None, matchPrice=False, symbol=None, future=None):
if type is None or price is None or amount is None:
Log(QUOTES[LANG]['PARAMERR'] % (COLORS['RED']))
return False
side = side.lower()
if side == 'buy':
tp = 1
cl = COLORS['DEEPGREEN']
if side == 'sell':
tp = 2
cl = COLORS['DEEPRED']
if side == 'closebuy':
tp = 3
cl = COLORS['LIGHTRED']
if side == 'closesell':
tp = 4
cl = COLORS['LIGHTGREEN']
if symbol is None:
symbol = self.symbol
if future is None:
future = self.future
order = {}
order['price'] = price
order['amount'] = amount
order['type'] = tp
if matchPrice:
order['matchPrice'] = 1
try:
self.bulks[symbol]
except KeyError:
self.bulks[symbol] = {}
try:
self.bulks[symbol][future]
except KeyError:
self.bulks[symbol][future] = []
self.bulks[symbol][future].append(order)
Log(QUOTES[LANG]['NEWORDER'] % (symbol.upper(),future.upper(),side.upper(),price,amount,cl))
return True
def BulkOrders(self, symbol=None, future=None):
if symbol is None:
return self.bulks
else:
if future is None:
return self.bulks[symbol]
else:
return self.bulks[symbol][future]
def BulkClear(self, symbol=None, future=None, notify=True):
if symbol is None:
self.bulks = {}
if notify:
Log(QUOTES[LANG]['CLEARALL'] % (COLORS['RED']))
else:
if future is None:
self.bulks[symbol] = {}
if notify:
Log(QUOTES[LANG]['CLEARS'] % (symbol.encode().upper(), COLORS['RED']))
else:
self.bulks[symbol][future] = []
if notify:
Log(QUOTES[LANG]['CLEAR'] % (symbol.encode().upper(), future.encode().upper(), COLORS['RED']))
#Log(QUOTES[LANG]['CLEAR'] % (symbol.upper(), future.upper(), COLORS['RED']))
return True
#exchange.IO("api", "POST", "/api/v1/future_batch_trade.do", "symbol=etc_usd&contract_type=this_week&orders_data="+json.dumps(orders))
def __post(self, symbol='', future=''):
count = len(self.bulks[symbol][future])
orders = self.bulks[symbol][future]
ret = []
if count == 0:
return
Log(QUOTES[LANG]['THISBATCH'] % (symbol.upper(),future.upper(),count,COLORS['LAPIS']))
if count <= 5:
params = 'symbol=%s&contract_type=%s&orders_data=%s' % (symbol, future, json.dumps(orders))
res = self.IO("api", "POST", "/api/v1/future_batch_trade.do", params)
ret+=res['order_info']
Log(QUOTES[LANG]['ORDSENT'] % (symbol.upper(),future.upper(),len(orders),COLORS['LAPIS']))
if count > 5:
Log(QUOTES[LANG]['NEEDSPLIT'] % (COLORS['LAPIS']))
batch = []
for item in orders:
batch.append(item)
if len(batch) == 5:
params = 'symbol=%s&contract_type=%s&orders_data=%s' % (symbol, future, json.dumps(batch))
res = self.IO("api", "POST", "/api/v1/future_batch_trade.do", params)
try:
ret+=res['order_info']
except:
pass
Log(QUOTES[LANG]['ORDSENT'] % (symbol.upper(),future.upper(),len(batch),COLORS['LAPIS']))
batch = []
time.sleep(0.3) # OkEX限制每秒只能进行三个请求
params = 'symbol=%s&contract_type=%s&orders_data=%s' % (symbol, future, json.dumps(batch))
res = self.IO("api", "POST", "/api/v1/future_batch_trade.do", params)
try:
ret+=res['order_info']
except:
pass
Log(QUOTES[LANG]['ORDSENT'] % (symbol.upper(),future.upper(),len(batch),COLORS['LAPIS']))
return ret
def BulkPost(self, symbol=None, future=None):
ret = []
count = 0
if symbol is None:
symbols = self.bulks.keys()
for s in symbols:
futures = self.bulks[s].keys()
for f in futures:
count+=len(self.bulks[s][f])
ret+=self.__post(s, f)
time.sleep(0.3) # OkEX限制每秒只能进行三个请求
self.BulkClear(notify=False)
else:
if future is None:
futures = self.bulks[symbol].keys()
for f in futures:
count+=len(self.bulks[symbol][f])
ret+=self.__post(symbol, f)
time.sleep(0.3) # OkEX限制每秒只能进行三个请求
self.BulkClear(symbol=symbol, notify=False)
else:
count+=len(self.bulks[symbol][future])
ret+=self.__post(symbol, future)
self.BulkClear(symbol=symbol, future=future, notify=False)
Log(QUOTES[LANG]['ORDCOUNT'] % (count,COLORS['LAPIS']))
return ret
class OkEXSpot:
def __init__(self, exchange):
self.IO = exchange.IO
#TBD
ext.OkEXFuturePlus = OkEXFuture # 导出OkEXFuture Class, 主策略可以通过FuturePlus = ext.OkEXFuturePlus(exchange, future)调用
ext.OkEXSpotPlus = OkEXSpot # 导出OkEXSpot Class, 主策略可以通过SpotPlus = ext.OkEXSpotPlus(exchange)调用
# 模块功能测试
def main():
LogReset()
Log(exchange.GetAccount())
OKEXPlus = ext.OkEXFuturePlus(exchange)
# 4 Buy 2 Sell 1 next_week
base_price = exchange.GetTicker()['Last']
OKEXPlus.BulkAdd("sell", base_price*1.2, 1)
OKEXPlus.BulkAdd("closebuy", base_price*1.2, 1)
OKEXPlus.BulkAdd("sell", base_price*1.3, 1)
OKEXPlus.BulkAdd("buy", base_price*0.7, 1, future='next_week')
OKEXPlus.BulkClear()
OKEXPlus.BulkAdd("buy", base_price*0.8, 1)
OKEXPlus.BulkAdd("closebuy", base_price*1.2, 1)
OKEXPlus.BulkAdd("sell", base_price*1.3, 1)
OKEXPlus.BulkAdd("buy", base_price*0.7, 1, future='next_week')
OKEXPlus.BulkClear(symbol=(exchange.GetCurrency()).lower(),future='this_week')
OKEXPlus.BulkClear(symbol=(exchange.GetCurrency()).lower(),future='next_week')
OKEXPlus.BulkAdd("buy", base_price*0.8, 1)
OKEXPlus.BulkAdd("buy", base_price*0.7, 1, future='next_week')
OKEXPlus.BulkClear(symbol=(exchange.GetCurrency()).lower())
OKEXPlus.BulkAdd("buy", base_price*0.8, 1)
OKEXPlus.BulkAdd("buy", base_price*0.81, 1)
OKEXPlus.BulkAdd("buy", base_price*0.82, 1)
OKEXPlus.BulkAdd("closesell", base_price*0.8, 1)
OKEXPlus.BulkAdd("sell", base_price*1.2, 1)
OKEXPlus.BulkAdd("closebuy", base_price*1.2, 1)
OKEXPlus.BulkAdd("sell", base_price*1.3, 1)
OKEXPlus.BulkAdd("buy", base_price*0.7, 1, future='next_week')
Log(OKEXPlus.BulkOrders())
for item in OKEXPlus.BulkPost():
Log(str(item))
Log(OKEXPlus.BulkOrders())
```
> 策略出处
https://www.fmz.com/strategy/113979
> 更新时间
2018-11-12 20:55:49
+261
View File
@@ -0,0 +1,261 @@
> 策略名称
Paul "The Gambler" Lévy
> 策略作者
FawkesPan
> 策略描述
###### 期货赌徒策略
##### 方向做错了就自动反向翻倍开仓
#### 实盘会亏完所有钱!!!
### 实盘会亏完所有钱!!!
## 实盘会亏完所有钱!!!
# 实盘会亏完所有钱!!!
> 策略参数
|参数|默认值|描述|
|----|----|----|
|STOP_LOSS|0.015|止损距离|
|TAKE_PROFIT|0.03|止盈距离|
|START_SIZE|true|初始仓位|
|RISK_LIMIT|1025|最大仓位|
|LEVERAGE_RATE|20|杠杆大小|
|CONTRACT_TYPE|this_week|合约类型|
|DELAY|30|刷新间隔|
|AMP|2|反向倍数|
> 源码 (python)
``` python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# encoding: utf-8
#
# Paul "The Gambler" Lévy.
#
# Copyright 2018 FawkesPan
# Contact : i@fawkex.me / Telegram@FawkesPan
#
# Do What the Fuck You Want To Public License
#
import random
from math import *
Account = {}
Ticker = {}
LPosition = 0
SPosition = 0
Positions = {}
TotalLoss = 0
TotalWin = 0
FullLoss = 0
MaxPosition = 0
TotalLongs = 0
TotalShorts = 0
def cancelAllOrders():
orders = exchange.GetOrders()
for order in orders:
exchange.CancelOrder(order['Id'], order)
return True
def updateMarket():
global Ticker
Ticker = exchange.GetTicker()
return True
def updateAccount():
global Account
global LPosition
global SPosition
global Positions
global MaxPosition
LPosition = 0
SPosition = 0
Positions = {}
for item in exchange.GetPosition():
if item['MarginLevel'] == LEVERAGE_RATE:
if item['Type'] == 1:
Positions['Short'] = item
SPosition += item['Amount']
else:
Positions['Long'] = item
LPosition += item['Amount']
MaxPosition = max(MaxPosition, SPosition, LPosition)
Account = exchange.GetAccount()
return True
def updatePositions():
global TotalWin
global TotalLoss
global FullLoss
opened = False
try:
Long = Positions['Long']['Amount']
LongEntry = Positions['Long']['Price']
Current = Ticker['Sell']
StopLoss = LongEntry * (1-STOP_LOSS)
TakeProfit = LongEntry * (1+TAKE_PROFIT)
if Current > TakeProfit:
Risked = True
Log('多仓达到预设止盈价位. #0000FF')
TotalWin+=1
Log('总计止盈次数: ', TotalWin, ' 总计止损次数: ', TotalLoss, ' 完全止损次数: ', FullLoss, ' 持有过的最大仓位: ', MaxPosition, ' 总计开多: ', TotalLongs, ' 总计开空: ', TotalShorts)
coverLong(Long, True)
if Current < StopLoss:
Risked = True
Log('多仓达到预设止损价位. #FF0000')
TotalLoss+=1
Log('总计止盈次数: ', TotalWin, ' 总计止损次数: ', TotalLoss, ' 完全止损次数: ', FullLoss, ' 持有过的最大仓位: ', MaxPosition, ' 总计开多: ', TotalLongs, ' 总计开空: ', TotalShorts)
coverLong(Long, True)
if Long*AMP < RISK_LIMIT:
openShort(Long*AMP, True)
else:
FullLoss+=1
Log('超过允许的最大仓位,停止开仓. #FF0000')
Log('总计止盈次数: ', TotalWin, ' 总计止损次数: ', TotalLoss, ' 完全止损次数: ', FullLoss, ' 持有过的最大仓位: ', MaxPosition, ' 总计开多: ', TotalLongs, ' 总计开空: ', TotalShorts)
opened = True
except KeyError:
pass
try:
Short = Positions['Short']['Amount']
ShortEntry = Positions['Short']['Price']
Current = Ticker['Buy']
StopLoss = ShortEntry * (1+STOP_LOSS)
TakeProfit = ShortEntry * (1-TAKE_PROFIT)
if Current < TakeProfit:
Risked = True
Log('空仓达到预设止盈价位. #0000FF')
TotalWin+=1
Log('总计止盈次数: ', TotalWin, ' 总计止损次数: ', TotalLoss, ' 完全止损次数: ', FullLoss, ' 持有过的最大仓位: ', MaxPosition, ' 总计开多: ', TotalLongs, ' 总计开空: ', TotalShorts)
coverShort(Short, True)
if Current > StopLoss:
Risked = True
Log('空仓达到预设止损价位. #FF0000')
TotalLoss+=1
Log('总计止盈次数: ', TotalWin, ' 总计止损次数: ', TotalLoss, ' 完全止损次数: ', FullLoss, ' 持有过的最大仓位: ', MaxPosition, ' 总计开多: ', TotalLongs, ' 总计开空: ', TotalShorts)
coverShort(Short, True)
if Short*AMP < RISK_LIMIT:
openLong(Short*AMP, True)
else:
FullLoss+=1
Log('超过允许的最大仓位,停止开仓. #FF0000')
Log('总计止盈次数: ', TotalWin, ' 总计止损次数: ', TotalLoss, ' 完全止损次数: ', FullLoss, ' 持有过的最大仓位: ', MaxPosition, ' 总计开多: ', TotalLongs, ' 总计开空: ', TotalShorts)
opened = True
except KeyError:
pass
if not opened:
Log('还没开仓,随便开个仓位.')
rand = random.choice([1,2,3,4,5,6])
if rand in [1,3,5]:
Log('骰子抛到了: ',rand,' 正在开多.')
openLong(START_SIZE, True)
else:
Log('骰子抛到了: ',rand,' 正在开空.')
openShort(START_SIZE, True)
return True
def openLong(Amount=0, marketPrice=False):
global TotalLongs
Amount = floor(Amount)
TotalLongs+=Amount
exchange.SetDirection('buy')
if marketPrice:
exchange.Buy(Ticker['Sell']*1.01, Amount)
else:
exchange.Buy(Ticker['Sell'], Amount)
return True
def coverLong(Amount=0, marketPrice=False):
exchange.SetDirection('closebuy')
if marketPrice:
exchange.Sell(Ticker['Buy']*0.99, Amount)
else:
exchange.Sell(Ticker['Buy'], Amount)
return True
def openShort(Amount=0, marketPrice=False):
global TotalShorts
Amount = floor(Amount)
TotalShorts+=Amount
exchange.SetDirection('sell')
if marketPrice:
exchange.Sell(Ticker['Buy']*0.99, Amount)
else:
exchange.Sell(Ticker['Buy'], Amount)
return True
def coverShort(Amount=0, marketPrice=False):
exchange.SetDirection('closesell')
if marketPrice:
exchange.Buy(Ticker['Sell']*1.01, Amount)
else:
exchange.Buy(Ticker['Sell'], Amount)
return True
def onTick():
cancelAllOrders()
updateMarket()
updateAccount()
updatePositions()
return True
def main():
exchange.SetContractType(CONTRACT_TYPE)
exchange.SetMarginLevel(LEVERAGE_RATE)
while True:
onTick()
Sleep(DELAY*1000)
```
> 策略出处
https://www.fmz.com/strategy/117768
> 更新时间
2018-09-21 01:34:13
@@ -0,0 +1,53 @@
> 策略名称
Push Binance deal order to WeChat|实时推送币安成交到微信(wss协议练习)
> 策略作者
botvsing
> 策略参数
|参数|默认值|描述|
|----|----|----|
|APIKEY||your binance API Key|
> 源码 (javascript)
``` javascript
function main() {
var listenKey = JSON.parse(HttpQuery('https://api.binance.com/api/v1/userDataStream','',null,'X-MBX-APIKEY:'+APIKEY)).listenKey;
HttpQuery('https://api.binance.com/api/v1/userDataStream', {method:'DELETE',data:'listenKey='+listenKey}, null,'X-MBX-APIKEY:'+ APIKEY);
listenKey = JSON.parse(HttpQuery('https://api.binance.com/api/v1/userDataStream','',null,'X-MBX-APIKEY:'+ APIKEY)).listenKey;
var datastream = Dial("wss://stream.binance.com:9443/ws/"+listenKey, 100);
var update_listenKey_time = Date.now()/1000;
while (true){
if (Date.now()/1000 - update_listenKey_time > 1800){
update_listenKey_time = Date.now()/1000;
HttpQuery('https://api.binance.com/api/v1/userDataStream', {method:'PUT',data:'listenKey='+listenKey}, null,'X-MBX-APIKEY:'+ APIKEY);
Log('keep listenKey alive');
}
var data = datastream.read();
if(data){
data = JSON.parse(data);
if(data.e == 'executionReport' && data.x == 'TRADE'){
Log(data.S, data.s, 'amount is ', data.l, 'at price:', data.p, '@');
}
}
}
}
```
> 策略出处
https://www.fmz.com/strategy/122649
> 更新时间
2018-10-20 15:06:05
@@ -1,8 +1,13 @@
'''
策略出处: https://www.fmz.com/strategy/43965
策略名称: Python 精简多品种 MACD 趋势策略
策略作者: Zero
策略描述:
> 策略名称
Python 精简多品种 MACD 趋势策略
> 策略作者
Zero
> 策略描述
需要引用小小梦公开的商品期货交易类库
@@ -10,13 +15,19 @@
https://www.botvs.com/strategy/24288
> 策略参数
参数 默认值 描述
------------ ------------ ----
Amount 2 开仓手数
ContractList MA701,rb1701 合约列表
'''
|参数|默认值|描述|
|----|----|----|
|Amount|2|开仓手数|
|ContractList|MA701,rb1701|合约列表|
> 源码 (python)
``` python
'''
/*backtest
start: 2016-01-30
@@ -77,3 +88,12 @@ def main():
t.onTick()
q.poll()
Sleep(1000)
```
> 策略出处
https://www.fmz.com/strategy/43965
> 更新时间
2017-06-30 10:15:54
+23 -6
View File
@@ -1,13 +1,21 @@
'''
策略出处: https://www.fmz.com/strategy/21365
策略名称: Python API 测试
策略作者: Zero
策略描述:
> 策略名称
Python API 测试
'''
> 策略作者
Zero
> 策略描述
Python API 测试
> 源码 (python)
``` python
import sys
import time
import talib
@@ -119,3 +127,12 @@ def main():
x.add(0, [ts, ticker.Buy])
x.add(1, [ts, ticker.Sell])
Sleep(10000)
```
> 策略出处
https://www.fmz.com/strategy/21365
> 更新时间
2016-12-18 18:00:34
@@ -1,26 +1,40 @@
'''
策略出处: https://www.fmz.com/strategy/21023
策略名称: Python 双平台对冲策略
策略作者: Zero
策略描述:
> 策略名称
Python 双平台对冲策略
> 策略作者
参数 默认值 描述
------------ ------ --------
MinSpreadA 0.51 A->B差价
MinSpreadB 0.52 B->A差价
MaxAmount 0.3 最大操作量
BalanceTime 10 平衡周期(秒)
LoopInterval 200 轮询周期(ms)
Zero
按钮 默认值 描述
---- ----- ----------
A->B 0.51 更改价差(A->B)
B->A 0.52 更改价差(B->A)
'''
> 策略描述
Python 双平台对冲策略
> 策略参数
|参数|默认值|描述|
|----|----|----|
|MinSpreadA|0.51|A->B差价|
|MinSpreadB|0.52|B->A差价|
|MaxAmount|0.3|最大操作量|
|BalanceTime|10|平衡周期(秒)|
|LoopInterval|200|轮询周期(ms)|
|按钮|默认值|描述|
|----|----|----|
|A->B|0.51|更改价差(A->B)|
|B->A|0.52|更改价差(B->A)|
> 源码 (python)
``` python
import time
import json
@@ -167,3 +181,12 @@ def main():
hedgeNum[HPos] += 1
```
> 策略出处
https://www.fmz.com/strategy/21023
> 更新时间
2016-09-26 11:33:18
@@ -1,8 +1,13 @@
'''
策略出处: https://www.fmz.com/strategy/21370
策略名称: Python 机器学习之 SVM 预测买卖
策略作者: Zero
策略描述:
> 策略名称
Python 机器学习之 SVM 预测买卖
> 策略作者
Zero
> 策略描述
Python入门简单策略 sklearn 机器学习库的使用
@@ -11,12 +16,18 @@ numpy pandas TA-Lib scipy statsmodels sklearn cvxopt hmmlearn pykalman arch matp
实盘需要在托管者所在机器安装策略需要的库
> 策略参数
参数 默认值 描述
--------- ----- ----
SpreadVal 2 预测价差
'''
|参数|默认值|描述|
|----|----|----|
|SpreadVal|2|预测价差|
> 源码 (python)
``` python
from sklearn import svm
import numpy as np
@@ -106,3 +117,12 @@ def main():
if marketPosition == 0:
LogProfit(_N(nowAccount.Balance - initAccount.Balance, 4), nowAccount)
```
> 策略出处
https://www.fmz.com/strategy/21370
> 更新时间
2018-06-05 16:46:36
@@ -1,13 +1,19 @@
'''
策略出处: https://www.fmz.com/strategy/46031
策略名称: Python版 TableTemplet (测试版)
策略作者: 小小梦
策略描述:
> 策略名称
Python版 TableTemplet (测试版)
> 策略作者
小小梦
'''
> 源码 (python)
``` python
# TableTemplet
import json
listener = {}
@@ -159,3 +165,12 @@ def main():
```
> 策略出处
https://www.fmz.com/strategy/46031
> 更新时间
2018-01-13 17:44:46
@@ -1,20 +1,31 @@
'''
策略出处: https://www.fmz.com/strategy/20761
策略名称: Python简单测试策略
策略作者: Zero
策略描述:
> 策略名称
Python简单测试策略
> 策略作者
Zero
> 策略描述
需要下载最新的托管者, 托管者机器个需要安装python, (Linux自带无需安装)
> 策略参数
参数 默认值 描述
---- ------- -------------------
a 1.2 number
b 你好hello str
c true bool
d 0 select: abc|def|xxx
'''
|参数|默认值|描述|
|----|----|----|
|a|1.2|number|
|b|你好hello|str|
|c|true|bool|
|d|0|select: abc|def|xxx|
> 源码 (python)
``` python
import time
import talib
@@ -74,3 +85,12 @@ def main():
x.add(1, [ts, ticker.Sell])
LogStatus(ticker)
Sleep(10000)
```
> 策略出处
https://www.fmz.com/strategy/20761
> 更新时间
2018-06-05 16:43:46
@@ -1,13 +1,21 @@
'''
策略出处: https://www.fmz.com/strategy/23531
策略名称: R-Breaker 交易策略
策略作者: 太极
策略描述:
> 策略名称
R-Breaker 交易策略
'''
> 策略作者
太极
> 策略描述
R-Breaker 交易策略
> 源码 (python)
``` python
#!/usr/local/bin/python
#-*- coding: UTF-8 -*-
#R-Breaker 交易策略
@@ -224,3 +232,12 @@ def main():
Sleep(1000)
```
> 策略出处
https://www.fmz.com/strategy/23531
> 更新时间
2016-10-28 19:37:57
@@ -1,13 +1,21 @@
'''
策略出处: https://www.fmz.com/strategy/23874
策略名称: R-Breaker11 交易策略
策略作者: 太极
策略描述:
> 策略名称
R-Breaker11 交易策略
> 策略作者
太极
> 策略描述
R-Breaker 交易策略
'''
> 源码 (python)
``` python
# botvs@f976b25629baf8373e73da860a54030d
#!/usr/local/bin/python
#-*- coding: UTF-8 -*-
@@ -334,3 +342,12 @@ def main():
nowAccount = ext.GetAccount() #交易模板的导出函数 获取账户信息
print_log(0,nowAccount)
Sleep(1000)
```
> 策略出处
https://www.fmz.com/strategy/23874
> 更新时间
2017-02-13 11:58:17
+87 -23
View File
@@ -4,18 +4,97 @@
> 开源策略列表
- [RUMI策略](https://www.fmz.com/strategy/129082)
- [日本云图简化版策略](https://www.fmz.com/strategy/129083)
- [高胜率ORB交易策略](https://www.fmz.com/strategy/129084)
- [麦语言海龟策略体验](https://www.fmz.com/strategy/126968)
- [升级版恒温器策略](https://www.fmz.com/strategy/129086)
- [Dual Thrust (麦语言版)](https://www.fmz.com/strategy/128884)
- [传统均线指标与KD指标的交易策略](https://www.fmz.com/strategy/128249)
- [双均线策略与相对强弱RSI指标组合](https://www.fmz.com/strategy/128250)
- [抛物线转向SAR与价格高低点策略](https://www.fmz.com/strategy/128251)
- [波动率ATR轨道突破策略](https://www.fmz.com/strategy/128252)
- [价格高低点与一目均线双重趋势策略](https://www.fmz.com/strategy/128415)
- [动向指数(DMI)与高低点策略](https://www.fmz.com/strategy/128418)
- [MACD+MA指标组合策略](https://www.fmz.com/strategy/128134)
- [双均线DDI策略](https://www.fmz.com/strategy/128133)
- [高低点突破成交量指数加权策略](https://www.fmz.com/strategy/128125)
- [标准差价格通道策略](https://www.fmz.com/strategy/128121)
- [基于ATR波动率指标构建的通道策略](https://www.fmz.com/strategy/128126)
- [三均线顺势价格突破策略](https://www.fmz.com/strategy/128130)
- [高低点与波动率ROC指标策略](https://www.fmz.com/strategy/128417)
- [瀑布线策略](https://www.fmz.com/strategy/128420)
- [Bitmex仓位变化推送微信(wss协议,需要bitmex api ID)|Bitmex position-change push(websocket)](https://www.fmz.com/strategy/128624)
- [开收盘均价差ATR策略](https://www.fmz.com/strategy/128136)
- [多级止盈趋势策略](https://www.fmz.com/strategy/128122)
- [三轨道波动率策略](https://www.fmz.com/strategy/128129)
- [基于ATR波动率指标构建的通道策略](https://www.fmz.com/strategy/127691)
- [海龟](https://www.fmz.com/strategy/128382)
- [OKEX期现对冲](https://www.fmz.com/strategy/127939)
- [商品期货交易类库(旧版)](https://www.fmz.com/strategy/127341)
- [现现对冲(搬砖)](https://www.fmz.com/strategy/127154)
- [你不知道的MACD+MA指标组合策略](https://www.fmz.com/strategy/127101)
- [BitMEX 高级API功能 V.1.1.0 (期货:批量下单,编辑订单,冰山订单,一键撤单,定时撤单) Python2/3](https://www.fmz.com/strategy/114148)
- [OkEX 高级API功能 V.1.1.0 (期货:批量下单,现货;TBD) Python2/3](https://www.fmz.com/strategy/113979)
- [多交易所集合行情/下单 策略 范例](https://www.fmz.com/strategy/125569)
- [使用画线类库画K线以及均线图表范例](https://www.fmz.com/strategy/125770)
- [MA5](https://www.fmz.com/strategy/125474)
- [设定价格微信推送(教学)](https://www.fmz.com/strategy/125482)
- [OkEX Websocket Realtime](https://www.fmz.com/strategy/91176)
- [移植 OKCoin 韭菜收割机 注释](https://www.fmz.com/strategy/124178)
- [Binance buy and sell statistics|币安买卖统计](https://www.fmz.com/strategy/121917)
- [Push Binance deal order to WeChat|实时推送币安成交到微信(wss协议练习)](https://www.fmz.com/strategy/122649)
- [Get cryptocurrency current and max supply|获取币种供应量](https://www.fmz.com/strategy/122370)
- [指数均衡策略 (教学)](https://www.fmz.com/strategy/120581)
- [指数平衡策略|Index Balance Bot](https://www.fmz.com/strategy/116012)
- [简单均线策略|Moving Average Bot 30 lines](https://www.fmz.com/strategy/103070)
- [币安取消所有交易对未完成订单(IO扩展示范)|Cancel ALL Binance Orders](https://www.fmz.com/strategy/121549)
- [冰山委托卖出简单版|Simple Iceberg order to sell](https://www.fmz.com/strategy/121524)
- [冰山委托买入简单版|Simple Iceberg order to buy](https://www.fmz.com/strategy/121522)
- [简单预定买入后卖出机器人|Buy then Sell (ping-pong strategy)](https://www.fmz.com/strategy/121228)
- [简单固定价格止损机器人|Stop Loss Below Fixed Price](https://www.fmz.com/strategy/121081)
- [经典均线策略](https://www.fmz.com/strategy/12348)
- [闪崩机器人 (教学)](https://www.fmz.com/strategy/118939)
- [模拟测试kdj](https://www.fmz.com/strategy/119057)
- [BTC-V反策略](https://www.fmz.com/strategy/117202)
- [合成任意周期K线 使用请看源码最下面](https://www.fmz.com/strategy/117473)
- [Paul "The Gambler" Lévy](https://www.fmz.com/strategy/117768)
- [动态平衡 做市策略](https://www.fmz.com/strategy/113618)
- [OKEX交易对信息](https://www.fmz.com/strategy/117000)
- [简单网格测试](https://www.fmz.com/strategy/116289)
- [(13)策略框架](https://www.fmz.com/strategy/20663)
- [跨平台套利新手测试](https://www.fmz.com/strategy/115574)
- [Fomo3D 智能合约监控 / Fomo3D Smart Contract Monitoring](https://www.fmz.com/strategy/107916)
- [动态平衡alpha](https://www.fmz.com/strategy/115321)
- [CoinPark交易所通用协议 6.27 16:00 更新 关闭了SSL验证](https://www.fmz.com/strategy/101399)
- [30行赌徒策略](https://www.fmz.com/strategy/113796)
- [交易所最小数量和精度](https://www.fmz.com/strategy/108887)
- [Shannon's Demon](https://www.fmz.com/strategy/64455)
- [BitMEX 高级API功能 (期货:批量下单,一键撤单) JavaScript](https://www.fmz.com/strategy/105056)
- [动态平衡 做市策略 (小高)](https://www.fmz.com/strategy/114044)
- [30行赌徒策略 (做空)](https://www.fmz.com/strategy/113986)
- [GuoJian_First](https://www.fmz.com/strategy/113871)
- [50行网格策略(教学)](https://www.fmz.com/strategy/113144)
- [50行多平台对冲策略(教学)](https://www.fmz.com/strategy/113278)
- [Dual Thrust OKEX期货 (教学)](https://www.fmz.com/strategy/112425)
- [[VNC] SVM Test](https://www.fmz.com/strategy/112188)
- [Dynamic Balance Strategy](https://www.fmz.com/strategy/110900)
- [区块链量化投资系列课程(3) - 跨期套利](https://www.fmz.com/strategy/104964)
- [区块链量化投资系列课程(4) - 动态平衡策略](https://www.fmz.com/strategy/110545)
- [单平台均衡策略](https://www.fmz.com/strategy/345)
- [商品期货跨期对冲 - 单品种套利合约](https://www.fmz.com/strategy/27122)
- [新手上路CoinEx交易 (LTC_USDT)](https://www.fmz.com/strategy/103464)
- [画线类库|Plot library](https://www.fmz.com/strategy/27293)
- [Iceberg Buy Order](https://www.fmz.com/strategy/103319)
- [Dual Thrust OKEX Feature](https://www.fmz.com/strategy/103247)
- [Moving Average Strategy in 30 lines](https://www.fmz.com/strategy/103070)
- [商品期货跟单系统](https://www.fmz.com/strategy/79351)
- [CoinPark交易所通用协议 6.27 16:00 更新 关闭了SSL验证](https://www.fmz.com/strategy/101399)
- [转换任意K线周期管理模板(最近更新20180627)](https://www.fmz.com/strategy/41163)
- [商品期货跨期对冲 - 单品种套利合约](https://www.fmz.com/strategy/27122)
- [检查https://quant.la/Argus/是否正常](https://www.fmz.com/strategy/100344)
- [2014年的简易短线机器人](https://www.fmz.com/strategy/1088)
- [FCoin交易手续费统计(感谢满总分享)](https://www.fmz.com/strategy/98405)
- [fcoin挖矿演示](https://www.fmz.com/strategy/97791)
- [币安出售所有山寨币](https://www.fmz.com/strategy/97629)
- [RSI 双均线策略](https://www.fmz.com/strategy/46605)
- [商品期货 - 形态策略(增强型锤子)](https://www.fmz.com/strategy/97130)
- [追涨杀跌](https://www.fmz.com/strategy/96634)
- [Python 机器学习之 SVM 预测买卖](https://www.fmz.com/strategy/21370)
- [Python简单测试策略](https://www.fmz.com/strategy/20761)
@@ -27,16 +106,17 @@
- [抢盘口做市策略 - 高频逼近型](https://www.fmz.com/strategy/348)
- [网格变形策略之单边网格 (OK期货)](https://www.fmz.com/strategy/8474)
- [测试-CTP商品期货连接状态 (图表显示)](https://www.fmz.com/strategy/22838)
- [图表模板(增加状态栏表格)](https://www.fmz.com/strategy/20967)
- [测试-布林带策略(基于策略框架)](https://www.fmz.com/strategy/28128)
- [策略框架模板](https://www.fmz.com/strategy/30861)
- [python版CTP商品期货交易类库(支持2/3 测试版)](https://www.fmz.com/strategy/24288)
- [指数量化](https://www.fmz.com/strategy/91704)
- [顺大势逆小势策略之代码实现及可行性分析](https://www.fmz.com/strategy/59356)
- [判断MA线的排列 - btcdw](https://www.fmz.com/strategy/89969)
- [基于回归幅度的反转交易策略](https://www.fmz.com/strategy/69937)
- [单边网格](https://www.fmz.com/strategy/88472)
- [okex币币最小交易量](https://www.fmz.com/strategy/88754)
- [基于CCI周期性区间交易策略](https://www.fmz.com/strategy/60287)
- [商品期货交易类库](https://www.fmz.com/strategy/12961)
- [网格变形策略之单边网格](https://www.fmz.com/strategy/629)
- [talib简单应用之查找三只乌鸦](https://www.fmz.com/strategy/62163)
- [内外盘期货品种实时差价图](https://www.fmz.com/strategy/82929)
@@ -52,25 +132,16 @@
- [CTP商品期货多品种海龟交易策略](https://www.fmz.com/strategy/17289)
- [python版 Dual Thrust OKCoin 期货](https://www.fmz.com/strategy/21856)
- [五线向上&&突破前高](https://www.fmz.com/strategy/76827)
- [单平台均衡策略](https://www.fmz.com/strategy/345)
- [数字货币现货交易类库](https://www.fmz.com/strategy/10989)
- [数字货币交易类库 (期货支持OKCoin期货/BitVC, 支持$.CTA函数)](https://www.fmz.com/strategy/57267)
- [C++ API调用例子](https://www.fmz.com/strategy/61533)
- [定期定额投资BTC盈利验证](https://www.fmz.com/strategy/65030)
- [双平台对冲js版本(two platforms hedging-JS)](https://www.fmz.com/strategy/57556)
- [代替废弃的GetMinStock()函数](https://www.fmz.com/strategy/69436)
- [Python版 TableTemplet (测试版)](https://www.fmz.com/strategy/46031)
- [网格(波段)香农版](https://www.fmz.com/strategy/67495)
- [价值平均定投](https://www.fmz.com/strategy/67128)
- [定投简单版](https://www.fmz.com/strategy/67098)
- [Shannon's Demon](https://www.fmz.com/strategy/64455)
- [画线类库](https://www.fmz.com/strategy/27293)
- [回测保存K线到本地CSV](https://www.fmz.com/strategy/61867)
- [02顺大势逆小势策略之代码实现及可行性分析 (Share 1513097042)](https://www.fmz.com/strategy/63223)
- [03基于商品期货的套利策略模型 (Share 1513096985)](https://www.fmz.com/strategy/63221)
- [幽灵交易者策略 (Share 1512580165)](https://www.fmz.com/strategy/62303)
- [bitfinex保证金交易](https://www.fmz.com/strategy/57333)
- [双平台对冲js版本(two platforms hedging-JS) (Copy)](https://www.fmz.com/strategy/61405)
- [简单多品种商品期货均线策略](https://www.fmz.com/strategy/57029)
- [测试 默认 参数组功能](https://www.fmz.com/strategy/40155)
- [全球10大交易系统之 Aberration 多品种商品期货交易系统](https://www.fmz.com/strategy/25943)
@@ -78,6 +149,7 @@
- [python版 画线类库 (兼容2/3)](https://www.fmz.com/strategy/39066)
- [BotVS 商品期货 量化 测试入门 策略](https://www.fmz.com/strategy/59120)
- [如何找出一定Bar数量的 K线前期高点、低点 及 Demo 程序](https://www.fmz.com/strategy/58179)
- [OKCoin期货跨期对冲策略(模板测试使用)](https://www.fmz.com/strategy/36762)
- [python版现货数字货币交易类库](https://www.fmz.com/strategy/21104)
- [一目均衡](https://www.fmz.com/strategy/55839)
- [StochRSI(和okcoin一致)](https://www.fmz.com/strategy/56119)
@@ -95,10 +167,10 @@
- [Ma单均线趋势交易](https://www.fmz.com/strategy/42451)
- [KingKeltner趋势策略_低频](https://www.fmz.com/strategy/42283)
- [buy-hold 买入持有](https://www.fmz.com/strategy/41786)
- [知乎专栏 实例文章策略](https://www.fmz.com/strategy/39586)
- [知乎专栏 实例文章策略](https://www.fmz.com/strategy/40266)
- [BitMEX 简单测试](https://www.fmz.com/strategy/40289)
- [商品期货查看账户详细信息](https://www.fmz.com/strategy/37793)
- [股票证券查询买卖示例](https://www.fmz.com/strategy/5541)
- [测试多图表展示](https://www.fmz.com/strategy/38203)
- [商品期货结算单平仓盈亏历史查询](https://www.fmz.com/strategy/38083)
- [Convert_Record_Cycle](https://www.fmz.com/strategy/37678)
@@ -113,13 +185,11 @@
- [范例-定时测试微信消息推送](https://www.fmz.com/strategy/15098)
- [Python API 测试](https://www.fmz.com/strategy/21365)
- [从第三方获取K线 (商品期货版) Rev. 161216](https://www.fmz.com/strategy/15498)
- [均线策略 30 行搞定](https://www.fmz.com/strategy/12348)
- [商品期货跨期对冲 - 百行代码实现](https://www.fmz.com/strategy/23896)
- [短信通知类库](https://www.fmz.com/strategy/26921)
- [获取和讯期货数据(Python版本)](https://www.fmz.com/strategy/26017)
- [高频收割机一号](https://www.fmz.com/strategy/6237)
- [R-Breaker 交易策略](https://www.fmz.com/strategy/23531)
- [(13)策略框架](https://www.fmz.com/strategy/20663)
- [均线策略(python版)](https://www.fmz.com/strategy/21157)
- [Python 双平台对冲策略](https://www.fmz.com/strategy/21023)
- [各大平台API可用率统计](https://www.fmz.com/strategy/4404)
@@ -130,17 +200,13 @@
- [对冲2.7收益率统计系统 支持多组账号统计](https://www.fmz.com/strategy/18678)
- [收益率统计](https://www.fmz.com/strategy/19329)
- [从第三方网站获取K线 (0804更新)](https://www.fmz.com/strategy/12977)
- [不要怂就是干](https://www.fmz.com/strategy/18943)
- [入门模板之各个平台余额](https://www.fmz.com/strategy/48)
- [商品期货主力合约过滤](https://www.fmz.com/strategy/9837)
- [商品期货交易类库(增加下限价单功能)](https://www.fmz.com/strategy/14198)
- [获取OK期货实时限价](https://www.fmz.com/strategy/17028)
- [定期定额投资BTC盈利验证](https://www.fmz.com/strategy/16845)
- [My-1-价值平均定投策略](https://www.fmz.com/strategy/8602)
- [记录净资产变动情况2.0](https://www.fmz.com/strategy/8916)
- [非常简单的策略,但是很有效](https://www.fmz.com/strategy/15085)
- [单独计算收益(代码来自zero)](https://www.fmz.com/strategy/1084)
- [10行人品策略](https://www.fmz.com/strategy/14436)
- [平台价格指标监控1.1](https://www.fmz.com/strategy/12442)
- [窜天猴 - 移动止损版](https://www.fmz.com/strategy/13594)
- [窜天猴 多空较量 爆破版](https://www.fmz.com/strategy/13597)
@@ -156,7 +222,6 @@
- [多平台账户统计](https://www.fmz.com/strategy/7827)
- [阶梯下单 - 可设置触发价格](https://www.fmz.com/strategy/639)
- [796期货反手加倍算法](https://www.fmz.com/strategy/3648)
- [冰山委托 - 支持价格触发 BitVC期货专用](https://www.fmz.com/strategy/951)
- [多线程获取多个交易的深度信息](https://www.fmz.com/strategy/3651)
- [账户余额变动邮箱提醒, 支持添加多个交易所](https://www.fmz.com/strategy/2006)
- [多线程获取多个交易的账户信息](https://www.fmz.com/strategy/3297)
@@ -166,7 +231,6 @@
- [统计K线回测是否存在趋势](https://www.fmz.com/strategy/1125)
- [价格波动报警](https://www.fmz.com/strategy/885)
- [取消所有订单](https://www.fmz.com/strategy/280)
- [新手入门之 - 下买单卖单](https://www.fmz.com/strategy/796)
- [短信通知接口测试](https://www.fmz.com/strategy/653)
- [每1分钟统计各个平台间的差价(by JackConan)](https://www.fmz.com/strategy/98)
- [统计各个平台间的最大差价(by JackConan)](https://www.fmz.com/strategy/86)
@@ -1,26 +1,38 @@
/*
策略出处: https://www.fmz.com/strategy/46605
策略名称: RSI 双均线策略
策略作者: yilidalei
策略描述:
> 策略名称
RSI 双均线策略
> 策略作者
yilidalei
> 策略参数
|参数|默认值|描述|
|----|----|----|
|RSI_Period|14|RSI周期|
|MA_fast_Period|10|快线周期|
|MA_slow_Period|24|慢线周期|
|SuperSellValue|20|超卖阈值|
|SuperBuyValue|80|超买阈值|
参数 默认值 描述
-------------- ----- -----
RSI_Period 14 RSI周期
MA_fast_Period 10 快线周期
MA_slow_Period 24 慢线周期
SuperSellValue 20 超卖阈值
SuperBuyValue 80 超买阈值
|按钮|默认值|描述|
|----|----|----|
|btn1|__button__|test|
|btn2|__button__|test2|
按钮 默认值 描述
---- ---------- -----
btn1 __button__ test
btn2 __button__ test2
*/
> 源码 (javascript)
``` javascript
// 以下是测试代码
/*- 状态 在使用 模板时需要在 主策略内声明
var TASK_IDLE = 0;
@@ -126,3 +138,12 @@ function main() {
$.Relation_Exchange_onTick(exchanges[0], onTick1);
$.Trend(); // 不用传参数。
}
```
> 策略出处
https://www.fmz.com/strategy/46605
> 更新时间
2018-06-09 17:45:28
+35 -15
View File
@@ -1,23 +1,34 @@
/*
策略出处: https://www.fmz.com/strategy/11604
策略名称: RSI_now_sb_ok
策略作者: tfboys
策略描述:
> 策略名称
RSI_now_sb_ok
> 策略作者
tfboys
> 策略描述
RSI简单买卖测试, 默认 70-100卖出,0-30买入
> 策略参数
参数 默认值 描述
---------- ------ ---------
RSIPeriod 14 RSI周期
SlidePrice 0.3 下单滑动值
RSIBuyL 50 RSI买入点(低)
RSIBuyH 50 RSI买入点(高)
RSISellL 50 RSI卖出点(低)
RSISellH 50 RSI卖出点(高)
Interval 1000 出错重试(毫秒)
*/
|参数|默认值|描述|
|----|----|----|
|RSIPeriod|14|RSI周期|
|SlidePrice|0.3|下单滑动值|
|RSIBuyL|50|RSI买入点(低)|
|RSIBuyH|50|RSI买入点(高)|
|RSISellL|50|RSI卖出点(低)|
|RSISellH|50|RSI卖出点(高)|
|Interval|1000|出错重试(毫秒)|
> 源码 (javascript)
``` javascript
function adjustFloat(v) {
return Math.floor(v*1000)/1000;
}
@@ -180,3 +191,12 @@ function main() {
Sleep(Interval);
}
}
```
> 策略出处
https://www.fmz.com/strategy/11604
> 更新时间
2016-03-08 16:00:06
+66
View File
@@ -0,0 +1,66 @@
> 策略名称
RUMI策略
> 策略作者
littleDreamXX
> 策略描述
- 策略名称:RUMI策略
- 适用周期:多周期
- 支持:商品期货、数字货币期货、数字货币现货
- 官方网站:www.quant.la
/upload/asset/df2427683a93f2c896c853c89e3ae494.png
/upload/asset/67f75ccbe20acf6cbaa62a1d580daeda.png
- 主图:
无
- 副图:
AOS指标,公式: AOS:MA(OS,N3);
> 策略参数
|参数|默认值|描述|
|----|----|----|
|N1|3|AOS指标参数1|
|N2|100|AOS指标参数2|
|N3|30|AOS指标参数3|
> 源码 (麦语言)
``` pascal
(*backtest
start: 2018-01-01 00:00:00
end: 2018-01-07 00:00:00
period: 5m
exchanges: [{"eid":"Futures_OKCoin","currency":"BTC_USD"}]
args: [["TradeAmount",100,126961],["ContractType","this_week",126961]]
*)
OS:=MA(CLOSE,N1)-EMA2(CLOSE,N2);
AOS:MA(OS,N3);
CONDITION1:=CROSSUP(AOS,0);
CONDITION2:=CROSSDOWN(AOS,0);
CONDITION1,BPK;
CONDITION2,SPK;
AUTOFILTER;
```
> 策略出处
https://www.fmz.com/strategy/129082
> 更新时间
2018-12-07 11:36:11
+41 -11
View File
@@ -1,21 +1,42 @@
> 策略名称
Shannon's Demon
> 策略作者
FawkesPan
> 策略参数
|参数|默认值|描述|
|----|----|----|
|DELAY|30|平衡间隔|
|DS|1.04|Sell|
|DB|1.08|Buy|
|RSIB|80|RSI Buy|
|RSIS|20|RSI Sell|
> 源码 (javascript)
``` javascript
/*
策略出处: https://www.fmz.com/strategy/64455
策略名称: Shannon's Demon
策略作者: FawkesPan
策略描述:
Shannon's Demon Demo Code
Copyright 2018 FawkesPan
Contact : i@fawkex.me / Telegram@FawkesPan
Do What the Fuck You Want To Public License
参数 默认值 描述
----- ----- --------
DELAY 30 平衡间隔
DS 1.04 Sell
DB 1.08 Buy
RSIB 80 RSI Buy
RSIS 20 RSI Sell
*/
function onTick(){
var Account = exchange.GetAccount();
var Depth = exchange.GetDepth();
@@ -50,3 +71,12 @@ function main(){
Sleep(DELAY*1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/64455
> 更新时间
2018-08-30 03:04:37
@@ -1,13 +1,19 @@
/*
策略出处: https://www.fmz.com/strategy/56119
策略名称: StochRSI(和okcoin一致)
策略作者: fangj
策略描述:
> 策略名称
StochRSI(和okcoin一致)
> 策略作者
fangj
*/
> 源码 (javascript)
``` javascript
function Stoch_RSI(records) {
/*
LC:=REF(CLOSE,1);
@@ -128,3 +134,12 @@ function main() {
Sleep(2000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/56119
> 更新时间
2017-09-26 13:04:37
+23 -6
View File
@@ -1,13 +1,21 @@
/*
策略出处: https://www.fmz.com/strategy/44319
策略名称: TableTemplet
策略作者: 职业养鸡户
策略描述:
> 策略名称
TableTemplet
> 策略作者
职业养鸡户
> 策略描述
//by 养鸡专业户 17/6/21
*/
> 源码 (javascript)
``` javascript
var listener = Array();
//----------绘制Table-----------
{
@@ -138,3 +146,12 @@ function main(){
tb.SetRowByTableInfo(0,tbInfo)
tbMgr.LogStatus("上","下")
}
```
> 策略出处
https://www.fmz.com/strategy/44319
> 更新时间
2017-06-21 11:27:08
+92
View File
@@ -0,0 +1,92 @@
> 策略名称
[VNC] SVM Test
> 策略作者
virtualpeer
> 源码 (python)
``` python
import numpy as np
import pandas as pd
data = DataAPI.MktIdxdGet(indexID=u"",ticker=u"000300",tradeDate=u"",beginDate=u"20100101",endDate=u"20180501",exchangeCD=u"XSHE,XSHG",field=u"",pandas="1")
data.set_index('tradeDate', inplace = True)
# 获取HS300的每日价格数据
for i in range(1, 21, 1):
data['close-' + str(i) + 'd'] = data['closeIndex'].shift(i)
# 对于收盘价,在data中增加了20列数据,分别为1天前的收盘价至20天前的收盘价
hs_close = data[[x for x in data.columns if 'close' in x]].iloc[20:]
# 选取今天及1-20天前的收盘价,iloc[20:]剔除了无效数据
hs_close = hs_close.iloc[:, ::-1]
# 将新DataFrame的列按倒序排列
################################################################################################
from sklearn import svm
# 从sklearn库中导入svm算法
days = 1500
# 设定全局变量,分割训练集和测试集的数据,1500在上文数据中约占75%
clf_close = svm.SVR(kernel='linear')
# 使用svm下的SVR算法,'linear'表示线性核
f_close_train = hs_close[:days]
# 训练集features
l_close_train = hs_close['closeIndex'].shift(-1)[:days]
# 训练集labels,将收盘价shift(-1)表示预测的是下一天的收盘价
f_close_test = hs_close[days:]
# 测试集features
l_close_test = hs_close['closeIndex'].shift(-1)[days:]
# 训练集labels,将收盘价shift(-1)表示预测的是下一天的收盘价
clf_close.fit(f_close_train, l_close_train)
# 训练模型
######################################################################################
p_close_train = clf_close.predict(f_close_train)
# 将训练集features导入模型进行预测,生成预测的收盘价
df_close_train = pd.DataFrame(l_close_train)
# 新建一个DataFrame,内容为训练集labels,即下一天的收盘价
df_close_train.columns = ['next close']
# 列名重命名为'next close'
df_close_train['predicted next close'] = p_close_train
# 加入一列预测的收盘价数据
df_close_train['next open'] = data['openIndex'][20:20 + days].shift(-1)
# 加入一列下一天开盘价的数据,从data而非hs_close中获取,需要切片
trigger = 1.0
df_close_train['position'] = np.where(df_close_train['predicted next close'] > df_close_train['next open'] * trigger, 1, 0)
# 通过np.where函数判断,当预测的下一天收盘价 > 下一天开盘价相乘或相加一个trigger时,仓位设置为1,否则为0
df_close_train['PL'] = np.where(df_close_train['position'] == 1, (df_close_train['next close'] - df_close_train['next open']) / df_close_train['next open'], 0)
# 当仓位为1时,在下一天开盘时买入,收盘时卖出,记录下一天应获得的收益率,否则收益率为0
df_close_train['strategy'] = (df_close_train['PL'].shift(1) + 1).cumprod()
# 策略每日收益的累积收益率,其中shift(1)表示当日记录的是下一天才能获得的收益率,当日无法获得
df_close_train['return'] = (df_close_train['next close'].pct_change() + 1).cumprod()
# benchmark的累积收益率
df_close_train[['strategy', 'return']].dropna().plot()
# 画出策略与benchmark的累计收益率图
##########################################################################
def main():
Log(exchange.GetAccount())
```
> 策略出处
https://www.fmz.com/strategy/112188
> 更新时间
2018-08-18 20:34:19
@@ -1,13 +1,19 @@
/*
策略出处: https://www.fmz.com/strategy/57333
策略名称: bitfinex保证金交易
策略作者: 7meter
策略描述:
> 策略名称
bitfinex保证金交易
> 策略作者
7meter
*/
> 源码 (javascript)
``` javascript
var bitfinexIndex = 0;
var basecurrency;
var quotecurrency;
@@ -57,3 +63,12 @@ $.marginBalance = function(){
var balance = exchanges[bitfinexIndex].IO("api", "POST", "/v1/margin_infos")
return balance[0].tradable_balance;
}
```
> 策略出处
https://www.fmz.com/strategy/57333
> 更新时间
2017-12-02 22:04:28
@@ -1,13 +1,21 @@
/*
策略出处: https://www.fmz.com/strategy/41786
策略名称: buy-hold 买入持有
策略作者: ipqhjjybj
策略描述:
> 策略名称
buy-hold 买入持有
> 策略作者
ipqhjjybj
> 策略描述
买入持有策略
*/
> 源码 (javascript)
``` javascript
/*
策略出处: rqalpha
策略名称: buy-hold买入持有
@@ -84,3 +92,12 @@ function main() {
Sleep(LoopInterval*1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/41786
> 更新时间
2017-06-02 22:18:11
+30 -10
View File
@@ -1,20 +1,31 @@
/*
策略出处: https://www.fmz.com/strategy/97791
策略名称: fcoin挖矿演示
策略作者: 爆仓小王子
策略描述:
> 策略名称
fcoin挖矿演示
> 策略作者
爆仓小王子
> 策略描述
看到官方api群里开源的python版本,虽然很简单了,但是还有很多人架不起来环境
出问题的原因也有很多种,不太适合新手
本着开源共享的精神,我也开源一份,请大家斧正
> 策略参数
参数 默认值 描述
------ ----- -------
Amount 10 下单量
Wait true 等待间隔(秒)
*/
|参数|默认值|描述|
|----|----|----|
|Amount|10|下单量|
|Wait|true|等待间隔(秒)|
> 源码 (javascript)
``` javascript
function DealOrder(orderType, sellPrice) {
var ticker = _C(exchange.GetTicker);
var action = orderType == ORDER_TYPE_BUY ? 'Buy' : 'Sell';
@@ -44,3 +55,12 @@ function main() {
}
}
```
> 策略出处
https://www.fmz.com/strategy/97791
> 更新时间
2018-06-12 10:28:01
+23 -6
View File
@@ -1,13 +1,21 @@
/*
策略出处: https://www.fmz.com/strategy/36195
策略名称: js R-Breaker
策略作者: 太极
策略描述:
> 策略名称
js R-Breaker
> 策略作者
太极
> 策略描述
R-Breaker
*/
> 源码 (javascript)
``` javascript
NPeriod=2 //周期
f1=0.47 //中轨上下顶部区间系数
f2=0.07 //中轨上下区间系数
@@ -157,3 +165,12 @@ function main() {
```
> 策略出处
https://www.fmz.com/strategy/36195
> 更新时间
2017-02-20 15:33:43
@@ -1,13 +1,19 @@
/*
策略出处: https://www.fmz.com/strategy/83189
策略名称: okex-BTC合约账户公开
策略作者: leviyuan
策略描述:
> 策略名称
okex-BTC合约账户公开
> 策略作者
leviyuan
*/
> 源码 (javascript)
``` javascript
var exchangeRate = 6.4,
usdprice = 1000
@@ -87,3 +93,12 @@ function main() {
Sleep(nxttime - nowtime)
}
}
```
> 策略出处
https://www.fmz.com/strategy/83189
> 更新时间
2018-03-29 09:51:37
@@ -1,13 +1,19 @@
/*
策略出处: https://www.fmz.com/strategy/88754
策略名称: okex币币最小交易量
策略作者: leviyuan
策略描述:
> 策略名称
okex币币最小交易量
> 策略作者
leviyuan
*/
> 源码 (javascript)
``` javascript
// 数据来源 https://github.com/okcoin-okex/API-docs-OKEx.com/blob/master/%E5%B8%81%E5%B8%81%E6%9C%80%E5%B0%8F%E4%BA%A4%E6%98%93%E9%87%8F(min_trade_size%20for%20spot).mda_btc
// 更新时间 2018-4-25 13:37
function main() {
@@ -518,3 +524,12 @@ $.GetMinTradeSize = function(exchIndex) {
return 0
return min_trade_size[currency]
}
```
> 策略出处
https://www.fmz.com/strategy/88754
> 更新时间
2018-04-25 13:45:38
@@ -1,25 +1,36 @@
'''
策略出处: https://www.fmz.com/strategy/21856
策略名称: python版 Dual Thrust OKCoin 期货
策略作者: 小小梦
策略描述:
> 策略名称
python版 Dual Thrust OKCoin 期货
> 策略作者
小小梦
> 策略描述
Dual Thrust 策略包含完整的图表显示, 图表动态更新,模板引用等功能, 可做学习模板使用.
> 策略参数
参数 默认值 描述
--------------- ----- --------------
ContractTypeIdx 0 合约品种: 当周|次周|季度
MarginLevelIdx 0 杠杆大小: 10|20
NPeriod 4 计算周期
Ks 0.5 上轨系数
Kx 0.5 下轨系数
AmountOP true 开仓合约张数
Interval 2000 重试间隔(毫秒)
LoopInterval 3 轮询间隔(秒)
PeriodShow 500 图表最大显示K线柱数
'''
|参数|默认值|描述|
|----|----|----|
|ContractTypeIdx|0|合约品种: 当周|次周|季度|
|MarginLevelIdx|0|杠杆大小: 10|20|
|NPeriod|4|计算周期|
|Ks|0.5|上轨系数|
|Kx|0.5|下轨系数|
|AmountOP|true|开仓合约张数|
|Interval|2000|重试间隔(毫秒)|
|LoopInterval|3|轮询间隔(秒)|
|PeriodShow|500|图表最大显示K线柱数|
> 源码 (python)
``` python
import time
class Error_noSupport(BaseException):
def __init__(self):
@@ -231,3 +242,12 @@ def main():
```
> 策略出处
https://www.fmz.com/strategy/21856
> 更新时间
2018-03-23 16:53:49
@@ -1,8 +1,13 @@
'''
策略出处: https://www.fmz.com/strategy/39066
策略名称: python版 画线类库 (兼容2-3)
策略作者: 小小梦
策略描述:
> 策略名称
python版 画线类库 (兼容2-3)
> 策略作者
小小梦
> 策略描述
简化了策略图表画线的逻辑, 可以直接调用封装好的函数
@@ -16,8 +21,11 @@
移植于JS版 画线类库
### 如有问题请联系 小小梦 359706687
'''
> 源码 (python)
``` python
# Python 2/3 兼容版本
import time
chart = None
@@ -239,3 +247,12 @@ def main():
Sleep(60000)
```
> 策略出处
https://www.fmz.com/strategy/39066
> 更新时间
2017-11-09 21:22:40
@@ -1,20 +1,31 @@
'''
策略出处: https://www.fmz.com/strategy/24288
策略名称: python版CTP商品期货交易类库(支持2-3 测试版)
策略作者: 小小梦
策略描述:
> 策略名称
python版CTP商品期货交易类库(支持2-3 测试版)
> 策略作者
小小梦
> 策略描述
python版CTP商品期货交易类库
测试版 如有BUG 欢迎提出,作者QQ : 359706687 小小梦
1、2017.4.25 更新:增加 if (insDetail.MaxLimitOrderVolume == 0) 条件判断,有些期货公司服务器 会返回0 值,特此处理。共修改3处 【1】self.pollTask 【2】function Cover 【3】function Open
> 策略参数
参数 默认值 描述
--------- ----- ----
SlideTick true 滑价
Interval 500 轮询间隔
'''
|参数|默认值|描述|
|----|----|----|
|SlideTick|true|滑价|
|Interval|500|轮询间隔|
> 源码 (python)
``` python
import json # json 模块
import types # 类型 模块
import platform # 版本信息
@@ -726,3 +737,12 @@ def main():
q.poll()
Sleep(1000)
```
> 策略出处
https://www.fmz.com/strategy/24288
> 更新时间
2018-05-15 14:29:05
@@ -1,23 +1,34 @@
'''
策略出处: https://www.fmz.com/strategy/21104
策略名称: python版现货数字货币交易类库
策略作者: 小小梦
策略描述:
> 策略名称
python版现货数字货币交易类库
> 策略作者
小小梦
> 策略描述
现货数字货币交易类库(python版)
> 策略参数
参数 默认值 描述
------------- ------ ------------------
OpMode 0 下单方式: 吃单|挂单
MaxSpace 0.5 挂单失效距离
SlidePrice 0.1 下单滑动价
MaxAmount 0.8 开仓单次最大下单量
RetryDelay 500 失败重试毫秒
MAType 0 均线类型: TA.EMA|TA.MA
_GetMinStocks 0.01 最小交易量
'''
|参数|默认值|描述|
|----|----|----|
|OpMode|0|下单方式: 吃单|挂单|
|MaxSpace|0.5|挂单失效距离|
|SlidePrice|0.1|下单滑动价|
|MaxAmount|0.8|开仓单次最大下单量|
|RetryDelay|500|失败重试毫秒|
|MAType|0|均线类型: TA.EMA|TA.MA|
|_GetMinStocks|0.01|最小交易量|
> 源码 (python)
``` python
import types # 导入类型模块
import time # 导入时间模块
import platform # 版本信息
@@ -241,3 +252,12 @@ def main():
avgprice = ret['price']
dealamount = ret['amount']
Log("avgprice:",avgprice," dealamount:",dealamount)
```
> 策略出处
https://www.fmz.com/strategy/21104
> 更新时间
2017-10-20 18:02:17
@@ -1,13 +1,21 @@
/*
策略出处: https://www.fmz.com/strategy/20383
策略名称: stochRSI策略 (指标框架)
策略作者: 小小梦
策略描述:
> 策略名称
stochRSI策略 (指标框架)
> 策略作者
小小梦
> 策略描述
stochRSI指标策略
*/
> 源码 (javascript)
``` javascript
/*参数
stochRSI 指标参数 数组 [14,14,3,3]
使用现货数字货币交易类库
@@ -331,3 +339,12 @@ function main(){
4、参数设置
5、可视图表
*/
```
> 策略出处
https://www.fmz.com/strategy/20383
> 更新时间
2016-08-22 19:23:00
@@ -1,13 +1,19 @@
/*
策略出处: https://www.fmz.com/strategy/62163
策略名称: talib简单应用之查找三只乌鸦
策略作者: Zero
策略描述:
> 策略名称
talib简单应用之查找三只乌鸦
> 策略作者
Zero
*/
> 源码 (javascript)
``` javascript
/*backtest
start: 2017-12-05 00:00:00
end: 2017-12-06 12:00:00
@@ -29,3 +35,12 @@ function main() {
Sleep(1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/62163
> 更新时间
2018-04-07 11:47:38
@@ -1,20 +1,31 @@
/*
策略出处: https://www.fmz.com/strategy/82325
策略名称: 【001】单平台均衡策略 【研究】
策略作者: 风利
策略描述:
> 策略名称
【001】单平台均衡策略 【研究】
> 策略作者
风利
> 策略描述
这个需要建仓,比如账户有5000块钱,跟1个币,如果币的价值大于账户的余额5000了并且差价超过阀值,比如币现在值6000块钱,就卖掉(6000-5000)/6000/2个币,说明币升值了,把钱兑换回来,如果币贬值了,比如4000块钱了,就买入(5000-4000)/4000/2个币, 币跌的时候买一些回来,如果再涨了,就再卖掉,好像天平一样,两边不同的对冲,所以我命名为均衡策略
> 策略参数
参数 默认值 描述
------------ ----- ----------
threshold 10 阀值
Interval 2000 出错重试间隔(毫秒)
LoopInterval 60 轮询间隔(秒)
*/
|参数|默认值|描述|
|----|----|----|
|threshold|10|阀值|
|Interval|2000|出错重试间隔(毫秒)|
|LoopInterval|60|轮询间隔(秒)|
> 源码 (javascript)
``` javascript
/* 单平台策略*/
@@ -124,3 +135,12 @@ function main() { //这里调用了主函数进
Sleep(LoopInterval * 1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/82325
> 更新时间
2018-03-24 00:41:40
@@ -1,18 +1,31 @@
/*
策略出处: https://www.fmz.com/strategy/8379
策略名称: 【Demo】如何利用“策略交互“动态调整策略参数
策略作者: momox
策略描述:
> 策略名称
【Demo】如何利用“策略交互“动态调整策略参数
> 策略作者
momox
> 策略描述
策略需要不断的测试调整,参数也经常改来改去,每次都停止再重启,费事费力,还会丢失原来的盈利进度(虽然也可以通过全局参数来恢复),其实botvs已经提供了动态调整参数的途径--”策略交互“
> 策略参数
按钮 默认值 描述
---- ----- ------
A3 999 AAA的参数
B3 Botvs BBB的参数
*/
|按钮|默认值|描述|
|----|----|----|
|A3|999|AAA的参数|
|B3|Botvs|BBB的参数|
> 源码 (javascript)
``` javascript
var Interval=2000;
//AAA,BBB为策略中希望动态调整的参数
@@ -52,3 +65,12 @@ function onTick(){
}
}
```
> 策略出处
https://www.fmz.com/strategy/8379
> 更新时间
2016-01-09 21:18:07
@@ -1,15 +1,23 @@
/*
策略出处: https://www.fmz.com/strategy/7547
策略名称: 【Demo】速度测试 websocket vs rest
策略作者: momox
策略描述:
> 策略名称
【Demo】速度测试 websocket vs rest
> 策略作者
momox
> 策略描述
websocket 接口 与 REST 接口的 速度测试,支持添加多个交易所测试,注意会短时增加你的api调用频率,请在确保不影响其他机器人运行的情况下运行。如果出现”Futures_OP 4: argument error“的错误,请更新到最新的托管者程序
特别提醒:只能添加支持websocket接口的交易所(有点废话,不支持websocket接口,你还测什么速度),不然会出错,目前 ok,火币提供websocket接口 ,BTCC不提供,其他请咨询查阅相关交易所API介绍或帮助
*/
> 源码 (javascript)
``` javascript
var Interval=1000;
@@ -133,3 +141,12 @@ function main() {
```
> 策略出处
https://www.fmz.com/strategy/7547
> 更新时间
2016-01-09 20:58:20
+34 -14
View File
@@ -1,8 +1,13 @@
/*
策略出处: https://www.fmz.com/strategy/55839
策略名称: 一目均衡
策略作者: icesun963
策略描述:
> 策略名称
一目均衡
> 策略作者
icesun963
> 策略描述
一目均衡 初级版
@@ -10,17 +15,23 @@
通过云层厚度,基准线和转换线为信号,进行买入卖出。
未作判断止损。
> 策略参数
参数 默认值 描述
------------------ ----- ---------------------
keh 12 HullMA
TenkanSenPeriods 9 TenkanSen转换值间隔
KijunSenPeriods 24 Kijun Sen基准线 间隔
SenkouSpanBPeriods 51 Senkou Span B 先行上限2间隔
displacement 24 Displacement延迟线间隔
CX 100 云层厚度
*/
|参数|默认值|描述|
|----|----|----|
|keh|12|HullMA|
|TenkanSenPeriods|9|TenkanSen转换值间隔|
|KijunSenPeriods|24|Kijun Sen基准线 间隔|
|SenkouSpanBPeriods|51|Senkou Span B 先行上限2间隔|
|displacement|24|Displacement延迟线间隔|
|CX|100|云层厚度|
> 源码 (javascript)
``` javascript
var diffarray = [];
var diff1array = [];
var TenkanSenArray = [];
@@ -229,3 +240,12 @@ function main() {
Sleep(60 * 60 * 1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/55839
> 更新时间
2017-09-27 13:52:15
+73
View File
@@ -0,0 +1,73 @@
> 策略名称
三均线顺势价格突破策略
> 策略作者
littleDreamXX
> 策略描述
- 公式名称:三均线顺势价格突破策略
- 数据周期:多周期
- 数据合约:指数合约
- 交易合约:主力合约
- 适合品种:商品期货
- 官方网站:www.quant.la
/upload/asset/4327c3e54a8618bb6f5b0ac3ea54dfc2.png
> 策略参数
|参数|默认值|描述|
|----|----|----|
|SLOSS|2|止损百分比|
|N1|30|均线1参数|
|N2|60|均线2参数|
|N3|90|均线3参数|
> 源码 (麦语言)
``` pascal
(*backtest
start: 2018-01-01 00:00:00
end: 2018-02-28 00:00:00
period: 1h
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES","balance":20000}]
*)
LOTS:=MAX(1,INTPART(MONEYTOT/(O*UNIT*0.1)));
MA1^^MA(C,N1);
MA2^^MA(C,N2);
MA3^^MA(C,N3);
BUYK:=BARPOS>N3 AND BKVOL=0 AND MA1>MA2 AND MA2>MA3 AND C>MA1;
SELLK:=BARPOS>N3 AND SKVOL=0 AND MA1<MA2 AND MA2<MA3 AND C<MA1;
BUYP:=SKVOL>0 AND CROSS(C,MA2) AND C>MA1 AND C<=SKPRICE*(1-2*SLOSS*0.01);
SELLP:=BKVOL>0 AND CROSS(MA2,C) AND MA1>C AND C>=BKPRICE*(1+2*SLOSS*0.01);
BUYK,BK(LOTS);
SELLK,SK(LOTS);
//止盈
BUYP,BP(SKVOL);
SELLP,SP(BKVOL);
//止损
C>=SKPRICE*(1+SLOSS*0.01),BP(SKVOL);
C<=BKPRICE*(1-SLOSS*0.01),SP(BKVOL);
//TRADE_OTHER('AUTO');
```
> 策略出处
https://www.fmz.com/strategy/128130
> 更新时间
2018-12-04 22:11:09
+89
View File
@@ -0,0 +1,89 @@
> 策略名称
三轨道波动率策略
> 策略作者
littleDreamXX
> 策略描述
- K线走完下单:收盘价开仓、平仓
- 数据合约:螺纹指数,郑煤指数,热卷指数,铁矿指数,焦炭指数,棕榈指数,橡胶指数,郑醇指数,PP指数,沪铜指数;
- 交易合约:螺纹主连,郑煤主连,热卷主连,铁矿主连,焦炭主连,棕榈主连,橡胶主连,郑醇主连,PP主连,沪铜主连;
- 数据级别:日K线;
/upload/asset/785c3a0e4e8c164bc831b05dcdc355a3.png
- 主图指标显示:
MIDTR^^MA(C,CN); // 确定MIDTR
UPTR^^MIDTR+2*STD(C,CN); // 确定UPTR
DOWNTR^^MIDTR-2*STD(C,CN); // 确定DOWNTR
HPOINT^^HV(H,CN),DOT,COLORRED; // 计算前一周期CN周期内最高价的最大值。
LPOINT^^LV(L,CN),DOT,COLORBLUE; // 计算前一周期CN周期内最低价的最小值。
- 副图:
无
> 策略参数
|参数|默认值|描述|
|----|----|----|
|AMOUNT|true|单仓|
|N|20|标准差周期数|
|MINN|20|CN最小值|
|MAXN|60|CN最大值|
|STOPRANGE|50|止损幅度|
> 源码 (麦语言)
``` pascal
(*backtest
start: 2017-07-01 00:00:00
end: 2018-11-30 00:00:00
period: 1d
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
*)
// 确定CN
VOLAT:=STD(C,N); // VOLAT(波动率):M周期收盘价的标准差
VOLATCHANGE:=(VOLAT-REF(VOLAT,1))/VOLAT; // 2个VOLAT的变化率
N1:=(1+VOLATCHANGE)*MINN; // VOLATCHANGE : 波动率变化
N2:=INTPART(N1); // 取整
N3:=MIN(N2,MAXN); // 确认CN不大于60
CN:=MAX(N3,MINN); // 确认CN不小于20
MIDTR^^MA(C,CN); // 确定MIDTR
UPTR^^MIDTR+2*STD(C,CN); // 确定UPTR
DOWNTR^^MIDTR-2*STD(C,CN); // 确定DOWNTR
HPOINT^^HV(H,CN),DOT,COLORRED; // 计算前一周期CN周期内最高价的最大值。
LPOINT^^LV(L,CN),DOT,COLORBLUE; // 计算前一周期CN周期内最低价的最小值。
// 开仓
L<=LPOINT AND L<DOWNTR AND BARPOS>MINN,SK(AMOUNT); // 当最低价小于DOWNTR和低点,且K线位置大于60,收盘价卖开
H>=HPOINT AND H>UPTR AND BARPOS>MINN,BK(AMOUNT); // 当最高价大于UPTR和高点,且K线位置大于60,收盘价买开
// 启动止损
C>=SKPRICE*(1+STOPRANGE*0.001),BP(SKVOL);
C<=BKPRICE*(1-STOPRANGE*0.001),SP(BKVOL);
// 平仓
C<MIDTR,SP(BKVOL); // 当收盘价小于MIDTR,收盘价卖平
C>MIDTR,BP(SKVOL); // 当收盘价大于MIDTR,收盘价买平
// 动态止损
REF(BKHIGH,1)>BKPRICE*(1+2*0.001*STOPRANGE) AND C<HV(C,BARSBK)*(1-STOPRANGE*0.001),SP(BKVOL); // 买开后最高价大于买开价*(1+2*0.001*STOPRANGE),且收盘价小于买开后最高收盘价*(1-STOPRANGE*0.001),收盘价卖平
REF(SKLOW,1)<SKPRICE*(1-2*0.001*STOPRANGE) AND C>LV(C,BARSSK)*(1+STOPRANGE*0.001),BP(SKVOL); // 卖开后最低价小于卖开价*(1-2*0.001*STOPRANGE),且收盘价大于卖开后最低收盘价*(1+STOPRANGE*0.001),收盘价买平
```
> 策略出处
https://www.fmz.com/strategy/128129
> 更新时间
2018-12-03 09:52:12
-74
View File
@@ -1,74 +0,0 @@
/*
策略出处: https://www.fmz.com/strategy/18943
策略名称: 不要怂就是干
策略作者: qq110888000
策略描述:
"Talk is cheap. Show me the code"
注: ` 策略使用了交易模板类库`
`希望新手从此策略入门, 一步步学习编写策略, 并体验到模拟与真实环境对交易系统的影响`
https://dn-filebox.qbox.me/fb4d0c7d773ca83e9d0230927705d419dc0bbeaa.png
参数 默认值 描述
------------- ----- -------
EnterPeriod 2 入市观察期
FastPeriod 5 入市快线周期
SlowPeriod 30 入市慢线周期
PositionRatio true 仓位比例
Interval 10 轮询周期(秒)
SlidePrice 0.01 滑动值
按钮 默认值 描述
---- ---------- ----
简单策略 __button__ 不懂
*/
function main()
{
var STATE_IDLE = -1;
var state = STATE_IDLE;
var initAccount = $.GetAccount();
var price = 0;
Log(initAccount);
while (true)
{
ticker = exchange.GetTicker();
var nowAccount = $.GetAccount();
var n = $.Cross(FastPeriod, SlowPeriod);
if (Math.abs(n) >= EnterPeriod && Math.abs(n) < EnterPeriod +1 )
{
if (n > 0)
{
price = ticker.Sell;
var opAmount = parseFloat((nowAccount.Balance * PositionRatio/(ticker.Sell+SlidePrice)).toFixed(3));
}
else
{
price = ticker.Buy;
var opAmount = nowAccount.Stocks;
}
if (opAmount> exchange.GetMinStock())
{
var obj = n > 0 ? exchange.Buy(price, opAmount) : $.Sell(price, opAmount);
if (obj)
{
opAmount = obj.amount;
// state = n > 0 ? PD_LONG : PD_SHORT;
Log("开仓详情", obj, "交叉周期", n, "币:", nowAccount.Stocks);
LogProfit(nowAccount.Balance + nowAccount.Stocks * ticker.Last , '钱');
}
/*else
{
continue;
} */
}
}
Sleep(Interval*1000);
}
}
@@ -1,13 +1,21 @@
'''
策略出处: https://www.fmz.com/strategy/76827
策略名称: 五线向上&&突破前高
策略作者: 围龙小子
策略描述:
> 策略名称
五线向上&&突破前高
> 策略作者
围龙小子
> 策略描述
均线策略(python版)教学性质,实盘慎用。
'''
> 源码 (python)
``` python
import types
import peakutils
import os
@@ -46,3 +54,12 @@ def main():
reported_price_list.append(previous_high)
Sleep(1000)
```
> 策略出处
https://www.fmz.com/strategy/76827
> 更新时间
2018-03-16 12:42:24
File diff suppressed because it is too large Load Diff
@@ -1,8 +1,13 @@
/*
策略出处: https://www.fmz.com/strategy/12977
策略名称: 从第三方网站获取K线 (0804更新)
策略作者: 数·狂
策略描述:
> 策略名称
从第三方网站获取K线 (0804更新)
> 策略作者
数·狂
> 策略描述
对于不支持获取K线数据的平台(BitVC期货、BTCC的BTC现货、中国比特币的ETH、ETC),如果在策略开始时必须获取足够多的K线,使用本模板则可从第三方网站直接获得平台的历史K线数据。
注意:
@@ -12,9 +17,12 @@ K线数据每3秒更新一次,因此无法高频调用。
0427更新:处理了Parse JSON数据时可能抛出的异常、出现异常时返回值统一为null。
*/
> 源码 (javascript)
``` javascript
$.AltRecords = function(exchange, timeframe, size, includeLastBar) {
var symbol;
var info;
@@ -63,3 +71,12 @@ function main() {
rec = $.AltRecords(exchange, "4hour", 100, 1); // 获取4小时K线, 100条, 含最后一条Bar
if (rec) Log(rec.length, rec[rec.length-1]);
}
```
> 策略出处
https://www.fmz.com/strategy/12977
> 更新时间
2016-08-04 22:35:27
@@ -1,8 +1,13 @@
/*
策略出处: https://www.fmz.com/strategy/15498
策略名称: 从第三方获取K线 (商品期货版) Rev. 161216
策略作者: 数·狂
策略描述:
> 策略名称
从第三方获取K线 (商品期货版) Rev. 161216
> 策略作者
数·狂
> 策略描述
如果在策略开始时必须获取足够多的K线,使用本模板则可从第三方直接获得指定合约的历史K线数据。
Update 20160810:支持和讯数据源。(推荐!注意:K线周期支持1、5、15、30、60<分钟>和1440<日线>、10080<周线>)
@@ -11,8 +16,11 @@ Update 20160615:支持新浪财经数据源。
仅适用于实盘交易。
作者不保证第三方数据准确性和程序正确性,仅供学习参考。
*/
> 源码 (javascript)
``` javascript
$.BTRecords = function(instrument, timeframe, size, includeLastBar) {
var info;
var record = [];
@@ -188,3 +196,12 @@ function main() {
rec = $.SNRecords('i1705', 15, 100, true); // 新浪财经数据对比
if (rec) Log(rec.length, rec[rec.length - 1]);
}
```
> 策略出处
https://www.fmz.com/strategy/15498
> 更新时间
2016-12-16 17:23:55
+28 -10
View File
@@ -1,18 +1,27 @@
/*
策略出处: https://www.fmz.com/strategy/54182
策略名称: 仓位均衡策略
策略作者: 春哥
策略描述:
> 策略名称
仓位均衡策略
> 策略作者
春哥
> 策略参数
参数 默认值 描述
--------------- ----- -----
TARGET_POSITION 0.5 固定仓位
ACT_DIFF 0.1 仓位变化量
*/
|参数|默认值|描述|
|----|----|----|
|TARGET_POSITION|0.5|固定仓位|
|ACT_DIFF|0.1|仓位变化量|
> 源码 (javascript)
``` javascript
function main() {
while (true) {
Sleep(300000);
@@ -41,3 +50,12 @@ function main() {
}
}
```
> 策略出处
https://www.fmz.com/strategy/54182
> 更新时间
2017-09-06 21:57:31
@@ -1,13 +1,19 @@
/*
策略出处: https://www.fmz.com/strategy/69436
策略名称: 代替废弃的GetMinStock()函数
策略作者: hugo_zhou
策略描述:
> 策略名称
代替废弃的GetMinStock()函数
> 策略作者
hugo_zhou
*/
> 源码 (javascript)
``` javascript
/****************
针对 火币pro 获取不同货币对的最小交易量
其他平台需要自行添加不同的错误解析代码
@@ -35,3 +41,12 @@ function main() {
Log(exchange.GetName()+huobipro[j],":",_G(exchange.GetName()+huobipro[j]));
}
}
```
> 策略出处
https://www.fmz.com/strategy/69436
> 更新时间
2018-01-17 17:42:25
+35 -15
View File
@@ -1,8 +1,13 @@
/*
策略出处: https://www.fmz.com/strategy/10744
策略名称: 价值0.418
策略作者: kakababy
策略描述:
> 策略名称
价值0.418
> 策略作者
kakababy
> 策略描述
设定一个用于投资的资金额度,如10000元。设定一个资金和比特币的价值比例,如50:50。根据现价,一直维持资金和比特币的价值比例。
@@ -12,18 +17,24 @@
同理,币价下跌时则买入以保持比例不变。
> 策略参数
参数 默认值 描述
-------------- ----- ---------
UseAccount true 使用帐户内全部资金
InitMoney 10000 初始资金量。
InitStock 5 初始币数。
StockRatio 0.418 币价值占总价值比例
InvestInterval true 投资间隔。
ErrorInterval 300 出错重试间隔。
SlidePrice 0.01 滑点
*/
|参数|默认值|描述|
|----|----|----|
|UseAccount|true|使用帐户内全部资金|
|InitMoney|10000|初始资金量。|
|InitStock|5|初始币数。|
|StockRatio|0.418|币价值占总价值比例|
|InvestInterval|true|投资间隔。|
|ErrorInterval|300|出错重试间隔。|
|SlidePrice|0.01|滑点|
> 源码 (javascript)
``` javascript
var initAccount = null;
var initPrice = 0;
var stockHold = 0;
@@ -246,3 +257,12 @@ function onexit() {
Log('Set prices:', prices);
Log('Robot Stopped!#ff0000@');
}
```
> 策略出处
https://www.fmz.com/strategy/10744
> 更新时间
2016-02-14 00:09:10
+28 -10
View File
@@ -1,19 +1,28 @@
/*
策略出处: https://www.fmz.com/strategy/67128
策略名称: 价值平均定投
策略作者: 小码哥
策略描述:
> 策略名称
价值平均定投
> 策略作者
小码哥
> 策略参数
参数 默认值 描述
------------------ ----- -----
singleInvestAmount 0.1 单次买入量
expectGrowthRate 0.008 预期增长率
*/
|参数|默认值|描述|
|----|----|----|
|singleInvestAmount|0.1|单次买入量|
|expectGrowthRate|0.008|预期增长率|
> 源码 (javascript)
``` javascript
/*backtest
start: 2017-12-01
end: 2018-01-01
@@ -90,3 +99,12 @@ function main() {
}
}
```
> 策略出处
https://www.fmz.com/strategy/67128
> 更新时间
2018-01-04 21:01:07
+34 -14
View File
@@ -1,23 +1,34 @@
/*
策略出处: https://www.fmz.com/strategy/885
策略名称: 价格波动报警
策略作者: Zero
策略描述:
> 策略名称
价格波动报警
> 策略作者
Zero
> 策略描述
程序监视指定周期内价格波动幅度,如果超过指定幅度, 就短信通知给指定手机用户, 使用短信宝接口,可以发送给多个手机号, 以逗号分开
周期请选择K线周期, K线周期为1分钟则为监视一分钟内的数据
> 策略参数
参数 默认值 描述
------------ ----- ---------
MaxRatio 1.5 波动幅度(百分比)
LoopInterval 5 采集间隔(秒)
EnableSMS true 开启短信通知
SMSUser test 短信宝用户名
SMSPass test 短信宝密码MD5
PhoneNum 111 通知手机号
*/
|参数|默认值|描述|
|----|----|----|
|MaxRatio|1.5|波动幅度(百分比)|
|LoopInterval|5|采集间隔(秒)|
|EnableSMS|true|开启短信通知|
|SMSUser|test|短信宝用户名|
|SMSPass|test|短信宝密码MD5|
|PhoneNum|111|通知手机号|
> 源码 (javascript)
``` javascript
function _N(v) {
return Math.floor(parseFloat(v.toFixed(10))*1000)/1000;
}
@@ -110,3 +121,12 @@ function main() {
Sleep(LoopInterval * 1000);
}
}
```
> 策略出处
https://www.fmz.com/strategy/885
> 更新时间
2014-10-11 18:47:40
@@ -0,0 +1,67 @@
> 策略名称
价格高低点与一目均线双重趋势策略
> 策略作者
littleDreamXX
> 策略描述
- 策略名称:价格高低点与一目均线双重趋势策略
- 数据周期:15M等
- 支持:商品期货
- 官方网站:www.quant.la
/upload/asset/487949c7affb8521d9c041610551c3cd.png
- 主图:
LINE1指标线,公式:LINE1^^(HHV(H,N1)+LLV(L,N1))*0.5;
LINE2指标线,公式:LINE2^^(HHV(H,N2)+LLV(L,N2))*0.5;
> 策略参数
|参数|默认值|描述|
|----|----|----|
|N1|150|高点低点均值1周期|
|N2|500|高点低点均值2周期|
|SLOSS|2|止损百分比|
> 源码 (麦语言)
``` pascal
(*backtest
start: 2018-07-01 00:00:00
end: 2018-08-16 00:00:00
period: 15m
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
args: [["N1",90],["N2",150]]
*)
LINE1^^(HHV(H,N1)+LLV(L,N1))*0.5;
LINE2^^(HHV(H,N2)+LLV(L,N2))*0.5;
BKVOL=0 AND BARPOS>N2 AND REF(LINE1,1)<REF(LINE2,1) AND LINE1>=LINE2,BPK;
SKVOL=0 AND BARPOS>N2 AND REF(LINE1,1)>REF(LINE2,1) AND LINE1<=LINE2,SPK;
BKVOL=0 AND H>=HHV(H,N1),BK;
SKVOL=0 AND L<=LLV(L,N1),SK;
C<BKPRICE*(1-SLOSS*0.01),SP(BKVOL);
C>SKPRICE*(1+SLOSS*0.01),BP(SKVOL);
AUTOFILTER;
```
> 策略出处
https://www.fmz.com/strategy/128415
> 更新时间
2018-12-05 16:59:14
@@ -0,0 +1,73 @@
> 策略名称
传统均线指标与KD指标的交易策略
> 策略作者
littleDreamXX
> 策略描述
- 策略名称:传统均线指标与KD指标的交易策略
- 数据周期:15M,30M等
- 支持:商品期货
- 指标使用了EMA,KD线,其中KD线使用的是默认参数(指标参数固定3,3,9)
- 官方网站:www.quant.la
/upload/asset/f842e44b0b8451cb562b8d5bd888e4c0.png
- 主图
EMA均线,公式:MAC^^EMA(C,N);
- 副图
KD线中的K线,公式:K:SMA(RSV,M1,1);//RSV的移动平均值
KD线中的D线,公式:D:SMA(K,M2,1);//K的移动平均值
> 策略参数
|参数|默认值|描述|
|----|----|----|
|SLOSS|2|止损百分比|
|N|120|EMA参数|
> 源码 (麦语言)
``` pascal
(*backtest
start: 2018-04-01 00:00:00
end: 2018-05-15 00:00:00
period: 30m
exchanges: [{"eid":"Futures_BitMEX","currency":"XBT_USD"}]
args: [["TradeAmount",100,126961],["ContractType","XBTUSD",126961]]
*)
MAC^^EMA(C,N);
NKD:=9;
M1:=3;
M2:=3;
RSV:=(CLOSE-LLV(LOW,NKD))/(HHV(HIGH,NKD)-LLV(LOW,NKD))*100;//收盘价与NKD周期最低值做差,NKD周期最高值与NKD周期最低值做差,两差之间做比值。
K:SMA(RSV,M1,1);//RSV的移动平均值
D:SMA(K,M2,1);//K的移动平均值
BARPOS>N AND C>MAC AND K<D,BK;
BARPOS>N AND C<MAC AND K>D,SK;
C<=BKPRICE*(1-SLOSS*0.01),SP(BKVOL);
C>=SKPRICE*(1+SLOSS*0.01),BP(SKVOL);
C>=BKPRICE*(1+SLOSS*0.01) AND C<MAC,SP(BKVOL);
C<=SKPRICE*(1-SLOSS*0.01) AND C>MAC,BP(SKVOL);
```
> 策略出处
https://www.fmz.com/strategy/128249
> 更新时间
2018-12-05 18:34:08
@@ -1,24 +1,35 @@
/*
策略出处: https://www.fmz.com/strategy/5379
策略名称: 传统期货差价监控 (CTP)
策略作者: Zero
策略描述:
> 策略名称
传统期货差价监控 (CTP)
> 策略作者
Zero
> 策略描述
只支持两个交易所, 可自定义差价的类型, 支持2.77托管者的自定义图表功能
> 策略参数
参数 默认值 描述
------------ ------ ----------------------
AInstrument au1506 主合约
BInstrument au1512 次合约
AType 0 主合约价格类型: 上次成交价|买一价|卖一价
BType 0 次合约价格类型: 上次成交价|买一价|卖一价
Interval 2000 出错重试间隔(毫秒)
TickInterval 2000 检测频率(毫秒)
NormalDiff 0.1 普通差价
HighDiff 0.3 较高差价
*/
|参数|默认值|描述|
|----|----|----|
|AInstrument|au1506|主合约|
|BInstrument|au1512|次合约|
|AType|0|主合约价格类型: 上次成交价|买一价|卖一价|
|BType|0|次合约价格类型: 上次成交价|买一价|卖一价|
|Interval|2000|出错重试间隔(毫秒)|
|TickInterval|2000|检测频率(毫秒)|
|NormalDiff|0.1|普通差价|
|HighDiff|0.3|较高差价|
> 源码 (javascript)
``` javascript
var __lastDiff = 0;
var __AType = ["Last", "Buy", "Sell"][AType];
var __BType = ["Last", "Buy", "Sell"][BType];
@@ -143,3 +154,12 @@ function main() {
Sleep(TickInterval);
}
}
```
> 策略出处
https://www.fmz.com/strategy/5379
> 更新时间
2016-01-21 00:54:49
@@ -0,0 +1,79 @@
> 策略名称
你不知道的MACD+MA指标组合策略
> 策略作者
Zero
> 策略描述
本期分享MACD+MA指标组合策略,在技术分析中,指标的组合使用是非常常见的,不同的指标组合在一起具有不同的操作要点和分析方法,指标的组合使用可以增强信号的准确性。该策略正是通过比较价格与MA的相互关系,再以MACD指标衡量价格运动加速度,来判断市场所处的状态,构建一种简单的择时交易策略。
> 源码 (麦语言)
``` pascal
(*backtest
start: 2018-11-01 00:00:00
end: 2018-11-22 00:00:00
period: 1h
exchanges: [{"eid":"OKCoin_EN","currency":"BTC_USD"}]
*)
// 公式名称:MACD+MA指标组合策略
// 数据周期:4小时
// 适合品种:商品期货/数字货币现货/数字货币期货
// MACD计算参数
FASTLENGTH:=12;
SLOWLENGTH:=26;
MACDLENGTH:=9;
// 均线长度
L1:=50;
L2:=120;
// 止损5%
STOPLOSS:=5;
//MACD
MACDVALUE:=EMA(CLOSE,FASTLENGTH)-EMA(CLOSE,SLOWLENGTH);
AVGMACD:=EMA(MACDVALUE,MACDLENGTH);
MACDDIFF:=MACDVALUE-AVGMACD;
//MA1、MA2
DMA1:=MA(C,L1);
DMA2:=MA(C,L2);
买入开仓价:=VALUEWHEN(BARSBK=1,O);
卖出开仓价:=VALUEWHEN(BARSSK=1,O);
BUYCONDITION:=MACDVALUE>0 && DMA1>DMA2 && MACDDIFF>0 && C>DMA1 && REF(C,1)>REF(DMA1,1);
SELLCONDITION:=MACDVALUE<0 && DMA1<DMA2 && MACDDIFF<0 && C<DMA1 && REF(C,1)<REF(DMA1,1);
//开仓条件
BKVOL=0 AND BUYCONDITION,BK;
SETSIGPRICETYPE(BK,NEW_ORDER);
SKVOL=0 AND SELLCONDITION,SK;
SETSIGPRICETYPE(SK,NEW_ORDER);
//离场条件
BKVOL>0 AND (REF(MACDVALUE,1)<0 OR REF(DMA1,1)<REF(DMA2,1)),SP;
SKVOL>0 AND (REF(MACDVALUE,1)>0 OR REF(DMA1,1)>REF(DMA2,1)),BP;
// 启动止损
SKVOL>0 AND HIGH>=卖出开仓价*(1+STOPLOSS*0.01),BP;
SETSIGPRICETYPE(BP,MAX(O,卖出开仓价*(1+STOPLOSS*0.01)));
BKVOL>0 AND LOW<=买入开仓价*(1-STOPLOSS*0.01),SP;
SETSIGPRICETYPE(SP,MIN(O,买入开仓价*(1-STOPLOSS*0.01)));
AUTOFILTER;
```
> 策略出处
https://www.fmz.com/strategy/127101
> 更新时间
2018-11-22 22:47:00
@@ -1,14 +1,22 @@
/*
策略出处: https://www.fmz.com/strategy/40357
策略名称: 使用 BotVS 构建一个机械化策略
策略作者: 小小梦
策略描述:
> 策略名称
使用 BotVS 构建一个机械化策略
> 策略作者
小小梦
> 策略描述
知乎专栏文章 附带策略
使用 BotVS 构建一个机械化策略
*/
> 源码 (javascript)
``` javascript
// 参数
var ContractType = "rb1710";
var PointAmount = 1;
@@ -140,3 +148,12 @@ function main(){
Sleep(Interval); // 暂停 0.5 秒, 避免轮询频率过高,访问交易所服务器过于频繁导致问题。
}
}
```
> 策略出处
https://www.fmz.com/strategy/40357
> 更新时间
2017-09-21 09:16:02
@@ -0,0 +1,67 @@
> 策略名称
使用画线类库画K线以及均线图表范例
> 策略作者
小小梦
> 策略参数
|参数|默认值|描述|
|----|----|----|
|MaCyc|10|均线参数|
> 源码 (javascript)
``` javascript
var PreBarTime = 0
function PlotMA_Kline(records, param, isFirst){
var ma = TA.MA(records, param)
$.PlotRecords(records, "K")
if(isFirst){
for(var i = records.length - 1; i >= 0; i--){
if(ma[i] !== null){
$.PlotLine("ma", ma[i], records[i].Time)
}
}
PreBarTime = records[records.length - 1].Time
} else {
if(PreBarTime !== records[records.length - 1].Time){
$.PlotLine("ma", ma[ma.length - 2], records[records.length - 2].Time)
PreBarTime = records[records.length - 1].Time
}
$.PlotLine("ma", ma[ma.length - 1], records[records.length - 1].Time)
}
}
function main(){
var maCyc = MaCyc
var isFirst = true
while(1){
var records = exchange.GetRecords()
if(records && records.length > maCyc){
PlotMA_Kline(records, maCyc, isFirst)
isFirst = false
}
Sleep(1000)
}
}
```
> 策略出处
https://www.fmz.com/strategy/125770
> 更新时间
2018-11-12 11:39:09
@@ -1,17 +1,28 @@
/*
策略出处: https://www.fmz.com/strategy/48
策略名称: 入门模板之各个平台余额
策略作者: Zero
策略描述:
> 策略名称
入门模板之各个平台余额
> 策略作者
Zero
> 策略描述
查看各个平台的余额和货币数量
> 策略参数
参数 默认值 描述
----------- ----- ------
DisableRate false 禁用汇率转换
*/
|参数|默认值|描述|
|----|----|----|
|DisableRate|false|禁用汇率转换|
> 源码 (javascript)
``` javascript
function main() {
for (var i = 0; i < exchanges.length; i++) {
if (DisableRate) {
@@ -36,3 +47,12 @@ function main() {
}
}
}
```
> 策略出处
https://www.fmz.com/strategy/48
> 更新时间
2016-07-25 16:10:13

Some files were not shown because too many files have changed in this diff Show More