0%
#Bitcoin#Signals

Execute your Trading Strategy with the Honey Framework and Bitfinex Terminal

2020년 10월 1일 6 분 읽기
뉴스 기사 배너 이미지

In this article, we will use data that is streamed on Bitfinex Terminal to execute a live strategy. For demonstration purposes, the generated trading signals are sent to the Bitfinex Websocket API. In practice, however, we can do anything with them. Even if you want to power on a coffee machine with a Raspberry Pi every time your strategy would trade, you could do so!

For our tutorial, we are using a popular strategy, the EMA Cross Strategy. It emits a trading signal when two EMA indicators cross each other. The EMA Cross strategy is included as one of the examples in the bfx-hf-strategy library.

Let’s start

To begin we have to install the required dependencies:

npm install dazaar hyperbee bitfinex-terminal-key-encoding bfx-hf-util bfx-hf-strategy bfx-hf-strategy-dazaar
bitfinex-api-node bfx-api-node-models bitfinex-terminal-terms-of-use

We also need to create a file, which will contain the code we write, let’s call it exec-strategy.js:

touch exec-strategy.js

Now we can load the required dependencies. Readers of our backtesting tutorial will spot a few similarities:

const dazaar = require('dazaar') const swarm = require('dazaar/swarm') const Hyperbee = require('hyperbee') const keyEncoding = require('bitfinex-terminal-key-encoding') const terms = require('bitfinex-terminal-terms-of-use')

const { SYMBOLS, TIME_FRAMES } = require('bfx-hf-util') const EMAStrategy = require('bfx-hf-strategy/examples/ema_cross') const execDazaar = require('bfx-hf-strategy-dazaar')

We also load and initialise the Bitfinex Websocket client. To make it work, you have to replace the placeholders with your credentials:

const { WSv2 } = require('bitfinex-api-node') const { Order } = require('bfx-api-node-models')

const apiKey = 'SECRET' const apiSecret = 'SECRETSECRET' const ws = new WSv2({ apiKey, apiSecret })

Next we initialise our strategy:

const market = { symbol: SYMBOLS.BTC_USD, tf: TIME_FRAMES.ONE_MINUTE }

const strat = EMAStrategy(market)

And initialise Dazaar:

const dmarket = dazaar('dbs/terminal-live') // stores received data in `dbs/terminal-live`

With wget we can pull the Dazaar Card for the data feed we want to consume. An overview of data feeds can be found here.

wget https://raw.githubusercontent.com/bitfinexcom/bitfinex-terminal/master/cards/bitfinex.terminal.btcusd.trades.json

That card is loaded into Dazaar and the Terms of Services are agreed by loading them into Dazaar after we have read them:

const card = require('./bitfinex.terminal.btcusd.candles.json') const buyer = dmarket.buy(card, { sparse: true, terms })

And if Dazaar emits a feed event, we set up Hyperbee and call a function called runStrategy:

buyer.on('feed', function () { console.log('got feed')

const db = new Hyperbee(buyer.feed, { keyEncoding, valueEncoding: 'json' })

runStrategy(db) })

So far, most of our setup is similar to the setup we used for backtests in the last article. Now we have to define the function runStrategy, which is enabling us to do something with the trading signals from our strategy:

async function runStrategy (db) {

}

The function runStrategy will set up the logic that runs our strategy on each received candle. First, we open the Websocket to the Bitfinex API.

await ws.open() await ws.auth()

We also set up the data stream. We call execDazaar with our strategy, the defined market and the Hyperbee database. As options, we pass in submitOrder, a custom function we will write in a bit. submitOrder will be called for every trading signal that is emitted from our strategy. The simulateFill option allows us to not wait for the order to be fully filled by the exchange, which is useful for our tutorial. The built-in submitOrder-function in the Honey Framework also submits orders by WebSocket and is waiting for an order to be filled before continuing. In production, you may want to use the built-in one, depending on your strategy and use case. We also seed the strategy state, we use a count of 120 candles.

const { exec, stream } = await execDazaar(strat, market, db, { submitOrder, simulateFill: true, includeTrades: false, seedCandleCount: 120 })

execDazaar returns a stream and a function called exec. We are calling exec on every entry that is sent in the stream:

for await (const data of stream) { const { key, value } = data await exec(key, value) }

Our function runStrategy is now complete, here is the full function:

