0bps

Strategy vault / Tools & templates

WebSocket Version OKEx Cross Period Hedging Strategy Lesson

- Live Screenshot: - Only do bull spreads; bear spreads can be done by swapping contracts, which is the bear spread. - Add Two Exchange Objects, the First for the Quarter, the Second for the Week. - Streamlined all…

Author
发明者量化-小小梦
Complexity
Intermediate · 56 lines
Parameters
7

Minimal OKEX cross-period hedging strategy (tutorial)

  • Live Screenshot: IMG

  • Only do bull spreads; bear spreads can be done by swapping contracts, which is the bear spread.

  • Add Two Exchange Objects, the First for the Quarter, the Second for the Week.

  • Streamlined all code that could be simplified, with significant room for optimization; teaching strategy is cautious in real trading, and there is some risk across periods.

  • Use counterparty price to place the order.

  • Feedback welcomeBUG.

Teaching strategy, use in live trading with caution.

Teaching strategy, use in live trading with caution.

Teaching strategy, use in live trading with caution.

Parameters

NameDefaultWhat it controls
_BegintrueStarting spread
_AddtruePrice difference
_ProfittrueClosing price spread profit
_Count10Number of nodes
_ContractNumtrueNode order quantity
_Instrument_id_ALTC-USD-190628AExchange quarterly contractID
_Instrument_id_BLTC-USD-190426BExchange current week contractID

Source JavaScript

function Hedge (isOpen, retSetA, retSetB) {
    exchanges[0].SetDirection(isOpen ? "sell" : "closesell")
    exchanges[1].SetDirection(isOpen ? "buy" : "closebuy");
    (function (routineA, routineB) {
        Log(routineA.wait(), routineB.wait(), retSetA, retSetB)
    })(exchanges[0].Go(isOpen ? "Sell" : "Buy", -1, _ContractNum), exchanges[1].Go(isOpen ? "Buy" : "Sell", -1, _ContractNum))
}

function main () {
    var param = {"op": "subscribe", "args": ["futures/ticker:" + _Instrument_id_A, "futures/ticker:" + _Instrument_id_B]}
    var client = Dial("wss://real.okex.com:8443/ws/v3|compress=gzip_raw&mode=recv&reconnect=true&payload=" + JSON.stringify(param))
    client.write(JSON.stringify(param))
    var tickerA, tickerB 
    var arr = []
    for (var i = 0 ; i < _Count ; i++) {
        arr.push({open: _Begin + i * _Add, cover: _Begin + i * _Add - _Profit, isHold: false})
    }
    while (1) {
        var tab = {type: "table", title: "Status", cols: ["Node Information"], rows: []}
        Sleep(10) 
        var ret = client.read(-2)
        if (!ret || ret == "") {
            continue
        }

        var obj = null
        try {
            obj = JSON.parse(ret)
        } catch (e) {
            Log(e)
            continue
        }

        if (obj.table == "futures/ticker" && obj.data[0].instrument_id == _Instrument_id_A) {   
            tickerA = obj.data[0]
        } else if (obj.table == "futures/ticker" && obj.data[0].instrument_id == _Instrument_id_B) {
            tickerB = obj.data[0]
        }

        if (tickerA && tickerB) {
            $.PlotLine(tickerA.instrument_id + "-" + tickerB.instrument_id, tickerA.last - tickerB.last)
            for (var j = 0 ; j < arr.length; j++) {
                if (tickerA.best_bid - tickerB.best_ask > arr[j].open && !arr[j].isHold) {   
                    Hedge(true, exchanges[0].SetContractType("quarter"), exchanges[1].SetContractType("this_week"))
                    arr[j].isHold = true
                }
                if (tickerA.best_ask - tickerB.best_bid < arr[j].cover && arr[j].isHold) {
                    Hedge(false, exchanges[0].SetContractType("quarter"), exchanges[1].SetContractType("this_week"))
                    arr[j].isHold = false 
                }
                tab.rows.push([JSON.stringify(arr[j])])
            }
        }
        LogStatus(_D(), "\n `" + JSON.stringify(tab) + "`")
    }
}

Published by 发明者量化-小小梦 on the FMZ strategy square · last modified 2020-04-27. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.

Build this with AgenKit

A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.

in Claude Code, Cursor, Codex & 4 more
/agenkit build a tested, production-ready module from strategies/WebSocket-Version-OKEx-Cross-Period-Hedging-Strategy-Lesson.md
  1. npx agenkit install engineering-kit in your project
  2. Paste the command into your agent and approve each phase
  3. Get tests, backtest, risk controls and a paper-trading switch

Understand it first

Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.

Related specs

esc

Try , , or .

↑↓ move↵ open