forked from jaimehgb/crypto-exchanges-php-APIs
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcryptopiaAPI.php
More file actions
206 lines (182 loc) · 8.71 KB
/
cryptopiaAPI.php
File metadata and controls
206 lines (182 loc) · 8.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
<?php
include 'exchange.php';
class Cryptopia extends Exchange{
public function __construct($priv, $pub) {
$this->privateKey = $priv;
$this->publicKey = $pub;
$result = json_decode($this->apiCall("GetBalance", array( 'Currency'=> 'BTC' )), true);
if( $result['Success'] != "true" ) {
throw new Exception("Can't Connect to Cryptopia, Error: " . $result['Error'] );
return false;
}
return true;
}
private function apiCall($method, array $req = array()) {
$public_set = array( "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" );
$private_set = array( "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip" );
static $ch = null;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ( in_array( $method ,$public_set ) ) {
$url = "https://www.cryptopia.co.nz/api/" . $method;
if ($req) { foreach ($req as $r ) { $url = $url . '/' . $r; } }
curl_setopt($ch, CURLOPT_URL, $url );
} elseif ( in_array( $method, $private_set ) ) {
$url = "https://www.cryptopia.co.nz/Api/" . $method;
$nonce = explode(' ', microtime())[1];
$post_data = json_encode( $req );
$m = md5( $post_data, true );
$requestContentBase64String = base64_encode( $m );
$signature = $this->publicKey . "POST" . strtolower( urlencode( $url ) ) . $nonce . $requestContentBase64String;
$hmacsignature = base64_encode( hash_hmac("sha256", $signature, base64_decode( $this->privateKey ), true ) );
$header_value = "amx " . $this->publicKey . ":" . $hmacsignature . ":" . $nonce;
$headers = array("Content-Type: application/json; charset=utf-8", "Authorization: $header_value");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $req ) );
}
// run the query
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE); // Do Not Cache
$res = curl_exec($ch);
if ($res === false) throw new Exception('Could not get reply: '.curl_error($ch));
return $res;
}
// Some API calls require TradePairId rather than the TradePair so this should store the TradePairId
public function setSymbols() {
$result = json_decode($this->apiCall("GetTradePairs", array() ), true);
if( $result['Success'] == "true" ) {
$json = $result['Data'];
} else {
throw new Exception("Can't get symbols, Error: " . $result['Error'] );
}
foreach($json as $pair) {
// creates associative array of key: StandardSymbol (i.e. BTCUSD) value: ExchangeSymbol (i.e. btc_usd)
$this->symbols[ $this->makeStandardSymbol( $pair["Label"] ) ] = $pair["Id"];
}
}
public function updatePrices() {
$result = json_decode($this->apiCall("GetMarkets", array() ), true);
if( $result['Success'] == "true" ) {
$json = $result['Data'];
} else {
throw new Exception("Can't get markets, Error: " . $result['Error'] );
}
foreach($json as $pair) {
$this->prices[$pair['Label']]['high'] = $pair['High'];
$this->prices[$pair['Label']]['low'] = $pair['Low'];
$this->prices[$pair['Label']]['bid'] = $pair['BidPrice'];
$this->prices[$pair['Label']]['ask'] = $pair['AskPrice'];
$this->prices[$pair['Label']]['last'] = $pair['LastPrice'];
$this->prices[$pair['Label']]['time'] = ''; // not available on Cryptopia
}
}
// @todo add setBalance
Public function getBalance() {
$result = $this->apiCall("GetBalance", array('Currency'=> "") ); // "" for All currency balances
$result = json_decode($result, true);
if( $result['Success'] == "true" ) {
// @todo ADD CODE TO REFORMAT Array to standard
return $result['Data'];
} else {
throw new Exception("Can't get balances, Error: " . $result['Error'] );
}
}
Public function getCurrencyBalance( $currency ) {
$result = $this->apiCall("GetBalance", array( 'Currency'=> $currency ) );
$result = json_decode($result, true);
if( $result['Success'] == "true" ) {
return $result['Data'][0]['Total'];
} else {
throw new Exception("Can't get balance, Error: " . $result['Error'] );
}
}
// currency pair $symbol should be in standard Format not exchange format
public function activeOrders( $symbol = "")
{
if($symbol == "") {
$apiParams = array( 'TradePairId'=>"" );
} else {
$apiParams = array( 'TradePairId'=>$this->getExchangeSymbol($symbol) );
}
$myOrders = json_decode($this->apiCall("GetOpenOrders", $apiParams), true);
$orders = array();
$price = array(); // sort by price
if( $myOrders['Success'] == "true" && $myOrders['Error'] == "") {
foreach ($myOrders['Data'] as $order) {
$orderSymbol = $this->makeStandardSymbol($order["Market"]); // convert to standard format currency pair
$orders[] = ["symbol"=>$orderSymbol, "type"=>$order["Type"], "price"=>$order["Rate"],
"amount"=>$order["Remaining"], "id"=>$order["OrderId"] ];
if ($order["Type"] == "Sell") {
$price[] = 0 - $order['Rate']; // lowest ask price if first
} else {
$price[] = $order['Rate'];
}
}
if($orders) // If there are any orders
array_multisort($price, SORT_DESC, $orders); // sort orders by price
} else {
throw new Exception("Can't get active orders, Error: " . $myOrders['Error'] );
}
return $orders;
}
public function permissions() {
}
public function cancelOrder($id) {
$result = $this->apiCall("CancelTrade", array( 'Type'=>"Trade", 'OrderId'=>$id ));
$result = json_decode($result, true);
if( $result['Success'] == "true" ) {
echo "Orders Canceled: " . implode( ", ", $result['Data']) . "\n";
} else {
throw new Exception("Can't Cancel Order # $id, Error: " . $result['Error']);
}
}
public function cancelAll() {
if(!$this->activeOrders()) return false; // "No open orders to cancel.\n"
$result = $this->apiCall("CancelTrade", array( 'Type'=>"All" ));
$result = json_decode($result, true);
if( $result['Success'] == "true" ) {
return "Orders Canceled: " . implode( ", ", $result['Data']) . "\n";
} else {
throw new Exception("Can't Cancel All Orders, Error: " . $result['Error']);
}
}
public function orderStatus($id) {
}
public function placeOrder($symbol, $amount, $price, $side) {
$result = $this->apiCall("SubmitTrade", array( 'Type'=> $side, 'TradePairId'=> $this->getExchangeSymbol($symbol),
'Rate'=> number_format((float)$price, 8, '.', ''), 'Amount'=> number_format((float)$amount, 8, '.', '') ) );
$result = json_decode($result, true);
if( $result['Success'] == "true" ) {
return "Order Placed. OrderId:" .$result['Data']['OrderId'] .
" FilledOrders: " . implode( ", ", $result['Data']['FilledOrders']) . "\n";
} else {
throw new Exception("Can't Place Order, Error: " . $result['Error'] ); //*** die instead of echo
}
}
public function buy($symbol, $amount, $price) {
return $this->placeOrder($symbol, $amount, $price, 'Buy');
}
public function sell($symbol, $amount, $price) {
return $this->placeOrder($symbol, $amount, $price, 'Sell');
}
public function marketOrderbook($symbol)
{
$mktOrders = json_decode($this->apiCall("GetMarketOrders", array('TradePairId'=>$this->getExchangeSymbol($symbol))), true);
unset($orders);
if( $mktOrders['Success'] == "true" && $mktOrders['Error'] == "") {
//print_r($mktOrders);
foreach ($mktOrders['Data'] as $orderType => $order) {
foreach($order as $ordersByType) {
// $standardSymbol = $this->getStandardSymbol($symbol); // @todo not yet implemented
$orders[] = ["symbol"=>$symbol, "type"=>$orderType, "price"=>$ordersByType["Price"],
"amount"=>$ordersByType["Volume"] ];
}
}
} else {
throw new Exception("Can't get orderbook, Error: " . $mktOrders['Error'] );
}
return $orders;
}
}
?>