async function runStrategy (db) { await ws.open() await ws.auth()

const { exec, stream } = await execDazaar(strat, market, db, { submitOrder, simulateFill: true, includeTrades: false, seedCandleCount: 10 })

for await (const data of stream) { const { key, value } = data await exec(key, value) } }

We still have to define the function submitOrder. For every signal emitted from our EMA Cross strategy, submitOrder is called with the current state of the strategy and the order data. In our case, we take the order data and send it to Bitfinex. We write a simplified version of the

async function submitOrder (strategyState = {}, order = {}) { const _o = { cid: Date.now(), ...order }

console.log('submitting order', _o)

const o = new Order(_o, ws) o.registerListeners()

o.on('update', () => { console.log(`order updated: ${o.serialize()}`) })

const res = await o.submit() return res }

To start everything, we have to connect to the network, which will trigger a feed event:

swarm(buyer)

When we run the file now, it will take the last 120 candles and pre-seed our strategy algorithm with it. Then it will follow the live stream of new candles coming in and run our strategy on it. In case a trading signal is generated, it is submitted to the Bitfinex API. You can find the full file we wrote in this article here.

And that’s it! In this article, we’ve learned how we can take a Honey Framework strategy, feed in data from Bitfinex Terminal, and submit the trading signals for trading. With the help of custom submitOrder functions, we can build custom functionality our trading strategy acts upon. We hope you enjoyed the article.

PS: Bitfinex is hiring!

🙂
🙂

The post appeared first on Bitfinex blog.

트레이딩을
자동화
하세요!

세계적 수준의 자동화된 암호화폐 거래 봇

시작하기
트레이딩 자동화

인기 뉴스

How to Set Up and Use Trust Wallet for Binance Smart Chain
#Bitcoin#Bitcoins#Config+2 더 많은 태그

How to Set Up and Use Trust Wallet for Binance Smart Chain

Your Essential Guide To Binance Leveraged Tokens

Your Essential Guide To Binance Leveraged Tokens

How to Sell Your Bitcoin Into Cash on Binance (2021 Update)
#Subscriptions

How to Sell Your Bitcoin Into Cash on Binance (2021 Update)

What is Grid Trading? (A Crypto-Futures Guide)

What is Grid Trading? (A Crypto-Futures Guide)

Cryptohopper에서 무료로 거래를 시작하세요!

무료 사용 - 신용카드 필요 없음

시작하기
Cryptohopper appCryptohopper app

면책 조항: Cryptohopper는 규제 기관이 아닙니다. 암호화폐 봇 거래에는 상당한 위험이 수반되며 과거 실적이 미래 결과를 보장하지 않습니다. 제품 스크린샷에 표시된 수익은 설명용이며 과장된 것일 수 있습니다. 봇 거래는 충분한 지식이 있거나 자격을 갖춘 재무 고문의 조언을 구한 경우에만 참여하세요. Cryptohopper는 어떠한 경우에도 (a) 당사 소프트웨어와 관련된 거래로 인해, 그로 인해 또는 이와 관련하여 발생하는 손실 또는 손해의 전부 또는 일부 또는 (b) 직접, 간접, 특별, 결과적 또는 부수적 손해에 대해 개인 또는 단체에 대한 어떠한 책임도 지지 않습니다. Cryptohopper 소셜 트레이딩 플랫폼에서 제공되는 콘텐츠는 Cryptohopper 커뮤니티 회원이 생성한 것이며 Cryptohopper 또는 그것을 대신한 조언이나 추천으로 구성되지 않는다는 점에 유의하시기 바랍니다. 마켓플레이스에 표시된 수익은 향후 결과를 나타내지 않습니다. Cryptohopper의 서비스를 사용함으로써 귀하는 암호화폐 거래와 관련된 내재적 위험을 인정하고 수락하며 발생하는 모든 책임이나 손실로부터 Cryptohopper를 면책하는 데 동의합니다. 당사의 소프트웨어를 사용하거나 거래 활동에 참여하기 전에 당사의 서비스 약관 및 위험 공개 정책을 검토하고 이해하는 것이 필수적입니다. 특정 상황에 따른 맞춤형 조언은 법률 및 재무 전문가와 상담하시기 바랍니다.

©2017 - 2024 저작권: Cryptohopper™ - 판권 소유.