├── README.md ├── coinigy_api_rest.py ├── coinigy_ws_config.json ├── curl_examples.sh ├── example_v1.php ├── python_ws_example.py ├── utils ├── __init__.py └── console.py └── ws_example.js /README.md: -------------------------------------------------------------------------------- 1 | # Coinigy API 2 | 3 | This repository contains example API clients that demonstrate connecting to the Coinigy API. 4 | 5 | V1 REST API documentation: http://docs.coinigy.apiary.io/#reference 6 | V2 REST API documentation: https://api.coinigy.com/api/v2/docs 7 | 8 | WEBSOCKET API documentation (Requires a V1 key): https://coinigy.docs.apiary.io/#reference/websocket-api 9 | 10 | WEBSOCKET SERVER INFO: 11 | HOST: sc-02.coinigy.com* 12 | PORT: 443 13 | SECURE: true 14 | 15 | 16 | WEBSOCKET CLIENTS: 17 | https://github.com/SocketCluster/client-drivers 18 | 19 | *If your client requires the full wss url for websockets, use: wss://sc-02.coinigy.com/socketcluster/ 20 | -------------------------------------------------------------------------------- /coinigy_api_rest.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | import numpy as np 3 | import pandas as pd 4 | import requests 5 | 6 | credentials = namedtuple('credentials', ('api', 'secret', 'endpoint')) 7 | connection = namedtuple('connection', ('hostname', 'port', 'secure')) 8 | alerts = namedtuple('alerts', ('open_alerts', 'alert_history')) 9 | 10 | 11 | class CoinigyREST: 12 | """ 13 | This class implements coinigy's REST api as documented in the documentation 14 | available at 15 | https://github.com/coinigy/api 16 | """ 17 | def __init__(self, acct): 18 | self.api = acct.api 19 | self.secret = acct.secret 20 | self.endpoint = acct.endpoint 21 | 22 | def request(self, method, query=None, json=False, **args): 23 | """ 24 | Generic interface to REST api 25 | :param method: query name 26 | :param query: dictionary of inputs 27 | :param json: if True return the raw results in json format 28 | :param args: keyword arguments added to the payload 29 | :return: 30 | """ 31 | url = '{endpoint}/{method}'.format(endpoint=self.endpoint, method=method) 32 | authAPI = {'X-API-KEY': self.api, 'X-API-SECRET': self.secret} 33 | payload = {} 34 | payload.update(**args) 35 | if query is not None: 36 | payload.update(query) 37 | r = requests.post(url, data=payload, headers=authAPI) 38 | if 'error' in r.json().keys(): 39 | print(r.json()['error']) 40 | return 41 | 42 | if json: 43 | return r.json() 44 | return pd.DataFrame(r.json()['data']) 45 | 46 | def data(self, exchange, market, data_type): 47 | """ 48 | Common wrapper for data related queries 49 | :param exchange: 50 | :param market: 51 | :param data_type: currently supported are 'history', 'bids', 'asks', 'orders' 52 | :return: 53 | """ 54 | d = self.request('data', exchange_code=exchange, exchange_market=market, type=data_type, json=True)['data'] 55 | 56 | res = dict() 57 | 58 | for key in ['history', 'bids', 'asks']: 59 | if key in d.keys(): 60 | dat = pd.DataFrame.from_records(d[key]) 61 | if 'price' in dat.columns: 62 | dat.price = dat.price.astype(np.float) 63 | if 'quantity' in dat.columns: 64 | dat.quantity = dat.quantity.astype(np.float) 65 | if 'total' in dat.columns: 66 | dat.total = dat.total.astype(np.float) 67 | if 'time_local' in dat.columns: 68 | dat.time_local = pd.to_datetime(dat.time_local, format='%Y-%m-%d %H:%M:%S') 69 | dat.set_index('time_local', inplace=True) 70 | if 'type' in dat.columns: 71 | dat.type = dat.type.astype(str) 72 | if not dat.empty: 73 | dat['base_ccy'] = d['primary_curr_code'] 74 | dat['counter_ccy'] = d['secondary_curr_code'] 75 | 76 | res[key] = dat 77 | 78 | return res 79 | 80 | def accounts(self): 81 | return self.request('accounts') 82 | 83 | def activity(self): 84 | return self.request('activity') 85 | 86 | def balances(self): 87 | return self.request('balances') 88 | 89 | def push_notifications(self): 90 | return self.request('pushNotifications') 91 | 92 | def open_orders(self): 93 | """ 94 | FIXME: untested 95 | """ 96 | return self.request('orders', json=True) 97 | 98 | def alerts(self): 99 | all_alerts = self.request('alerts', json=True)['data'] 100 | open_alerts = pd.DataFrame(all_alerts['open_alerts']) 101 | alert_history = pd.DataFrame(all_alerts['alert_history']) 102 | return alerts(open_alerts=open_alerts, alert_history=alert_history) 103 | 104 | def exchanges(self): 105 | return self.request('exchanges') 106 | 107 | def markets(self, exchange): 108 | return self.request('markets',exchange_code=exchange) 109 | 110 | def history(self, exchange, market): 111 | return self.data(exchange=exchange, market=market, data_type='history')['history'] 112 | 113 | def asks(self, exchange, market): 114 | return self.data(exchange=exchange, market=market, data_type='asks')['asks'] 115 | 116 | def bids(self, exchange, market): 117 | return self.data(exchange=exchange, market=market, data_type='bids')['bids'] 118 | 119 | def orders(self, exchange, market): 120 | return self.data(exchange=exchange, market=market, data_type='orders') 121 | 122 | def news_feed(self): 123 | dat = self.request('newsFeed') 124 | dat.timestamp = pd.to_datetime(dat.timestamp) 125 | dat.set_index('timestamp', inplace=True) 126 | return dat 127 | 128 | def order_types(self): 129 | dat = self.request('orderTypes', json=True)['data'] 130 | return dict(order_types=pd.DataFrame.from_records(dat['order_types']), 131 | price_types=pd.DataFrame.from_records(dat['price_types'])) 132 | 133 | def refresh_balance(self): 134 | return self.request('refreshBalance', json=True) 135 | 136 | def add_alert(self, exchange, market, price, note): 137 | return self.request('addAlert', 138 | exch_code=exchange, 139 | market_name=market, 140 | alert_price=price, 141 | alert_note=note, 142 | json=True)['notifications'] 143 | 144 | def delete_alert(self, alert_id): 145 | return self.request('deleteAlert', alert_id=alert_id, json=True)['notifications'] 146 | 147 | def add_order(self, auth_id, exch_id, mkt_id, order_type_id, price_type_id, limit_price, stop_price, order_quantity): 148 | """ 149 | FIXME: untested 150 | """ 151 | return self.request('addOrder', 152 | auth_id = auth_id, 153 | exch_id=exch_id, 154 | mkt_id=mkt_id, 155 | order_type_id=order_type_id, 156 | price_type_id=price_type_id, 157 | limit_price=limit_price, 158 | stop_price=stop_price, 159 | order_quantity=order_quantity, 160 | json=True) 161 | 162 | def cancel_order(self, order_id): 163 | return self.request('cancelOrder', internal_order_id=order_id, json=True) 164 | 165 | def balance_history(self, date): 166 | """ 167 | NB: the timestamp columns is the time when the account was last snapshot, not the time the balances were 168 | effectively refreshed 169 | :param date: date str in format YYYY-MM-DD 170 | :return: a view of the acccount balances as of the date provided 171 | """ 172 | bh = pd.DataFrame.from_records(self.request('balanceHistory', date=date, json=True)['data']['balance_history']) 173 | if bh.empty: 174 | return bh 175 | acct = self.accounts()[['auth_id', 'exch_name']] 176 | return pd.merge(bh, acct, on='auth_id', how='left') 177 | 178 | 179 | if __name__ == "__main__": 180 | credentials.api = "actual/from_file_or_env" 181 | credentials.secret = "actual/from_file_or_env" 182 | credentials.endpoint = "https://api.coinigy.com/api/v1/" 183 | cr = CoinigyREST(credentials) 184 | print(cr.balances()) 185 | -------------------------------------------------------------------------------- /coinigy_ws_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "api": { 3 | "apiKey": "xxx", 4 | "apiSecret": "xxx" 5 | }, 6 | 7 | "subscriptions": { 8 | "trade": [ 9 | "TRADE-OK--BTC--CNY", 10 | "TRADE-BITF--BTC--USD", 11 | ], 12 | "order": [ 13 | "ORDER-OK--BTC--USD", 14 | ] 15 | }, 16 | 17 | "publishers": { 18 | "trade": "./data/trades.csv", 19 | "order": "./data/orders.csv" 20 | } 21 | } -------------------------------------------------------------------------------- /curl_examples.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #list exchanges 4 | curl -H "X-API-KEY:yourapikeyhere" -H "X-API-SECRET:yoursecrethere" -X POST "https://api.coinigy.com/api/v1/exchanges" 5 | 6 | #post data in json format 7 | curl -H "Content-Type: application/json" -H "X-API-KEY:yourapikeyhere" -H "X-API-SECRET:yoursecrethere" -X POST -d '{"exchange_code":"BTCC"}' "https://api.coinigy.com/api/v1/markets" 8 | 9 | #post data as params 10 | curl -H "X-API-KEY:yourapikeyhere" -H "X-API-SECRET:yoursecrethere" -X POST -d 'exchange_code=BTCC' "https://api.coinigy.com/api/v1/markets" 11 | 12 | #post multiple parameter data 13 | curl -H "X-API-KEY:yourapikeyhere" -H "X-API-SECRET:yoursecrethere" -X POST -d 'exch_code=BTCC&market_name=BTC/CNY&alert_price=6000.00&alert_note="time to buy the yacht"' "https://api.coinigy.com/api/v1/addAlert" 14 | 15 | #post multiple parameter data in json format 16 | curl -H "Content-Type: application/json" -H "X-API-KEY:yourapikeyhere" -H "X-API-SECRET:yoursecrethere" -X POST -d '{"exch_code":"BTCC","market_name":"BTC/CNY","alert_price":"6000.00","alert_note":"time to buy the yacht"}' "https://api.coinigy.com/api/v1/addAlert" 17 | -------------------------------------------------------------------------------- /example_v1.php: -------------------------------------------------------------------------------- 1 | exchanges(); 10 | $coinigy_api->markets('OK'); 11 | * 12 | * 13 | * 14 | */ 15 | 16 | 17 | 18 | class coinigy_api_example_v1 { 19 | 20 | //private class vars set in constructor 21 | //see API docs for more info 22 | private $coinigy_api_key; 23 | private $coinigy_api_secret; 24 | private $endpoint; 25 | 26 | 27 | function __construct() 28 | { 29 | //see API docs for more info 30 | $this->coinigy_api_key = ''; 31 | $this->coinigy_api_secret = ''; 32 | $this->endpoint = 'https://api.coinigy.com/api/v1/'; //with trailing slash 33 | } 34 | 35 | 36 | 37 | 38 | 39 | public function accounts() 40 | { 41 | $post_arr = array(); 42 | $result = $this->doWebRequest('accounts', $post_arr); 43 | $this->output_result($result); 44 | } 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | public function activity() 55 | { 56 | $post_arr = array(); 57 | $result = $this->doWebRequest('activity', $post_arr); 58 | $this->output_result($result); 59 | } 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | public function balances($auth_ids) 68 | { 69 | $post_arr = array(); 70 | $post_arr["auth_ids"] = $auth_ids; 71 | 72 | $result = $this->doWebRequest('balances', $post_arr); 73 | $this->output_result($result); 74 | } 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | public function pushNotifications() 83 | { 84 | $post_arr = array(); 85 | $result = $this->doWebRequest('pushNotifications', $post_arr); 86 | $this->output_result($result); 87 | } 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | public function user_orders() 99 | { 100 | $post_arr = array(); 101 | $result = $this->doWebRequest('orders', $post_arr); 102 | $this->output_result($result); 103 | } 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | public function alerts() 115 | { 116 | $post_arr = array(); 117 | $result = $this->doWebRequest('alerts', $post_arr); 118 | $this->output_result($result); 119 | } 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | public function exchanges() 130 | { 131 | $post_arr = array(); 132 | $result = $this->doWebRequest('exchanges', $post_arr); 133 | $this->output_result($result); 134 | } 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | public function markets($exchange_code) 145 | { 146 | $post_arr = array(); 147 | $post_arr["exchange_code"] = $exchange_code; 148 | 149 | $result = $this->doWebRequest('markets', $post_arr); 150 | $this->output_result($result); 151 | } 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | public function history($exchange_code, $exchange_market) 163 | { 164 | $post_arr = array(); 165 | $post_arr["exchange_code"] = $exchange_code; 166 | $post_arr["exchange_market"] = $exchange_market; 167 | $post_arr["type"] = "history"; 168 | 169 | 170 | $result = $this->doWebRequest('data', $post_arr); 171 | $this->output_result($result); 172 | } 173 | 174 | 175 | 176 | 177 | 178 | 179 | public function asks($exchange_code, $exchange_market) 180 | { 181 | $post_arr = array(); 182 | $post_arr["exchange_code"] = $exchange_code; 183 | $post_arr["exchange_market"] = $exchange_market; 184 | $post_arr["type"] = "asks"; 185 | 186 | $result = $this->doWebRequest('data', $post_arr); 187 | $this->output_result($result); 188 | } 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | public function bids($exchange_code, $exchange_market) 198 | { 199 | $post_arr = array(); 200 | $post_arr["exchange_code"] = $exchange_code; 201 | $post_arr["exchange_market"] = $exchange_market; 202 | $post_arr["type"] = "bids"; 203 | 204 | $result = $this->doWebRequest('data', $post_arr); 205 | $this->output_result($result); 206 | } 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | //asks + bids + history 220 | public function data($exchange_code, $exchange_market) 221 | { 222 | $post_arr = array(); 223 | $post_arr["exchange_code"] = $exchange_code; 224 | $post_arr["exchange_market"] = $exchange_market; 225 | $post_arr["type"] = "all"; 226 | 227 | $result = $this->doWebRequest('data', $post_arr); 228 | $this->output_result($result); 229 | } 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | //asks + bids 245 | public function orders($exchange_code, $exchange_market) 246 | { 247 | 248 | $post_arr = array(); 249 | $post_arr["exchange_code"] = $exchange_code; 250 | $post_arr["exchange_market"] = $exchange_market; 251 | $post_arr["type"] = "orders"; 252 | 253 | $result = $this->doWebRequest('data', $post_arr); 254 | 255 | $this->output_result($result); 256 | } 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | public function newsFeed() 265 | { 266 | $post_arr = array(); 267 | 268 | $result = $this->doWebRequest('newsFeed', $post_arr); 269 | $this->output_result($result); 270 | } 271 | 272 | 273 | 274 | 275 | 276 | 277 | public function orderTypes() 278 | { 279 | $post_arr = array(); 280 | $result = $this->doWebRequest('orderTypes', $post_arr); 281 | $this->output_result($result); 282 | } 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | //////////////////////////////////////////////////////////////////////////////////// 292 | //////////////////////////////////////////////////////////////////////////////////// 293 | ////////////////////// //////////////////////////////////////// 294 | ///////////// ACTION METHODS //////////////////////////////////// 295 | ///////////////////// //////////////////////////////////////// 296 | //////////////////////////////////////////////////////////////////////////////////// 297 | //////////////////////////////////////////////////////////////////////////////////// 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | public function refreshBalance($auth_id) 307 | { 308 | 309 | $post_arr = array(); 310 | $post_arr["auth_id"] = $auth_id; 311 | 312 | $result = $this->doWebRequest('refreshBalance', $post_arr); 313 | $this->output_result($result); 314 | } 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | public function addAlert($exchange_code, $exchange_market, $alert_price) 324 | { 325 | $post_arr = array(); 326 | $post_arr["exch_code"] = $exchange_code; 327 | $post_arr["market_name"] = $exchange_market; 328 | $post_arr["alert_price"] = $alert_price; 329 | 330 | $result = $this->doWebRequest('addAlert', $post_arr); 331 | $this->output_result($result); 332 | } 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | public function deleteAlert($delete_alert_id) 344 | { 345 | $post_arr = array(); 346 | $post_arr["alert_id"] = $delete_alert_id; 347 | 348 | $result = $this->doWebRequest('deleteAlert', $post_arr); 349 | $this->output_result($result); 350 | } 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | public function addOrder($order_auth_id, $order_exch_id, $order_mkt_id, $order_type_id, $price_type_id, $limit_price, $stop_price, $order_quantity) 362 | { 363 | $post_arr = array(); 364 | $post_arr["auth_id"] = $order_auth_id; 365 | $post_arr["exch_id"] = $order_exch_id; 366 | $post_arr["mkt_id"] = $order_mkt_id; 367 | $post_arr["order_type_id"] = $order_type_id; 368 | $post_arr["price_type_id"] = $price_type_id; 369 | $post_arr["limit_price"] =$limit_price; 370 | $post_arr["stop_price"] = $stop_price; 371 | $post_arr["order_quantity"] = $order_quantity; 372 | 373 | $result = $this->doWebRequest('addOrder', $post_arr); 374 | $this->output_result($result); 375 | 376 | } 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | public function cancelOrder($cancel_order_id) 390 | { 391 | $post_arr = array(); 392 | $post_arr["internal_order_id"] = $cancel_order_id; 393 | 394 | $result = $this->doWebRequest('cancelOrder', $post_arr); 395 | $this->output_result($result); 396 | 397 | } 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | private function doWebRequest($method, $post_arr) 411 | { 412 | 413 | $url = $this->endpoint.$method; 414 | 415 | $headers = array('X-API-KEY: ' . $this->coinigy_api_key, 416 | 'X-API-SECRET: ' . $this->coinigy_api_secret); 417 | 418 | 419 | // our curl handle (initialize if required) 420 | static $ch = null; 421 | if (is_null($ch)) { 422 | $ch = curl_init(); 423 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 424 | curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; Coinigy App Client; '.php_uname('s').'; PHP/'.phpversion().')'); 425 | } 426 | 427 | curl_setopt($ch, CURLOPT_URL, $url); 428 | curl_setopt($ch, CURLOPT_POSTFIELDS, $post_arr); 429 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 430 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE); 431 | $res = curl_exec($ch); 432 | 433 | if ($res === false) { 434 | echo "CURL Failed - Check URL"; 435 | return false; 436 | } 437 | 438 | $dec = json_decode($res); 439 | 440 | if (!$dec) { 441 | 442 | echo "Invalid JSON returned - Redirect to Login"; 443 | return false; 444 | } 445 | 446 | return $dec; 447 | 448 | } 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | private function output_result($result) 458 | { 459 | if($result) 460 | { 461 | if(isset($result->error)) 462 | $this->pre($result->error); 463 | elseif(isset($result)) 464 | $this->pre($result); 465 | } 466 | } 467 | 468 | 469 | 470 | private function pre($array) { 471 | echo "
".print_r($array, true)."
"; 472 | } 473 | 474 | 475 | } 476 | 477 | 478 | 479 | -------------------------------------------------------------------------------- /python_ws_example.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from socketclusterclient import Socketcluster 3 | logging.basicConfig(format="%s(levelname)s:%(message)s", level=logging.DEBUG) 4 | 5 | import json 6 | 7 | api_credentials = json.loads('{}') 8 | api_credentials["apiKey"]="xxx" 9 | api_credentials["apiSecret"]="xxx" 10 | 11 | 12 | def your_code_starts_here(socket): 13 | ###Code for subscription 14 | socket.subscribe('TRADE-OK--BTC--CNY') # Channel to be subscribed 15 | 16 | def channelmessage(key, data): # Messages will be received here 17 | print ("\n\n\nGot data "+json.dumps(data, sort_keys=True)+" from channel "+key) 18 | 19 | socket.onchannel('TRADE-OK--BTC--CNY', channelmessage) # This is used for watching messages over channel 20 | 21 | ###Code for emit 22 | 23 | def ack(eventname, error, data): 24 | print ("\n\n\nGot ack data " + json.dumps(data, sort_keys=True) + " and eventname is " + eventname) 25 | 26 | socket.emitack("exchanges",None, ack) 27 | 28 | socket.emitack("channels", "OK", ack) 29 | 30 | 31 | 32 | def onconnect(socket): 33 | logging.info("on connect got called") 34 | 35 | def ondisconnect(socket): 36 | logging.info("on disconnect got called") 37 | 38 | def onConnectError(socket, error): 39 | logging.info("On connect error got called") 40 | 41 | def onSetAuthentication(socket, token): 42 | logging.info("Token received " + token) 43 | socket.setAuthtoken(token) 44 | 45 | def onAuthentication(socket, isauthenticated): 46 | logging.info("Authenticated is " + str(isauthenticated)) 47 | def ack(eventname, error, data): 48 | print ("token is "+ json.dumps(data, sort_keys=True)) 49 | your_code_starts_here(socket); 50 | 51 | socket.emitack("auth", api_credentials, ack) 52 | 53 | if __name__ == "__main__": 54 | socket = Socketcluster.socket("wss://sc-02.coinigy.com/socketcluster/") 55 | socket.setBasicListener(onconnect, ondisconnect, onConnectError) 56 | socket.setAuthenticationListener(onSetAuthentication, onAuthentication) 57 | socket.setreconnection(False) 58 | socket.connect() 59 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Coinigy/api/558e391fd89cc34e3396200eb25271063533de8b/utils/__init__.py -------------------------------------------------------------------------------- /utils/console.py: -------------------------------------------------------------------------------- 1 | # adapted from https://twistedmatrix.com/documents/current/_downloads/stdiodemo.py 2 | 3 | from twisted.internet import stdio, reactor 4 | from twisted.protocols import basic 5 | """ 6 | A basic user console 7 | """ 8 | 9 | 10 | class Console(basic.LineReceiver): 11 | 12 | delimiter = '\n' # unix terminal style newlines. remove this line 13 | 14 | # for use with Telnet 15 | def connectionMade(self): 16 | self.sendLine("Command line interface. Type 'help' for help.") 17 | self.transport.write('>>> ') 18 | 19 | def connectionLost(self, reason): 20 | # stop the reactor, only because this is meant to be run in Stdio. 21 | reactor.stop() 22 | 23 | def lineReceived(self, line): 24 | # Ignore blank lines 25 | if not line: return 26 | 27 | # Parse the command 28 | commandParts = line.split() 29 | command = commandParts[0].lower() 30 | args = commandParts[1:] 31 | 32 | # Dispatch the command to the appropriate method. Note that all you 33 | # need to do to implement a new command is add another do_* method. 34 | res = None 35 | try: 36 | method = getattr(self, 'do_' + command) 37 | except AttributeError, e: 38 | self.sendLine('Error: no such command.') 39 | else: 40 | try: 41 | method(*args) 42 | except Exception, e: 43 | self.sendLine('Error: ' + str(e)) 44 | 45 | self.transport.write('>>> ') 46 | 47 | def printResult(self, res): 48 | if res is not None: 49 | self.sendLine(str(res)) 50 | self.transport.write('>>> ') 51 | 52 | def do_help(self, command=None): 53 | """help [command]: List commands, or show help on the given command""" 54 | if command: 55 | self.sendLine(getattr(self, 'do_' + command).__doc__) 56 | else: 57 | commands = [cmd[3:] for cmd in dir(self) if cmd.startswith('do_')] 58 | self.sendLine("Valid commands: " + " ".join(commands)) 59 | 60 | def do_echo(self, message): 61 | """echo [message]: repeat input message""" 62 | if message: 63 | self.printResult(message) 64 | 65 | def do_quit(self): 66 | """quit: Quit this session""" 67 | self.sendLine('Goodbye.') 68 | self.transport.loseConnection() 69 | 70 | 71 | if __name__ == "__main__": 72 | stdio.StandardIO(Plugin()) 73 | reactor.run() -------------------------------------------------------------------------------- /ws_example.js: -------------------------------------------------------------------------------- 1 | 2 | //run "npm install socketcluster-client" in terminal before attempting to use 3 | var socketCluster = require('socketcluster-client'); 4 | 5 | var api_credentials = 6 | { 7 | "apiKey" : "", 8 | "apiSecret" : "" 9 | } 10 | 11 | var options = { 12 | hostname : "sc-02.coinigy.com", 13 | port : "443", 14 | secure : "true" 15 | }; 16 | 17 | console.log(options); 18 | var SCsocket = socketCluster.connect(options); 19 | 20 | 21 | SCsocket.on('connect', function (status) { 22 | 23 | console.log(status); 24 | 25 | SCsocket.on('error', function (err) { 26 | console.log(err); 27 | }); 28 | 29 | 30 | SCsocket.emit("auth", api_credentials, function (err, token) { 31 | 32 | if (!err && token) { 33 | 34 | var scChannel = SCsocket.subscribe("TRADE-OK--BTC--CNY"); 35 | console.log(scChannel); 36 | scChannel.watch(function (data) { 37 | console.log(data); 38 | }); 39 | 40 | SCsocket.emit("exchanges", null, function (err, data) { 41 | if (!err) { 42 | console.log(data); 43 | } else { 44 | console.log(err) 45 | } 46 | }); 47 | 48 | 49 | SCsocket.emit("channels", "OK", function (err, data) { 50 | if (!err) { 51 | console.log(data); 52 | } else { 53 | console.log(err) 54 | } 55 | }); 56 | } else { 57 | console.log(err) 58 | } 59 | }); 60 | }); 61 | 62 | 63 | 64 | 65 | --------------------------------------------------------------------------------