Skip to content
This repository has been archived by the owner on Feb 15, 2022. It is now read-only.

Which version do you like more? #366

Closed
ghost opened this issue Jul 8, 2017 · 4 comments
Closed

Which version do you like more? #366

ghost opened this issue Jul 8, 2017 · 4 comments

Comments

@ghost
Copy link

ghost commented Jul 8, 2017

Version one: Auto coin-switching trading python plugin (trades for 20 minutes, searches for coins for 5:

import json
import requests
import re
import unicodedata
import subprocess
import os
import sqlite3
import time
from decimal import *

flag = "undefined"

##Main App Loop
while True:
	##DB Refresh
	os.remove('/example.db')
	print("File Removed!")
	conn = sqlite3.connect('/example.db')
	c = conn.cursor()
	c.execute('''CREATE TABLE gains (ke4,pct1,dips,dips1)''')
	wjdata = requests.get('https://poloniex.com/public?command=returnTicker&period=60').json()
	##Load Initial Data
	for key in wjdata:
		if re.match(r'BTC_+', key):
			ke1=key.replace('_', '-')
			ke2=ke1.replace('BTC-', '')
			ke3='-BTC'
			ke9=ke2+ke3
			pct=(wjdata[key]['last'])
			pct0=Decimal(pct)
			pct1=format(pct0, 'f')
			print(ke9)
			print(pct1)
			dips='undefined'
			dips1='undefined'
			c.execute("INSERT INTO gains VALUES (?, ?, ?, ?);", (ke9, pct1, dips, dips1))
			conn.commit()
	print('Waiting some time for comparison...')
	time.sleep(300)
	wjdata = requests.get('https://poloniex.com/public?command=returnTicker&period=60').json()
	##Load the second Data
	for key in wjdata:
		if re.match(r'BTC_+', key):
			ke1=key.replace('_', '-')
			ke2=ke1.replace('BTC-', '')
			ke3='-BTC'
			ke4=ke2+ke3
			pct2=(wjdata[key]['last'])
			pct3=Decimal(pct2)
			dips=format(pct3, 'f')
			print(ke4)
			print(dips)
			c.execute('UPDATE gains SET dips = ? WHERE ke4 = ?;', (dips, ke4))
			conn.commit()
	for row in c.execute('SELECT ke4, (dips-pct1) as diff FROM gains ORDER BY diff DESC LIMIT 1;'):
			print(row)
			row=str(tuple(row))
			ro1=row.replace("u", '')
			ro2=ro1.replace("'", '')
			ro3=ro2.replace('(', '')
			ro4=ro3.replace(')', '')
			ro5=ro4.replace(",", '')
			s = ro5
			s=re.sub('\d', '', s)
			ros=s.replace(".", '')
	if flag == ros:
			print(ros)
			print(flag)
			print ('Current Profitable Coin Is The Same!')
	else:
			print(ros)
			print(flag)
			sell=subprocess.call('./zenbot.sh sell --order_adjust_time=20000 --debug  poloniex.'+flag,shell=True)
	##Doublecheck the data
			for key in wjdata:
				if re.match(r'BTC_+', key):
					ke1=key.replace('_', '-')
					ke2=ke1.replace('BTC-', '')
					ke3='-BTC'
					ke4=ke2+ke3
					pct2=(wjdata[key]['last'])
					pct3=Decimal(pct2)
					dips1=format(pct3, 'f')
					print(ke4)
					print(dips1)
					c.execute('UPDATE gains SET dips1 = ? WHERE ke4 = ?;', (dips1, ke4))
					conn.commit()
			for row in c.execute('SELECT ke4, (dips1-pct1) as diff FROM gains ORDER BY diff DESC LIMIT 1;'):
					print(row)
					row=str(tuple(row))
					ro1=row.replace("u", '')
					ro2=ro1.replace("'", '')
					ro3=ro2.replace('(', '')
					ro4=ro3.replace(')', '')
					ro5=ro4.replace(",", '')
					s = ro5
					s=re.sub('\d', '', s)
					ros=s.replace(".", '')
					time.sleep(10)
					timeout="& sleep 1200 ; kill $!"
					buy=subprocess.call('./zenbot.sh trade --order_adjust_time=20000 --debug  poloniex.'+ros +timeout,shell=True)
	flag=ros

Or is this version more suitable: That only trades between coins on a set interval of 10 minutes:

import json
import requests
import re
import unicodedata
import subprocess
import os
import sqlite3
import time
from decimal import *

flag = "undefined"

##Main App Loop
while True:
	##DB Refresh
	os.remove('/example.db')
	print("File Removed!")
	conn = sqlite3.connect('/example.db')
	c = conn.cursor()
	c.execute('''CREATE TABLE gains (ke4,pct1,dips,dips1)''')
	wjdata = requests.get('https://poloniex.com/public?command=returnTicker&period=60').json()
	##Load Initial Data
	for key in wjdata:
		if re.match(r'BTC_+', key):
			ke1=key.replace('_', '-')
			ke2=ke1.replace('BTC-', '')
			ke3='-BTC'
			ke9=ke2+ke3
			pct=(wjdata[key]['last'])
			pct0=Decimal(pct)
			pct1=format(pct0, 'f')
			print(ke9)
			print(pct1)
			dips='undefined'
			dips1='undefined'
			c.execute("INSERT INTO gains VALUES (?, ?, ?, ?);", (ke9, pct1, dips, dips1))
			conn.commit()
	print('Waiting some time for comparison...')
	time.sleep(300)
	wjdata = requests.get('https://poloniex.com/public?command=returnTicker&period=60').json()
	##Load the second Data
	for key in wjdata:
		if re.match(r'BTC_+', key):
			ke1=key.replace('_', '-')
			ke2=ke1.replace('BTC-', '')
			ke3='-BTC'
			ke4=ke2+ke3
			pct2=(wjdata[key]['last'])
			pct3=Decimal(pct2)
			dips=format(pct3, 'f')
			print(ke4)
			print(dips)
			c.execute('UPDATE gains SET dips = ? WHERE ke4 = ?;', (dips, ke4))
			conn.commit()
	for row in c.execute('SELECT ke4, (dips-pct1) as diff FROM gains ORDER BY diff DESC LIMIT 1;'):
			print(row)
			row=str(tuple(row))
			ro1=row.replace("u", '')
			ro2=ro1.replace("'", '')
			ro3=ro2.replace('(', '')
			ro4=ro3.replace(')', '')
			ro5=ro4.replace(",", '')
			s = ro5
			s=re.sub('\d', '', s)
			ros=s.replace(".", '')
	if flag == ros:
			print(ros)
			print(flag)
			print ('Current Profitable Coin Is The Same!')
	for row in c.execute('SELECT ke4, (dips1-pct1) as diff FROM gains ORDER BY diff DESC LIMIT 1;'):
			print(row)
			row=str(tuple(row))
			ro1=row.replace("u", '')
			ro2=ro1.replace("'", '')
			ro3=ro2.replace('(', '')
			ro4=ro3.replace(')', '')
			ro5=ro4.replace(",", '')
			s = ro5
			s=re.sub('\d', '', s)
			ros=s.replace(".", '')
			time.sleep(10)
			timeout="& sleep 1200 ; kill $!"
			buy=subprocess.call('./zenbot.sh trade --order_adjust_time=30000 --debug  poloniex.'+ros +timeout,shell=True)
	else:
			print(ros)
			print(flag)
			sell=subprocess.call('./zenbot.sh sell --order_adjust_time=30000 --debug  poloniex.'+flag,shell=True)
	##Doublecheck the data
			for key in wjdata:
				if re.match(r'BTC_+', key):
					ke1=key.replace('_', '-')
					ke2=ke1.replace('BTC-', '')
					ke3='-BTC'
					ke4=ke2+ke3
					pct2=(wjdata[key]['last'])
					pct3=Decimal(pct2)
					dips1=format(pct3, 'f')
					print(ke4)
					print(dips1)
					c.execute('UPDATE gains SET dips1 = ? WHERE ke4 = ?;', (dips1, ke4))
					conn.commit()
			for row in c.execute('SELECT ke4, (dips1-pct1) as diff FROM gains ORDER BY diff DESC LIMIT 1;'):
					print(row)
					row=str(tuple(row))
					ro1=row.replace("u", '')
					ro2=ro1.replace("'", '')
					ro3=ro2.replace('(', '')
					ro4=ro3.replace(')', '')
					ro5=ro4.replace(",", '')
					s = ro5
					s=re.sub('\d', '', s)
					ros=s.replace(".", '')
					time.sleep(10)
					timeout="& sleep 1200 ; kill $!"
					buy=subprocess.call('./zenbot.sh trade --order_adjust_time=30000 --debug  poloniex.'+ros +timeout,shell=True)
	flag=ros

My configs:

var c = module.exports = {}

// mongo configuration
c.mongo = {}
c.mongo.host = process.env.MONGODB_PORT_27017_TCP_ADDR || 'localhost'
c.mongo.port = 27017
c.mongo.db = 'zenbot4'
c.mongo.username = null
c.mongo.password = null
// when using mongodb replication, i.e. when running a mongodb cluster, you can define your replication set here; when you are not using replication (most of the users), just set it to `null` (default).
c.mongo.replicaSet = null

// default selector. only used if omitting [selector] argument from a command.
c.selector = 'bitfinex.BTC-USD'
// name of default trade strategy
c.strategy = 'trend_ema'

// Exchange API keys:

// to enable GDAX trading, enter your API credentials:
c.gdax = {}
c.gdax.key = 'YOUR-API-KEY'
c.gdax.b64secret = 'YOUR-BASE64-SECRET'
c.gdax.passphrase = 'YOUR-PASSPHRASE'

// to enable Poloniex trading, enter your API credentials:
c.poloniex = {}
c.poloniex.key = ''
c.poloniex.secret = ''
// please note: poloniex does not support market orders via the API

// to enable Kraken trading, enter your API credentials:
c.kraken = {}
c.kraken.key = 'YOUR-API-KEY'
c.kraken.secret = 'YOUR-SECRET'
// Please read API TOS on https://www.kraken.com/u/settings/api
c.kraken.tosagree = 'disagree'

// to enable Bittrex trading, enter your API credentials:
c.bittrex = {}
c.bittrex.key = 'YOUR-API-KEY'
c.bittrex.secret = 'YOUR-SECRET'
// make sure to give your API key access to only: "Trade Limit" and "Read Info",
// please note that this might change in the future.
// please note that bittrex API is limited, you cannot use backfills or sims (paper/live trading only)

// to enable Bitfinex trading, enter your API credentials:
c.bitfinex = {}
c.bitfinex.key = 'YOUR-API-KEY'
c.bitfinex.secret = 'YOUR-SECRET'
// May use 'exchange' or 'trading' wallet balances. However margin trading may not work...read the API documentation.
c.bitfinex.wallet = 'exchange'

// to enable Bitfinex trading, enter your API credentials:
c.bitstamp = {}
c.bitstamp.key = ''
c.bitstamp.secret = ''
// A client ID is required on Bitstamp
c.bitstamp.client_id = 'YOUR-CLIENT-ID'

// to enable QuadrigaCX tranding, enter your API credentials:
c.quadriga = {}
c.quadriga.key = 'YOUR-API-KEY';

// this is the manual secret key entered by editing the API access
// and NOT the md5 hash you see in the summary
c.quadriga.secret = 'YOUR-SECRET';

// replace with the client id used at login, as a string, not number
c.quadriga.client_id = 'YOUR-CLIENT-ID';

// Optional stop-order triggers:

// sell if price drops below this % of bought price (0 to disable)
c.sell_stop_pct = 0
// buy if price surges above this % of sold price (0 to disable)
c.buy_stop_pct = 0
// enable trailing sell stop when reaching this % profit (0 to disable)
c.profit_stop_enable_pct = 0
// maintain a trailing stop this % below the high-water mark of profit
c.profit_stop_pct = 1

// Order execution rules:

// avoid trading at a slippage above this pct
c.max_slippage_pct = 5
// buy with this % of currency balance (WARNING : sim won't work properly if you set this value to 100) 
c.buy_pct = 100
// sell with this % of asset balance (WARNING : sim won't work properly if you set this value to 100)
c.sell_pct = 100
// ms to adjust non-filled order after
c.order_adjust_time = 30000
// avoid selling at a loss below this pct
c.max_sell_loss_pct = 25
// ms to poll order status
c.order_poll_time = 10000
// ms to wait for settlement (after an order cancel)
c.wait_for_settlement = 5000
// % to mark up or down price for orders
c.markup_pct = 0.0
// become a market taker (high fees) or a market maker (low fees)
c.order_type = 'maker'

// Misc options:

// default # days for backfill and sim commands
c.days = 14
// ms to poll new trades at
c.poll_trades = 30000
// amount of currency to start simulations with
c.currency_capital = 1000
// amount of asset to start simulations with
c.asset_capital = 0
// for sim, reverse time at the end of the graph, normalizing buy/hold to 0
c.symmetrical = false
// number of periods to calculate RSI at
c.rsi_periods = 14
// period to record balances for stats
c.balance_snapshot_period = '15m'
// avg. amount of slippage to apply to sim trades
c.avg_slippage_pct = 0.045

Trade.js:


var tb = require('timebucket')
  , minimist = require('minimist')
  , n = require('numbro')
  , fs = require('fs')
  , path = require('path')
  , spawn = require('child_process').spawn
  , moment = require('moment')
  , crypto = require('crypto')
  , readline = require('readline')

module.exports = function container (get, set, clear) {
  var c = get('conf')
  return function (program) {
    program
      .command('trade [selector]')
      .allowUnknownOption()
      .description('run trading bot against live market data')
      .option('--conf <path>', 'path to optional conf overrides file')
      .option('--strategy <name>', 'strategy to use', String, c.strategy)
      .option('--order_type <type>', 'order type to use (maker/taker)', /^(maker|taker)$/i, c.order_type)
      .option('--paper', 'use paper trading mode (no real trades will take place)', Boolean, false)
      .option('--manual', 'watch price and account balance, but do not perform trades automatically', Boolean, false)
      .option('--currency_capital <amount>', 'for paper trading, amount of start capital in currency', Number, c.currency_capital)
      .option('--asset_capital <amount>', 'for paper trading, amount of start capital in asset', Number, c.asset_capital)
      .option('--avg_slippage_pct <pct>', 'avg. amount of slippage to apply to paper trades', Number, c.avg_slippage_pct)
      .option('--buy_pct <pct>', 'buy with this % of currency balance', Number, c.buy_pct)
      .option('--sell_pct <pct>', 'sell with this % of asset balance', Number, c.sell_pct)
      .option('--markup_pct <pct>', '% to mark up or down ask/bid price', Number, c.markup_pct)
      .option('--order_adjust_time <ms>', 'adjust bid/ask on this interval to keep orders competitive', Number, c.order_adjust_time)
      .option('--order_poll_time <ms>', 'poll order status on this interval', Number, c.order_poll_time)
      .option('--sell_stop_pct <pct>', 'sell if price drops below this % of bought price', Number, c.sell_stop_pct)
      .option('--buy_stop_pct <pct>', 'buy if price surges above this % of sold price', Number, c.buy_stop_pct)
      .option('--profit_stop_enable_pct <pct>', 'enable trailing sell stop when reaching this % profit', Number, c.profit_stop_enable_pct)
      .option('--profit_stop_pct <pct>', 'maintain a trailing stop this % below the high-water mark of profit', Number, c.profit_stop_pct)
      .option('--max_sell_loss_pct <pct>', 'avoid selling at a loss pct under this float', c.max_sell_loss_pct)
      .option('--max_slippage_pct <pct>', 'avoid selling at a slippage pct above this float', c.max_slippage_pct)
      .option('--rsi_periods <periods>', 'number of periods to calculate RSI at', Number, c.rsi_periods)
      .option('--poll_trades <ms>', 'poll new trades at this interval in ms', Number, c.poll_trades)
      .option('--disable_stats', 'disable printing order stats')
      .option('--reset_profit', 'start new profit calculation from 0')
      .option('--debug', 'output detailed debug info')
      .action(function (selector, cmd) {
        var raw_opts = minimist(process.argv)
        var s = {options: JSON.parse(JSON.stringify(raw_opts))}
        var so = s.options
        delete so._
        Object.keys(c).forEach(function (k) {
          if (typeof cmd[k] !== 'undefined') {
            so[k] = cmd[k]
          }
        })
        so.debug = cmd.debug
        so.stats = !cmd.disable_stats
        so.mode = so.paper ? 'paper' : 'live'
        if (cmd.conf) {
          var overrides = require(path.resolve(process.cwd(), cmd.conf))
          Object.keys(overrides).forEach(function (k) {
            so[k] = overrides[k]
          })
        }
        so.selector = get('lib.normalize-selector')(so.selector || selector || c.selector)
        var exchange_id = so.selector.split('.')[0]
        var product_id = so.selector.split('.')[1]
        var exchange = get('exchanges.' + exchange_id)
        if (!exchange) {
          console.error('cannot trade ' + so.selector + ': exchange not implemented')
          process.exit(1)
        }
        var engine = get('lib.engine')(s)

        var order_types = ['maker', 'taker']
        if (!so.order_type in order_types || !so.order_type) {
          so.order_type = 'maker'
        }

        var db_cursor, trade_cursor
        var query_start = tb().resize(so.period).subtract(so.min_periods * 2).toMilliseconds()
        var days = Math.ceil((new Date().getTime() - query_start) / 86400000)
        var trades_per_min = 0
        var session = null
        var sessions = get('db.sessions')
        var balances = get('db.balances')
        var trades = get('db.trades')
        get('db.mongo').collection('trades').ensureIndex({selector: 1, time: 1})
        var resume_markers = get('db.resume_markers')
        get('db.mongo').collection('resume_markers').ensureIndex({selector: 1, to: -1})
        var marker = {
          id: crypto.randomBytes(4).toString('hex'),
          selector: so.selector,
          from: null,
          to: null,
          oldest_time: null
        }
        var lookback_size = 0
        var my_trades_size = 0
        var my_trades = get('db.my_trades')
        var periods = get('db.periods')

        console.log('fetching pre-roll data:')
        var backfiller = spawn(path.resolve(__dirname, '..', 'zenbot.sh'), ['backfill', so.selector, '--days', days])
        backfiller.stdout.pipe(process.stdout)
        backfiller.stderr.pipe(process.stderr)
        backfiller.on('exit', function (code) {
          if (code) {
            process.exit(code)
          }
          function getNext () {
            var opts = {
              query: {
                selector: so.selector
              },
              sort: {time: 1},
              limit: 1000
            }
            if (db_cursor) {
              opts.query.time = {$gt: db_cursor}
            }
            else {
              opts.query.time = {$gte: query_start}
            }
            get('db.trades').select(opts, function (err, trades) {
              if (err) throw err
              if (!trades.length) {
                console.log('---------------------------- STARTING ' + so.mode.toUpperCase() + ' TRADING ----------------------------')
                if (so.mode === 'paper') {
                  console.log('!!! Paper mode enabled. No real trades are performed until you remove --paper from the startup command.')
                }
                engine.syncBalance(function (err) {
                  if (err) {
                    if (err.desc) console.error(err.desc)
                    if (err.body) console.error(err.body)
                    throw err
                  }
                  session = {
                    id: crypto.randomBytes(4).toString('hex'),
                    selector: so.selector,
                    started: new Date().getTime(),
                    mode: so.mode,
                    options: so
                  }
                  sessions.select({query: {selector: so.selector}, limit: 1, sort: {started: -1}}, function (err, prev_sessions) {
                    if (err) throw err
                    var prev_session = prev_sessions[0]
                    if (prev_session && !cmd.reset_profit) {
                      if (prev_session.orig_capital && prev_session.orig_price && ((so.mode === 'paper' && !raw_opts.currency_capital && !raw_opts.asset_capital) || (so.mode === 'live' && prev_session.balance.asset == s.balance.asset && prev_session.balance.currency == s.balance.currency))) {
                        s.orig_capital = session.orig_capital = prev_session.orig_capital
                        s.orig_price = session.orig_price = prev_session.orig_price
                        if (so.mode === 'paper') {
                          s.balance = prev_session.balance
                        }
                      }
                    }
                    lookback_size = s.lookback.length
                    forwardScan()
                    setInterval(forwardScan, c.poll_trades)
                    readline.emitKeypressEvents(process.stdin)
      //              process.stdin.setRawMode(true)
                    process.stdin.on('keypress', function (key, info) {
                      if (key === 'b' && !info.ctrl ) {
                        engine.executeSignal('buy')
                      }
                      else if (key === 'B' && !info.ctrl) {
                        engine.executeSignal('buy', null, null, false, true)
                      }
                      else if (key === 's' && !info.ctrl) {
                        engine.executeSignal('sell')
                      }
                      else if (key === 'S' && !info.ctrl) {
                        engine.executeSignal('sell', null, null, false, true)
                      }
                      else if ((key === 'c' || key === 'C') && !info.ctrl) {
                        delete s.buy_order
                        delete s.sell_order
                      }
                      else if ((key === 'm' || key === 'M') && !info.ctrl) {
                        so.manual = !so.manual
                        console.log('\nmanual mode: ' + (so.manual ? 'ON' : 'OFF') + '\n')
                      }
                      else if (info.name === 'c' && info.ctrl) {
                        // @todo: cancel open orders before exit
                        console.log()
                        process.exit()
                      }
                    })
                  })
                })
                return
              }
              engine.update(trades, true, function (err) {
                if (err) throw err
                db_cursor = trades[trades.length - 1].time
                trade_cursor = exchange.getCursor(trades[trades.length - 1])
                setImmediate(getNext)
              })
            })
          }
          engine.writeHeader()
          getNext()
        })

        var prev_timeout = null
        function forwardScan () {
          function saveSession () {
            engine.syncBalance(function (err) {
              if (err) {
                console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error syncing balance')
                if (err.desc) console.error(err.desc)
                if (err.body) console.error(err.body)
                console.error(err)
              }
              session.updated = new Date().getTime()
              session.balance = s.balance
              session.start_capital = s.start_capital
              session.start_price = s.start_price
              session.num_trades = s.my_trades.length
              if (!session.orig_capital) session.orig_capital = s.start_capital
              if (!session.orig_price) session.orig_price = s.start_price
              if (s.period) {
                session.price = s.period.close
                var d = tb().resize(c.balance_snapshot_period)
                var b = {
                  id: so.selector + '-' + d.toString(),
                  selector: so.selector,
                  time: d.toMilliseconds(),
                  currency: s.balance.currency,
                  asset: s.balance.asset,
                  price: s.period.close,
                  start_capital: session.orig_capital,
                  start_price: session.orig_price,
                }
                b.consolidated = n(s.balance.asset).multiply(s.period.close).add(s.balance.currency).value()
                b.profit = (b.consolidated - session.orig_capital) / session.orig_capital
                b.buy_hold = s.period.close * (session.orig_capital / session.orig_price)
                b.buy_hold_profit = (b.buy_hold - session.orig_capital) / session.orig_capital
                b.vs_buy_hold = (b.consolidated - b.buy_hold) / b.buy_hold
                if (so.mode === 'live') {
                  balances.save(b, function (err) {
                    if (err) {
                      console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving balance')
                      console.error(err)
                    }
                  })
                }
                session.balance = b
              }
              else {
                session.balance = {
                  currency: s.balance.currency,
                  asset: s.balance.asset
                }
              }
              sessions.save(session, function (err) {
                if (err) {
                  console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving session')
                  console.error(err)
                }
                engine.writeReport(true)
              })
            })
          }
          var opts = {product_id: product_id, from: trade_cursor}
          exchange.getTrades(opts, function (err, trades) {
            if (err) {
              if (err.code === 'ETIMEDOUT' || err.code === 'ENOTFOUND' || err.code === 'ECONNRESET') {
                if (prev_timeout) {
                  console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - getTrades request timed out. retrying...')
                }
                prev_timeout = true
              }
              else if (err.code === 'HTTP_STATUS') {
                if (prev_timeout) {
                  console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - getTrades request failed: ' + err.message + '. retrying...')
                }
                prev_timeout = true
              }
              else {
                console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - getTrades request failed. retrying...')
                console.error(err)
              }
              return
            }
            prev_timeout = null
            if (trades.length) {
              trades.sort(function (a, b) {
                if (a.time > b.time) return -1
                if (a.time < b.time) return 1
                return 0
              })
              trades.forEach(function (trade) {
                var this_cursor = exchange.getCursor(trade)
                trade_cursor = Math.max(this_cursor, trade_cursor)
                saveTrade(trade)
              })
              engine.update(trades, function (err) {
                if (err) {
                  console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving session')
                  console.error(err)
                }
                resume_markers.save(marker, function (err) {
                  if (err) {
                    console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving marker')
                    console.error(err)
                  }
                })
                if (s.my_trades.length > my_trades_size) {
                  s.my_trades.slice(my_trades_size).forEach(function (my_trade) {
                    my_trade.id = crypto.randomBytes(4).toString('hex')
                    my_trade.selector = so.selector
                    my_trade.session_id = session.id
                    my_trade.mode = so.mode
                    my_trades.save(my_trade, function (err) {
                      if (err) {
                        console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving my_trade')
                        console.error(err)
                      }
                    })
                  })
                  my_trades_size = s.my_trades.length
                }
                function savePeriod (period) {
                  if (!period.id) {
                    period.id = crypto.randomBytes(4).toString('hex')
                    period.selector = so.selector
                    period.session_id = session.id
                  }
                  periods.save(period, function (err) {
                    if (err) {
                      console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving my_trade')
                      console.error(err)
                    }
                  })
                }
                if (s.lookback.length > lookback_size) {
                  savePeriod(s.lookback[0])
                  lookback_size = s.lookback.length
                }
                if (s.period) {
                  savePeriod(s.period)
                }
                saveSession()
              })
            }
            else {
              saveSession()
            }
          })
          function saveTrade (trade) {
            trade.id = so.selector + '-' + String(trade.trade_id)
            trade.selector = so.selector
            if (!marker.from) {
              marker.from = trade_cursor
              marker.oldest_time = trade.time
              marker.newest_time = trade.time
            }
            marker.to = marker.to ? Math.max(marker.to, trade_cursor) : trade_cursor
            marker.newest_time = Math.max(marker.newest_time, trade.time)
            trades.save(trade, function (err) {
              // ignore duplicate key errors
              if (err && err.code !== 11000) {
                console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving trade')
                console.error(err)
              }
            })
          }
        }
      })
  }
}


Exchange.js:

var tb = require('timebucket')
  , minimist = require('minimist')
  , n = require('numbro')
  , fs = require('fs')
  , path = require('path')
  , spawn = require('child_process').spawn
  , moment = require('moment')
  , crypto = require('crypto')
  , readline = require('readline')

module.exports = function container (get, set, clear) {
  var c = get('conf')
  return function (program) {
    program
      .command('trade [selector]')
      .allowUnknownOption()
      .description('run trading bot against live market data')
      .option('--conf <path>', 'path to optional conf overrides file')
      .option('--strategy <name>', 'strategy to use', String, c.strategy)
      .option('--order_type <type>', 'order type to use (maker/taker)', /^(maker|taker)$/i, c.order_type)
      .option('--paper', 'use paper trading mode (no real trades will take place)', Boolean, false)
      .option('--manual', 'watch price and account balance, but do not perform trades automatically', Boolean, false)
      .option('--currency_capital <amount>', 'for paper trading, amount of start capital in currency', Number, c.currency_capital)
      .option('--asset_capital <amount>', 'for paper trading, amount of start capital in asset', Number, c.asset_capital)
      .option('--avg_slippage_pct <pct>', 'avg. amount of slippage to apply to paper trades', Number, c.avg_slippage_pct)
      .option('--buy_pct <pct>', 'buy with this % of currency balance', Number, c.buy_pct)
      .option('--sell_pct <pct>', 'sell with this % of asset balance', Number, c.sell_pct)
      .option('--markup_pct <pct>', '% to mark up or down ask/bid price', Number, c.markup_pct)
      .option('--order_adjust_time <ms>', 'adjust bid/ask on this interval to keep orders competitive', Number, c.order_adjust_time)
      .option('--order_poll_time <ms>', 'poll order status on this interval', Number, c.order_poll_time)
      .option('--sell_stop_pct <pct>', 'sell if price drops below this % of bought price', Number, c.sell_stop_pct)
      .option('--buy_stop_pct <pct>', 'buy if price surges above this % of sold price', Number, c.buy_stop_pct)
      .option('--profit_stop_enable_pct <pct>', 'enable trailing sell stop when reaching this % profit', Number, c.profit_stop_enable_pct)
      .option('--profit_stop_pct <pct>', 'maintain a trailing stop this % below the high-water mark of profit', Number, c.profit_stop_pct)
      .option('--max_sell_loss_pct <pct>', 'avoid selling at a loss pct under this float', c.max_sell_loss_pct)
      .option('--max_slippage_pct <pct>', 'avoid selling at a slippage pct above this float', c.max_slippage_pct)
      .option('--rsi_periods <periods>', 'number of periods to calculate RSI at', Number, c.rsi_periods)
      .option('--poll_trades <ms>', 'poll new trades at this interval in ms', Number, c.poll_trades)
      .option('--disable_stats', 'disable printing order stats')
      .option('--reset_profit', 'start new profit calculation from 0')
      .option('--debug', 'output detailed debug info')
      .action(function (selector, cmd) {
        var raw_opts = minimist(process.argv)
        var s = {options: JSON.parse(JSON.stringify(raw_opts))}
        var so = s.options
        delete so._
        Object.keys(c).forEach(function (k) {
          if (typeof cmd[k] !== 'undefined') {
            so[k] = cmd[k]
          }
        })
        so.debug = cmd.debug
        so.stats = !cmd.disable_stats
        so.mode = so.paper ? 'paper' : 'live'
        if (cmd.conf) {
          var overrides = require(path.resolve(process.cwd(), cmd.conf))
          Object.keys(overrides).forEach(function (k) {
            so[k] = overrides[k]
          })
        }
        so.selector = get('lib.normalize-selector')(so.selector || selector || c.selector)
        var exchange_id = so.selector.split('.')[0]
        var product_id = so.selector.split('.')[1]
        var exchange = get('exchanges.' + exchange_id)
        if (!exchange) {
          console.error('cannot trade ' + so.selector + ': exchange not implemented')
          process.exit(1)
        }
        var engine = get('lib.engine')(s)

        var order_types = ['maker', 'taker']
        if (!so.order_type in order_types || !so.order_type) {
          so.order_type = 'maker'
        }

        var db_cursor, trade_cursor
        var query_start = tb().resize(so.period).subtract(so.min_periods * 2).toMilliseconds()
        var days = Math.ceil((new Date().getTime() - query_start) / 86400000)
        var trades_per_min = 0
        var session = null
        var sessions = get('db.sessions')
        var balances = get('db.balances')
        var trades = get('db.trades')
        get('db.mongo').collection('trades').ensureIndex({selector: 1, time: 1})
        var resume_markers = get('db.resume_markers')
        get('db.mongo').collection('resume_markers').ensureIndex({selector: 1, to: -1})
        var marker = {
          id: crypto.randomBytes(4).toString('hex'),
          selector: so.selector,
          from: null,
          to: null,
          oldest_time: null
        }
        var lookback_size = 0
        var my_trades_size = 0
        var my_trades = get('db.my_trades')
        var periods = get('db.periods')

        console.log('fetching pre-roll data:')
        var backfiller = spawn(path.resolve(__dirname, '..', 'zenbot.sh'), ['backfill', so.selector, '--days', days])
        backfiller.stdout.pipe(process.stdout)
        backfiller.stderr.pipe(process.stderr)
        backfiller.on('exit', function (code) {
          if (code) {
            process.exit(code)
          }
          function getNext () {
            var opts = {
              query: {
                selector: so.selector
              },
              sort: {time: 1},
              limit: 1000
            }
            if (db_cursor) {
              opts.query.time = {$gt: db_cursor}
            }
            else {
              opts.query.time = {$gte: query_start}
            }
            get('db.trades').select(opts, function (err, trades) {
              if (err) throw err
              if (!trades.length) {
                console.log('---------------------------- STARTING ' + so.mode.toUpperCase() + ' TRADING ----------------------------')
                if (so.mode === 'paper') {
                  console.log('!!! Paper mode enabled. No real trades are performed until you remove --paper from the startup command.')
                }
                engine.syncBalance(function (err) {
                  if (err) {
                    if (err.desc) console.error(err.desc)
                    if (err.body) console.error(err.body)
                    throw err
                  }
                  session = {
                    id: crypto.randomBytes(4).toString('hex'),
                    selector: so.selector,
                    started: new Date().getTime(),
                    mode: so.mode,
                    options: so
                  }
                  sessions.select({query: {selector: so.selector}, limit: 1, sort: {started: -1}}, function (err, prev_sessions) {
                    if (err) throw err
                    var prev_session = prev_sessions[0]
                    if (prev_session && !cmd.reset_profit) {
                      if (prev_session.orig_capital && prev_session.orig_price && ((so.mode === 'paper' && !raw_opts.currency_capital && !raw_opts.asset_capital) || (so.mode === 'live' && prev_session.balance.asset == s.balance.asset && prev_session.balance.currency == s.balance.currency))) {
                        s.orig_capital = session.orig_capital = prev_session.orig_capital
                        s.orig_price = session.orig_price = prev_session.orig_price
                        if (so.mode === 'paper') {
                          s.balance = prev_session.balance
                        }
                      }
                    }
                    lookback_size = s.lookback.length
                    forwardScan()
                    setInterval(forwardScan, c.poll_trades)
                    readline.emitKeypressEvents(process.stdin)
      //              process.stdin.setRawMode(true)
                    process.stdin.on('keypress', function (key, info) {
                      if (key === 'b' && !info.ctrl ) {
                        engine.executeSignal('buy')
                      }
                      else if (key === 'B' && !info.ctrl) {
                        engine.executeSignal('buy', null, null, false, true)
                      }
                      else if (key === 's' && !info.ctrl) {
                        engine.executeSignal('sell')
                      }
                      else if (key === 'S' && !info.ctrl) {
                        engine.executeSignal('sell', null, null, false, true)
                      }
                      else if ((key === 'c' || key === 'C') && !info.ctrl) {
                        delete s.buy_order
                        delete s.sell_order
                      }
                      else if ((key === 'm' || key === 'M') && !info.ctrl) {
                        so.manual = !so.manual
                        console.log('\nmanual mode: ' + (so.manual ? 'ON' : 'OFF') + '\n')
                      }
                      else if (info.name === 'c' && info.ctrl) {
                        // @todo: cancel open orders before exit
                        console.log()
                        process.exit()
                      }
                    })
                  })
                })
                return
              }
              engine.update(trades, true, function (err) {
                if (err) throw err
                db_cursor = trades[trades.length - 1].time
                trade_cursor = exchange.getCursor(trades[trades.length - 1])
                setImmediate(getNext)
              })
            })
          }
          engine.writeHeader()
          getNext()
        })

        var prev_timeout = null
        function forwardScan () {
          function saveSession () {
            engine.syncBalance(function (err) {
              if (err) {
                console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error syncing balance')
                if (err.desc) console.error(err.desc)
                if (err.body) console.error(err.body)
                console.error(err)
              }
              session.updated = new Date().getTime()
              session.balance = s.balance
              session.start_capital = s.start_capital
              session.start_price = s.start_price
              session.num_trades = s.my_trades.length
              if (!session.orig_capital) session.orig_capital = s.start_capital
              if (!session.orig_price) session.orig_price = s.start_price
              if (s.period) {
                session.price = s.period.close
                var d = tb().resize(c.balance_snapshot_period)
                var b = {
                  id: so.selector + '-' + d.toString(),
                  selector: so.selector,
                  time: d.toMilliseconds(),
                  currency: s.balance.currency,
                  asset: s.balance.asset,
                  price: s.period.close,
                  start_capital: session.orig_capital,
                  start_price: session.orig_price,
                }
                b.consolidated = n(s.balance.asset).multiply(s.period.close).add(s.balance.currency).value()
                b.profit = (b.consolidated - session.orig_capital) / session.orig_capital
                b.buy_hold = s.period.close * (session.orig_capital / session.orig_price)
                b.buy_hold_profit = (b.buy_hold - session.orig_capital) / session.orig_capital
                b.vs_buy_hold = (b.consolidated - b.buy_hold) / b.buy_hold
                if (so.mode === 'live') {
                  balances.save(b, function (err) {
                    if (err) {
                      console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving balance')
                      console.error(err)
                    }
                  })
                }
                session.balance = b
              }
              else {
                session.balance = {
                  currency: s.balance.currency,
                  asset: s.balance.asset
                }
              }
              sessions.save(session, function (err) {
                if (err) {
                  console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving session')
                  console.error(err)
                }
                engine.writeReport(true)
              })
            })
          }
          var opts = {product_id: product_id, from: trade_cursor}
          exchange.getTrades(opts, function (err, trades) {
            if (err) {
              if (err.code === 'ETIMEDOUT' || err.code === 'ENOTFOUND' || err.code === 'ECONNRESET') {
                if (prev_timeout) {
                  console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - getTrades request timed out. retrying...')
                }
                prev_timeout = true
              }
              else if (err.code === 'HTTP_STATUS') {
                if (prev_timeout) {
                  console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - getTrades request failed: ' + err.message + '. retrying...')
                }
                prev_timeout = true
              }
              else {
                console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - getTrades request failed. retrying...')
                console.error(err)
              }
              return
            }
            prev_timeout = null
            if (trades.length) {
              trades.sort(function (a, b) {
                if (a.time > b.time) return -1
                if (a.time < b.time) return 1
                return 0
              })
              trades.forEach(function (trade) {
                var this_cursor = exchange.getCursor(trade)
                trade_cursor = Math.max(this_cursor, trade_cursor)
                saveTrade(trade)
              })
              engine.update(trades, function (err) {
                if (err) {
                  console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving session')
                  console.error(err)
                }
                resume_markers.save(marker, function (err) {
                  if (err) {
                    console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving marker')
                    console.error(err)
                  }
                })
                if (s.my_trades.length > my_trades_size) {
                  s.my_trades.slice(my_trades_size).forEach(function (my_trade) {
                    my_trade.id = crypto.randomBytes(4).toString('hex')
                    my_trade.selector = so.selector
                    my_trade.session_id = session.id
                    my_trade.mode = so.mode
                    my_trades.save(my_trade, function (err) {
                      if (err) {
                        console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving my_trade')
                        console.error(err)
                      }
                    })
                  })
                  my_trades_size = s.my_trades.length
                }
                function savePeriod (period) {
                  if (!period.id) {
                    period.id = crypto.randomBytes(4).toString('hex')
                    period.selector = so.selector
                    period.session_id = session.id
                  }
                  periods.save(period, function (err) {
                    if (err) {
                      console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving my_trade')
                      console.error(err)
                    }
                  })
                }
                if (s.lookback.length > lookback_size) {
                  savePeriod(s.lookback[0])
                  lookback_size = s.lookback.length
                }
                if (s.period) {
                  savePeriod(s.period)
                }
                saveSession()
              })
            }
            else {
              saveSession()
            }
          })
          function saveTrade (trade) {
            trade.id = so.selector + '-' + String(trade.trade_id)
            trade.selector = so.selector
            if (!marker.from) {
              marker.from = trade_cursor
              marker.oldest_time = trade.time
              marker.newest_time = trade.time
            }
            marker.to = marker.to ? Math.max(marker.to, trade_cursor) : trade_cursor
            marker.newest_time = Math.max(marker.newest_time, trade.time)
            trades.save(trade, function (err) {
              // ignore duplicate key errors
              if (err && err.code !== 11000) {
                console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving trade')
                console.error(err)
              }
            })
          }
        }
      })
  }
}

Thanks!!!

@ghost
Copy link
Author

ghost commented Jul 8, 2017

import json
import requests
import re
import unicodedata
import subprocess
import os
import sqlite3
import time
from multiprocessing import Process
from decimal import *
import threading
variable = []
class same(object):
	def __init__(self):
		while 1:
				global variable
				variable=str(variable)
				print(variable)
				print(flag)
				print ('Current Profitable Coin Is The Same!')
				subprocess.call('./zenbot.sh trade --order_adjust_time=30000 --debug  poloniex.'+variable,shell=True)
class diff(object):
	def __init__(self):
		while 1:
				global variable
				variable=str(variable)
				print(variable)
				subprocess.call('./zenbot.sh sell --order_adjust_time=30000 --debug  poloniex.'+variable,shell=True)
				subprocess.call('./zenbot.sh trade --order_adjust_time=30000 --debug  poloniex.'+variable,shell=True)
class firstFunction(object):
	def __init__(self):
		while 1:
		##Main App Loop
		##DB Refresh
			global variable
			os.remove('/example.db')
			conn = sqlite3.connect('/example.db')
			c = conn.cursor()
			c.execute('''CREATE TABLE gains (ke4,pct1,dips,dips1)''')
			wjdata = requests.get('https://poloniex.com/public?command=returnTicker&period=60').json()
			##Load Initial Data
			for key in wjdata:
				if re.match(r'BTC_+', key):
					ke1=key.replace('_', '-')
					ke2=ke1.replace('BTC-', '')
					ke3='-BTC'
					ke9=ke2+ke3
					pct=(wjdata[key]['last'])
					pct0=Decimal(pct)
					pct1=format(pct0, 'f')
					dips='undefined'
					dips1='undefined'
					c.execute("INSERT INTO gains VALUES (?, ?, ?, ?);", (ke9, pct1, dips, dips1))
					conn.commit()
			time.sleep(5)
			wjdata = requests.get('https://poloniex.com/public?command=returnTicker&period=60').json()
			##Load the second Data
			for key in wjdata:
				if re.match(r'BTC_+', key):
					ke1=key.replace('_', '-')
					ke2=ke1.replace('BTC-', '')
					ke3='-BTC'
					ke4=ke2+ke3
					pct2=(wjdata[key]['last'])
					pct3=Decimal(pct2)
					dips=format(pct3, 'f')
					c.execute('UPDATE gains SET dips = ? WHERE ke4 = ?;', (dips, ke4))
					conn.commit()
			for row in c.execute('SELECT ke4, (dips-pct1) as diff FROM gains ORDER BY diff DESC LIMIT 1;'):
					row=str(tuple(row))
					ro1=row.replace("u", '')
					ro2=ro1.replace("'", '')
					ro3=ro2.replace('(', '')
					ro4=ro3.replace(')', '')
					ro5=ro4.replace(",", '')
					s = ro5
					s=re.sub('\d', '', s)
					variable=s.replace(".", '')
					print(variable)
def main():
	threading.Thread(target=firstFunction).start()
	time.sleep(20)
	threading.Thread(target=same).start()
	threading.Thread(target=diff).start()
main()

Just putting this here for reference... A incomplete threaded version.

@ghost
Copy link
Author

ghost commented Jul 8, 2017

Almost there!!!

import json
import requests
import re
import unicodedata
import subprocess
import os
import sqlite3
import time
from decimal import *
import threading
variable = []
flag = []
stop = []
class same(object):
	def __init__(self):
		while 1:
				global variable
				global stop
				variable=str(variable)
				print(variable)
				print(flag)
				print ('Current Profitable Coin Is The Same!')
				subprocess.call('./zenbot.sh trade --order_adjust_time=30000 --debug  poloniex.'+variable,shell=True)
				if stop == True:
					print("  Exiting loop.")
					break

class diff(object):
	def __init__(self):
		while 1:
				global flag
				global variable
				global stop
				variable=str(variable)
				print(variable)
				subprocess.call('./zenbot.sh sell --order_adjust_time=30000 --debug  poloniex.'+flag,shell=True)
				flag=variable
				if stop == True:
					print("  Exiting loop.")
					break

class firstFunction(object):
	def __init__(self):
		while 1:
		##Main App Loop
		##DB Refresh
			global variable
			os.remove('/example.db')
			conn = sqlite3.connect('/example.db')
			c = conn.cursor()
			c.execute('''CREATE TABLE gains (ke4,pct1,dips,dips1)''')
			wjdata = requests.get('https://poloniex.com/public?command=returnTicker&period=60').json()
			##Load Initial Data
			for key in wjdata:
				if re.match(r'BTC_+', key):
					ke1=key.replace('_', '-')
					ke2=ke1.replace('BTC-', '')
					ke3='-BTC'
					ke9=ke2+ke3
					pct=(wjdata[key]['last'])
					pct0=Decimal(pct)
					pct1=format(pct0, 'f')
					dips='undefined'
					dips1='undefined'
					c.execute("INSERT INTO gains VALUES (?, ?, ?, ?);", (ke9, pct1, dips, dips1))
					conn.commit()
			time.sleep(30)
			wjdata = requests.get('https://poloniex.com/public?command=returnTicker&period=60').json()
			##Load the second Data
			for key in wjdata:
				if re.match(r'BTC_+', key):
					ke1=key.replace('_', '-')
					ke2=ke1.replace('BTC-', '')
					ke3='-BTC'
					ke4=ke2+ke3
					pct2=(wjdata[key]['last'])
					pct3=Decimal(pct2)
					dips=format(pct3, 'f')
					c.execute('UPDATE gains SET dips = ? WHERE ke4 = ?;', (dips, ke4))
					conn.commit()
			for row in c.execute('SELECT ke4, (dips-pct1) as diff FROM gains ORDER BY diff DESC LIMIT 1;'):
					row=str(tuple(row))
					ro1=row.replace("u", '')
					ro2=ro1.replace("'", '')
					ro3=ro2.replace('(', '')
					ro4=ro3.replace(')', '')
					ro5=ro4.replace(",", '')
					s = ro5
					s=re.sub('\d', '', s)
					variable=s.replace(".", '')
					print(variable)
					time.sleep(30)
def main():
	stop = False
	threading.Thread(target=firstFunction).start()
	if flag == variable:
		threading.Thread(target=same).start()
	else:
		stop = True
		threading.Thread(target=diff).start()
main()

@ghost
Copy link
Author

ghost commented Jul 9, 2017

Version 3, almost almost done.... Has a lot of print output for debugging, might and probably is still buggy as hell.

Sometimes I forget to start mongod... or the loop literally spams poloniex NOT GOOD!!!!

Basically, this version has threading so that the data update is continuous and there is no lag/downtime between trading but you still must set the data update timer manually... 10 minutes is a good number since I see a lot of coins that go up in that amount of time will still go up for at-least another 5.


import json
import requests
import re
import unicodedata
import subprocess
from subprocess import PIPE,Popen,STDOUT
import os
import sqlite3
import time
from decimal import *
import threading
variable = []
flag = []
class same(object):
	def __init__(self):
		while 1:
				time.sleep(5)
				global variable
				global p1
				global flag
				variable=str(variable)
				print(variable)
				print ('COINS ARE THE SAME')
				subprocess.call('./zenbot.sh trade --order_adjust_time=30000 --debug  poloniex.'+variable,shell=True)
class diff(object):
	def __init__(self):
		while 1:
				time.sleep(5)
				global variable
				global flag
				variable=str(variable)
				print(variable)
				print(flag)
				print('COINS ARE DIFFERENT, SWITCHING')
				subprocess.call('./zenbot.sh sell --order_adjust_time=30000 --debug  poloniex.'+flag,shell=True)
class firstFunction(object):
	def __init__(self):
		while 1:
		##Main App Loop
		##DB Refresh
			global variable
			global flag
			os.remove('/example.db')
			conn = sqlite3.connect('/example.db')
			c = conn.cursor()
			c.execute('''CREATE TABLE gains (ke4,pct1,dips,dips1)''')
			wjdata = requests.get('https://poloniex.com/public?command=returnTicker&period=60').json()
			##Load Initial Data
			for key in wjdata:
				if re.match(r'BTC_+', key):
					ke1=key.replace('_', '-')
					ke2=ke1.replace('BTC-', '')
					ke3='-BTC'
					ke9=ke2+ke3
					pct=(wjdata[key]['last'])
					pct0=Decimal(pct)
					pct1=format(pct0, 'f')
					dips='undefined'
					dips1='undefined'
					c.execute("INSERT INTO gains VALUES (?, ?, ?, ?);", (ke9, pct1, dips, dips1))
					conn.commit()
			time.sleep(600)
			wjdata = requests.get('https://poloniex.com/public?command=returnTicker&period=60').json()
			##Load the second Data
			for key in wjdata:
				if re.match(r'BTC_+', key):
					ke1=key.replace('_', '-')
					ke2=ke1.replace('BTC-', '')
					ke3='-BTC'
					ke4=ke2+ke3
					pct2=(wjdata[key]['last'])
					pct3=Decimal(pct2)
					dips=format(pct3, 'f')
					c.execute('UPDATE gains SET dips = ? WHERE ke4 = ?;', (dips, ke4))
					conn.commit()
			for row in c.execute('SELECT ke4, (dips-pct1) as diff FROM gains ORDER BY diff DESC LIMIT 1;'):
					row=str(tuple(row))
					ro1=row.replace("u", '')
					ro2=ro1.replace("'", '')
					ro3=ro2.replace('(', '')
					ro4=ro3.replace(')', '')
					ro5=ro4.replace(",", '')
					s = ro5
					s=re.sub('\d', '', s)
					variable=s.replace(".", '')
					print('MAIN LOOP DONE')
					print(variable)
					
					
class sync(object):
	def __init__(self):
		while 1:
				global variable
				global flag
				time.sleep(5)
				if flag == variable:
					continue
					print('coin is the same')
				else:
					time.sleep(5)
					subprocess.call('sudo kill -a node',shell=True)
					threading.Thread(target=diff).start()
					time.sleep(5)
					flag=variable
					threading.Thread(target=same).start()
					print('FLAG SET flag=variable')

def main():
	d = threading.Thread(target=firstFunction)
	d.start()
	e = threading.Thread(target=sync)
	e.daemon = True
	e.start()
main()

@DeviaVir
Copy link
Owner

Hey @TheRoboKitten I appreciate the work you're doing, but this should really be PR's, this is not really reviewable in an issue.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant