• Stars
    star
    381
  • Rank 112,502 (Top 3 %)
  • Language
    JavaScript
  • License
    BSD 2-Clause "Sim...
  • Created over 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Helping our users understand how to trade programatically.

Blockbid CCXT Tutorials

blockbid.io - Australian crypto exchange, no KYC required

We thought it would be useful to show our users how to trade programatically at Blockbid. This repo will eventually contain a series of tutorials ranging from super beginner to advanced. Please use issues to suggest ideas about what you would like to see.

Requirements

  • Basic understanding of Javascript
  • Basic understanding of trading
  • NodeJS

Getting Started

After you have cloned the repo.

  1. Generate an API key on your settings page
  2. Edit stragies/safeMargins.js to add your new API key
  3. Execute the commands below
npm i
npm run start

Safe High Margin Limit Order Tutorial

This tutorial will show you how to periodically set orders with high margins based off the average global market price.

It is actually quite easy to write trading bots, and this one in particular is really only around 30-40 lines of code.

It expects you to have two currencies e.g. BTC TUSD

It will then place one sell order and one buy order every minute with fluctuating prices on the BTCTUSD market.

We call it safe because the script is set to place orders 20% above and below market price, ensuring no one will likely match them, but if they do you should be happy.

The code is fully documentated and you should be able to read it even if you have no programming experience.

We love all feedback!

Successful output should look like:

Starting safe margin limit order strategy
Fetching current orders on BTC/TUSD
Cancelling current orders on BTC/TUSD
Finished cancelling 2 open orders
Fetching the global average price for BTC/TUSD
The global average price for BTC/TUSD is 10055.30417295
By our calculations we want to
Buy 0.0003019033084706648 BTC when the price is 8044.24333836
Sell 0.0011350974232612501 TUSD when the price is 12066.36500754
Successfully placed orders

Here is the contents of the script

const ccxt = require("ccxt");
const axios = require("axios"); // Used for API requests

// WARNING: You will be placing orders on a real market place
const TRADE = false;
// WARNING: Change the above to true, if you want to actually execute orders

const API_KEY = "";
const SECRET = "";

// CCXT is a framework that was built to make trading across hundreds of exchanges
// Here we initialize CCXT to trade with Blockbid
let blockbidClient = new ccxt.blockbid({
  apiKey: API_KEY,
  secret: SECRET
});

// Here we define the configuration for a simple safe margin limit order strategy

const marketQuote = "BTC";
const marketBase = "TUSD";
const market = `${marketQuote}/${marketBase}`; // e.g BTC/TUSD"

const volumePercentage = 0.1; // What percentage of our available funds do we want to trade
const priceVariation = 0.2; // What price increase/decrease do we want to margin our orders with
const shiftSeconds = 60; // How often should we shift the price of our orders

