Bitcoin Price API: Bitcoin Ticker & Exchange Rate API ...

[ANN][ANDROID MINING][AIRDROP] NewEnglandcoin: Scrypt RandomSpike

New England
New England 6 States Songs: https://www.reddit.com/newengland/comments/er8wxd/new_england_6_states_songs/
NewEnglandcoin
Symbol: NENG
NewEnglandcoin is a clone of Bitcoin using scrypt as a proof-of-work algorithm with enhanced features to protect against 51% attack and decentralize on mining to allow diversified mining rigs across CPUs, GPUs, ASICs and Android phones.
Mining Algorithm: Scrypt with RandomSpike. RandomSpike is 3rd generation of Dynamic Difficulty (DynDiff) algorithm on top of scrypt.
1 minute block targets base difficulty reset: every 1440 blocks subsidy halves in 2.1m blocks (~ 2 to 4 years) 84,000,000,000 total maximum NENG 20000 NENG per block Pre-mine: 1% - reserved for dev fund ICO: None RPCPort: 6376 Port: 6377
NewEnglandcoin has dogecoin like supply at 84 billion maximum NENG. This huge supply insures that NENG is suitable for retail transactions and daily use. The inflation schedule of NengEnglandcoin is actually identical to that of Litecoin. Bitcoin and Litecoin are already proven to be great long term store of value. The Litecoin-like NENG inflation schedule will make NewEnglandcoin ideal for long term investment appreciation as the supply is limited and capped at a fixed number
Bitcoin Fork - Suitable for Home Hobbyists
NewEnglandcoin core wallet continues to maintain version tag of "Satoshi v0.8.7.5" because NewEnglandcoin is very much an exact clone of bitcoin plus some mining feature changes with DynDiff algorithm. NewEnglandcoin is very suitable as lite version of bitcoin for educational purpose on desktop mining, full node running and bitcoin programming using bitcoin-json APIs.
The NewEnglandcoin (NENG) mining algorithm original upgrade ideas were mainly designed for decentralization of mining rigs on scrypt, which is same algo as litecoin/dogecoin. The way it is going now is that NENG is very suitable for bitcoin/litecoin/dogecoin hobbyists who can not , will not spend huge money to run noisy ASIC/GPU mining equipments, but still want to mine NENG at home with quiet simple CPU/GPU or with a cheap ASIC like FutureBit Moonlander 2 USB or Apollo pod on solo mining setup to obtain very decent profitable results. NENG allows bitcoin litecoin hobbyists to experience full node running, solo mining, CPU/GPU/ASIC for a fun experience at home at cheap cost without breaking bank on equipment or electricity.
MIT Free Course - 23 lectures about Bitcoin, Blockchain and Finance (Fall,2018)
https://www.youtube.com/playlist?list=PLUl4u3cNGP63UUkfL0onkxF6MYgVa04Fn
CPU Minable Coin Because of dynamic difficulty algorithm on top of scrypt, NewEnglandcoin is CPU Minable. Users can easily set up full node for mining at Home PC or Mac using our dedicated cheetah software.
Research on the first forked 50 blocks on v1.2.0 core confirmed that ASIC/GPU miners mined 66% of 50 blocks, CPU miners mined the remaining 34%.
NENG v1.4.0 release enabled CPU mining inside android phones.
Youtube Video Tutorial
How to CPU Mine NewEnglandcoin (NENG) in Windows 10 Part 1 https://www.youtube.com/watch?v=sdOoPvAjzlE How to CPU Mine NewEnglandcoin (NENG) in Windows 10 Part 2 https://www.youtube.com/watch?v=nHnRJvJRzZg
How to CPU Mine NewEnglandcoin (NENG) in macOS https://www.youtube.com/watch?v=Zj7NLMeNSOQ
Decentralization and Community Driven NewEnglandcoin is a decentralized coin just like bitcoin. There is no boss on NewEnglandcoin. Nobody nor the dev owns NENG.
We know a coin is worth nothing if there is no backing from community. Therefore, we as dev do not intend to make decision on this coin solely by ourselves. It is our expectation that NewEnglandcoin community will make majority of decisions on direction of this coin from now on. We as dev merely view our-self as coin creater and technical support of this coin while providing NENG a permanent home at ShorelineCrypto Exchange.
Twitter Airdrop
Follow NENG twitter and receive 100,000 NENG on Twitter Airdrop to up to 1000 winners
Graphic Redesign Bounty
Top one award: 90.9 million NENG Top 10 Winners: 500,000 NENG / person Event Timing: March 25, 2019 - Present Event Address: NewEnglandcoin DISCORD at: https://discord.gg/UPeBwgs
Please complete above Twitter Bounty requirement first. Then follow Below Steps to qualify for the Bounty: (1) Required: submit your own designed NENG logo picture in gif, png jpg or any other common graphic file format into DISCORD "bounty-submission" board (2) Optional: submit a second graphic for logo or any other marketing purposes into "bounty-submission" board. (3) Complete below form.
Please limit your submission to no more than two total. Delete any wrongly submitted or undesired graphics in the board. Contact DISCORD u/honglu69#5911 or u/krypton#6139 if you have any issues.
Twitter Airdrop/Graphic Redesign bounty sign up: https://goo.gl/forms/L0vcwmVi8c76cR7m1
Milestones
Roadmap
NENG v1.4.0 Android Mining, randomSpike Evaluation https://github.com/ShorelineCrypto/NewEnglandCoin/releases/download/NENG_2020_Q3_report/NENG_2020_Q3_report.pdf
RandomSpike - NENG core v1.3.0 Hardfork Upgrade Proposal https://github.com/ShorelineCrypto/NewEnglandCoin/releases/download/2020Q1_Report/Scrypt_RandomSpike_NENGv1.3.0_Hardfork_Proposal.pdf
NENG Security, Decentralization & Valuation
https://github.com/ShorelineCrypto/NewEnglandCoin/releases/download/2019Q2_report/NENG_Security_Decentralization_Value.pdf
Whitepaper v1.0 https://github.com/ShorelineCrypto/NewEnglandCoin/releases/download/whitepaper_v1.0/NENG_WhitePaper.pdf
DISCORD https://discord.gg/UPeBwgs
Explorer
http://www.findblocks.com/exploreNENG http://86.100.49.209/exploreNENG http://nengexplorer.mooo.com:3001/
Step by step guide on how to setup an explorer: https://github.com/ShorelineCrypto/nengexplorer
Github https://github.com/ShorelineCrypto/NewEnglandCoin
Wallet
Android with UserLand App (arm64/armhf), Chromebook (x64/arm64/armhf): https://github.com/ShorelineCrypto/NewEnglandCoin/releases/tag/v1.4.0.5
Linux Wallet (Ubuntu/Linux Mint, Debian/MX Linux, Arch/Manjaro, Fedora, openSUSE): https://github.com/ShorelineCrypto/NewEnglandCoin/releases/tag/v1.4.0.3
MacOS Wallet (10.11 El Capitan or higher): https://github.com/ShorelineCrypto/NewEnglandCoin/releases/tag/v1.4.0.2
Android with GNUroot on 32 bits old Phones (alpha release) wallet: https://github.com/ShorelineCrypto/NewEnglandCoin/releases/tag/v1.4.0
Windows wallet: https://github.com/ShorelineCrypto/NewEnglandCoin/releases/tag/v1.3.0.1
addnode ip address for the wallet to sync faster, frequently updated conf file: https://github.com/ShorelineCrypto/cheetah_cpumineblob/mastenewenglandcoin.conf-example
How to Sync Full Node Desktop Wallet https://www.reddit.com/NewEnglandCoin/comments/er6f0q/how_to_sync_full_node_desktop_wallet/
TWITTER https://twitter.com/newenglandcoin
REDDIT https://www.reddit.com/NewEnglandCoin/
Cheetah CPU Miner Software https://github.com/ShorelineCrypto/cheetah_cpuminer
Solo Mining with GPU or ASIC https://bitcointalk.org/index.php?topic=5027091.msg52187727#msg52187727
How to Run Two Full Node in Same Desktop PC https://bitcointalk.org/index.php?topic=5027091.msg53581449#msg53581449
ASIC/GPU Mining Pools Warning to Big ASIC Miners Due to DynDiff Algo on top of Scrypt, solo mining is recommended for ASIC/GPU miners. Further more, even for mining pools, small mining pool will generate better performance than big NENG mining pool because of new algo v1.2.x post hard fork.
The set up configuration of NENG for scrypt pool mining is same as a typical normal scrypt coin. In other word, DynDiff on Scrypt algo is backward compatible with Scrypt algo. Because ASIC/GPU miners rely on CPU miners for smooth blockchain movement, checkout bottom of "Latest News" section for A WARNING to All ASIC miners before you decide to dump big ASIC hash rate into NENG mining.
(1) Original DynDiff Warning: https://bitcointalk.org/index.php?topic=5027091.msg48324708#msg48324708 (2) New Warning on RandomSpike Spike difficulty (244k) introduced in RandomSpike served as roadblocks to instant mining and provide security against 51% attack risk. However, this spike difficulty like a roadblock that makes big ASIC mining less profitable. In case of spike block to be mined, the spike difficulty immediately serve as base difficulty, which will block GPU/ASIC miners effectively and leave CPU cheetah solo miners dominating mining almost 100% until next base difficulty reset.
FindBlocks http://findblocks.com/
CRpool http://crpool.xyz/
Cminors' Pool http://newenglandcoin.cminors-pool.com/
SPOOL https://spools.online/
Exchange
📷
https://shorelinecrypto.com/
Features: anonymous sign up and trading. No restriction or limit on deposit or withdraw.
The trading pairs available: NewEnglandcoin (NENG) / Dogecoin (DOGE)
Trading commission: A round trip trading will incur 0.10% trading fees in average. Fees are paid only on buyer side. buy fee: 0.2% / sell fee: 0% Deposit fees: free for all coins Withdraw fees: ZERO per withdraw. Mining fees are appointed by each coin blockchain. To cover the blockchain mining fees, there is minimum balance per coin per account: * Dogecoin 2 DOGE * NewEnglandcoin 1 NENG
Latest News Aug 30, 2020 - NENG v1.4.0.5 Released for Android/Chromebook Upgrade with armhf, better hardware support https://bitcointalk.org/index.php?topic=5027091.msg55098029#msg55098029
Aug 11, 2020 - NENG v1.4.0.4 Released for Android arm64 Upgrade / Chromebook Support https://bitcointalk.org/index.php?topic=5027091.msg54977437#msg54977437
Jul 30, 2020 - NENG v1.4.0.3 Released for Linux Wallet Upgrade with 8 Distros https://bitcointalk.org/index.php?topic=5027091.msg54898540#msg54898540
Jul 21, 2020 - NENG v1.4.0.2 Released for MacOS Upgrade with Catalina https://bitcointalk.org/index.php?topic=5027091.msg54839522#msg54839522
Jul 19, 2020 - NENG v1.4.0.1 Released for MacOS Wallet Upgrade https://bitcointalk.org/index.php?topic=5027091.msg54830333#msg54830333
Jul 15, 2020 - NENG v1.4.0 Released for Android Mining, Ubuntu 20.04 support https://bitcointalk.org/index.php?topic=5027091.msg54803639#msg54803639
Jul 11, 2020 - NENG v1.4.0 Android Mining, randomSpike Evaluation https://bitcointalk.org/index.php?topic=5027091.msg54777222#msg54777222
Jun 27, 2020 - Pre-Announce: NENG v1.4.0 Proposal for Mobile Miner Upgrade, Android Mining Start in July 2020 https://bitcointalk.org/index.php?topic=5027091.msg54694233#msg54694233
Jun 19, 2020 - Best Practice for Futurebit Moonlander2 USB ASIC on solo mining mode https://bitcointalk.org/index.php?topic=5027091.msg54645726#msg54645726
Mar 15, 2020 - Scrypt RandomSpike - NENG v1.3.0.1 Released for better wallet syncing https://bitcointalk.org/index.php?topic=5027091.msg54030923#msg54030923
Feb 23, 2020 - Scrypt RandomSpike - NENG Core v1.3.0 Relased, Hardfork on Mar 1 https://bitcointalk.org/index.php?topic=5027091.msg53900926#msg53900926
Feb 1, 2020 - Scrypt RandomSpike Proposal Published- NENG 1.3.0 Hardfork https://bitcointalk.org/index.php?topic=5027091.msg53735458#msg53735458
Jan 15, 2020 - NewEnglandcoin Dev Team Expanded with New Kickoff https://bitcointalk.org/index.php?topic=5027091.msg53617358#msg53617358
Jan 12, 2020 - Explanation of Base Diff Reset and Effect of Supply https://www.reddit.com/NewEnglandCoin/comments/envmo1/explanation_of_base_diff_reset_and_effect_of/
Dec 19, 2019 - Shoreline_tradingbot version 1.0 is released https://bitcointalk.org/index.php?topic=5121953.msg53391184#msg53391184
Sept 1, 2019 - NewEnglandcoin (NENG) is Selected as Shoreline Tradingbot First Supported Coin https://bitcointalk.org/index.php?topic=5027091.msg52331201#msg52331201
Aug 15, 2019 - Mining Update on Effect of Base Difficulty Reset, GPU vs ASIC https://bitcointalk.org/index.php?topic=5027091.msg52169572#msg52169572
Jul 7, 2019 - CPU Mining on macOS Mojave is supported under latest Cheetah_Cpuminer Release https://bitcointalk.org/index.php?topic=5027091.msg51745839#msg51745839
Jun 1, 2019 - NENG Fiat project is stopped by Square, Inc https://bitcointalk.org/index.php?topic=5027091.msg51312291#msg51312291
Apr 21, 2019 - NENG Fiat Project is Launched by ShorelineCrypto https://bitcointalk.org/index.php?topic=5027091.msg50714764#msg50714764
Apr 7, 2019 - Announcement of Fiat Project for all U.S. Residents & Mobile Miner Project Initiation https://bitcointalk.org/index.php?topic=5027091.msg50506585#msg50506585
Apr 1, 2019 - Disclosure on Large Buying on NENG at ShorelineCrypto Exchange https://bitcointalk.org/index.php?topic=5027091.msg50417196#msg50417196
Mar 27, 2019 - Disclosure on Large Buying on NENG at ShorelineCrypto Exchange https://bitcointalk.org/index.php?topic=5027091.msg50332097#msg50332097
Mar 17, 2019 - Disclosure on Large Buying on NENG at ShorelineCrypto Exchange https://bitcointalk.org/index.php?topic=5027091.msg50208194#msg50208194
Feb 26, 2019 - Community Project - NewEnglandcoin Graphic Redesign Bounty Initiated https://bitcointalk.org/index.php?topic=5027091.msg49931305#msg49931305
Feb 22, 2019 - Dev Policy on Checkpoints on NewEnglandcoin https://bitcointalk.org/index.php?topic=5027091.msg49875242#msg49875242
Feb 20, 2019 - NewEnglandCoin v1.2.1 Released to Secure the Hard Kork https://bitcointalk.org/index.php?topic=5027091.msg49831059#msg49831059
Feb 11, 2019 - NewEnglandCoin v1.2.0 Released, Anti-51% Attack, Anti-instant Mining after Hard Fork https://bitcointalk.org/index.php?topic=5027091.msg49685389#msg49685389
Jan 13, 2019 - Cheetah_CpuMiner added support for CPU Mining on Mac https://bitcointalk.org/index.php?topic=5027091.msg49218760#msg49218760
Jan 12, 2019 - NENG Core v1.1.2 Released to support MacOS OSX Wallet https://bitcointalk.org/index.php?topic=5027091.msg49202088#msg49202088
Jan 2, 2019 - Cheetah_Cpuminer v1.1.0 is released for both Linux and Windows https://bitcointalk.org/index.php?topic=5027091.msg49004345#msg49004345
Dec 31, 2018 - Technical Whitepaper is Released https://bitcointalk.org/index.php?topic=5027091.msg48990334#msg48990334
Dec 28, 2018 - Cheetah_Cpuminer v1.0.0 is released for Linux https://bitcointalk.org/index.php?topic=5027091.msg48935135#msg48935135
Update on Dec 14, 2018 - NENG Blockchain Stuck Issue https://bitcointalk.org/index.php?topic=5027091.msg48668375#msg48668375
Nov 27, 2018 - Exclusive for PC CPU Miners - How to Steal a Block from ASIC Miners https://bitcointalk.org/index.php?topic=5027091.msg48258465#msg48258465
Nov 28, 2018 - How to CPU Mine a NENG block with window/linux PC https://bitcointalk.org/index.php?topic=5027091.msg48298311#msg48298311
Nov 29, 2018 - A Warning to ASIC Miners https://bitcointalk.org/index.php?topic=5027091.msg48324708#msg48324708
Disclosure: Dev Team Came from ShorelineCrypto, a US based Informatics Service Business offering Fee for service for Coin Creation, Coin Exchange Listing, Blockchain Consulting, etc.
submitted by honglu69 to NewEnglandCoin [link] [comments]

FlowCards: A Declarative Framework for Development of Ergo dApps

FlowCards: A Declarative Framework for Development of Ergo dApps
Introduction
ErgoScript is the smart contract language used by the Ergo blockchain. While it has concise syntax adopted from Scala/Kotlin, it still may seem confusing at first because conceptually ErgoScript is quite different compared to conventional languages which we all know and love. This is because Ergo is a UTXO based blockchain, whereas smart contracts are traditionally associated with account based systems like Ethereum. However, Ergo's transaction model has many advantages over the account based model and with the right approach it can even be significantly easier to develop Ergo contracts than to write and debug Solidity code.
Below we will cover the key aspects of the Ergo contract model which makes it different:
Paradigm
The account model of Ethereum is imperative. This means that the typical task of sending coins from Alice to Bob requires changing the balances in storage as a series of operations. Ergo's UTXO based programming model on the other hand is declarative. ErgoScript contracts specify conditions for a transaction to be accepted by the blockchain (not changes to be made in the storage state as result of the contract execution).
Scalability
In the account model of Ethereum both storage changes and validity checks are performed on-chain during code execution. In contrast, Ergo transactions are created off-chain and only validation checks are performed on-chain thus reducing the amount of operations performed by every node on the network. In addition, due to immutability of the transaction graph, various optimization strategies are possible to improve throughput of transactions per second in the network. Light verifying nodes are also possible thus further facilitating scalability and accessibility of the network.
Shared state
The account-based model is reliant on shared mutable state which is known to lead to complex semantics (and subtle million dollar bugs) in the context of concurrent/ distributed computation. Ergo's model is based on an immutable graph of transactions. This approach, inherited from Bitcoin, plays well with the concurrent and distributed nature of blockchains and facilitates light trustless clients.
Expressive Power
Ethereum advocated execution of a turing-complete language on the blockchain. It theoretically promised unlimited potential, however in practice severe limitations came to light from excessive blockchain bloat, subtle multi-million dollar bugs, gas costs which limit contract complexity, and other such problems. Ergo on the flip side extends UTXO to enable turing-completeness while limiting the complexity of the ErgoScript language itself. The same expressive power is achieved in a different and more semantically sound way.
With the all of the above points, it should be clear that there are a lot of benefits to the model Ergo is using. In the rest of this article I will introduce you to the concept of FlowCards - a dApp developer component which allows for designing complex Ergo contracts in a declarative and visual way.

From Imperative to Declarative

In the imperative programming model of Ethereum a transaction is a sequence of operations executed by the Ethereum VM. The following Solidity function implements a transfer of tokens from sender to receiver . The transaction starts when sender calls this function on an instance of a contract and ends when the function returns.
// Sends an amount of existing coins from any caller to an address function send(address receiver, uint amount) public { require(amount <= balances[msg.sender], "Insufficient balance."); balances[msg.sender] -= amount; balances[receiver] += amount; emit Sent(msg.sender, receiver, amount); } 
The function first checks the pre-conditions, then updates the storage (i.e. balances) and finally publishes the post-condition as the Sent event. The gas which is consumed by the transaction is sent to the miner as a reward for executing this transaction.
Unlike Ethereum, a transaction in Ergo is a data structure holding a list of input coins which it spends and a list of output coins which it creates preserving the total balances of ERGs and tokens (in which Ergo is similar to Bitcoin).
Turning back to the example above, since Ergo natively supports tokens, therefore for this specific example of sending tokens we don't need to write any code in ErgoScript. Instead we need to create the ‘send’ transaction shown in the following figure, which describes the same token transfer but declaratively.
https://preview.redd.it/sxs3kesvrsv41.png?width=1348&format=png&auto=webp&s=582382bc26912ff79114d831d937d94b6988e69f
The picture visually describes the following steps, which the network user needs to perform:
  1. Select unspent sender's boxes, containing in total tB >= amount of tokens and B >= txFee + minErg ERGs.
  2. Create an output target box which is protected by the receiver public key with minErg ERGs and amount of T tokens.
  3. Create one fee output protected by the minerFee contract with txFee ERGs.
  4. Create one change output protected by the sender public key, containing B - minErg - txFee ERGs and tB - amount of T tokens.
  5. Create a new transaction, sign it using the sender's secret key and send to the Ergo network.
What is important to understand here is that all of these steps are preformed off-chain (for example using Appkit Transaction API) by the user's application. Ergo network nodes don't need to repeat this transaction creation process, they only need to validate the already formed transaction. ErgoScript contracts are stored in the inputs of the transaction and check spending conditions. The node executes the contracts on-chain when the transaction is validated. The transaction is valid if all of the conditions are satisfied.
Thus, in Ethereum when we “send amount from sender to recipient” we are literally editing balances and updating the storage with a concrete set of commands. This happens on-chain and thus a new transaction is also created on-chain as the result of this process.
In Ergo (as in Bitcoin) transactions are created off-chain and the network nodes only verify them. The effects of the transaction on the blockchain state is that input coins (or Boxes in Ergo's parlance) are removed and output boxes are added to the UTXO set.
In the example above we don't use an ErgoScript contract but instead assume a signature check is used as the spending pre-condition. However in more complex application scenarios we of course need to use ErgoScript which is what we are going to discuss next.

From Changing State to Checking Context

In the send function example we first checked the pre-condition (require(amount <= balances[msg.sender],...) ) and then changed the state (i.e. update balances balances[msg.sender] -= amount ). This is typical in Ethereum transactions. Before we change anything we need to check if it is valid to do so.
In Ergo, as we discussed previously, the state (i.e. UTXO set of boxes) is changed implicitly when a valid transaction is included in a block. Thus we only need to check the pre-conditions before the transaction can be added to the block. This is what ErgoScript contracts do.
It is not possible to “change the state” in ErgoScript because it is a language to check pre-conditions for spending coins. ErgoScript is a purely functional language without side effects that operates on immutable data values. This means all the inputs, outputs and other transaction parameters available in a script are immutable. This, among other things, makes ErgoScript a very simple language that is easy to learn and safe to use. Similar to Bitcoin, each input box contains a script, which should return the true value in order to 1) allow spending of the box (i.e. removing from the UTXO set) and 2) adding the transaction to the block.
If we are being pedantic, it is therefore incorrect (strictly speaking) to think of ErgoScript as the language of Ergo contracts, because it is the language of propositions (logical predicates, formulas, etc.) which protect boxes from “illegal” spending. Unlike Bitcoin, in Ergo the whole transaction and a part of the current blockchain context is available to every script. Therefore each script may check which outputs are created by the transaction, their ERG and token amounts (we will use this capability in our example DEX contracts), current block number etc.
In ErgoScript you define the conditions of whether changes (i.e. coin spending) are allowed to happen in a given context. This is in contrast to programming the changes imperatively in the code of a contract.
While Ergo's transaction model unlocks a whole range of applications like (DEX, DeFi Apps, LETS, etc), designing contracts as pre-conditions for coin spending (or guarding scripts) directly is not intuitive. In the next sections we will consider a useful graphical notation to design contracts declaratively using FlowCard Diagrams, which is a visual representation of executable components (FlowCards).
FlowCards aim to radically simplify dApp development on the Ergo platform by providing a high-level declarative language, execution runtime, storage format and a graphical notation.
We will start with a high level of diagrams and go down to FlowCard specification.

FlowCard Diagrams