// This is our main function, once executed, our orders will be placed
const strategy = async () => {
  console.log("\n\n Starting safe margin limit order strategy");

  // First let's cancel any open orders open on this market
  // To do that, we need to fetch a list of our open orders
  console.log("Fetching current orders on", market);
  const openOrders = await blockbidClient.fetchOpenOrders(market);
  // Now that we have the open orders, let's loop over them and cancel them
  console.log("Cancelling current orders on", market);
  openOrders.forEach(async order => {
    await blockbidClient.cancelOrder(order.id);
  });
  console.log("Finished cancelling", openOrders.length, "open orders");

  // The purpose of this script is to set safe/high-margin orders
  // We use cryptonator to get a current rough global price for the market
  console.log("Fetching the global average price for", market);
  const globalPriceUrl = `https://api.cryptonator.com/api/ticker/${marketQuote}-${marketBase}`;
  const globalPriceResponse = await axios(globalPriceUrl); // Axios makes network requests
  const globalPrice = globalPriceResponse.data.ticker.price * 1;
  console.log("The global average price for", market, "is", globalPrice);

  // Now that we have an average price, we want to calculate what our safe margins would be
  // e.g. If the average global price for BTCTUSD is $10000
  //      And our desired price variation is 20%
  //      We would want to sell at $10000 + ($10000 * 0.2) which would be ~$12000

  const sellPrice = globalPrice + globalPrice * priceVariation;
  const buyPrice = globalPrice - globalPrice * priceVariation;

  // Now we calculate what amount of volume we want to trade based off what we have

  // First, let's fetch our current balances on the exchange
  const balances = await blockbidClient.fetchBalance();

  // Now let's find the balance of our accounts for the market we wish to trade on
  const quoteBalance = balances.free[marketQuote]; // e.g. 0.01 BTC
  const baseBalance = balances.free[marketBase]; // e.g. 30 TUSD

  // To calculate how much we want to sell on this market we just
  // simply use our account balance of the quote currency and multiply
  // it by the percentage configured at the top of the file
  const sellVolume = quoteBalance * volumePercentage;

  // To buy on this market is slightly different. We can only buy as much as we
  // can afford by the balance of our base pair.
  // If the price of BTCTUSD is $10000 and we only have $1000 TUSD
  // then we can only afford to buy $1000 / $10000 = 0.1 BTC
  const buyVolume = (baseBalance * volumePercentage) / globalPrice;

  console.log("By our calculations we want to");
  console.log("Buy", buyVolume, marketQuote, "when the price is", buyPrice);
  console.log("Sell", sellVolume, marketBase, "when the price is", sellPrice);

  if (TRADE) {
    // Now we simply execute our limit orders using CCXT
    await blockbidClient.createLimitSellOrder(market, sellVolume, sellPrice);
    await blockbidClient.createLimitBuyOrder(market, buyVolume, buyPrice);
    console.log("Successfully placed orders");
  } else {
    console.log("TRADE EXECUTION IS DISABLED, SEE TOP OF FILE WARNING");
  }
};

const safeMargins = () => {
  if (API_KEY.length === 0) {
    console.log("You need to set your API key at the top of the file");
    return;
  }
  strategy(); // Call the strategy once
  // Now set an interval which calls the function every X seconds
  setInterval(strategy, shiftSeconds * 1000);
};
module.exports = safeMargins;

More Repositories

1

backbonetutorials

As single page apps and large scale javascript applications become more prominent on the web, useful resources for those developers who are jumping the ship are crucial.
JavaScript
2,303
star
2

kaleistyleguide

This project aims at making sure your style sheets are fully documented whilst being synchronized with your webpages styles. To do this it actually uses your live stylesheets in so that at anytime you can review how your styleguide looks.
JavaScript
671
star
3

backboneboilerplate

The project aims at being a modular backbone environment with as little authority on development as possible such that developers can innovate and contribute in an attempt to mimic the success of backbone.js ambiguous nature.
JavaScript
569
star
4

seoserver

SEO Server is a command line tool that runs a server that allows GoogleBot, as well as other crawlers, to crawl Javascript heavy websites.
JavaScript
218
star
5

w3cjs

A npm package for testing files or url's again the wc3 validator
JavaScript
159
star
6

thomasdavis.github.io

Technical Tips generally about backbone.js,node.js and couchdb
CSS
87
star
7

omega

clubhouse + google deep voice + gpt3
JavaScript
40
star
8

pinjs

Pinjs is an node.js API client for Pin which is an Australian payment gateway.
JavaScript
25
star
9

saveprivacy

Signups for Australian campaign against Mass Surveillance
CSS
13
star
10

resume

Resume of Thomas Davis
9
star
11

video-backbone-beginner-server

JavaScript
8
star
12

markdownresume

Markdown Resume
JavaScript
8
star
13

react-redux-tutorials

HTML
7
star
14

gitgossip

Place holder for gitgossip.com which will be open sourced soon.
7
star
15

chess

api
JavaScript
5
star
16

jQuery-Social-Sidebar

A jQuery plugin that
JavaScript
5
star
17

browser-node-slides

Running node.js in the browser
JavaScript
5
star
18

jQuery-DataTables-Backbone

Manipulate a DataTable using BackBone.js
5
star
19

boilerplate

mm
JavaScript
4
star
20

CDN-Js-Website

Frontend
JavaScript
4
star
21

backbone-workshop-client

Client repo
JavaScript
4
star
22

styleguide

JavaScript
4
star
23

ancient-greek-tutorials

by http://www.reddit.com/user/Nanocyborgasm
4
star
24