The idea behind FlowCard diagrams is based on the following observations: 1) An Ergo box is immutable and can only be spent in the transaction which uses it as an input. 2) We therefore can draw a flow of boxes through transactions, so that boxes flowing in to the transaction are spent and those flowing out are created and added to the UTXO. 3) A transaction from this perspective is simply a transformer of old boxes to the new ones preserving the balances of ERGs and tokens involved.
The following figure shows the main elements of the Ergo transaction we've already seen previously (now under the name of FlowCard Diagram).
https://preview.redd.it/06aqkcd1ssv41.png?width=1304&format=png&auto=webp&s=106eda730e0526919aabd5af9596b97e45b69777
There is a strictly defined meaning (semantics) behind every element of the diagram, so that the diagram is a visual representation (or a view) of the underlying executable component (called FlowCard).
The FlowCard can be used as a reusable component of an Ergo dApp to create and initiate the transaction on the Ergo blockchain. We will discuss this in the coming sections.
Now let's look at the individual pieces of the FlowCard diagram one by one.
1. Name and Parameters
Each flow card is given a name and a list of typed parameters. This is similar to a template with parameters. In the above figure we can see the Send flow card which has five parameters. The parameters are used in the specification.
2. Contract Wallet
This is a key element of the flow card. Every box has a guarding script. Often it is the script that checks a signature against a public key. This script is trivial in ErgoScript and is defined like the def pk(pubkey: Address) = { pubkey } template where pubkey is a parameter of the type Address . In the figure, the script template is applied to the parameter pk(sender) and thus a concrete wallet contract is obtained. Therefore pk(sender) and pk(receiver) yield different scripts and represent different wallets on the diagram, even though they use the same template.
Contract Wallet contains a set of all UTXO boxes which have a given script derived from the given script template using flow card parameters. For example, in the figure, the template is pk and parameter pubkey is substituted with the `sender’ flow card parameter.
3. Contract
Even though a contract is a property of a box, on the diagram we group the boxes by their contracts, therefore it looks like the boxes belong to the contracts, rather than the contracts belong to the boxes. In the example, we have three instantiated contracts pk(sender) , pk(receiver) and minerFee . Note, that pk(sender) is the instantiation of the pk template with the concrete parameter sender and minerFee is the instantiation of the pre-defined contract which protects the miner reward boxes.
4. Box name
In the diagram we can give each box a name. Besides readability of the diagram, we also use the name as a synonym of a more complex indexed access to the box in the contract. For example, change is the name of the box, which can also be used in the ErgoScript conditions instead of OUTPUTS(2) . We also use box names to associate spending conditions with the boxes.
5. Boxes in the wallet
In the diagram, we show boxes (darker rectangles) as belonging to the contract wallets (lighter rectangles). Each such box rectangle is connected with a grey transaction rectangle by either orange or green arrows or both. An output box (with an incoming green arrow) may include many lines of text where each line specifies a condition which should be checked as part of the transaction. The first line specifies the condition on the amount of ERG which should be placed in the box. Other lines may take one of the following forms:
  1. amount: TOKEN - the box should contain the given amount of the given TOKEN
  2. R == value - the box should contain the given value of the given register R
  3. boxName ? condition - the box named boxName should check condition in its script.
We discuss these conditions in the sections below.
6. Amount of ERGs in the box
Each box should store a minimum amount of ERGs. This is checked when the creating transaction is validated. In the diagram the amount of ERGs is always shown as the first line (e.g. B: ERG or B - minErg - txFee ). The value type ascription B: ERG is optional and may be used for readability. When the value is given as a formula, then this formula should be respected by the transaction which creates the box.
It is important to understand that variables like amount and txFee are not named properties of the boxes. They are parameters of the whole diagram and representing some amounts. Or put it another way, they are shared parameters between transactions (e.g. Sell Order and Swap transactions from DEX example below share the tAmt parameter). So the same name is tied to the same value throughout the diagram (this is where the tooling would help a lot). However, when it comes to on-chain validation of those values, only explicit conditions which are marked with ? are transformed to ErgoScript. At the same time, all other conditions are ensured off-chain during transaction building (for example in an application using Appkit API) and transaction validation when it is added to the blockchain.
7. Amount of T token
A box can store values of many tokens. The tokens on the diagram are named and a value variable may be associated with the token T using value: T expression. The value may be given by formula. If the formula is prefixed with a box name like boxName ? formula , then it is should also be checked in the guarding script of the boxName box. This additional specification is very convenient because 1) it allows to validate the visual design automatically, and 2) the conditions specified in the boxes of a diagram are enough to synthesize the necessary guarding scripts. (more about this below at “From Diagrams To ErgoScript Contracts”)
8. Tx Inputs
Inputs are connected to the corresponding transaction by orange arrows. An input arrow may have a label of the following forms:
  1. [email protected] - optional name with an index i.e. [email protected] or u/2 . This is a property of the target endpoint of the arrow. The name is used in conditions of related boxes and the index is the position of the corresponding box in the INPUTS collection of the transaction.
  2. !action - is a property of the source of the arrow and gives a name for an alternative spending path of the box (we will see this in DEX example)
Because of alternative spending paths, a box may have many outgoing orange arrows, in which case they should be labeled with different actions.
9. Transaction
A transaction spends input boxes and creates output boxes. The input boxes are given by the orange arrows and the labels are expected to put inputs at the right indexes in INPUTS collection. The output boxes are given by the green arrows. Each transaction should preserve a strict balance of ERG values (sum of inputs == sum of outputs) and for each token the sum of inputs >= the sum of outputs. The design diagram requires an explicit specification of the ERG and token values for all of the output boxes to avoid implicit errors and ensure better readability.
10. Tx Outputs
Outputs are connected to the corresponding transaction by green arrows. An output arrow may have a label of the following [email protected] , where an optional name is accompanied with an index i.e. [email protected] or u/2 . This is a property of the source endpoint of the arrow. The name is used in conditions of the related boxes and the index is the position of the corresponding box in the OUTPUTS collection of the transaction.

Example: Decentralized Exchange (DEX)

Now let's use the above described notation to design a FlowCard for a DEX dApp. It is simple enough yet also illustrates all of the key features of FlowCard diagrams which we've introduced in the previous section.
The dApp scenario is shown in the figure below: There are three participants (buyer, seller and DEX) of the DEX dApp and five different transaction types, which are created by participants. The buyer wants to swap ergAmt of ERGs for tAmt of TID tokens (or vice versa, the seller wants to sell TID tokens for ERGs, who sends the order first doesn't matter). Both the buyer and the seller can cancel their orders any time. The DEX off-chain matching service can find matching orders and create the Swap transaction to complete the exchange.
The following diagram fully (and formally) specifies all of the five transactions that must be created off-chain by the DEX dApp. It also specifies all of the spending conditions that should be verified on-chain.

https://preview.redd.it/piogz0v9ssv41.png?width=1614&format=png&auto=webp&s=e1b503a635ad3d138ef91e2f0c3b726e78958646
Let's discuss the FlowCard diagram and the logic of each transaction in details:
Buy Order Transaction
A buyer creates a Buy Order transaction. The transaction spends E amount of ERGs (which we will write E: ERG ) from one or more boxes in the pk(buyer) wallet. The transaction creates a bid box with ergAmt: ERG protected by the buyOrder script. The buyOrder script is synthesized from the specification (see below at “From Diagrams To ErgoScript Contracts”) either manually or automatically by a tool. Even though we don't need to define the buyOrder script explicitly during designing, at run time the bid box should contain the buyOrder script as the guarding proposition (which checks the box spending conditions), otherwise the conditions specified in the diagram will not be checked.
The change box is created to make the input and output sums of the transaction balanced. The transaction fee box is omitted because it can be added automatically by the tools. In practice, however, the designer can add the fee box explicitly to the a diagram. It covers the cases of more complex transactions (like Swap) where there are many ways to pay the transaction fee.
Cancel Buy, Cancel Sell Transactions
At any time, the buyer can cancel the order by sending CancelBuy transaction. The transaction should satisfy the guarding buyOrder contract which protects the bid box. As you can see on the diagram, both the Cancel and the Swap transactions can spend the bid box. When a box has spending alternatives (or spending paths) then each alternative is identified by a unique name prefixed with ! (!cancel and !swap for the bid box). Each alternative path has specific spending conditions. In our example, when the Cancel Buy transaction spends the bid box the ?buyer condition should be satisfied, which we read as “the signature for the buyer address should be presented in the transaction”. Therefore, only buyer can cancel the buy order. This “signature” condition is only required for the !cancel alternative spending path and not required for !swap .
Sell Order Transaction
The Sell Order transaction is similar to the BuyOrder in that it deals with tokens in addition to ERGs. The transaction spends E: ERG and T: TID tokens from seller's wallet (specified as pk(seller) contract). The two outputs are ask and change . The change is a standard box to balance transaction. The ask box keeps tAmt: TID tokens for the exchange and minErg: ERG - the minimum amount of ERGs required in every box.
Swap Transaction
This is a key transaction in the DEX dApp scenario. The transaction has several spending conditions on the input boxes and those conditions are included in the buyOrder and sellOrder scripts (which are verified when the transaction is added to the blockchain). However, on the diagram those conditions are not specified in the bid and ask boxes, they are instead defined in the output boxes of the transaction.
This is a convention for improved usability because most of the conditions relate to the properties of the output boxes. We could specify those properties in the bid box, but then we would have to use more complex expressions.
Let's consider the output created by the arrow labeled with [email protected] . This label tells us that the output is at the index 0 in the OUTPUTS collection of the transaction and that in the diagram we can refer to this box by the buyerOut name. Thus we can label both the box itself and the arrow to give the box a name.
The conditions shown in the buyerOut box have the form bid ? condition , which means they should be verified on-chain in order to spend the bid box. The conditions have the following meaning:
  • tAmt: TID requires the box to have tAmt amount of TID token
  • R4 == bid.id requires R4 register in the box to be equal to id of the bid box.
  • script == buyer requires the buyerOut box to have the script of the wallet where it is located on the diagram, i.e. pk(buyer)
Similar properties are added to the sellerOut box, which is specified to be at index 1 and the name is given to it using the label on the box itself, rather than on the arrow.
The Swap transaction spends two boxes bid and ask using the !swap spending path on both, however unlike !cancel the conditions on the path are not specified. This is where the bid ? and ask ? prefixes come into play. They are used so that the conditions listed in the buyerOut and sellerOut boxes are moved to the !swap spending path of the bid and ask boxes correspondingly.
If you look at the conditions of the output boxes, you will see that they exactly specify the swap of values between seller's and buyer's wallets. The buyer gets the necessary amount of TID token and seller gets the corresponding amount of ERGs. The Swap transaction is created when there are two matching boxes with buyOrder and sellOrder contracts.

From Diagrams To ErgoScript Contracts

What is interesting about FlowCard specifications is that we can use them to automatically generate the necessary ErgoTree scripts. With the appropriate tooling support this can be done automatically, but with the lack of thereof, it can be done manually. Thus, the FlowCard allows us to capture and visually represent all of the design choices and semantic details of an Ergo dApp.
What we are going to do next is to mechanically create the buyOrder contract from the information given in the DEX flow card.
Recall that each script is a proposition (boolean valued expression) which should evaluate to true to allow spending of the box. When we have many conditions to be met at the same time we can combine them in a logical formula using the AND binary operation, and if we have alternatives (not necessarily exclusive) we can put them into the OR operation.
The buyOrder box has the alternative spending paths !cancel and !swap . Thus the ErgoScript code should have OR operation with two arguments - one for each spending path.
/** buyOrder contract */ { val cancelCondition = {} val swapCondition = {} cancelCondition || swapCondition } 
The formula for the cancelCondition expression is given in the !cancel spending path of the buyOrder box. We can directly include it in the script.
/** buyOrder contract */ { val cancelCondition = { buyer } val swapCondition = {} cancelCondition || swapCondition } 
For the !swap spending path of the buyOrder box the conditions are specified in the buyerOut output box of the Swap transaction. If we simply include them in the swapCondition then we get a syntactically incorrect script.
/** buyOrder contract */ { val cancelCondition = { buyer } val swapCondition = { tAmt: TID && R4 == bid.id && @contract } cancelCondition || swapCondition } 
We can however translate the conditions from the diagram syntax to ErgoScript expressions using the following simple rules
  1. [email protected] ==> val buyerOut = OUTPUTS(0)
  2. tAmt: TID ==> tid._2 == tAmt where tid = buyerOut.tokens(TID)
  3. R4 == bid.id ==> R4 == SELF.id where R4 = buyerOut.R4[Coll[Byte]].get
  4. script == buyer ==> buyerOut.propositionBytes == buyer.propBytes
Note, in the diagram TID represents a token id, but ErgoScript doesn't have access to the tokens by the ids so we cannot write tokens.getByKey(TID) . For this reason, when the diagram is translated into ErgoScript, TID becomes a named constant of the index in tokens collection of the box. The concrete value of the constant is assigned when the BuyOrder transaction with the buyOrder box is created. The correspondence and consistency between the actual tokenId, the TID constant and the actual tokens of the buyerOut box is ensured by the off-chain application code, which is completely possible since all of the transactions are created by the application using FlowCard as a guiding specification. This may sound too complicated, but this is part of the translation from diagram specification to actual executable application code, most of which can be automated.
After the transformation we can obtain a correct script which checks all the required preconditions for spending the buyOrder box.
/** buyOrder contract */ def DEX(buyer: Addrss, seller: Address, TID: Int, ergAmt: Long, tAmt: Long) { val cancelCondition: SigmaProp = { buyer } // verify buyer's sig (ProveDlog) val swapCondition = OUTPUTS.size > 0 && { // securing OUTPUTS access val buyerOut = OUTPUTS(0) // from [email protected] buyerOut.tokens.size > TID && { // securing tokens access val tid = buyerOut.tokens(TID) val regR4 = buyerOut.R4[Coll[Byte]] regR4.isDefined && { // securing R4 access val R4 = regR4.get tid._2 == tAmt && // from tAmt: TID R4 == SELF.id && // from R4 == bid.id buyerOut.propositionBytes == buyer.propBytes // from script == buyer } } } cancelCondition || swapCondition } 
A similar script for the sellOrder box can be obtained using the same translation rules. With the help of the tooling the code of contracts can be mechanically generated from the diagram specification.

Conclusions

Declarative programming models have already won the battle against imperative programming in many application domains like Big Data, Stream Processing, Deep Learning, Databases, etc. Ergo is pioneering the declarative model of dApp development as a better and safer alternative to the now popular imperative model of smart contracts.
The concept of FlowCard shifts the focus from writing ErgoScript contracts to the overall flow of values (hence the name), in such a way, that ErgoScript can always be generated from them. You will never need to look at the ErgoScript code once the tooling is in place.
Here are the possible next steps for future work:
  1. Storage format for FlowCard Spec and the corresponding EIP standardized file format (Json/XML/Protobuf). This will allow various tools (Diagram Editor, Runtime, dApps etc) to create and use *.flowcard files.
  2. FlowCard Viewer, which can generate the diagrams from *.flowcard files.
  3. FlowCard Runtime, which can run *.flowcard files, create and send transactions to Ergo network.
  4. FlowCard Designer Tool, which can simplify development of complex diagrams . This will make designing and validation of Ergo contracts a pleasant experience, more like drawing rather than coding. In addition, the correctness of the whole dApp scenario can be verified and controlled by the tooling.
submitted by eleanorcwhite to btc [link] [comments]

FlowCards: A Declarative Framework for Development of Ergo dApps

FlowCards: A Declarative Framework for Development of Ergo dApps
Introduction
ErgoScript is the smart contract language used by the Ergo blockchain. While it has concise syntax adopted from Scala/Kotlin, it still may seem confusing at first because conceptually ErgoScript is quite different compared to conventional languages which we all know and love. This is because Ergo is a UTXO based blockchain, whereas smart contracts are traditionally associated with account based systems like Ethereum. However, Ergo's transaction model has many advantages over the account based model and with the right approach it can even be significantly easier to develop Ergo contracts than to write and debug Solidity code.
Below we will cover the key aspects of the Ergo contract model which makes it different:
Paradigm
The account model of Ethereum is imperative. This means that the typical task of sending coins from Alice to Bob requires changing the balances in storage as a series of operations. Ergo's UTXO based programming model on the other hand is declarative. ErgoScript contracts specify conditions for a transaction to be accepted by the blockchain (not changes to be made in the storage state as result of the contract execution).
Scalability
In the account model of Ethereum both storage changes and validity checks are performed on-chain during code execution. In contrast, Ergo transactions are created off-chain and only validation checks are performed on-chain thus reducing the amount of operations performed by every node on the network. In addition, due to immutability of the transaction graph, various optimization strategies are possible to improve throughput of transactions per second in the network. Light verifying nodes are also possible thus further facilitating scalability and accessibility of the network.
Shared state
The account-based model is reliant on shared mutable state which is known to lead to complex semantics (and subtle million dollar bugs) in the context of concurrent/ distributed computation. Ergo's model is based on an immutable graph of transactions. This approach, inherited from Bitcoin, plays well with the concurrent and distributed nature of blockchains and facilitates light trustless clients.
Expressive Power
Ethereum advocated execution of a turing-complete language on the blockchain. It theoretically promised unlimited potential, however in practice severe limitations came to light from excessive blockchain bloat, subtle multi-million dollar bugs, gas costs which limit contract complexity, and other such problems. Ergo on the flip side extends UTXO to enable turing-completeness while limiting the complexity of the ErgoScript language itself. The same expressive power is achieved in a different and more semantically sound way.
With the all of the above points, it should be clear that there are a lot of benefits to the model Ergo is using. In the rest of this article I will introduce you to the concept of FlowCards - a dApp developer component which allows for designing complex Ergo contracts in a declarative and visual way.
From Imperative to Declarative
In the imperative programming model of Ethereum a transaction is a sequence of operations executed by the Ethereum VM. The following Solidity function implements a transfer of tokens from sender to receiver . The transaction starts when sender calls this function on an instance of a contract and ends when the function returns.
// Sends an amount of existing coins from any caller to an address function send(address receiver, uint amount) public { require(amount <= balances[msg.sender], "Insufficient balance."); balances[msg.sender] -= amount; balances[receiver] += amount; emit Sent(msg.sender, receiver, amount); } 
The function first checks the pre-conditions, then updates the storage (i.e. balances) and finally publishes the post-condition as the Sent event. The gas which is consumed by the transaction is sent to the miner as a reward for executing this transaction.
Unlike Ethereum, a transaction in Ergo is a data structure holding a list of input coins which it spends and a list of output coins which it creates preserving the total balances of ERGs and tokens (in which Ergo is similar to Bitcoin).
Turning back to the example above, since Ergo natively supports tokens, therefore for this specific example of sending tokens we don't need to write any code in ErgoScript. Instead we need to create the ‘send’ transaction shown in the following figure, which describes the same token transfer but declaratively.
https://preview.redd.it/id5kjdgn9tv41.png?width=1348&format=png&auto=webp&s=31b937d7ad0af4afe94f4d023e8c90c97c8aed2e
The picture visually describes the following steps, which the network user needs to perform:
  1. Select unspent sender's boxes, containing in total tB >= amount of tokens and B >= txFee + minErg ERGs.
  2. Create an output target box which is protected by the receiver public key with minErg ERGs and amount of T tokens.
  3. Create one fee output protected by the minerFee contract with txFee ERGs.
  4. Create one change output protected by the sender public key, containing B - minErg - txFee ERGs and tB - amount of T tokens.
  5. Create a new transaction, sign it using the sender's secret key and send to the Ergo network.
What is important to understand here is that all of these steps are preformed off-chain (for example using Appkit Transaction API) by the user's application. Ergo network nodes don't need to repeat this transaction creation process, they only need to validate the already formed transaction. ErgoScript contracts are stored in the inputs of the transaction and check spending conditions. The node executes the contracts on-chain when the transaction is validated. The transaction is valid if all of the conditions are satisfied.
Thus, in Ethereum when we “send amount from sender to recipient” we are literally editing balances and updating the storage with a concrete set of commands. This happens on-chain and thus a new transaction is also created on-chain as the result of this process.
In Ergo (as in Bitcoin) transactions are created off-chain and the network nodes only verify them. The effects of the transaction on the blockchain state is that input coins (or Boxes in Ergo's parlance) are removed and output boxes are added to the UTXO set.
In the example above we don't use an ErgoScript contract but instead assume a signature check is used as the spending pre-condition. However in more complex application scenarios we of course need to use ErgoScript which is what we are going to discuss next.
From Changing State to Checking Context
In the send function example we first checked the pre-condition (require(amount <= balances[msg.sender],...) ) and then changed the state (i.e. update balances balances[msg.sender] -= amount ). This is typical in Ethereum transactions. Before we change anything we need to check if it is valid to do so.
In Ergo, as we discussed previously, the state (i.e. UTXO set of boxes) is changed implicitly when a valid transaction is included in a block. Thus we only need to check the pre-conditions before the transaction can be added to the block. This is what ErgoScript contracts do.
It is not possible to “change the state” in ErgoScript because it is a language to check pre-conditions for spending coins. ErgoScript is a purely functional language without side effects that operates on immutable data values. This means all the inputs, outputs and other transaction parameters available in a script are immutable. This, among other things, makes ErgoScript a very simple language that is easy to learn and safe to use. Similar to Bitcoin, each input box contains a script, which should return the true value in order to 1) allow spending of the box (i.e. removing from the UTXO set) and 2) adding the transaction to the block.
If we are being pedantic, it is therefore incorrect (strictly speaking) to think of ErgoScript as the language of Ergo contracts, because it is the language of propositions (logical predicates, formulas, etc.) which protect boxes from “illegal” spending. Unlike Bitcoin, in Ergo the whole transaction and a part of the current blockchain context is available to every script. Therefore each script may check which outputs are created by the transaction, their ERG and token amounts (we will use this capability in our example DEX contracts), current block number etc.
In ErgoScript you define the conditions of whether changes (i.e. coin spending) are allowed to happen in a given context. This is in contrast to programming the changes imperatively in the code of a contract.
While Ergo's transaction model unlocks a whole range of applications like (DEX, DeFi Apps, LETS, etc), designing contracts as pre-conditions for coin spending (or guarding scripts) directly is not intuitive. In the next sections we will consider a useful graphical notation to design contracts declaratively using FlowCard Diagrams, which is a visual representation of executable components (FlowCards).
FlowCards aim to radically simplify dApp development on the Ergo platform by providing a high-level declarative language, execution runtime, storage format and a graphical notation.
We will start with a high level of diagrams and go down to FlowCard specification.
FlowCard Diagrams
The idea behind FlowCard diagrams is based on the following observations: 1) An Ergo box is immutable and can only be spent in the transaction which uses it as an input. 2) We therefore can draw a flow of boxes through transactions, so that boxes flowing in to the transaction are spent and those flowing out are created and added to the UTXO. 3) A transaction from this perspective is simply a transformer of old boxes to the new ones preserving the balances of ERGs and tokens involved.
The following figure shows the main elements of the Ergo transaction we've already seen previously (now under the name of FlowCard Diagram).
https://preview.redd.it/9kcxl11o9tv41.png?width=1304&format=png&auto=webp&s=378a7f50769292ca94de35ff597dc1a44af56d14
There is a strictly defined meaning (semantics) behind every element of the diagram, so that the diagram is a visual representation (or a view) of the underlying executable component (called FlowCard).
The FlowCard can be used as a reusable component of an Ergo dApp to create and initiate the transaction on the Ergo blockchain. We will discuss this in the coming sections.
Now let's look at the individual pieces of the FlowCard diagram one by one.
  1. Name and Parameters
Each flow card is given a name and a list of typed parameters. This is similar to a template with parameters. In the above figure we can see the Send flow card which has five parameters. The parameters are used in the specification.
  1. Contract Wallet
This is a key element of the flow card. Every box has a guarding script. Often it is the script that checks a signature against a public key. This script is trivial in ErgoScript and is defined like the def pk(pubkey: Address) = { pubkey } template where pubkey is a parameter of the type Address . In the figure, the script template is applied to the parameter pk(sender) and thus a concrete wallet contract is obtained. Therefore pk(sender) and pk(receiver) yield different scripts and represent different wallets on the diagram, even though they use the same template.
Contract Wallet contains a set of all UTXO boxes which have a given script derived from the given script template using flow card parameters. For example, in the figure, the template is pk and parameter pubkey is substituted with the `sender’ flow card parameter.
  1. Contract
Even though a contract is a property of a box, on the diagram we group the boxes by their contracts, therefore it looks like the boxes belong to the contracts, rather than the contracts belong to the boxes. In the example, we have three instantiated contracts pk(sender) , pk(receiver) and minerFee . Note, that pk(sender) is the instantiation of the pk template with the concrete parameter sender and minerFee is the instantiation of the pre-defined contract which protects the miner reward boxes.
  1. Box name
In the diagram we can give each box a name. Besides readability of the diagram, we also use the name as a synonym of a more complex indexed access to the box in the contract. For example, change is the name of the box, which can also be used in the ErgoScript conditions instead of OUTPUTS(2) . We also use box names to associate spending conditions with the boxes.
  1. Boxes in the wallet
In the diagram, we show boxes (darker rectangles) as belonging to the contract wallets (lighter rectangles). Each such box rectangle is connected with a grey transaction rectangle by either orange or green arrows or both. An output box (with an incoming green arrow) may include many lines of text where each line specifies a condition which should be checked as part of the transaction. The first line specifies the condition on the amount of ERG which should be placed in the box. Other lines may take one of the following forms:
  1. amount: TOKEN - the box should contain the given amount of the given TOKEN
  2. R == value - the box should contain the given value of the given register R
  3. boxName ? condition - the box named boxName should check condition in its script.
We discuss these conditions in the sections below.
  1. Amount of ERGs in the box
Each box should store a minimum amount of ERGs. This is checked when the creating transaction is validated. In the diagram the amount of ERGs is always shown as the first line (e.g. B: ERG or B - minErg - txFee ). The value type ascription B: ERG is optional and may be used for readability. When the value is given as a formula, then this formula should be respected by the transaction which creates the box.
It is important to understand that variables like amount and txFee are not named properties of the boxes. They are parameters of the whole diagram and representing some amounts. Or put it another way, they are shared parameters between transactions (e.g. Sell Order and Swap transactions from DEX example below share the tAmt parameter). So the same name is tied to the same value throughout the diagram (this is where the tooling would help a lot). However, when it comes to on-chain validation of those values, only explicit conditions which are marked with ? are transformed to ErgoScript. At the same time, all other conditions are ensured off-chain during transaction building (for example in an application using Appkit API) and transaction validation when it is added to the blockchain.
  1. Amount of T token
A box can store values of many tokens. The tokens on the diagram are named and a value variable may be associated with the token T using value: T expression. The value may be given by formula. If the formula is prefixed with a box name like boxName ? formula , then it is should also be checked in the guarding script of the boxName box. This additional specification is very convenient because 1) it allows to validate the visual design automatically, and 2) the conditions specified in the boxes of a diagram are enough to synthesize the necessary guarding scripts. (more about this below at “From Diagrams To ErgoScript Contracts”)
  1. Tx Inputs
Inputs are connected to the corresponding transaction by orange arrows. An input arrow may have a label of the following forms:
  1. [email protected] - optional name with an index i.e. [email protected] or u/2 . This is a property of the target endpoint of the arrow. The name is used in conditions of related boxes and the index is the position of the corresponding box in the INPUTS collection of the transaction.
  2. !action - is a property of the source of the arrow and gives a name for an alternative spending path of the box (we will see this in DEX example)
Because of alternative spending paths, a box may have many outgoing orange arrows, in which case they should be labeled with different actions.
  1. Transaction
A transaction spends input boxes and creates output boxes. The input boxes are given by the orange arrows and the labels are expected to put inputs at the right indexes in INPUTS collection. The output boxes are given by the green arrows. Each transaction should preserve a strict balance of ERG values (sum of inputs == sum of outputs) and for each token the sum of inputs >= the sum of outputs. The design diagram requires an explicit specification of the ERG and token values for all of the output boxes to avoid implicit errors and ensure better readability.
  1. Tx Outputs