old-facebook

Old submission for Facebook application
JavaScript
3
star
25

thomasdav.is

my new home page
CSS
3
star
26

ancient-greek

JavaScript
3
star
27

philo

philo = love of
JavaScript
3
star
28

bob

bob
JavaScript
3
star
29

Wordpress-Social-Sidebar

A Wordpress plugin enabling jQuery plugin Social Sidebar
PHP
3
star
30

jsonresume-theme-techlead

A theme inspired by Techlead (millionaire) https://youtu.be/xpaz7nrNmXA?t=528
HTML
3
star
31

brendandyer

Brendan Dyers Thoughts
3
star
32

backbone-workshop-server

Backbone server
JavaScript
3
star
33

islandbreeze

JavaScript
3
star
34

amazon-caching-demo-with-node.js

A demo for how to use amazons dynamic caching. used at bris js august 2012
3
star
35

backbone-and-couch

A example application to help people learn easy ways to make the two work together.
3
star
36

resetthenet-cloudflare-app

Cloudflare App for Reset The Net
JavaScript
3
star
37

white

UI components for some stuff
2
star
38

living

JavaScript
2
star
39

dickbird

2
star
40

cyclone-yasi

blue
2
star
41

ciara

2
star
42

tarshadavis.com

my sisters websitee
2
star
43

workplease

asd
JavaScript
2
star
44

cpricelandscapes

JavaScript
2
star
45

sittella

2
star
46

UMD-Sample-Project

To compile or not to compile that is the question
2
star
47

ecortes.net

2
star
48

blackshatan

2
star
49

skipchimp

Bypass MailChimp opt in process by using the API
JavaScript
2
star
50

whatwedo

asd
JavaScript
2
star
51

anki-riak

learning ancient greek the easy way
2
star
52

joeslawnscaping

Website for joe
JavaScript
2
star
53

btwb.js

Beyond The Whiteboard API Client
2
star
54

anki-web

2
star
55

altproducts

JavaScript
2
star
56

green

2
star
57

antwonthedon.com

Antwon, born Anthony Murray, is a young Aboriginal rap artist from Mildura Australia. His first album " The Aboriginal Criminal " was released on iTunes in 2009 under his own label CME Criminal Minded Entertainment.
2
star
58

world-db-postgres

Use this to upload to postgres esp heroku. never lose this so annoying to find
2
star
59

productscript

1
star
60

thomasdavis

1
star
61

requirejs-delights

A presentation on require.js as module system and a loader
1
star
62

jspurf

JavaScript
1
star
63

ajaxdavis.com

I like this name
1
star
64

asda

1
star
65

testingjsonblog

HTML
1
star
66

homepage

My personal homepage and blog
CSS
1
star
67

fawziyah.com

HTML
1
star
68

impossible

modern application building conventions
1
star
69

jsonblog-cli

JavaScript
1
star
70

roarrecruitment.com.au

a
CSS
1
star
71

rolandnsharp

1
star
72

mushroomvoice

1
star
73

tarshaart

1
star
74

dotavoid

1
star
75

opendesertdreams.github.io

HTML
1
star
76

todo-backbone-requirejs

A todo app
1
star
77

covidcalc

JavaScript
1
star
78

mecaptureyou

JavaScript
1
star
79

ineedto

CSS
1
star
80

roarrecruitment

JavaScript
1
star
81

jquery-plugin-pattern

In progress
1
star
82

lordajax.com

Built with github.com/jsonblog
HTML
1
star
83

somejs

somejs
1
star
84

shout-ubuntu

shout irc for ubuntu
1
star
85

corsgithub

A cors proxy server for raw.github.com
JavaScript
1
star
86

eed

example docs
CSS
1
star
87

dummyjaresumesite

1
star
88

ideas

1
star
89

jsonblog-generator-boilerplate

An example generator for people to learn how to construct generators
JavaScript
1
star
90

bb-whitepaper

1
star
91

sad

1
star
92

sibyelleruppert

HTML
1
star
93

jsonresume-theme-professional

1
star
94

recommend

1
star
95

ajaxdavis

HTML
1
star
96

privacy-pack

privacy pack website
CSS
1
star
97

artgallery

JavaScript
1
star