Outputs are connected to the corresponding transaction by green arrows. An output arrow may have a label of the following [email protected] , where an optional name is accompanied with an index i.e. [email protected] or u/2 . This is a property of the source endpoint of the arrow. The name is used in conditions of the related boxes and the index is the position of the corresponding box in the OUTPUTS collection of the transaction.
Example: Decentralized Exchange (DEX)
Now let's use the above described notation to design a FlowCard for a DEX dApp. It is simple enough yet also illustrates all of the key features of FlowCard diagrams which we've introduced in the previous section.
The dApp scenario is shown in the figure below: There are three participants (buyer, seller and DEX) of the DEX dApp and five different transaction types, which are created by participants. The buyer wants to swap ergAmt of ERGs for tAmt of TID tokens (or vice versa, the seller wants to sell TID tokens for ERGs, who sends the order first doesn't matter). Both the buyer and the seller can cancel their orders any time. The DEX off-chain matching service can find matching orders and create the Swap transaction to complete the exchange.
The following diagram fully (and formally) specifies all of the five transactions that must be created off-chain by the DEX dApp. It also specifies all of the spending conditions that should be verified on-chain.

https://preview.redd.it/fnt5f4qp9tv41.png?width=1614&format=png&auto=webp&s=34f145f9a6d622454906857e645def2faba057bd
Let's discuss the FlowCard diagram and the logic of each transaction in details:
Buy Order Transaction
A buyer creates a Buy Order transaction. The transaction spends E amount of ERGs (which we will write E: ERG ) from one or more boxes in the pk(buyer) wallet. The transaction creates a bid box with ergAmt: ERG protected by the buyOrder script. The buyOrder script is synthesized from the specification (see below at “From Diagrams To ErgoScript Contracts”) either manually or automatically by a tool. Even though we don't need to define the buyOrder script explicitly during designing, at run time the bid box should contain the buyOrder script as the guarding proposition (which checks the box spending conditions), otherwise the conditions specified in the diagram will not be checked.
The change box is created to make the input and output sums of the transaction balanced. The transaction fee box is omitted because it can be added automatically by the tools. In practice, however, the designer can add the fee box explicitly to the a diagram. It covers the cases of more complex transactions (like Swap) where there are many ways to pay the transaction fee.
Cancel Buy, Cancel Sell Transactions
At any time, the buyer can cancel the order by sending CancelBuy transaction. The transaction should satisfy the guarding buyOrder contract which protects the bid box. As you can see on the diagram, both the Cancel and the Swap transactions can spend the bid box. When a box has spending alternatives (or spending paths) then each alternative is identified by a unique name prefixed with ! (!cancel and !swap for the bid box). Each alternative path has specific spending conditions. In our example, when the Cancel Buy transaction spends the bid box the ?buyer condition should be satisfied, which we read as “the signature for the buyer address should be presented in the transaction”. Therefore, only buyer can cancel the buy order. This “signature” condition is only required for the !cancel alternative spending path and not required for !swap .
Sell Order Transaction
The Sell Order transaction is similar to the BuyOrder in that it deals with tokens in addition to ERGs. The transaction spends E: ERG and T: TID tokens from seller's wallet (specified as pk(seller) contract). The two outputs are ask and change . The change is a standard box to balance transaction. The ask box keeps tAmt: TID tokens for the exchange and minErg: ERG - the minimum amount of ERGs required in every box.
Swap Transaction
This is a key transaction in the DEX dApp scenario. The transaction has several spending conditions on the input boxes and those conditions are included in the buyOrder and sellOrder scripts (which are verified when the transaction is added to the blockchain). However, on the diagram those conditions are not specified in the bid and ask boxes, they are instead defined in the output boxes of the transaction.
This is a convention for improved usability because most of the conditions relate to the properties of the output boxes. We could specify those properties in the bid box, but then we would have to use more complex expressions.
Let's consider the output created by the arrow labeled with [email protected] . This label tells us that the output is at the index 0 in the OUTPUTS collection of the transaction and that in the diagram we can refer to this box by the buyerOut name. Thus we can label both the box itself and the arrow to give the box a name.
The conditions shown in the buyerOut box have the form bid ? condition , which means they should be verified on-chain in order to spend the bid box. The conditions have the following meaning:
  • tAmt: TID requires the box to have tAmt amount of TID token
  • R4 == bid.id requires R4 register in the box to be equal to id of the bid box.
  • script == buyer requires the buyerOut box to have the script of the wallet where it is located on the diagram, i.e. pk(buyer)
Similar properties are added to the sellerOut box, which is specified to be at index 1 and the name is given to it using the label on the box itself, rather than on the arrow.
The Swap transaction spends two boxes bid and ask using the !swap spending path on both, however unlike !cancel the conditions on the path are not specified. This is where the bid ? and ask ? prefixes come into play. They are used so that the conditions listed in the buyerOut and sellerOut boxes are moved to the !swap spending path of the bid and ask boxes correspondingly.
If you look at the conditions of the output boxes, you will see that they exactly specify the swap of values between seller's and buyer's wallets. The buyer gets the necessary amount of TID token and seller gets the corresponding amount of ERGs. The Swap transaction is created when there are two matching boxes with buyOrder and sellOrder contracts.
From Diagrams To ErgoScript Contracts
What is interesting about FlowCard specifications is that we can use them to automatically generate the necessary ErgoTree scripts. With the appropriate tooling support this can be done automatically, but with the lack of thereof, it can be done manually. Thus, the FlowCard allows us to capture and visually represent all of the design choices and semantic details of an Ergo dApp.
What we are going to do next is to mechanically create the buyOrder contract from the information given in the DEX flow card.
Recall that each script is a proposition (boolean valued expression) which should evaluate to true to allow spending of the box. When we have many conditions to be met at the same time we can combine them in a logical formula using the AND binary operation, and if we have alternatives (not necessarily exclusive) we can put them into the OR operation.
The buyOrder box has the alternative spending paths !cancel and !swap . Thus the ErgoScript code should have OR operation with two arguments - one for each spending path.
/** buyOrder contract */ { val cancelCondition = {} val swapCondition = {} cancelCondition || swapCondition } 
The formula for the cancelCondition expression is given in the !cancel spending path of the buyOrder box. We can directly include it in the script.
/** buyOrder contract */ { val cancelCondition = { buyer } val swapCondition = {} cancelCondition || swapCondition } 
For the !swap spending path of the buyOrder box the conditions are specified in the buyerOut output box of the Swap transaction. If we simply include them in the swapCondition then we get a syntactically incorrect script.
/** buyOrder contract */ { val cancelCondition = { buyer } val swapCondition = { tAmt: TID && R4 == bid.id && @contract } cancelCondition || swapCondition } 
We can however translate the conditions from the diagram syntax to ErgoScript expressions using the following simple rules
  1. [email protected] ==> val buyerOut = OUTPUTS(0)
  2. tAmt: TID ==> tid._2 == tAmt where tid = buyerOut.tokens(TID)
  3. R4 == bid.id ==> R4 == SELF.id where R4 = buyerOut.R4[Coll[Byte]].get
  4. script == buyer ==> buyerOut.propositionBytes == buyer.propBytes
Note, in the diagram TID represents a token id, but ErgoScript doesn't have access to the tokens by the ids so we cannot write tokens.getByKey(TID) . For this reason, when the diagram is translated into ErgoScript, TID becomes a named constant of the index in tokens collection of the box. The concrete value of the constant is assigned when the BuyOrder transaction with the buyOrder box is created. The correspondence and consistency between the actual tokenId, the TID constant and the actual tokens of the buyerOut box is ensured by the off-chain application code, which is completely possible since all of the transactions are created by the application using FlowCard as a guiding specification. This may sound too complicated, but this is part of the translation from diagram specification to actual executable application code, most of which can be automated.
After the transformation we can obtain a correct script which checks all the required preconditions for spending the buyOrder box.
/** buyOrder contract */ def DEX(buyer: Addrss, seller: Address, TID: Int, ergAmt: Long, tAmt: Long) { val cancelCondition: SigmaProp = { buyer } // verify buyer's sig (ProveDlog) val swapCondition = OUTPUTS.size > 0 && { // securing OUTPUTS access val buyerOut = OUTPUTS(0) // from [email protected] buyerOut.tokens.size > TID && { // securing tokens access val tid = buyerOut.tokens(TID) val regR4 = buyerOut.R4[Coll[Byte]] regR4.isDefined && { // securing R4 access val R4 = regR4.get tid._2 == tAmt && // from tAmt: TID R4 == SELF.id && // from R4 == bid.id buyerOut.propositionBytes == buyer.propBytes // from script == buyer } } } cancelCondition || swapCondition } 
A similar script for the sellOrder box can be obtained using the same translation rules. With the help of the tooling the code of contracts can be mechanically generated from the diagram specification.
Conclusions
Declarative programming models have already won the battle against imperative programming in many application domains like Big Data, Stream Processing, Deep Learning, Databases, etc. Ergo is pioneering the declarative model of dApp development as a better and safer alternative to the now popular imperative model of smart contracts.
The concept of FlowCard shifts the focus from writing ErgoScript contracts to the overall flow of values (hence the name), in such a way, that ErgoScript can always be generated from them. You will never need to look at the ErgoScript code once the tooling is in place.
Here are the possible next steps for future work:
  1. Storage format for FlowCard Spec and the corresponding EIP standardized file format (Json/XML/Protobuf). This will allow various tools (Diagram Editor, Runtime, dApps etc) to create and use *.flowcard files.
  2. FlowCard Viewer, which can generate the diagrams from *.flowcard files.
  3. FlowCard Runtime, which can run *.flowcard files, create and send transactions to Ergo network.
  4. FlowCard Designer Tool, which can simplify development of complex diagrams . This will make designing and validation of Ergo contracts a pleasant experience, more like drawing rather than coding. In addition, the correctness of the whole dApp scenario can be verified and controlled by the tooling.
submitted by Guilty_Pea to CryptoCurrencies [link] [comments]

While the general adoption of cryptocurrencies is increasing every day and especially in 2019, cryptocurrencies exchanges play a major role in the evolution of this sphere as they act as the direct link between investors and projects. They provide coins developers access to a new user base and vice.

While the general adoption of cryptocurrencies is increasing every day and especially in 2019, cryptocurrencies exchanges play a major role in the evolution of this sphere as they act as the direct link between investors and projects. They provide coins developers access to a new user base and vice-versa. The combined monthly trading volume of the largest crypto-exchanges exceeds hundreds of billions of US dollars. As a traditional financial exchange, the cryptocurrency exchange’s core operation is to allow for the buying and selling of these digital assets, as well as others. In that way, it is important to be always on top of innovations and upgrades to ensure the best user experience and security associated with investor’s funds.
Launched in 2016, TradeSatoshi is a crypto-to-crypto exchange that allows users to trade today more than 200 digital currencies. It lists popular coins like bitcoin, Bitcoin Cash and Litecoin as well as a wide variety of lesser-known currencies. TradeSatoshi features a basic user interface and supports 2-factor authentication for account security. TradeSatoshi’s Team has been working hard on improvements and changes for the exchange. With an increasing community, which now amount to 360K+ users, TradeSatoshi became an attraction to both cryptocurrency projects owners and traders to list their coins and actively trade on the platform and felt the need to bring some improvements and evolution to the entire platform.
Easy Registration: The registration process is simple and anyone can easily create an account and activate it by an e-mail verification process.
· Intuitive navigation: Everything is based on the Homepage: It displays the top trading pairs and has tabs for Trading and on-going competitions. It also features the support team, live chat, latest news and an interesting faucet to earn free coins. Projects wanting to get a listing can also access this dropdown to apply for listing evaluation.
· Balance Overview: Users can consult their entire portfolio in a single interface and view and thus the best trading decisions can easily be taken.
· Platform Themes: The UI comes with both Day and Night theme to suit individual’s visual liking.
· Trading Tabs: The Trading exchange has 2 options: Basic and Advanced. Basic is for a quick trade and displays all the basic relevant information needed like the order book, day high and low, trade volume etc. The advanced option is a deep dive view with further details needed for expert trading decisions. Both the views are simultaneously accompanied by real time graphs powered by Trading View.
· API Bridge: TradeSatoshi’s platform uses JSON format to allow APIs to integrate and scale-up, thus providing a perfect tool for automated trading. The API’s can be set up easily by clicking on the user dropdown and clicking profile.
· Security: TradeSatoshi ensures the system has multiple layers of security to provide the highest protection of the user funds. Firewalls, 2FA, cold storage, live backups, DDoS mitigation, encryption of wallets are a few features in place to avoid any theft on the platform.
· Speed: Fast response time helps traders to gain an edge over others relying on slow basic exchanges. With high-performance types of equipment, TradeSatoshi gives its users an edge to leverage from its fast-paced execution.
· Mobile View: TradeSatoshi’s HTML coding provides for an excellent mobile view thus helping users to buy/sell/trade on the go.
· Fees: TradeSatoshi trading fee is 0.1% and is the same for all markets.
· Customer Support: TradeSatoshi provides 24/7 customer support, via embedded chat and ticketing system to answer all concerns and questions.
· TabTrader: TradeSatoshi is supported via TabTrader app along with other big exchanges. TabTrader enables you to connect your exchange accounts via API keys, and then use the app itself to access your accounts and trade.
submitted by vitalysmetanin241219 to Tradesatoshi [link] [comments]

Detailed explanation of BitMEX pending order strategy

article originally from FMZ.COM ( A place you can create your own trading bot by Python, JavaScript and C++) https://www.fmz.com/bbs-topic/2710
BitMEX has become the platform of choice for cryptocurrency leverage trading, but its API trading restrictions are strict and make automatic traders feeling very confused. This article mainly shares some tips on the use of APIs in the FMZ quantitative trading platform, mainly for the market making strategy.

1. Features of BitMEX

The most significant advantage is that the trading liquidity is very active, especially the Bitcoin perpetual contract, the transaction amount per minute often exceeds one million or even ten million US dollars; BitMEX pending orders trading have the policy of return commission fee, although it is not much, but attracted a large number of market making tradings, which made the price depth very rich. the latest buying and selling price often have more than one million dollars worth pending orders; because of this point, the transaction price often fluctuates around the minimum change unit of $0.50.

2.BitMEX API frequency limit

The request frequency of the REST API is limited to 300 times every 5 minutes, almost equal to 1 time every second, this limit can be said to be very strict compared to other trading platforms. After the limit is exceeded, 'Rate limit exceeded' will be prompted. If you keep exceeding the limit, the IP may be disabled for one hour. Multiple disables in a short time will result in a week being disabled. For each API request, BitMEX will return the header data, header data is used to see the current number of remaining requests. In fact, if the API is used properly, it will not exceed the frequency limit and generally does not need to be checked.

3.Use websocket to get the market quote

The BitMEX REST API is more restrictive. The official recommendation is to use the websocket protocol more, and push more data types than the average exchange. Pay attention to the following points for specific use:
If the depth data push time is too long, there will be an error, which does not correspond to the real depth. It is estimated that there are too many depth changes and there are omissions in the push, but in general, due to excellent fluidity, you can subscribe to "ticker" or "trades". The order details push is missing a lot and is almost unavailable. There is a significant delay in the push of account information, preferably using the REST API. When the market is volatile too big, the push delay will reach a few seconds. The following code uses the websocket protocol to obtain market and account information in real time, mainly for market-making strategies. The specific use needs to be performed in the main() function.
var ticker = {price:0, buy:0, sell:0, time:0} //Ticker information, the latest price, "buy one" price, "sell one" price, update time //Account information, respectively, position, buying and selling price, buying and selling quantity, position status, order Id var info = {position:0, buyPrice:0, sellPrice:0, buyAmount:0, sellAmount:0, buyState:0, sellState:0, buyId:0, sellId:0} var buyListId = []//Global variables, pre-emptive buying id list, will described below var sellListId = [] var APIKEY = 'your api id' //Need to fill in the BitMEX API ID here. Note that it is not a key, which is required for websocket protocol authentication. var expires = parseInt(Date.now() / 1000) + 10 var signature = exchange.HMAC("sha256", "hex", "GET/realtime" + expires, "{{secretkey}}")//The secretkey will be automatically replaced at the bottom level and does not need to be filled in. var bitmexClient = Dial("wss://www.bitmex.com/realtime", 60) var auth = JSON.stringify({args: [APIKEY, expires, signature], op: "authKeyExpires"})//Authentication information, otherwise you cannot subscribe to the account bitmexClient.write(auth) bitmexClient.write('{"op": "subscribe", "args": ["position","execution","trade:XBTUSD"]}')//Subscribed to positions, order execution and perpetual contract real-time transaction while(true){ var data = bitmexClient.read() if(data){ bitmexData = JSON.parse(data) if('table' in bitmexData && bitmexData.table == 'trade'){ data = bitmexData.data ticker.price = parseFloat(data[data.length-1].price)//The latest transaction price, will push multiple transactions at a time, take one will be ok //You can get the "buy one" and "sell one" price according to the direction of the latest transaction, without subscribing to the depth. if(data[data.length-1].side == 'Buy'){ ticker.sell = parseFloat(data[data.length-1].price) ticker.buy = parseFloat(data[data.length-1].price)-0.5 }else{ ticker.buy = parseFloat(data[data.length-1].price) ticker.sell = parseFloat(data[data.length-1].price)+0.5 } ticker.time = new Date(data[data.length-1].timestamp);//Update time, can be used to determine the delay } }else if(bitmexData.table == 'position'){ var position = parseInt(bitmexData.data[0].currentQty) if(position != info.position){ Log('Position change: ', position, info.position, '#[email protected]')//Position change Log, and pushed to WeChat, remove @ means Do not push info.position = position } info.position = parseInt(bitmexData.data[0].currentQty) } }

4. Placing order skills

BitMEX officially recommends using "bulk ordering" and "order modification" to place order. "bulk ordering" can be executed faster due to BitMEX real-time auditing, risk checking, margin calculation, and commissioning. Therefore, the frequency of the "bulk ordering" is calculated as one tenth of the normal frequency. Futhermore, our order operation should use the method of "bulk ordering" and "order modification" to minimize the use of API. The query order status also needs to consume the API using frequency. It can judge the order status according to the position change or modification order failure.
"bulk ordering" does not limit the order quantity (can't be too much), in fact, a single order can also use the "bulk ordering" interface. Due to the operation of modifying the order, we can "pre-order" some orders where the price deviates greatly, these orders will not be executed, but when we need to place an order, we only need to modify the price and quantity of the placed order. when modifying the order occurs failure, it can also be used as a signal for the order to be executed.
The following is the specific implementation code:
// Cancel all orders and reset global variables function cancelAll(){ exchange.IO("api","DELETE","/api/v1/ordeall","symbol=XBTUSD")//Call IO extension revocation info = {position:0, buyPrice:0, sellPrice:0, buyAmount:0, sellAmount:0, buyState:0, sellState:0, buyId:0, sellId:0} buyListId = [] sellListId = [] } //placing alternate order function waitOrders(){ var orders = [] if(buyListId.length<4){ //When the number of inspections is insufficient, place another "bulk" for(var i=0;i<7;i++){ //Due to BitMEX restrictions, the price can not be excessively excessive, the order quantity can not be too small, and the "execInst" parameter guarantees that only the market making transaction can be executed. orders.push({symbol:'XBTUSD', side:'Buy', orderQty:100, price:ticker.buy-400+i, execInst:'ParticipateDoNotInitiate'}) } } if(sellListId.length<4){ for(var i=0;i<7;i++){ orders.push({symbol:'XBTUSD', side:'Sell', orderQty:100, price:ticker.buy+400+i, execInst:'ParticipateDoNotInitiate'}) } } if(orders.length>0){ var param = "orders=" + JSON.stringify(orders); var ids = exchange.IO("api", "POST", "/api/v1/ordebulk", param);//Bulk orders submitted here for(var i=0;i0){ info.position = pos[0].Type == 0 ? pos[0].Amount : -pos[0].Amount }else{ info.position = 0 } } //Unknown error cannot be modified, all orders are cancelled, reset once else if(err.includes('Invalid orderID')){ cancelAll() Log('Invalid orderID,reset once') } //Exceed the frequency limit, you can continue to try after hibernation else if(err.includes('Rate limit exceeded')){ Sleep(2000) return } //The account is banned, all orders are revoked, and sleep is awaiting recovery for a long time. else if(err.includes('403 Forbidden')){ cancelAll() Log('403,reset once') Sleep(5*60*1000) } }else{ //Modify order successfully if(direction == 'buy'){ info.buyState = 1 info.buyPrice = price info.buyAmount = amount }else{ info.sellState = 1 info.sellPrice = price info.sellAmount = amount } } } //0.5 price change function fixSize(num){ if(num>=_N(num,0)+0.75){ num = _N(num,0)+1 }else if(num>=_N(num,0)+0.5){ num=_N(num,0)+0.5 }else{ num=_N(num,0) } return num } //Trading function function trade(){ waitOrders()//Check if you need a replacement order var buyPrice = fixSize(ticker.buy-5) //For demonstration purposes only, specific transactions should be written by yourself. var sellPrice = fixSize(ticker.sell+5) var buyAmount = 500 var sellAmount = 500 //Modify from an alternate order when there is no order if(info.buyState == 0 && buyListId.length > 0){ info.buyId = buyListId.shift() amendOrders([{orderID:info.buyId, price:buyPrice, orderQty:buyAmount}],'buy', group, buyPrice, buyAmount, info.buyId) } if(info.sellState == 0 && sellListId.length > 0){ info.sellId = sellListId.shift() amendOrders([{orderID: info.sellId, price:sellPrice, orderQty:sellAmount}],'sell', group, sellPrice, sellAmount, info.sellId ) } //Existing orders need to change price if(buyPrice != info.buyPrice && info.buyState == 1){ amendOrders([{orderID:info.buyId, price:buyPrice, orderQty:buyAmount}],'buy', group, buyPrice, buyAmount) } if(sellPrice != info.sellPrice && info.sellState == 1){ amendOrders([{orderID:info.sellId, price:sellPrice, orderQty:sellAmount}],'sell', group, sellPrice, sellAmount) } }

5. Others

BitMEX's server is in the Amazon's server in Dublin, Ireland. The server running strategy ping is less than 1ms when you choose a AWS cloud sever in Dublin, but when there is still a delay in pushing, the overload problem cannot be solved. In addition, when the account is logged in, the server agent cannot be located in the United States and other places where don't allow cryptocurrency tradings. Due to the regulation, the account will be banned.
The code in this article has been modified from my personal strategy and is not guaranteed to be completely correct for reference. The specific use of the market code should be executed in the main function, the trading-related code is placed before the main function, and the trade() function is placed in the push market quote.
article originally from FMZ.COM ( A place you can create your own trading bot by Python, JavaScript and C++) https://www.fmz.com/bbs-topic/2710
submitted by FmzQuant to BitMEX [link] [comments]

How does the perpetual ETHUSD contract works? An intuitive guide

Read my guide to XBTUSD contract first, as this only add complexity.
This is a common language explanation of how the ETHUSD perpetual contract works; it's meant to illustrate the intuition behind it and some of the details you might have to ask. It's not exhaustive, it only useful intuitions.
Note that Bitmex accepts Bitcoin only, and settle contracts in BTC, so you only own, gain or loses Bitcoin, even if you speculate on the price of ETHUSD.
The ETHUSD Perpetual contract
You have an amount of BTC. You want this amount to grow in the same way as the price of ETH-USD (when you buy the contract) or in the opposite direction (when you sell the contract). Please note that even if the contract is settled in BTC, the price of BTC-USD does not influence the computation of PnL and funding rate for this contract.
Size of the contract
Each contract is worth a variable amount of BTC. From the page https://www.bitmex.com/app/contract/ETHUSD = "Each contract is worth 0.001 mXBT per $1 price". Which means if the price of the ETHUSD contract is 115.95 than each contract is worth 115.95*0.000001 BTC = 0.00011595 BTC.
For example when you buy 20 contracts @115.95 it means you have to pay it with 20*115.95*0.000001 BTC. If later you sell it at 130.0 you will received 20*130*0.000001 BTC.
If you sell 20 contracts @115.95 you have to lock down 20*115.95*0.000001 BTC; later if you buy at 110.0 you will have your fund unlocked and will get the difference of (115.95-110.0)*0.000001 BTC as realised PnL.
Note that you are not specifying anywhere the amount of equivalent ETH that you are trading.
Note also that you are buying contracts and not USD or ETH; so how does it guarantee that the price of the contract will follow the price of ETH-USD? With the Funding Rate.
Funding Rate
https://www.bitmex.com/app/perpetualContractsGuide#Funding
The funding rate work exactly as the funding rate for XBTUSD, see my previous guide for more explantion. The only difference is that the ETH reference price is based on the .BETH index (instead of .BXBT)
API Explanation
How does API trade messages look like? When a trade happens on the exchange you will receive a JSON message like this throught the websocket or REST API:
'{"timestamp":"2019-01-13T19:11:04.721Z","symbol":"ETHUSD","side":"Sell","size":1100,"price":114,"tickDirection":"ZeroPlusTick","trdMatchID":"48aa6a2a-11ff-fa7c-148a-77fa4ee44ef1","grossValue":12540000,"homeNotional":3.8601909039865245,"foreignNotional":440.06176305446377}'
Let's break it down: remember that by definition each contract with these values is worth 114*0.000001 BTC = 0.000114 BTC
{ "timestamp": "2019-01-13T19:11:04.721Z", // when the trade happened, according to BITMEX server timestamp "symbol": "ETHUSD", // which contract is this "side": "Sell", // Side of the taker "size": 1100, // How many contracts were traded "price": 114, // price of each contract, same as USE for each ETH "tickDirection": "ZeroPlusTick", // this trade has a price equal or lower than the previous one "trdMatchID": "48aa6a2a-11ff-fa7c-148a-77fa4ee44ef1", // unique id of every trade "grossValue": 12540000, // how many satoshis were traded to pay for this contract "homeNotional": 3.8601909039865245, // How many equivalent ETH was this trade worth "foreignNotional": 440.06176305446377 // How many equivalent USD was this trade worth } 
I will happily add or change details if they helps simplifying the explanation.
EDIT: syntax
submitted by krywen to BitMEX [link] [comments]

How does the perpetual XBTUSD contract works? An intuitive guide

This is a basic explanation of how the XBTUSD perpetual contract works; it's meant to illustrate the intuition behind it and some of the details you might have to ask. It's not exhaustive, it only useful intuitions.
Bitmex accepts Bitcoin only, and settle contracts in BTC, so you only own, gain or loses Bitcoin, but you trade or gamble in other cryptocurrencies.
The XTBUSD Perpetual contract
You have an amount of BTC. You want this amount to grow in the same way as the price of BTC-USD (when you buy the contract) or in the opposite direction (when you sell the contract).
Each contract is worth 1USD, so When you buy 1 contract @3610.0 it means you have to pay 1 USD worth of bitcoin at the price you specified. When you sell the contract instead you receive 1USD woth of BTC at the price you sold at. The same is true if you sell before buying.
Note that you are buying contracts and not USD or BTC; so how does it guarantee that the price of the contract will follow the price of BTC-USD? With the Funding Rate
Funding Rate
https://www.bitmex.com/app/perpetualContractsGuide#Funding The price of the contract might differ from the price of BTC-USD. The price of BTC-USD is distilled into an index (.BXBT)[https://www.bitmex.com/app/index/.BXBT] which is the average of BTC-USD from other exchanegs. This is the 'price of BTC' and is usually slightly different from the 'price of the contract'. When the price of the contract is less than price of BTC, users with a long position get paid the funding rate so you have an incentive to buy the contracts, this push up the price of the contract thus realigning the price of the contract with the price of BTC-USD. At the same time users with short position will pay the same amunt of funding rate, so they have an incentive to reduce their position (by buying contracts), and this also tend to push up the price of the contract to match the price of BTC.
The funding rate is a zero sum game: longs pay shorts X or viceversa; bitmex does not get any fees out of the funding rate.
When the price of the contract is more than the price of BTC, the opposite happens: users with long position pays users with short position, this gives an incentive to sell the contract, pushind down its price to be closer to the price of BTC.
The amount of funding rate you receive or pay is proportional to the difference between the price of the contract and the price of BTC. The funding rate is given every 8 hours, and it's computed as an average over the last 8 hours (TWAP) of the difference between price of XBTUSD and .BXBT. The actual computation is more complex and out of the scope of this article, until someone find an intuitive way to describe it. You'll find examples here.
When is the funding rate charged?
The funding rate is charged at 4:00UTC, 12:00UTC and 20:00UTC every day. The funding rate is also published with an 8-hour grace period before it is charged https://blog.bitmex.com/xbtusd-funding-mean-reversion-strategy/. What does it means?
Let's take an example from 13/01/2019 at about 16:40UTC, the detail page https://www.bitmex.com/app/contract/XBTUSD says:
name value
Funding Rate -0.0230%
Next Funding Jan 13, 2019, 8:00:00 PM
Predicted Rate 0.0003%
At Jan 13, 2019, 20:00:00, the funding rate will be -0.0230%, meaning shorts will pay long 0.023% of their open position. This happens only among those users which have an open position at Jan 13, 2019, 20:00:00 . This funding rate has been computed as an average over time of the difference between the price of the XBTUSD contract and .BXBT, during the period (Jan 13, 2019, 12:00:00 - Jan 13, 2019, 16:00:00). (All times are UTC) Also the Predicted Rate is 0.0003%, which is computed during the period (Jan 13, 2019, 12:00:00 - Jan 13, 2019, 20:00:00) and will be paid at Jan 14, 2019, 04:00:00. This is 'predicted' because the period of computation has not finished yet, so this rate might still change.
The current price of the contract and .BXBT will not affect the next funding rate you get, but the one after that.
Note also that the funding rate is not per day, but per 8 hours period. To know which % you pay per day you have to sum 3 consecutive funding rates.
This means you can think of strategies to speculate on the funding rate and not on the price of BTC-USD itself; for example looking at (https://midascapital.eu/2018/08/03/the-xbtusd-perpetual-swap-contract/)[https://midascapital.eu/2018/08/03/the-xbtusd-perpetual-swap-contract/].
Fees
You only pay maketaker fees, there are no other fees, not even to borrow in order to trade on margin. You are effectively borrowing virtual money, so it cost no fees. Note that fees are charged on the matched volume, which is after leverage. Currently you get paid -0.025% if you are a maker and you pay 0.075% if you are a taker.
API Trades Explanation
How does an API trade messages look like? When a trade happens on the exchange you will receive a JSON message like this throught the websocket or REST API:
'{"timestamp":"2018-12-14T17:04:27.127Z","symbol":"XBTUSD","side":"Sell","size":5,"price":3170.5,"tickDirection":"MinusTick","trdMatchID":"15cdac8e-ccdc-5d4b-1300-a0899574239d","grossValue":157705,"homeNotional":0.00157705,"foreignNotional":5}'
Let's break it down:
{ "timestamp":"2018-12-14T17:04:27.127Z", // When the trade happened according to bitmex server timestamp "symbol":"XBTUSD", // which contract is this "side":"Sell", // The taker side; 'Sell' means someone sent and order to buy and didn't get mathced immediately; at this timestamp someone decided to match the offer and sell to them. "size":5, // How many contracts; just for convenience you can think of these as USD "price":3170.5, // pride of the contract "tickDirection":"MinusTick", // This trade happened at a price lower than the previous one "trdMatchID":"15cdac8e-ccdc-5d4b-1300-a0899574239d", // ID of this trade. It should always be unique. "grossValue":157705, // How many sathoshi were exchanged == 5/3170.5*100000000 "homeNotional":0.00157705, // How many BTC was this trade worth "foreignNotional":5 // How many USD was this trade worth } 
If any of these field seems irrelevant or trivial, please note that they are much less trivial for the ETHUSD contract.
I will happily add or change details if they helps simplifying the explanation.
EDIT: see also the guide to ETHUSD.
EDIT: added Fees section
submitted by krywen to BitMEX [link] [comments]

Detailed explanation of BitMEX pending order strategy

article originally from FMZ.COM ( A place you can create your own trading bot by Python, JavaScript and C++)
BitMEX has become the platform of choice for cryptocurrency leverage trading, but its API trading restrictions are strict and make automatic traders feeling very confused. This article mainly shares some tips on the use of APIs in the FMZ quantitative trading platform, mainly for the market making strategy.

1. Features of BitMEX

The most significant advantage is that the trading liquidity is very active, especially the Bitcoin perpetual contract, the transaction amount per minute often exceeds one million or even ten million US dollars; BitMEX pending orders trading have the policy of return commission fee, although it is not much, but attracted a large number of market making tradings, which made the price depth very rich. the latest buying and selling price often have more than one million dollars worth pending orders; because of this point, the transaction price often fluctuates around the minimum change unit of $0.50.

2.BitMEX API frequency limit

The request frequency of the REST API is limited to 300 times every 5 minutes, almost equal to 1 time every second, this limit can be said to be very strict compared to other trading platforms. After the limit is exceeded, 'Rate limit exceeded' will be prompted. If you keep exceeding the limit, the IP may be disabled for one hour. Multiple disables in a short time will result in a week being disabled. For each API request, BitMEX will return the header data, header data is used to see the current number of remaining requests. In fact, if the API is used properly, it will not exceed the frequency limit and generally does not need to be checked.

3.Use websocket to get the market quote

The BitMEX REST API is more restrictive. The official recommendation is to use the websocket protocol more, and push more data types than the average exchange. Pay attention to the following points for specific use:
If the depth data push time is too long, there will be an error, which does not correspond to the real depth. It is estimated that there are too many depth changes and there are omissions in the push, but in general, due to excellent fluidity, you can subscribe to "ticker" or "trades". The order details push is missing a lot and is almost unavailable. There is a significant delay in the push of account information, preferably using the REST API. When the market is volatile too big, the push delay will reach a few seconds. The following code uses the websocket protocol to obtain market and account information in real time, mainly for market-making strategies. The specific use needs to be performed in the main() function.
var ticker = {price:0, buy:0, sell:0, time:0} //Ticker information, the latest price, "buy one" price, "sell one" price, update time //Account information, respectively, position, buying and selling price, buying and selling quantity, position status, order Id var info = {position:0, buyPrice:0, sellPrice:0, buyAmount:0, sellAmount:0, buyState:0, sellState:0, buyId:0, sellId:0} var buyListId = []//Global variables, pre-emptive buying id list, will described below var sellListId = [] var APIKEY = 'your api id' //Need to fill in the BitMEX API ID here. Note that it is not a key, which is required for websocket protocol authentication. var expires = parseInt(Date.now() / 1000) + 10 var signature = exchange.HMAC("sha256", "hex", "GET/realtime" + expires, "{{secretkey}}")//The secretkey will be automatically replaced at the bottom level and does not need to be filled in. var bitmexClient = Dial("wss://www.bitmex.com/realtime", 60) var auth = JSON.stringify({args: [APIKEY, expires, signature], op: "authKeyExpires"})//Authentication information, otherwise you cannot subscribe to the account bitmexClient.write(auth) bitmexClient.write('{"op": "subscribe", "args": ["position","execution","trade:XBTUSD"]}')//Subscribed to positions, order execution and perpetual contract real-time transaction while(true){ var data = bitmexClient.read() if(data){ bitmexData = JSON.parse(data) if('table' in bitmexData && bitmexData.table == 'trade'){ data = bitmexData.data ticker.price = parseFloat(data[data.length-1].price)//The latest transaction price, will push multiple transactions at a time, take one will be ok //You can get the "buy one" and "sell one" price according to the direction of the latest transaction, without subscribing to the depth. if(data[data.length-1].side == 'Buy'){ ticker.sell = parseFloat(data[data.length-1].price) ticker.buy = parseFloat(data[data.length-1].price)-0.5 }else{ ticker.buy = parseFloat(data[data.length-1].price) ticker.sell = parseFloat(data[data.length-1].price)+0.5 } ticker.time = new Date(data[data.length-1].timestamp);//Update time, can be used to determine the delay } }else if(bitmexData.table == 'position'){ var position = parseInt(bitmexData.data[0].currentQty) if(position != info.position){ Log('Position change: ', position, info.position, '#[email protected]')//Position change Log, and pushed to WeChat, remove @ means Do not push info.position = position } info.position = parseInt(bitmexData.data[0].currentQty) } }

4. Placing order skills

BitMEX officially recommends using "bulk ordering" and "order modification" to place order. "bulk ordering" can be executed faster due to BitMEX real-time auditing, risk checking, margin calculation, and commissioning. Therefore, the frequency of the "bulk ordering" is calculated as one tenth of the normal frequency. Futhermore, our order operation should use the method of "bulk ordering" and "order modification" to minimize the use of API. The query order status also needs to consume the API using frequency. It can judge the order status according to the position change or modification order failure.
"bulk ordering" does not limit the order quantity (can't be too much), in fact, a single order can also use the "bulk ordering" interface. Due to the operation of modifying the order, we can "pre-order" some orders where the price deviates greatly, these orders will not be executed, but when we need to place an order, we only need to modify the price and quantity of the placed order. when modifying the order occurs failure, it can also be used as a signal for the order to be executed.
The following is the specific implementation code:
// Cancel all orders and reset global variables function cancelAll(){ exchange.IO("api","DELETE","/api/v1/ordeall","symbol=XBTUSD")//Call IO extension revocation info = {position:0, buyPrice:0, sellPrice:0, buyAmount:0, sellAmount:0, buyState:0, sellState:0, buyId:0, sellId:0} buyListId = [] sellListId = [] } //placing alternate order function waitOrders(){ var orders = [] if(buyListId.length<4){ //When the number of inspections is insufficient, place another "bulk" for(var i=0;i<7;i++){ //Due to BitMEX restrictions, the price can not be excessively excessive, the order quantity can not be too small, and the "execInst" parameter guarantees that only the market making transaction can be executed. orders.push({symbol:'XBTUSD', side:'Buy', orderQty:100, price:ticker.buy-400+i, execInst:'ParticipateDoNotInitiate'}) } } if(sellListId.length<4){ for(var i=0;i<7;i++){ orders.push({symbol:'XBTUSD', side:'Sell', orderQty:100, price:ticker.buy+400+i, execInst:'ParticipateDoNotInitiate'}) } } if(orders.length>0){ var param = "orders=" + JSON.stringify(orders); var ids = exchange.IO("api", "POST", "/api/v1/ordebulk", param);//Bulk orders submitted here for(var i=0;i0){ info.position = pos[0].Type == 0 ? pos[0].Amount : -pos[0].Amount }else{ info.position = 0 } } //Unknown error cannot be modified, all orders are cancelled, reset once else if(err.includes('Invalid orderID')){ cancelAll() Log('Invalid orderID,reset once') } //Exceed the frequency limit, you can continue to try after hibernation else if(err.includes('Rate limit exceeded')){ Sleep(2000) return } //The account is banned, all orders are revoked, and sleep is awaiting recovery for a long time. else if(err.includes('403 Forbidden')){ cancelAll() Log('403,reset once') Sleep(5*60*1000) } }else{ //Modify order successfully if(direction == 'buy'){ info.buyState = 1 info.buyPrice = price info.buyAmount = amount }else{ info.sellState = 1 info.sellPrice = price info.sellAmount = amount } } } //0.5 price change function fixSize(num){ if(num>=_N(num,0)+0.75){ num = _N(num,0)+1 }else if(num>=_N(num,0)+0.5){ num=_N(num,0)+0.5 }else{ num=_N(num,0) } return num } //Trading function function trade(){ waitOrders()//Check if you need a replacement order var buyPrice = fixSize(ticker.buy-5) //For demonstration purposes only, specific transactions should be written by yourself. var sellPrice = fixSize(ticker.sell+5) var buyAmount = 500 var sellAmount = 500 //Modify from an alternate order when there is no order if(info.buyState == 0 && buyListId.length > 0){ info.buyId = buyListId.shift() amendOrders([{orderID:info.buyId, price:buyPrice, orderQty:buyAmount}],'buy', group, buyPrice, buyAmount, info.buyId) } if(info.sellState == 0 && sellListId.length > 0){ info.sellId = sellListId.shift() amendOrders([{orderID: info.sellId, price:sellPrice, orderQty:sellAmount}],'sell', group, sellPrice, sellAmount, info.sellId ) } //Existing orders need to change price if(buyPrice != info.buyPrice && info.buyState == 1){ amendOrders([{orderID:info.buyId, price:buyPrice, orderQty:buyAmount}],'buy', group, buyPrice, buyAmount) } if(sellPrice != info.sellPrice && info.sellState == 1){ amendOrders([{orderID:info.sellId, price:sellPrice, orderQty:sellAmount}],'sell', group, sellPrice, sellAmount) } }

5. Others

BitMEX's server is in the Amazon's server in Dublin, Ireland. The server running strategy ping is less than 1ms when you choose a AWS cloud sever in Dublin, but when there is still a delay in pushing, the overload problem cannot be solved. In addition, when the account is logged in, the server agent cannot be located in the United States and other places where don't allow cryptocurrency tradings. Due to the regulation, the account will be banned.
The code in this article has been modified from my personal strategy and is not guaranteed to be completely correct for reference. The specific use of the market code should be executed in the main function, the trading-related code is placed before the main function, and the trade() function is placed in the push market quote.
article originally from FMZ.COM ( A place you can create your own trading bot by Python, JavaScript and C++)
submitted by FmzQuant to CryptoCurrencyTrading [link] [comments]

Detailed explanation of BitMEX pending order strategy

BitMEX has become the platform of choice for cryptocurrency leverage trading, but its API trading restrictions are strict and make automatic traders feeling very confused. This article mainly shares some tips on the use of APIs in the FMZ quantitative trading platform, mainly for the market making strategy.

1. Features of BitMEX

The most significant advantage is that the trading liquidity is very active, especially the Bitcoin perpetual contract, the transaction amount per minute often exceeds one million or even ten million US dollars; BitMEX pending orders trading have the policy of return commission fee, although it is not much, but attracted a large number of market making tradings, which made the price depth very rich. the latest buying and selling price often have more than one million dollars worth pending orders; because of this point, the transaction price often fluctuates around the minimum change unit of $0.50.

2.BitMEX API frequency limit

The request frequency of the REST API is limited to 300 times every 5 minutes, almost equal to 1 time every second, this limit can be said to be very strict compared to other trading platforms. After the limit is exceeded, 'Rate limit exceeded' will be prompted. If you keep exceeding the limit, the IP may be disabled for one hour. Multiple disables in a short time will result in a week being disabled. For each API request, BitMEX will return the header data, header data is used to see the current number of remaining requests. In fact, if the API is used properly, it will not exceed the frequency limit and generally does not need to be checked.

3.Use websocket to get the market quote

The BitMEX REST API is more restrictive. The official recommendation is to use the websocket protocol more, and push more data types than the average exchange. Pay attention to the following points for specific use:
If the depth data push time is too long, there will be an error, which does not correspond to the real depth. It is estimated that there are too many depth changes and there are omissions in the push, but in general, due to excellent fluidity, you can subscribe to "ticker" or "trades". The order details push is missing a lot and is almost unavailable. There is a significant delay in the push of account information, preferably using the REST API. When the market is volatile too big, the push delay will reach a few seconds. The following code uses the websocket protocol to obtain market and account information in real time, mainly for market-making strategies. The specific use needs to be performed in the main() function.
var ticker = {price:0, buy:0, sell:0, time:0} //Ticker information, the latest price, "buy one" price, "sell one" price, update time //Account information, respectively, position, buying and selling price, buying and selling quantity, position status, order Id var info = {position:0, buyPrice:0, sellPrice:0, buyAmount:0, sellAmount:0, buyState:0, sellState:0, buyId:0, sellId:0} var buyListId = []//Global variables, pre-emptive buying id list, will described below var sellListId = [] var APIKEY = 'your api id' //Need to fill in the BitMEX API ID here. Note that it is not a key, which is required for websocket protocol authentication. var expires = parseInt(Date.now() / 1000) + 10 var signature = exchange.HMAC("sha256", "hex", "GET/realtime" + expires, "{{secretkey}}")//The secretkey will be automatically replaced at the bottom level and does not need to be filled in. var bitmexClient = Dial("wss://www.bitmex.com/realtime", 60) var auth = JSON.stringify({args: [APIKEY, expires, signature], op: "authKeyExpires"})//Authentication information, otherwise you cannot subscribe to the account bitmexClient.write(auth) bitmexClient.write('{"op": "subscribe", "args": ["position","execution","trade:XBTUSD"]}')//Subscribed to positions, order execution and perpetual contract real-time transaction while(true){ var data = bitmexClient.read() if(data){ bitmexData = JSON.parse(data) if('table' in bitmexData && bitmexData.table == 'trade'){ data = bitmexData.data ticker.price = parseFloat(data[data.length-1].price)//The latest transaction price, will push multiple transactions at a time, take one will be ok //You can get the "buy one" and "sell one" price according to the direction of the latest transaction, without subscribing to the depth. if(data[data.length-1].side == 'Buy'){ ticker.sell = parseFloat(data[data.length-1].price) ticker.buy = parseFloat(data[data.length-1].price)-0.5 }else{ ticker.buy = parseFloat(data[data.length-1].price) ticker.sell = parseFloat(data[data.length-1].price)+0.5 } ticker.time = new Date(data[data.length-1].timestamp);//Update time, can be used to determine the delay } }else if(bitmexData.table == 'position'){ var position = parseInt(bitmexData.data[0].currentQty) if(position != info.position){ Log('Position change: ', position, info.position, '#[email protected]')//Position change Log, and pushed to WeChat, remove @ means Do not push info.position = position } info.position = parseInt(bitmexData.data[0].currentQty) } }

4. Placing order skills

BitMEX officially recommends using "bulk ordering" and "order modification" to place order. "bulk ordering" can be executed faster due to BitMEX real-time auditing, risk checking, margin calculation, and commissioning. Therefore, the frequency of the "bulk ordering" is calculated as one tenth of the normal frequency. Futhermore, our order operation should use the method of "bulk ordering" and "order modification" to minimize the use of API. The query order status also needs to consume the API using frequency. It can judge the order status according to the position change or modification order failure.
"bulk ordering" does not limit the order quantity (can't be too much), in fact, a single order can also use the "bulk ordering" interface. Due to the operation of modifying the order, we can "pre-order" some orders where the price deviates greatly, these orders will not be executed, but when we need to place an order, we only need to modify the price and quantity of the placed order. when modifying the order occurs failure, it can also be used as a signal for the order to be executed.
The following is the specific implementation code:
// Cancel all orders and reset global variables function cancelAll(){ exchange.IO("api","DELETE","/api/v1/ordeall","symbol=XBTUSD")//Call IO extension revocation info = {position:0, buyPrice:0, sellPrice:0, buyAmount:0, sellAmount:0, buyState:0, sellState:0, buyId:0, sellId:0} buyListId = [] sellListId = [] } //placing alternate order function waitOrders(){ var orders = [] if(buyListId.length<4){ //When the number of inspections is insufficient, place another "bulk" for(var i=0;i<7;i++){ //Due to BitMEX restrictions, the price can not be excessively excessive, the order quantity can not be too small, and the "execInst" parameter guarantees that only the market making transaction can be executed. orders.push({symbol:'XBTUSD', side:'Buy', orderQty:100, price:ticker.buy-400+i, execInst:'ParticipateDoNotInitiate'}) } } if(sellListId.length<4){ for(var i=0;i<7;i++){ orders.push({symbol:'XBTUSD', side:'Sell', orderQty:100, price:ticker.buy+400+i, execInst:'ParticipateDoNotInitiate'}) } } if(orders.length>0){ var param = "orders=" + JSON.stringify(orders); var ids = exchange.IO("api", "POST", "/api/v1/ordebulk", param);//Bulk orders submitted here for(var i=0;i0){ info.position = pos[0].Type == 0 ? pos[0].Amount : -pos[0].Amount }else{ info.position = 0 } } //Unknown error cannot be modified, all orders are cancelled, reset once else if(err.includes('Invalid orderID')){ cancelAll() Log('Invalid orderID,reset once') } //Exceed the frequency limit, you can continue to try after hibernation else if(err.includes('Rate limit exceeded')){ Sleep(2000) return } //The account is banned, all orders are revoked, and sleep is awaiting recovery for a long time. else if(err.includes('403 Forbidden')){ cancelAll() Log('403,reset once') Sleep(5*60*1000) } }else{ //Modify order successfully if(direction == 'buy'){ info.buyState = 1 info.buyPrice = price info.buyAmount = amount }else{ info.sellState = 1 info.sellPrice = price info.sellAmount = amount } } } //0.5 price change function fixSize(num){ if(num>=_N(num,0)+0.75){ num = _N(num,0)+1 }else if(num>=_N(num,0)+0.5){ num=_N(num,0)+0.5 }else{ num=_N(num,0) } return num } //Trading function function trade(){ waitOrders()//Check if you need a replacement order var buyPrice = fixSize(ticker.buy-5) //For demonstration purposes only, specific transactions should be written by yourself. var sellPrice = fixSize(ticker.sell+5) var buyAmount = 500 var sellAmount = 500 //Modify from an alternate order when there is no order if(info.buyState == 0 && buyListId.length > 0){ info.buyId = buyListId.shift() amendOrders([{orderID:info.buyId, price:buyPrice, orderQty:buyAmount}],'buy', group, buyPrice, buyAmount, info.buyId) } if(info.sellState == 0 && sellListId.length > 0){ info.sellId = sellListId.shift() amendOrders([{orderID: info.sellId, price:sellPrice, orderQty:sellAmount}],'sell', group, sellPrice, sellAmount, info.sellId ) } //Existing orders need to change price if(buyPrice != info.buyPrice && info.buyState == 1){ amendOrders([{orderID:info.buyId, price:buyPrice, orderQty:buyAmount}],'buy', group, buyPrice, buyAmount) } if(sellPrice != info.sellPrice && info.sellState == 1){ amendOrders([{orderID:info.sellId, price:sellPrice, orderQty:sellAmount}],'sell', group, sellPrice, sellAmount) } }

5. Others

BitMEX's server is in the Amazon's server in Dublin, Ireland. The server running strategy ping is less than 1ms when you choose a AWS cloud sever in Dublin, but when there is still a delay in pushing, the overload problem cannot be solved. In addition, when the account is logged in, the server agent cannot be located in the United States and other places where don't allow cryptocurrency tradings. Due to the regulation, the account will be banned.
The code in this article has been modified from my personal strategy and is not guaranteed to be completely correct for reference. The specific use of the market code should be executed in the main function, the trading-related code is placed before the main function, and the trade() function is placed in the push market quote.
submitted by FmzQuant to CryptoCurrencies [link] [comments]

Pass arguments into a new function

What I'm trying to do is add the new cryptocurrency prices into new lists(Right now, Ethereum is what I'm working on adding). I'd like to make it so if I add a new coin, it will automatically create a new list to analyze that coin's prices.
Tell your mom you love her!
import requests import json import threading import datetime prices = [] def get_price(): # The timer, to run every minute threading.Timer(6.0, get_price).start() p = requests.get("https://api.coinmarketcap.com/v2/ticke") bitcoin_price = '%d' % p.json()['data']["1"]["quotes"]["USD"]["price"] ethereum_price = '%d' % p.json()['data']['1027']['quotes']['USD']["price"] time = '%d' % p.json()['data']["1"]['last_updated'] #print('BTC $' + bitcoin_price) #print('ETH $' + ethereum_pricee) #print(datetime.datetime.fromtimestamp(int(time)).strftime('%Y-%m-%d %H:%M:%S')) return bitcoin_price return ethereum_price # $9254 at 10:12pm 4/26/18 # $9646 at 9:43pm 5/3/18 # $8657 at 1:47pm 5/13/18 def compare_price(): threading.Timer(12.0, compare_price).start() prices.insert(0, get_price()) del prices[2:] print(prices) if prices[0] > prices[1]: outcome = "SELL" elif prices[0] < prices[1]: outcome = "BUY!" elif prices[0] == prices [1]: outcome = "SAME" print(outcome) #get_price() compare_price() 
submitted by tbone912 to learnpython [link] [comments]

Project: Training strategies for algorithmic crypto-currency trading

The project consists in creating a bot that connects to a trading platform and manages a wallet of cryptocurrencies, executing orders to buy or sell.

Context

Cryptocurrencies have gained significant popularity over the past years as easy-to-use financial instruments, and many actors of the Fintech industry are now offering applications, frameworks and APIs to manipulate them. There are also multiple exchange platform where cryptocurrencies can be exchanged, purchased and sold with traditional fiat currencies.
Algorithmic trading has also seen a large adoption and now accounts for the majority of financial transactions conducted on global markets.
Accordingly, several tools can be used to build a bot that connects to a cryptocurrency exchange platform and performs automated algorithmic trading.

Cryptocurrencies

The first cryptocurrency, Bitcoin, was first published in 2009 by an anonymous user Satoshi Nakamoto, building on the previous works of the cypherpunk community.
Here is the original article that introduced Bitcoin and the blockchain technology it relies on. By combining several techniques leveraging Strong cryptography, Bitcoin allows its community of users to collectively manage the currency without the need for a central supervisor, undermining the need for banking actors.
Many alternate schemes were proposed since then, usually with small variations: this subreddit or that website may be good starting points to find out about them.
Many exchange were also created to offer trading capabilities, but most of the original actors were since then liquidated because of frauds or hacks where parts of the handled currency were stolen. Current reputable actors with APIs available include Bitstamp or Kraken.

The DNNBitcoin experiment

In the initial development stage of PKP, the environment currently used for this course hands'on sessions, DNNBitcoin was an early attempt at demonstrating the botting engine to host such an algorithmic trading engine.
Users could registered an account and a bot on the platform for free, connecting to several exchange APIs and running market making strategies. Several hundred bots were simultaneously run at some point. The experiment was eventually stopped, with all of the then supported exchanges shutting down, and a lot of maintenance involved, but some outdated code was still kept together with the DNN extension and provides some guidance on how to proceed.

How the legacy Bot worked

The main execution rules, which were left in the middle of some refactoring, include:

Connectors

When DNNBitcoin was developped, individual connectors were implemented to each supported exchange by means of customized API requests.
The XChange library now provides a safer alternative with many exchanges supported and the burden to keep up to date with APIs left out the the library's developers. It should be possible to port it to .Net using IKVM as was done with the AIMA library.

Authenticating to the trade platform

Platform usually authenticate users with a variety of cryptographic Hmac authentication (signing sent data with a private key provided by the platform). The XChange library should take care of performing that operation, given the required keys obtained online.

Data format

Data is usually retrieved and passed to the APIs using the Json format. Again, the XChange library should take care of the formatting and provide a unified set of classes to be leveraged regardless of the target exchange platform.

Trading engine

DNNBitcoin provides a lightweight framework for manipulating currencies and running various trading strategies, in the form of .Net classes implementing a common interface, with a method taking as arguments the user wallet, market and historical data, and returning orders to be executed. The PKP UI engine would transform the strategies class into web forms, which users accessed to customize their own strategies.
This was enough to implement different kinds of strategies, but since then, several open source libraries offering a complete trading engine were released, and probably provide a better alternative.
The Lean Framework constitutes a good candidate to replace the existing light weight Framework.

History and Simulation

The legacy bot also included features to collect and deal with historical market data, allowing for backtesting simulations, for a given period, of specific strategies. Leveraging a dedicated trading library should provide some alternate mean to support the same feature.

Initial requirements

The initial task is that of tying together:
This should be a matter of integrating the previously introduced libraries, and providing methods to flow the Data between them.
Automapper is a library that can ease providing the mappings between the corresponding classes.

Trading strategies

Then the main task of this project is figuring out appropriate trading strategies. Several traditional strategies can be successful, the lean framework provides several of them and you can explore the right panel of the Algorithmic trading subredit, or in some other subreddits, among those cited in the course resources.
However, more interesting and powerful strategies leverage AI techniques, such as neural networks. See for instance this paper for a basic neural network implementation, or more recent deep learning examples in the CNTK gallery or this article.
submitted by jeansylvain to AI101EPF2017 [link] [comments]

Introducing Itemplatform, a free-to-use SteamBot-as-a-Service platform with powerful API

Hi,
I'm Hermann, web developer since roughly 15 years, and avid gamer since even longer. I would like to introduce you to Itemplatform, an open platform that you can use for your application/website to take care of everything regarding item handling. Think of it as "SteamBot as a webservice"!
I hereby invite all developers to take a look at the Itemplatform API, which provides several features I hope you find interesting:
The API uses REST endpoints, JSON, and has a very extensive documention which can be found here.
I also created an open-source demo application showcasing all key functionalities. The source code can be found here on GitHub, and there is also a live version of this demo app online here. You can send items to the demo application, and it will immediately send them back to you, so you can see for yourself how fast and easy everything is going.
Using Itemplatform and its API is completely free. In the future, there might be usage tiers which will ask users requiring lots of resources (many items, many API calls, etc.) to sign up for a paid subscription, but there will always be a free tier and signing up for a paid plan will always be optional.
There is a lot you can do with this API that was not possible before. I've already implemented several integrations, for example TwitchAlerts and Streamtip. These are services that help streamers to display live notifications e.g. when receiving donations. Streamers can now set up their Itemplatform account, display their Itemplatform link on their profile, and whenever they get donated an item they can display a notification, just like with cash donations. This is something that would be VERY complicated to achieve with the Steam API alone. Of course, this is just an example, you can do basically everything regarding receiving and sending items!
I originally planned to launch Itemplatform mid of December, but in light of the recent news regarding Steam Escrow I decided to make it public now, as developers are quite likely facing big changes to their applications and might be looking for a solution like Itemplatform. Itemplatform will fully support the new Escrow system. In addition, users will be able to add two-factor authentication to their Itemplatform account. There will also be the option to enter a two-factor authentication code for each item transfer. This will ensure the maximum security for all items. If they choose to do so, developers will be able to not use these options in case they want to fully automate the "send out items"-process in their Itemplatform account.
Itemplatform comes with a full frontend for end users that takes care of all important tasks. In addition, it features the Itemplatform Market where items can be purchased and sold for cash. Itemplatform aims to provide a secure marketplace for both buyers and sellers, protecting both sides from fraud. Buyers get their items immediately transferred to their Itemplatform account (from where they can transfer it to their Steam account if they want to). Sellers get their revenue credited immediately and can have their earnings paid out. Payment methods supported for both buying items, and payouts: PayPal, Bitcoin, and SEPA bank transfers. Sofort Banking is available as well (for buying items). All market interactions (buying, selling, etc.) can of course be done with the Itemplatform API as well (the functionality is already there, I am writing the documentation as you are reading this)!
I hope that people are open for such a new approach towards solving many of the problems that are currently omnipresent when it comes to dealing with virtual items. I know that people's trust in the platform to be handling their items must be hard-earned. I put lots of effort into this project and am willing to continue to do so. I will actively listen to feedback from users as well as developers and add additional functions, API endpoints or whatever is needed to make Itemplatform the place to go for item handling, buying & selling items, and all related tasks.
This project does not intend to and will not replace SteamBot. It offers its features and advantages in a new way, that's it. You will always have more customization options when using your own SteamBot, but I hope Itemplatform might provide developers with a solution when maintaining your own bot is too cumbersome.
If you have any question, please feel free to ask me here in the comments or contact me.
TLDR: Check out Itemplatform and its API, providing developers with a well-documented webservice taking care of everything regarding sending, receiving, buying and selling Steam items. Integrate Itemplatform into your project and profit!
submitted by itemplatform to SteamBot [link] [comments]

EXACTLY when you should BUY and SELL BITCOIN? Excluding bubbles nets BTC cheat sheet? Localbitcoin clone script - most popular bitcoin buy sell website Buying/Selling Bitcoin with Paxful - YouTube How to do Automated Bitcoin Algo Trading via BTC-e Trade API How to Buy Cryptocurrency for Beginners (Ultimate Step-by ...

Buy, sell and store Bitcoin, Ethereum, Ripple (XRP), Litecoin & other cryptocurrencies with Naira. Quidax is simple, secure and safe. For successful API calls, our JSON response objects looks like: ... 0306: Order side not in (buy, sell) 0307: Order type not in (limit, market) 0308: Order request cannot include both minor and major; 0309: Order request must include either minor or major ; 0310: Incorrect WID (non-existent or does not belong to user) 0311: Incorrect FID (non-existent or does not belong to user) 0312 ... ask is the most profitable rate of active sell orders vwap is the weighted average from last 24 hours average is the average rate of 3 best sell orders. all - all above informations combined Returns JSON object, which looks like: under a single API CoinAPI is a platform which provides fast, reliable and unified data APIs to cryptocurrency markets. Get a free API key Contact sales. 0 exchanges integrated. 100 assets supported. 10 market data updates /sec. 0 TB of history market data {integration _provider} We are a high-quality, one-stop-solution market data provider for cryptocurrency markets. All CoinAPI data is ... Die Bitcoin.de API (Basic) ermöglicht Ihnen den Zugriff auf die Übersicht der erfolgreich abgeschlossenen Trades (Tradehistory), der aktuellen Kauf- und Verkaufsangebote (Orderbook) und den aktuellen Bitcoin.de-Kurs (Rate). Tradehistory und Orderbook werden alle 60 Sekunden aktualisiert.

[index] [584] [36701] [30818] [10040] [51097] [9348] [29096] [26086] [24340] [3610]

EXACTLY when you should BUY and SELL BITCOIN? Excluding bubbles nets BTC cheat sheet?

Join Binance Exchange Here! https://www.binance.com/?ref=13795076 Join Kucoin Exchange Here! https://www.kucoin.com/#/?r=7chr68 Mine Bitcoin and other Crypto... In this tutorial, you are shown how to use Python to communicate with a bitcoin trade API. In this case, we are using BTC-e's Trade API, though the trade API... Hey Guys, it's the voice of the block chain, Satoshi's big cousin, cryptography's finest, Champagne Crypto here, thanks for tuning in. Today I want to talk a... Data Presentation using DataTables JS Using BitPay API / Block.io API / Coinpayment API / BlackChain API Maintain full control of your private keys with our multi-signature vault. Bitcoin NodeJS Tutorial. Intro to NodeJS including installation, creating a basic http server, and fetching the current bitcoin price.

#